title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Prolog - Quick Guide
|
Prolog as the name itself suggests, is the short form of LOGical PROgramming. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is.
Logic Programming is one of the Computer Programming Paradigm, in which the program statements express the facts and rules about different problems within a system of formal logic. Here, the rules are written in the form of logical clauses, where head and body are present. For example, H is head and B1, B2, B3 are the elements of the body. Now if we state that “H is true, when B1, B2, B3 all are true”, this is a rule. On the other hand, facts are like the rules, but without any body. So, an example of fact is “H is true”.
Some logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely declarative languages. These languages allow statements about what the program should accomplish. There is no such step-by-step instruction on how to perform the task. However, other languages like Prolog, have declarative and also imperative properties. This may also include procedural statements like “To solve the problem H, perform B1, B2 and B3”.
Some logic programming languages are given below −
ALF (algebraic logic functional programming language).
ALF (algebraic logic functional programming language).
ASP (Answer Set Programming)
ASP (Answer Set Programming)
CycL
CycL
Datalog
Datalog
FuzzyCLIPS
FuzzyCLIPS
Janus
Janus
Parlog
Parlog
Prolog
Prolog
Prolog++
Prolog++
ROOP
ROOP
We will discuss about the differences between Logic programming and the traditional functional programming languages. We can illustrate these two using the below diagram −
From this illustration, we can see that in Functional Programming, we have to define the procedures, and the rule how the procedures work. These procedures work step by step to solve one specific problem based on the algorithm. On the other hand, for the Logic Programming, we will provide knowledge base. Using this knowledge base, the machine can find answers to the given questions, which is totally different from functional programming.
In functional programming, we have to mention how one problem can be solved, but in logic programming we have to specify for which problem we actually want the solution. Then the logic programming automatically finds a suitable solution that will help us solve that specific problem.
Now let us see some more differences below −
Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. This is the main reason to use Prolog as the programming language in Artificial Intelligence, where symbol manipulation and inference manipulation are the fundamental tasks.
In Prolog, we need not mention the way how one problem can be solved, we just need to mention what the problem is, so that Prolog automatically solves it. However, in Prolog we are supposed to give clues as the solution method.
Prolog language basically has three different elements −
Facts − The fact is predicate that is true, for example, if we say, “Tom is the son of Jack”, then this is a fact.
Rules − Rules are extinctions of facts that contain conditional clauses. To satisfy a rule these conditions should be met. For example, if we define a rule as −
grandfather(X, Y) :- father(X, Z), parent(Z, Y)
This implies that for X to be the grandfather of Y, Z should be a parent of Y and X should be father of Z.
Questions − And to run a prolog program, we need some questions, and those questions can be answered by the given facts and rules.
The heritage of prolog includes the research on theorem provers and some other automated deduction system that were developed in 1960s and 1970s. The Inference mechanism of the Prolog is based on Robinson’s Resolution Principle, that was proposed in 1965, and Answer extracting mechanism by Green (1968). These ideas came together forcefully with the advent of linear resolution procedures.
The explicit goal-directed linear resolution procedures, gave impetus to the development of a general purpose logic programming system. The first Prolog was the Marseille Prolog based on the work by Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter (Roussel, 1975) was the first detailed description of the Prolog language.
Prolog is also considered as a fourth generation programming language supporting the declarative programming paradigm. The well-known Japanese Fifth-Generation Computer Project, that was announced in 1981, adopted Prolog as a development language, and thereby grabbed considerable attention on the language and its capabilities.
Prolog is used in various domains. It plays a vital role in automation system. Following are some other important fields where Prolog is used −
Intelligent Database Retrieval
Intelligent Database Retrieval
Natural Language Understanding
Natural Language Understanding
Specification Language
Specification Language
Machine Learning
Machine Learning
Robot Planning
Robot Planning
Automation System
Automation System
Problem Solving
Problem Solving
In this chapter, we will discuss how to install Prolog in our system.
In this tutorial, we are using GNU Prolog, Version: 1.4.5
This is the official GNU Prolog website where we can see all the necessary details about GNU Prolog, and also get the download link.
http://www.gprolog.org/
Given below are the direct download links of GNU Prolog for Windows. For other operating systems like Mac or Linux, you can get the download links by visiting the official website (Link is given above) −
http://www.gprolog.org/setup-gprolog-1.4.5-mingw-x86.exe (32 Bit System)
http://www.gprolog.org/setup-gprolog-1.4.5-mingw-x64.exe(64 Bit System)
Download the exe file and run it.
Download the exe file and run it.
You will see the window as shown below, then click on next −
You will see the window as shown below, then click on next −
Select proper directory where you want to install the software, otherwise let it be installed on the default directory. Then click on next.
You will get the below screen, simply go to next.
You can verify the below screen, and check/uncheck appropriate boxes, otherwise you can leave it as default. Then click on next.
In the next step, you will see the below screen, then click on Install.
Then wait for the installation process to finish.
Finally click on Finish to start GNU Prolog.
The GNU prolog is installed successfully as shown below −
In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment.
After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows −
write('Hello World').
Note − After each line, you have to use one period (.) symbol to show that the line has ended.
The corresponding output will be as shown below −
Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console.
Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps −
Step 1 − From the prolog console, go to File > Change Dir, then click on that menu.
Step 2 − Select the proper folder and press OK.
Now we can see in the prolog console, it shows that we have successfully changed the directory.
Step 3 − Now create one file (extension is *.pl) and write the code as follows −
main :- write('This is sample Prolog program'),
write(' This program is written into hello_world.pl file').
Now let’s run the code. To run it, we have to write the file name as follows −
[hello_world]
The output is as follows −
In this chapter, we will gain some basic knowledge about Prolog. So we will move on to the first step of our Prolog Programming.
The different topics that will be covered in this chapter are −
Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail about the Knowledge Base, and how it helps in logic programming.
Facts, Rules and Queries − These are the building blocks of logic programming. We will get some detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic programming.
Here, we will discuss about the essential building blocks of logic programming. These building blocks are Facts, Rules and the Queries.
We can define fact as an explicit relationship between objects, and properties these objects might have. So facts are unconditionally true in nature. Suppose we have some facts as given below −
Tom is a cat
Tom is a cat
Kunal loves to eat Pasta
Kunal loves to eat Pasta
Hair is black
Hair is black
Nawaz loves to play games
Nawaz loves to play games
Pratyusha is lazy.
Pratyusha is lazy.
So these are some facts, that are unconditionally true. These are actually statements, that we have to consider as true.
Following are some guidelines to write facts −
Names of properties/relationships begin with lower case letters.
Names of properties/relationships begin with lower case letters.
The relationship name appears as the first term.
The relationship name appears as the first term.
Objects appear as comma-separated arguments within parentheses.
Objects appear as comma-separated arguments within parentheses.
A period "." must end a fact.
A period "." must end a fact.
Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’).
Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’).
phoneno(agnibha, 1122334455). is also called a predicate or clause.
phoneno(agnibha, 1122334455). is also called a predicate or clause.
The syntax for facts is as follows −
relation(object1,object2...).
Following is an example of the above concept −
cat(tom).
loves_to_eat(kunal,pasta).
of_color(hair,black).
loves_to_play_games(nawaz).
lazy(pratyusha).
We can define rule as an implicit relationship between objects. So facts are conditionally true. So when one associated condition is true, then the predicate is also true. Suppose we have some rules as given below −
Lili is happy if she dances.
Lili is happy if she dances.
Tom is hungry if he is searching for food.
Tom is hungry if he is searching for food.
Jack and Bili are friends if both of them love to play cricket.
Jack and Bili are friends if both of them love to play cricket.
will go to play if school is closed, and he is free.
will go to play if school is closed, and he is free.
So these are some rules that are conditionally true, so when the right hand side is true, then the left hand side is also true.
Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol, the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,) which is known as conjunction, and we can also use semicolon, that is known as disjunction.
rule_name(object1, object2, ...) :- fact/rule(object1,
object2, ...)
Suppose a clause is like :
P :- Q;R.
This can also be written as
P :- Q.
P :- R.
If one clause is like :
P :- Q,R;S,T,U.
Is understood as
P :- (Q,R);(S,T,U).
Or can also be written as:
P :- Q,R.
P :- S,T,U.
happy(lili) :- dances(lili).
hungry(tom) :- search_for_food(tom).
friends(jack, bili) :- lovesCricket(jack), lovesCricket(bili).
goToPlay(ryan) :- isClosed(school), free(ryan).
Queries are some questions on the relationships between objects and object properties. So question can be anything, as given below −
Is tom a cat?
Is tom a cat?
Does Kunal love to eat pasta?
Does Kunal love to eat pasta?
Is Lili happy?
Is Lili happy?
Will Ryan go to play?
Will Ryan go to play?
So according to these queries, Logic programming language can find the answer and return them.
In this section, we will see what knowledge base in logic programming is.
Well, as we know there are three main components in logic programming − Facts, Rules and Queries. Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we can say that the knowledge base is a collection of facts and rules.
Now, we will see how to write some knowledge bases. Suppose we have our very first knowledge base called KB1. Here in the KB1, we have some facts. The facts are used to state things, that are unconditionally true of the domain of interest.
Suppose we have some knowledge, that Priya, Tiyasha, and Jaya are three girls, among them, Priya can cook. Let’s try to write these facts in a more generic way as shown below −
girl(priya).
girl(tiyasha).
girl(jaya).
can_cook(priya).
Note − Here we have written the name in lowercase letters, because in Prolog, a string starting with uppercase letter indicates a variable.
Now we can use this knowledge base by posing some queries. “Is priya a girl?”, it will reply “yes”, “is jamini a girl?” then it will answer “No”, because it does not know who jamini is. Our next question is “Can Priya cook?”, it will say “yes”, but if we ask the same question for Jaya, it will say “No”.
GNU Prolog 1.4.5 (64 bits)
Compiled Jul 14 2018, 13:19:42 with x86_64-w64-mingw32-gcc
By Daniel Diaz
Copyright (C) 1999-2018 Daniel Diaz
| ?- change_directory('D:/TP Prolog/Sample_Codes').
yes
| ?- [kb1]
.
compiling D:/TP Prolog/Sample_Codes/kb1.pl for byte code...
D:/TP Prolog/Sample_Codes/kb1.pl compiled, 3 lines read - 489 bytes written, 10 ms
yes
| ?- girl(priya)
.
yes
| ?- girl(jamini).
no
| ?- can_cook(priya).
yes
| ?- can_cook(jaya).
no
| ?-
Let us see another knowledge base, where we have some rules. Rules contain some information that are conditionally true about the domain of interest. Suppose our knowledge base is as follows −
sing_a_song(ananya).
listens_to_music(rohit).
listens_to_music(ananya) :- sing_a_song(ananya).
happy(ananya) :- sing_a_song(ananya).
happy(rohit) :- listens_to_music(rohit).
playes_guitar(rohit) :- listens_to_music(rohit).
So there are some facts and rules given above. The first two are facts, but the rest are rules. As we know that Ananya sings a song, this implies she also listens to music. So if we ask “Does Ananya listen to music?”, the answer will be true. Similarly, “is Rohit happy?”, this will also be true because he listens to music. But if our question is “does Ananya play guitar?”, then according to the knowledge base, it will say “No”. So these are some examples of queries based on this Knowledge base.
| ?- [kb2].
compiling D:/TP Prolog/Sample_Codes/kb2.pl for byte code...
D:/TP Prolog/Sample_Codes/kb2.pl compiled, 6 lines read - 1066 bytes written, 15 ms
yes
| ?- happy(rohit).
yes
| ?- sing_a_song(rohit).
no
| ?- sing_a_song(ananya).
yes
| ?- playes_guitar(rohit).
yes
| ?- playes_guitar(ananya).
no
| ?- listens_to_music(ananya).
yes
| ?-
The facts and rules of Knowledge Base 3 are as follows −
can_cook(priya).
can_cook(jaya).
can_cook(tiyasha).
likes(priya,jaya) :- can_cook(jaya).
likes(priya,tiyasha) :- can_cook(tiyasha).
Suppose we want to see the members who can cook, we can use one variable in our query. The variables should start with uppercase letters. In the result, it will show one by one. If we press enter, then it will come out, otherwise if we press semicolon (;), then it will show the next result.
Let us see one practical demonstration output to understand how it works.
| ?- [kb3].
compiling D:/TP Prolog/Sample_Codes/kb3.pl for byte code...
D:/TP Prolog/Sample_Codes/kb3.pl compiled, 5 lines read - 737 bytes written, 22 ms
warning: D:/TP Prolog/Sample_Codes/kb3.pl:1: redefining procedure can_cook/1
D:/TP Prolog/Sample_Codes/kb1.pl:4: previous definition
yes
| ?- can_cook(X).
X = priya ? ;
X = jaya ? ;
X = tiyasha
yes
| ?- likes(priya,X).
X = jaya ? ;
X = tiyasha
yes
| ?-
Relationship is one of the main features that we have to properly mention in Prolog. These relationships can be expressed as facts and rules. After that we will see about the family relationships, how we can express family based relationships in Prolog, and also see the recursive relationships of the family.
We will create the knowledge base by creating facts and rules, and play query on them.
In Prolog programs, it specifies relationship between objects and properties of the objects.
Suppose, there’s a statement, “Amit has a bike”, then we are actually declaring the ownership relationship between two objects — one is Amit and the other is bike.
If we ask a question, “Does Amit own a bike?”, we are actually trying to find out about one relationship.
There are various kinds of relationships, of which some can be rules as well. A rule can find out about a relationship even if the relationship is not defined explicitly as a fact.
We can define a brother relationship as follows −
Two person are brothers, if,
They both are male.
They both are male.
They have the same parent.
They have the same parent.
Now consider we have the below phrases −
parent(sudip, piyus).
parent(sudip, piyus).
parent(sudip, raj).
parent(sudip, raj).
male(piyus).
male(piyus).
male(raj).
male(raj).
brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)
brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)
These clauses can give us the answer that piyus and raj are brothers, but we will get three pairs of output here. They are: (piyus, piyus), (piyus, raj), (raj, raj). For these pairs, given conditions are true, but for the pairs (piyus, piyus), (raj, raj), they are not actually brothers, they are the same persons. So we have to create the clauses properly to form a relationship.
The revised relationship can be as follows −
A and B are brothers if −
A and B, both are male
A and B, both are male
They have same father
They have same father
They have same mother
They have same mother
A and B are not same
A and B are not same
Here we will see the family relationship. This is an example of complex relationship that can be formed using Prolog. We want to make a family tree, and that will be mapped into facts and rules, then we can run some queries on them.
Suppose the family tree is as follows −
Here from this tree, we can understand that there are few relationships. Here bob is a child of pam and tom, and bob also has two children — ann and pat. Bob has one brother liz, whose parent is also tom. So we want to make predicates as follows −
parent(pam, bob).
parent(pam, bob).
parent(tom, bob).
parent(tom, bob).
parent(tom, liz).
parent(tom, liz).
parent(bob, ann).
parent(bob, ann).
parent(bob, pat).
parent(bob, pat).
parent(pat, jim).
parent(pat, jim).
parent(bob, peter).
parent(bob, peter).
parent(peter, jim).
parent(peter, jim).
From our example, it has helped to illustrate some important points −
We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree.
We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree.
The user can easily query the Prolog system about relations defined in the program.
The user can easily query the Prolog system about relations defined in the program.
A Prolog program consists of clauses terminated by a full stop.
A Prolog program consists of clauses terminated by a full stop.
The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables.
The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables.
Questions to the system consist of one or more goals.
Questions to the system consist of one or more goals.
Some facts can be written in two different ways, like sex of family members can be written in either of the forms −
female(pam).
female(pam).
male(tom).
male(tom).
male(bob).
male(bob).
female(liz).
female(liz).
female(pat).
female(pat).
female(ann).
female(ann).
male(jim).
male(jim).
Or in the below form −
sex( pam, feminine).
sex( pam, feminine).
sex( tom, masculine).
sex( tom, masculine).
sex( bob, masculine).
sex( bob, masculine).
... and so on.
... and so on.
Now if we want to make mother and sister relationship, then we can write as given below −
In Prolog syntax, we can write −
mother(X,Y) :- parent(X,Y), female(X).
mother(X,Y) :- parent(X,Y), female(X).
sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \== Y.
sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \== Y.
Now let us see the practical demonstration −
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
haschild(X):- parent(X,_).
sister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
| ?- [family].
compiling D:/TP Prolog/Sample_Codes/family.pl for byte code...
D:/TP Prolog/Sample_Codes/family.pl compiled, 23 lines read - 3088 bytes written, 9 ms
yes
| ?- parent(X,jim).
X = pat ? ;
X = peter
yes
| ?-
mother(X,Y).
X = pam
Y = bob ? ;
X = pat
Y = jim ? ;
no
| ?- haschild(X).
X = pam ? ;
X = tom ? ;
X = tom ? ;
X = bob ? ;
X = bob ? ;
X = pat ? ;
X = bob ? ;
X = peter
yes
| ?- sister(X,Y).
X = liz
Y = bob ? ;
X = ann
Y = pat ? ;
X = ann
Y = peter ? ;
X = pat
Y = ann ? ;
X = pat
Y = peter ? ;
(16 ms) no
| ?-
Now let us see some more relationships that we can make from the previous relationships of a family. So if we want to make a grandparent relationship, that can be formed as follows −
We can also create some other relationships like wife, uncle, etc. We can write the relationships as given below −
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
grandmother(X,Z) :- mother(X,Y), parent(Y,Z).
grandmother(X,Z) :- mother(X,Y), parent(Y,Z).
grandfather(X,Z) :- father(X,Y), parent(Y,Z).
grandfather(X,Z) :- father(X,Y), parent(Y,Z).
wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y).
wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y).
uncle(X,Z) :- brother(X,Y), parent(Y,Z).
uncle(X,Z) :- brother(X,Y), parent(Y,Z).
So let us write a prolog program to see this in action. Here we will also see the trace to trace-out the execution.
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):-parent(X,Y),male(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
grandparent(X,Y):-parent(X,Z),parent(Z,Y).
grandmother(X,Z):-mother(X,Y),parent(Y,Z).
grandfather(X,Z):-father(X,Y),parent(Y,Z).
wife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y).
uncle(X,Z):-brother(X,Y),parent(Y,Z).
| ?- [family_ext].
compiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...
D:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms
| ?- uncle(X,Y).
X = peter
Y = jim ? ;
no
| ?- grandparent(X,Y).
X = pam
Y = ann ? ;
X = pam
Y = pat ? ;
X = pam
Y = peter ? ;
X = tom
Y = ann ? ;
X = tom
Y = pat ? ;
X = tom
Y = peter ? ;
X = bob
Y = jim ? ;
X = bob
Y = jim ? ;
no
| ?- wife(X,Y).
X = pam
Y = tom ? ;
X = pat
Y = peter ? ;
(15 ms) no
| ?-
In Prolog we can trace the execution. To trace the output, you have to enter into the trace mode by typing “trace.”. Then from the output we can see that we are just tracing “pam is mother of whom?”. See the tracing output by taking X = pam, and Y as variable, there Y will be bob as answer. To come out from the tracing mode press “notrace.”
| ?- [family_ext].
compiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...
D:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms
(16 ms) yes
| ?- mother(X,Y).
X = pam
Y = bob ? ;
X = pat
Y = jim ? ;
no
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- mother(pam,Y).
1 1 Call: mother(pam,_23) ?
2 2 Call: parent(pam,_23) ?
2 2 Exit: parent(pam,bob) ?
3 2 Call: female(pam) ?
3 2 Exit: female(pam) ?
1 1 Exit: mother(pam,bob) ?
Y = bob
(16 ms) yes
{trace}
| ?- notrace.
The debugger is switched off
yes
| ?-
In the previous section, we have seen that we can define some family relationships. These relationships are static in nature. We can also create some recursive relationships which can be expressed from the following illustration −
So we can understand that predecessor relationship is recursive. We can express this relationship using the following syntax −
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
Now let us see the practical demonstration.
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
| ?- [family_rec].
compiling D:/TP Prolog/Sample_Codes/family_rec.pl for byte code...
D:/TP Prolog/Sample_Codes/family_rec.pl compiled, 21 lines read - 1851 bytes written, 14 ms
yes
| ?- predecessor(peter,X).
X = jim ? ;
no
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- predecessor(bob,X).
1 1 Call: predecessor(bob,_23) ?
2 2 Call: parent(bob,_23) ?
2 2 Exit: parent(bob,ann) ?
1 1 Exit: predecessor(bob,ann) ?
X = ann ? ;
1 1 Redo: predecessor(bob,ann) ?
2 2 Redo: parent(bob,ann) ?
2 2 Exit: parent(bob,pat) ?
1 1 Exit: predecessor(bob,pat) ?
X = pat ? ;
1 1 Redo: predecessor(bob,pat) ?
2 2 Redo: parent(bob,pat) ?
2 2 Exit: parent(bob,peter) ?
1 1 Exit: predecessor(bob,peter) ?
X = peter ? ;
1 1 Redo: predecessor(bob,peter) ?
2 2 Call: parent(bob,_92) ?
2 2 Exit: parent(bob,ann) ?
3 2 Call: predecessor(ann,_23) ?
4 3 Call: parent(ann,_23) ?
4 3 Fail: parent(ann,_23) ?
4 3 Call: parent(ann,_141) ?
4 3 Fail: parent(ann,_129) ?
3 2 Fail: predecessor(ann,_23) ?
2 2 Redo: parent(bob,ann) ?
2 2 Exit: parent(bob,pat) ?
3 2 Call: predecessor(pat,_23) ?
4 3 Call: parent(pat,_23) ?
4 3 Exit: parent(pat,jim) ?
3 2 Exit: predecessor(pat,jim) ?
1 1 Exit: predecessor(bob,jim) ?
X = jim ? ;
1 1 Redo: predecessor(bob,jim) ?
3 2 Redo: predecessor(pat,jim) ?
4 3 Call: parent(pat,_141) ?
4 3 Exit: parent(pat,jim) ?
5 3 Call: predecessor(jim,_23) ?
6 4 Call: parent(jim,_23) ?
6 4 Fail: parent(jim,_23) ?
6 4 Call: parent(jim,_190) ?
6 4 Fail: parent(jim,_178) ?
5 3 Fail: predecessor(jim,_23) ?
3 2 Fail: predecessor(pat,_23) ?
2 2 Redo: parent(bob,pat) ?
2 2 Exit: parent(bob,peter) ?
3 2 Call: predecessor(peter,_23) ?
4 3 Call: parent(peter,_23) ?
4 3 Exit: parent(peter,jim) ?
3 2 Exit: predecessor(peter,jim) ?
1 1 Exit: predecessor(bob,jim) ?
X = jim ?
(78 ms) yes
{trace}
| ?-
In this chapter, we will learn data objects in Prolog. They can be divided into few different categories as shown below −
Below are some examples of different kinds of data objects −
Atoms − tom, pat, x100, x_45
Atoms − tom, pat, x100, x_45
Numbers − 100, 1235, 2000.45
Numbers − 100, 1235, 2000.45
Variables − X, Y, Xval, _X
Variables − X, Y, Xval, _X
Structures − day(9, jun, 2017), point(10, 25)
Structures − day(9, jun, 2017), point(10, 25)
In this section, we will discuss the atoms, numbers and the variables of Prolog.
Atoms are one variation of constants. They can be any names or objects. There are few rules that should be followed when we are trying to use Atoms as given below −
Strings of letters, digits and the underscore character, ‘_', starting with a lower-case letter. For example −
azahar
azahar
b59
b59
b_59
b_59
b_59AB
b_59AB
b_x25
b_x25
antara_sarkar
antara_sarkar
We have to keep in mind that when using atoms of this form, some care is necessary as some strings of special characters already have a predefined meaning; for example ':-'.
<--->
<--->
=======>
=======>
...
...
.:.
.:.
::=
::=
This is useful if we want to have an atom that starts with a capital letter. By enclosing it in quotes, we make it distinguishable from variables −
‘Rubai'
‘Rubai'
‘Arindam_Chatterjee'
‘Arindam_Chatterjee'
‘Sumit Mitra'
‘Sumit Mitra'
Another variation of constants is the Numbers. So integer numbers can be represented as 100, 4, -81, 1202. In Prolog, the normal range of integers is from -16383 to 16383.
Prolog also supports real numbers, but normally the use-case of floating point number is very less in Prolog programs, because Prolog is for symbolic, non-numeric computation. The treatment of real numbers depends on the implementation of Prolog. Example of real numbers are 3.14159, -0.00062, 450.18, etc.
The variables come under the Simple Objects section. Variables can be used in many such cases in our Prolog program, that we have seen earlier. So there are some rules of defining variables in Prolog.
We can define Prolog variables, such that variables are strings of letters, digits and underscore characters. They start with an upper-case letter or an underscore character. Some examples of Variables are −
X
X
Sum
Sum
Memer_name
Memer_name
Student_list
Student_list
Shoppinglist
Shoppinglist
_a50
_a50
_15
_15
Anonymous variables have no names. The anonymous variables in prolog is written by a single underscore character ‘_’. And one important thing is that each individual anonymous variable is treated as different. They are not same.
Now the question is, where should we use these anonymous variables?
Suppose in our knowledge base we have some facts — “jim hates tom”, “pat hates bob”. So if tom wants to find out who hates him, then he can use variables. However, if he wants to check whether there is someone who hates him, we can use anonymous variables. So when we want to use the variable, but do not want to reveal the value of the variable, then we can use anonymous variables.
So let us see its practical implementation −
hates(jim,tom).
hates(pat,bob).
hates(dog,fox).
hates(peter,tom).
| ?- [var_anonymous].
compiling D:/TP Prolog/Sample_Codes/var_anonymous.pl for byte code...
D:/TP Prolog/Sample_Codes/var_anonymous.pl compiled, 3 lines read - 536 bytes written, 16 ms
yes
| ?- hates(X,tom).
X = jim ? ;
X = peter
yes
| ?- hates(_,tom).
true ? ;
(16 ms) yes
| ?- hates(_,pat).
no
| ?- hates(_,fox).
true ? ;
no
| ?-
In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators.
We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators.
Comparison operators are used to compare two equations or states. Following are different comparison operators −
You can see that the ‘=<’ operator, ‘=:=’ operator and ‘=\=’ operators are syntactically different from other languages. Let us see some practical demonstration to this.
| ?- 1+2=:=2+1.
yes
| ?- 1+2=2+1.
no
| ?- 1+A=B+2.
A = 2
B = 1
yes
| ?- 5<10.
yes
| ?- 5>10.
no
| ?- 10=\=100.
yes
Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern.
Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows −
Let us see one practical code to understand the usage of these operators.
calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl,
Y is 400 - 150,write('400 - 150 is '),write(Y),nl,
Z is 10 * 300,write('10 * 300 is '),write(Z),nl,
A is 100 / 30,write('100 / 30 is '),write(A),nl,
B is 100 // 30,write('100 // 30 is '),write(B),nl,
C is 100 ** 2,write('100 ** 2 is '),write(C),nl,
D is 100 mod 30,write('100 mod 30 is '),write(D),nl.
Note − The nl is used to create new line.
| ?- change_directory('D:/TP Prolog/Sample_Codes').
yes
| ?- [op_arith].
compiling D:/TP Prolog/Sample_Codes/op_arith.pl for byte code...
D:/TP Prolog/Sample_Codes/op_arith.pl compiled, 6 lines read - 2390 bytes written, 11 ms
yes
| ?- calc.
100 + 200 is 300
400 - 150 is 250
10 * 300 is 3000
100 / 30 is 3.3333333333333335
100 // 30 is 3
100 ** 2 is 10000.0
100 mod 30 is 10
yes
| ?-
In this chapter, we will discuss loops and decision making in Prolog.
Loop statements are used to execute the code block multiple times. In general, for, while, do-while are loop constructs in programming languages (like Java, C, C++).
Code block is executed multiple times using recursive predicate logic. There are no direct loops in some other languages, but we can simulate loops with few different techniques.
count_to_10(10) :- write(10),nl.
count_to_10(X) :-
write(X),nl,
Y is X + 1,
count_to_10(Y).
| ?- [loop].
compiling D:/TP Prolog/Sample_Codes/loop.pl for byte code...
D:/TP Prolog/Sample_Codes/loop.pl compiled, 4 lines read - 751 bytes written, 16 ms
(16 ms) yes
| ?- count_to_10(3).
3
4
5
6
7
8
9
10
true ?
yes
| ?-
Now create a loop that takes lowest and highest values. So, we can use the between() to simulate loops.
Let us see an example program −
count_down(L, H) :-
between(L, H, Y),
Z is H - Y,
write(Z), nl.
count_up(L, H) :-
between(L, H, Y),
Z is L + Y,
write(Z), nl.
| ?- [loop].
compiling D:/TP Prolog/Sample_Codes/loop.pl for byte code...
D:/TP Prolog/Sample_Codes/loop.pl compiled, 14 lines read - 1700 bytes written, 16 ms
yes
| ?- count_down(12,17).
5
true ? ;
4
true ? ;
3
true ? ;
2
true ? ;
1
true ? ;
0
yes
| ?- count_up(5,12).
10
true ? ;
11
true ? ;
12
true ? ;
13
true ? ;
14
true ? ;
15
true ? ;
16
true ? ;
17
yes
| ?-
The decision statements are If-Then-Else statements. So when we try to match some condition, and perform some task, then we use the decision making statements. The basic usage is as follows −
If <condition> is true, Then <do this>, Else
In some different programming languages, there are If-Else statements, but in Prolog we have to define our statements in some other manner. Following is an example of decision making in Prolog.
% If-Then-Else statement
gt(X,Y) :- X >= Y,write('X is greater or equal').
gt(X,Y) :- X < Y,write('X is smaller').
% If-Elif-Else statement
gte(X,Y) :- X > Y,write('X is greater').
gte(X,Y) :- X =:= Y,write('X and Y are same').
gte(X,Y) :- X < Y,write('X is smaller').
| ?- [test].
compiling D:/TP Prolog/Sample_Codes/test.pl for byte code...
D:/TP Prolog/Sample_Codes/test.pl compiled, 3 lines read - 529 bytes written, 15 ms
yes
| ?- gt(10,100).
X is smaller
yes
| ?- gt(150,100).
X is greater or equal
true ?
yes
| ?- gte(10,20).
X is smaller
(15 ms) yes
| ?- gte(100,20).
X is greater
true ?
yes
| ?- gte(100,100).
X and Y are same
true ?
yes
| ?-
In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax.
Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male.
Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true.
parent(jhon,bob).
parent(lili,bob).
male(jhon).
female(lili).
% Conjunction Logic
father(X,Y) :- parent(X,Y),male(X).
mother(X,Y) :- parent(X,Y),female(X).
% Disjunction Logic
child_of(X,Y) :- father(X,Y);mother(X,Y).
| ?- [conj_disj].
compiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code...
D:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read - 1513 bytes written, 24 ms
yes
| ?- father(jhon,bob).
yes
| ?- child_of(jhon,bob).
true ?
yes
| ?- child_of(lili,bob).
yes
| ?-
In this chapter, we will discuss one of the important concepts in Prolog, The Lists. It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection.
In the subsequent sections, we will discuss the following topics −
Representation of lists in Prolog
Representation of lists in Prolog
Basic operations on prolog such as Insert, delete, update, append.
Basic operations on prolog such as Insert, delete, update, append.
Repositioning operators such as permutation, combination, etc.
Repositioning operators such as permutation, combination, etc.
Set operations like set union, set intersection, etc.
Set operations like set union, set intersection, etc.
The list is a simple data structure that is widely used in non-numeric programming. List consists of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with square brackets.
A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom, []. In the second case, the list consists of two things as given below −
The first item, called the head of the list;
The first item, called the head of the list;
The remaining part of the list, called the tail.
The remaining part of the list, called the tail.
Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green, blue, white, dark]. So the tail is another list.
Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.
So the following list representations are also valid −
[a, b, c] = [x | [b, c] ]
[a, b, c] = [x | [b, c] ]
[a, b, c] = [a, b | [c] ]
[a, b, c] = [a, b | [c] ]
[a, b, c] = [a, b, c | [ ] ]
[a, b, c] = [a, b, c | [ ] ]
For these properties we can define the list as −
A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has to be a list.
Following table contains various operations on prolog lists −
During this operation, we can check whether a member X is present in list L or not? So how to check this? Well, we have to define one predicate to do so. Suppose the predicate name is list_member(X,L). The goal of this predicate is to check whether X is present in L or not.
To design this predicate, we can follow these observations. X is a member of L if either −
X is head of L, or
X is head of L, or
X is a member of the tail of L
X is a member of the tail of L
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 1 lines read - 467 bytes written, 13 ms
yes
| ?- list_member(b,[a,b,c]).
true ?
yes
| ?- list_member(b,[a,[b,c]]).
no
| ?- list_member([b,c],[a,[b,c]]).
true ?
yes
| ?- list_member(d,[a,b,c]).
no
| ?- list_member(d,[a,b,c]).
This is used to find the length of list L. We will define one predicate to do this task. Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This will count the elements in a list L and instantiate N to their number. As was the case with our previous relations involving lists, it is useful to consider two cases −
If list is empty, then length is 0.
If list is empty, then length is 0.
If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.
If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.
list_length([],0).
list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1.
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 4 lines read - 985 bytes written, 23 ms
yes
| ?- list_length([a,b,c,d,e,f,g,h,i,j],Len).
Len = 10
yes
| ?- list_length([],Len).
Len = 0
yes
| ?- list_length([[a,b],[c,d],[e,f]],Len).
Len = 3
yes
| ?-
Concatenation of two lists means adding the list items of the second list after the first one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this task we will create one predicate called list_concat(), that will take first list L1, second list L2, and the L3 as resultant list. There are two observations here.
If the first list is empty, and second list is L, then the resultant list will be L.
If the first list is empty, and second list is L, then the resultant list will be L.
If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List].
If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List].
list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 7 lines read - 1367 bytes written, 19 ms
yes
| ?- list_concat([1,2],[a,b,c],NewList).
NewList = [1,2,a,b,c]
yes
| ?- list_concat([],[a,b,c],NewList).
NewList = [a,b,c]
yes
| ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList).
NewList = [[1,2,3],[p,q,r],a,b,c]
yes
| ?-
Suppose we have a list L and an element X, we have to delete X from L. So there are three cases −
If X is the only element, then after deleting it, it will return empty list.
If X is the only element, then after deleting it, it will return empty list.
If X is head of L, the resultant list will be the Tail part.
If X is head of L, the resultant list will be the Tail part.
If X is present in the Tail part, then delete from there recursively.
If X is present in the Tail part, then delete from there recursively.
list_delete(X, [X], []).
list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 11 lines read - 1923 bytes written, 25 ms
yes
| ?- list_delete(a,[a,e,i,o,u],NewList).
NewList = [e,i,o,u] ?
yes
| ?- list_delete(a,[a],NewList).
NewList = [] ?
yes
| ?- list_delete(X,[a,e,i,o,u],[a,e,o,u]).
X = i ? ;
no
| ?-
Appending two lists means adding two lists together, or adding one list as an item. Now if the item is present in the list, then the append function will not work. So we will create one predicate namely, list_append(L1, L2, L3). The following are some observations −
Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already.
Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already.
Otherwise new list will be L2 = [A|L1].
Otherwise new list will be L2 = [A|L1].
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).
In this case, we have used (!) symbol, that is known as cut. So when the first line is executed successfully, then we cut it, so it will not execute the next operation.
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 14 lines read - 2334 bytes written, 25 ms
(16 ms) yes
| ?- list_append(a,[e,i,o,u],NewList).
NewList = [a,e,i,o,u]
yes
| ?- list_append(e,[e,i,o,u],NewList).
NewList = [e,i,o,u]
yes
| ?- list_append([a,b],[e,i,o,u],NewList).
NewList = [[a,b],e,i,o,u]
yes
| ?-
This method is used to insert an item X into list L, and the resultant list will be R. So the predicate will be in this form list_insert(X, L, R). So this can insert X into L in all possible positions. If we see closer, then there are some observations.
If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make new list L.
If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make new list L.
list_delete(X, [X], []).
list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
list_insert(X,L,R) :- list_delete(X,R,L).
| ?- [list_basics].
compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 16 lines read - 2558 bytes written, 22 ms
(16 ms) yes
| ?- list_insert(a,[e,i,o,u],NewList).
NewList = [a,e,i,o,u] ? a
NewList = [e,a,i,o,u]
NewList = [e,i,a,o,u]
NewList = [e,i,o,a,u]
NewList = [e,i,o,u,a]
NewList = [e,i,o,u,a]
(15 ms) no
| ?-
Following are repositioning operations −
This operation will change the list item positions and generate all possible outcomes. So we will create one predicate as list_perm(L1,L2), This will generate all permutation of L1, and store them into L2. To do this we need list_delete() clause to help.
To design this predicate, we can follow few observations as given below −
X is member of L if either −
If the first list is empty, then the second list must also be empty.
If the first list is empty, then the second list must also be empty.
If the first list is not empty then it has the form [X | L], and a permutation of such a list can be constructed as, first permute L obtaining L1 and then insert X at any position into L1.
If the first list is not empty then it has the form [X | L], and a permutation of such a list can be constructed as, first permute L obtaining L1 and then insert X at any position into L1.
list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
list_perm([],[]).
list_perm(L,[X|P]) :- list_delete(X,L,L1),list_perm(L1,P).
| ?- [list_repos].
compiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...
D:/TP Prolog/Sample_Codes/list_repos.pl compiled, 4 lines read - 1060 bytes written, 17 ms
(15 ms) yes
| ?- list_perm([a,b,c,d],X).
X = [a,b,c,d] ? a
X = [a,b,d,c]
X = [a,c,b,d]
X = [a,c,d,b]
X = [a,d,b,c]
X = [a,d,c,b]
X = [b,a,c,d]
X = [b,a,d,c]
X = [b,c,a,d]
X = [b,c,d,a]
X = [b,d,a,c]
X = [b,d,c,a]
X = [c,a,b,d]
X = [c,a,d,b]
X = [c,b,a,d]
X = [c,b,d,a]
X = [c,d,a,b]
X = [c,d,b,a]
X = [d,a,b,c]
X = [d,a,c,b]
X = [d,b,a,c]
X = [d,b,c,a]
X = [d,c,a,b]
X = [d,c,b,a]
(31 ms) no
| ?-
Suppose we have a list L = [a,b,c,d,e], and we want to reverse the elements, so the output will be [e,d,c,b,a]. To do this, we will create a clause, list_reverse(List, ReversedList). Following are some observations −
If the list is empty, then the resultant list will also be empty.
If the list is empty, then the resultant list will also be empty.
Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head.
Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head.
Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head.
Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head.
list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).
list_rev([],[]).
list_rev([Head|Tail],Reversed) :-
list_rev(Tail, RevTail),list_concat(RevTail, [Head],Reversed).
| ?- [list_repos].
compiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...
D:/TP Prolog/Sample_Codes/list_repos.pl compiled, 10 lines read - 1977 bytes written, 19 ms
yes
| ?- list_rev([a,b,c,d,e],NewList).
NewList = [e,d,c,b,a]
yes
| ?- list_rev([a,b,c,d,e],[e,d,c,b,a]).
yes
| ?-
Using Shift operation, we can shift one element of a list to the left rotationally. So if the list items are [a,b,c,d], then after shifting, it will be [b,c,d,a]. So we will make a clause list_shift(L1, L2).
We will express the list as [Head|Tail], then recursively concatenate Head after the Tail, so as a result we can feel that the elements are shifted.
We will express the list as [Head|Tail], then recursively concatenate Head after the Tail, so as a result we can feel that the elements are shifted.
This can also be used to check whether the two lists are shifted at one position or not.
This can also be used to check whether the two lists are shifted at one position or not.
list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).
list_shift([Head|Tail],Shifted) :- list_concat(Tail, [Head],Shifted).
| ?- [list_repos].
compiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...
D:/TP Prolog/Sample_Codes/list_repos.pl compiled, 12 lines read - 2287 bytes written, 10 ms
yes
| ?- list_shift([a,b,c,d,e],L2).
L2 = [b,c,d,e,a]
(16 ms) yes
| ?- list_shift([a,b,c,d,e],[b,c,d,e,a]).
yes
| ?-
Here we will define a predicate list_order(L) which checks whether L is ordered or not. So if L = [1,2,3,4,5,6], then the result will be true.
If there is only one element, that is already ordered.
If there is only one element, that is already ordered.
Otherwise take first two elements X and Y as Head, and rest as Tail. If X =< Y, then call the clause again with the parameter [Y|Tail], so this will recursively check from the next element.
Otherwise take first two elements X and Y as Head, and rest as Tail. If X =< Y, then call the clause again with the parameter [Y|Tail], so this will recursively check from the next element.
list_order([X, Y | Tail]) :- X =< Y, list_order([Y|Tail]).
list_order([X]).
| ?- [list_repos].
compiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...
D:/TP Prolog/Sample_Codes/list_repos.pl:15: warning: singleton variables [X] for list_order/1
D:/TP Prolog/Sample_Codes/list_repos.pl compiled, 15 lines read - 2805 bytes written, 18 ms
yes
| ?- list_order([1,2,3,4,5,6,6,7,7,8]).
true ?
yes
| ?- list_order([1,4,2,3,6,5]).
no
| ?-
We will try to write a clause that will get all possible subsets of a given set. So if the set is [a,b], then the result will be [], [a], [b], [a,b]. To do so, we will create one clause, list_subset(L, X). It will take L and return each subsets into X. So we will proceed in the following way −
If list is empty, the subset is also empty.
If list is empty, the subset is also empty.
Find the subset recursively by retaining the Head, and
Find the subset recursively by retaining the Head, and
Make another recursive call where we will remove Head.
Make another recursive call where we will remove Head.
list_subset([],[]).
list_subset([Head|Tail],[Head|Subset]) :- list_subset(Tail,Subset).
list_subset([Head|Tail],Subset) :- list_subset(Tail,Subset).
| ?- [list_set].
compiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...
D:/TP Prolog/Sample_Codes/list_set.pl:3: warning: singleton variables [Head] for list_subset/2
D:/TP Prolog/Sample_Codes/list_set.pl compiled, 2 lines read - 653 bytes written, 7 ms
yes
| ?- list_subset([a,b],X).
X = [a,b] ? ;
X = [a] ? ;
X = [b] ? ;
X = []
(15 ms) yes
| ?- list_subset([x,y,z],X).
X = [x,y,z] ? a
X = [x,y]
X = [x,z]
X = [x]
X = [y,z]
X = [y]
X = [z]
X = []
yes
| ?-
Let us define a clause called list_union(L1,L2,L3), So this will take L1 and L2, and perform Union on them, and store the result into L3. As you know if two lists have the same element twice, then after union, there will be only one. So we need another helper clause to check the membership.
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_union([X|Y],Z,W) :- list_member(X,Z),list_union(Y,Z,W).
list_union([X|Y],Z,[X|W]) :- \+ list_member(X,Z), list_union(Y,Z,W).
list_union([],Z,Z).
Note − In the program, we have used (\+) operator, this operator is used for NOT.
| ?- [list_set].
compiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...
D:/TP Prolog/Sample_Codes/list_set.pl:6: warning: singleton variables [Head] for list_subset/2
D:/TP Prolog/Sample_Codes/list_set.pl compiled, 9 lines read - 2004 bytes written, 18 ms
yes
| ?- list_union([a,b,c,d,e],[a,e,i,o,u],L3).
L3 = [b,c,d,a,e,i,o,u] ?
(16 ms) yes
| ?- list_union([a,b,c,d,e],[1,2],L3).
L3 = [a,b,c,d,e,1,2]
yes
Let us define a clause called list_intersection(L1,L2,L3), So this will take L1 and L2, and perform Intersection operation, and store the result into L3. Intersection will return those elements that are present in both lists. So L1 = [a,b,c,d,e], L2 = [a,e,i,o,u], then L3 = [a,e]. Here, we will use the list_member() clause to check if one element is present in a list or not.
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_intersect([X|Y],Z,[X|W]) :-
list_member(X,Z), list_intersect(Y,Z,W).
list_intersect([X|Y],Z,W) :-
\+ list_member(X,Z), list_intersect(Y,Z,W).
list_intersect([],Z,[]).
| ?- [list_set].
compiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...
D:/TP Prolog/Sample_Codes/list_set.pl compiled, 13 lines read - 3054 bytes written, 9 ms
(15 ms) yes
| ?- list_intersect([a,b,c,d,e],[a,e,i,o,u],L3).
L3 = [a,e] ?
yes
| ?- list_intersect([a,b,c,d,e],[],L3).
L3 = []
yes
| ?-
Following are some miscellaneous operations that can be performed on lists −
In this example, we will see two operations using which we can check whether the list has odd number of elements or the even number of elements. We will define predicates namely, list_even_len(L) and list_odd_len(L).
If the list has no elements, then that is even length list.
If the list has no elements, then that is even length list.
Otherwise we take it as [Head|Tail], then if Tail is of odd length, then the total list is even length string.
Otherwise we take it as [Head|Tail], then if Tail is of odd length, then the total list is even length string.
Similarly, if the list has only one element, then that is odd length list.
Similarly, if the list has only one element, then that is odd length list.
By taking it as [Head|Tail] and Tail is even length string, then entire list is odd length list.
By taking it as [Head|Tail] and Tail is even length string, then entire list is odd length list.
list_even_len([]).
list_even_len([Head|Tail]) :- list_odd_len(Tail).
list_odd_len([_]).
list_odd_len([Head|Tail]) :- list_even_len(Tail).
| ?- [list_misc].
compiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl compiled, 4 lines read - 726 bytes written, 20 ms
yes
| ?- list_odd_len([a,2,b,3,c]).
true ?
yes
| ?- list_odd_len([a,2,b,3]).
no
| ?- list_even_len([a,2,b,3]).
true ?
yes
| ?- list_even_len([a,2,b,3,c]).
no
| ?-
This operation divides a list into two lists, and these lists are of approximately same length. So if the given list is [a,b,c,d,e], then the result will be [a,c,e],[b,d]. This will place all of the odd placed elements into one list, and all even placed elements into another list. We will define a predicate, list_divide(L1,L2,L3) to solve this task.
If given list is empty, then it will return empty lists.
If given list is empty, then it will return empty lists.
If there is only one element, then the first list will be a list with that element, and the second list will be empty.
If there is only one element, then the first list will be a list with that element, and the second list will be empty.
Suppose X,Y are two elements from head, and rest are Tail, So make two lists [X|List1], [Y|List2], these List1 and List2 are separated by dividing Tail.
Suppose X,Y are two elements from head, and rest are Tail, So make two lists [X|List1], [Y|List2], these List1 and List2 are separated by dividing Tail.
list_divide([],[],[]).
list_divide([X],[X],[]).
list_divide([X,Y|Tail], [X|List1],[Y|List2]) :-
list_divide(Tail,List1,List2).
| ?- [list_misc].
compiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl compiled, 8 lines read - 1432 bytes written, 8 ms
yes
| ?- list_divide([a,1,b,2,c,3,d,5,e],L1,L2).
L1 = [a,b,c,d,e]
L2 = [1,2,3,5] ?
yes
| ?- list_divide([a,b,c,d],L1,L2).
L1 = [a,c]
L2 = [b,d]
yes
| ?-
This operation is used to find the maximum element from a list. We will define a predicate, list_max_elem(List, Max), then this will find Max element from the list and return.
If there is only one element, then it will be the max element.
If there is only one element, then it will be the max element.
Divide the list as [X,Y|Tail]. Now recursively find max of [Y|Tail] and store it into MaxRest, and store maximum of X and MaxRest, then store it to Max.
Divide the list as [X,Y|Tail]. Now recursively find max of [Y|Tail] and store it into MaxRest, and store maximum of X and MaxRest, then store it to Max.
max_of_two(X,Y,X) :- X >= Y.
max_of_two(X,Y,Y) :- X < Y.
list_max_elem([X],X).
list_max_elem([X,Y|Rest],Max) :-
list_max_elem([Y|Rest],MaxRest),
max_of_two(X,MaxRest,Max).
| ?- [list_misc].
compiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl compiled, 16 lines read - 2385 bytes written, 16 ms
yes
| ?- list_max_elem([8,5,3,4,7,9,6,1],Max).
Max = 9 ?
yes
| ?- list_max_elem([5,12,69,112,48,4],Max).
Max = 112 ?
yes
| ?-
In this example, we will define a clause, list_sum(List, Sum), this will return the sum of the elements of the list.
If the list is empty, then sum will be 0.
If the list is empty, then sum will be 0.
Represent list as [Head|Tail], find sum of tail recursively and store them into SumTemp, then set Sum = Head + SumTemp.
Represent list as [Head|Tail], find sum of tail recursively and store them into SumTemp, then set Sum = Head + SumTemp.
list_sum([],0).
list_sum([Head|Tail], Sum) :-
list_sum(Tail,SumTemp),
Sum is Head + SumTemp.
yes
| ?- [list_misc].
compiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1
D:/TP Prolog/Sample_Codes/list_misc.pl compiled, 21 lines read - 2897 bytes written, 21 ms
(32 ms) yes
| ?- list_sum([5,12,69,112,48,4],Sum).
Sum = 250
yes
| ?- list_sum([8,5,3,4,7,9,6,1],Sum).
Sum = 43
yes
| ?-
If the list is [4,5,3,7,8,1,2], then the result will be [1,2,3,4,5,7,8]. The steps of performing merge sort are shown below −
Take the list and split them into two sub-lists. This split will be performed recursively.
Take the list and split them into two sub-lists. This split will be performed recursively.
Merge each split in sorted order.
Merge each split in sorted order.
Thus the entire list will be sorted.
Thus the entire list will be sorted.
We will define a predicate called mergesort(L, SL), it will take L and return result into SL.
mergesort([],[]). /* covers special case */
mergesort([A],[A]).
mergesort([A,B|R],S) :-
split([A,B|R],L1,L2),
mergesort(L1,S1),
mergesort(L2,S2),
merge(S1,S2,S).
split([],[],[]).
split([A],[A],[]).
split([A,B|R],[A|Ra],[B|Rb]) :-
split(R,Ra,Rb).
merge(A,[],A).
merge([],B,B).
merge([A|Ra],[B|Rb],[A|M]) :-
A =< B, merge(Ra,[B|Rb],M).
merge([A|Ra],[B|Rb],[B|M]) :-
A > B, merge([A|Ra],Rb,M).
| ?- [merge_sort].
compiling D:/TP Prolog/Sample_Codes/merge_sort.pl for byte code...
D:/TP Prolog/Sample_Codes/merge_sort.pl compiled, 17 lines read - 3048 bytes written, 19 ms
yes
| ?- mergesort([4,5,3,7,8,1,2],L).
L = [1,2,3,4,5,7,8] ?
yes
| ?- mergesort([8,5,3,4,7,9,6,1],L).
L = [1,3,4,5,6,7,8,9] ?
yes
| ?-
This chapter covers recursion and structures.
Recursion is a technique in which one predicate uses itself (may be with some other predicates) to find the truth value.
Let us understand this definition with the help of an example −
is_digesting(X,Y) :- just_ate(X,Y).
is_digesting(X,Y) :- just_ate(X,Y).
is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y).
is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y).
So this predicate is recursive in nature. Suppose we say that just_ate(deer, grass), it means is_digesting(deer, grass) is true. Now if we say is_digesting(tiger, grass), this will be true if is_digesting(tiger, grass) :- just_ate(tiger, deer), is_digesting(deer, grass), then the statement is_digesting(tiger, grass) is also true.
There may be some other examples also, so let us see one family example. So if we want to express the predecessor logic, that can be expressed using the following diagram −
So we can understand the predecessor relationship is recursive. We can express this relationship using the following syntax −
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
Structures are Data Objects that contain multiple components.
For example, the date can be viewed as a structure with three components — day, month and year. Then the date 9th April, 2020 can be written as: date(9, apr, 2020).
Note − Structure can in turn have another structure as a component in it.
So we can see views as tree structure and Prolog Functors.
Now let us see one example of structures in Prolog. We will define a structure of points, Segments and Triangle as structures.
To represent a point, a line segment and a triangle using structure in Prolog, we can consider following statements −
p1 − point(1, 1)
p1 − point(1, 1)
p2 − point(2,3)
p2 − point(2,3)
S − seg( Pl, P2): seg( point(1,1), point(2,3))
S − seg( Pl, P2): seg( point(1,1), point(2,3))
T − triangle( point(4,Z), point(6,4), point(7,1) )
T − triangle( point(4,Z), point(6,4), point(7,1) )
Note − Structures can be naturally pictured as trees. Prolog can be viewed as a language for processing trees.
Matching is used to check whether two given terms are same (identical) or the variables in both terms can have the same objects after being instantiated. Let us see one example.
Suppose date structure is defined as date(D,M,2020) = date(D1,apr, Y1), this indicates that D = D1, M = feb and Y1 = 2020.
Following rules are to be used to check whether two terms S and T match −
If S and T are constants, S=T if both are same objects.
If S and T are constants, S=T if both are same objects.
If S is a variable and T is anything, T=S.
If S is a variable and T is anything, T=S.
If T is variable and S is anything, S=T.
If T is variable and S is anything, S=T.
If S and T are structures, S=T if −
S and T have same functor.
All their corresponding arguments components have to match.
If S and T are structures, S=T if −
S and T have same functor.
S and T have same functor.
All their corresponding arguments components have to match.
All their corresponding arguments components have to match.
Following is the structure of binary tree using recursive structures −
The definition of the structure is as follows −
node(2, node(1,nil,nil), node(6, node(4,node(3,nil,nil), node(5,nil,nil)), node(7,nil,nil))
Each node has three fields, data and two nodes. One node with no child (leaf node) structure is written as node(value, nil, nil), node with only one left child is written as node(value, left_node, nil), node with only one right child is written as node(value, nil; right_node), and node with both child has node(value, left_node, right_node).
In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops.
Let us see how backtracking takes place using one tree like structure −
Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops.
Now we know, what is the backtracking in Prolog. Let us see one example,
Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop.
Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules −
boy(tom).
boy(bob).
girl(alice).
girl(lili).
pay(X,Y) :- boy(X), girl(Y).
Following is the illustration of the above scenario −
As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working.
| ?- [backtrack].
compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...
D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read - 703 bytes written, 22 ms
yes
| ?- pay(X,Y).
X = tom
Y = alice ?
(15 ms) yes
| ?- pay(X,Y).
X = tom
Y = alice ? ;
X = tom
Y = lili ? ;
X = bob
Y = alice ? ;
X = bob
Y = lili
yes
| ?- trace.
The debugger will first creep -- showing everything (trace)
(16 ms) yes
{trace}
| ?- pay(X,Y).
1 1 Call: pay(_23,_24) ?
2 2 Call: boy(_23) ?
2 2 Exit: boy(tom) ?
3 2 Call: girl(_24) ?
3 2 Exit: girl(alice) ?
1 1 Exit: pay(tom,alice) ?
X = tom
Y = alice ? ;
1 1 Redo: pay(tom,alice) ?
3 2 Redo: girl(alice) ?
3 2 Exit: girl(lili) ?
1 1 Exit: pay(tom,lili) ?
X = tom
Y = lili ? ;
1 1 Redo: pay(tom,lili) ?
2 2 Redo: boy(tom) ?
2 2 Exit: boy(bob) ?
3 2 Call: girl(_24) ?
3 2 Exit: girl(alice) ?
1 1 Exit: pay(bob,alice) ?
X = bob
Y = alice ? ;
1 1 Redo: pay(bob,alice) ?
3 2 Redo: girl(alice) ?
3 2 Exit: girl(lili) ?
1 1 Exit: pay(bob,lili) ?
X = bob
Y = lili
yes
{trace}
| ?-
So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog.
Suppose we have some rules as follows −
Rule 1 &minnus; if X < 3 then Y = 0
Rule 1 &minnus; if X < 3 then Y = 0
Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2
Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2
Rule 3 &minnus; if 6 <= X then Y = 4
Rule 3 &minnus; if 6 <= X then Y = 4
In Prolog syntax we can write,
f(X,0) :- X < 3. % Rule 1
f(X,0) :- X < 3. % Rule 1
f(X,2) :- 3 =< X, X < 6. % Rule 2
f(X,2) :- 3 =< X, X < 6. % Rule 2
f(X,4) :- 6 =< X. % Rule 3
f(X,4) :- 6 =< X. % Rule 3
Now if we ask for a question as f (1,Y), 2 < Y.
The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that −
The three rules are mutually exclusive and one of them at most will succeed.
The three rules are mutually exclusive and one of them at most will succeed.
As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail.
As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail.
So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows −
f (X,0) :- X < 3, !. % Rule 1
f (X,0) :- X < 3, !. % Rule 1
f (X,2) :- 3 =< X, X < 6, !. % Rule 2
f (X,2) :- 3 =< X, X < 6, !. % Rule 2
f (X,4) :- 6 =< X. % Rule 3
f (X,4) :- 6 =< X. % Rule 3
Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated.
Let us see this in below execution −
f(X,0) :- X < 3. % Rule 1
f(X,2) :- 3 =< X, X < 6. % Rule 2
f(X,4) :- 6 =< X. % Rule 3
| ?- [backtrack].
compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...
D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1224 bytes written, 17 ms
yes
| ?- f(1,Y), 2<Y.
no
| ?- trace
.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- f(1,Y), 2<Y.
1 1 Call: f(1,_23) ?
2 2 Call: 1<3 ?
2 2 Exit: 1<3 ?
1 1 Exit: f(1,0) ?
3 1 Call: 2<0 ?
3 1 Fail: 2<0 ?
1 1 Redo: f(1,0) ?
2 2 Call: 3=<1 ?
2 2 Fail: 3=<1 ?
2 2 Call: 6=<1 ?
2 2 Fail: 6=<1 ?
1 1 Fail: f(1,_23) ?
(46 ms) no
{trace}
| ?-
Let us see the same using cut.
f(X,0) :- X < 3,!. % Rule 1
f(X,2) :- 3 =< X, X < 6,!. % Rule 2
f(X,4) :- 6 =< X. % Rule 3
| ?- [backtrack].
1 1 Call: [backtrack] ?
compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...
D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1373 bytes written, 15 ms
1 1 Exit: [backtrack] ?
(16 ms) yes
{trace}
| ?- f(1,Y), 2<Y.
1 1 Call: f(1,_23) ?
2 2 Call: 1<3 ?
2 2 Exit: 1<3 ?
1 1 Exit: f(1,0) ?
3 1 Call: 2<0 ?
3 1 Fail: 2<0 ?
no
{trace}
| ?-
Here we will perform failure when condition does not satisfy. Suppose we have a statement, “Mary likes all animals but snakes”, we will express this in Prolog.
It would be very easy and straight forward, if the statement is “Mary likes all animals”. In that case we can write “Mary likes X if X is an animal”. And in prolog we can write this statement as, likes(mary, X) := animal(X).
Our actual statement can be expressed as −
If X is snake, then “Mary likes X” is not true
If X is snake, then “Mary likes X” is not true
Otherwise if X is an animal, then Mary likes X.
Otherwise if X is an animal, then Mary likes X.
In prolog we can write this as −
likes(mary,X) :- snake(X), !, fail.
likes(mary,X) :- snake(X), !, fail.
likes(mary, X) :- animal(X).
likes(mary, X) :- animal(X).
The ‘fail’ statement causes the failure. Now let us see how it works in Prolog.
animal(dog).
animal(cat).
animal(elephant).
animal(tiger).
animal(cobra).
animal(python).
snake(cobra).
snake(python).
likes(mary, X) :- snake(X), !, fail.
likes(mary, X) :- animal(X).
| ?- [negate_fail].
compiling D:/TP Prolog/Sample_Codes/negate_fail.pl for byte code...
D:/TP Prolog/Sample_Codes/negate_fail.pl compiled, 11 lines read - 1118 bytes written, 17 ms
yes
| ?- likes(mary,elephant).
yes
| ?- likes(mary,tiger).
yes
| ?- likes(mary,python).
no
| ?- likes(mary,cobra).
no
| ?- trace
.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- likes(mary,dog).
1 1 Call: likes(mary,dog) ?
2 2 Call: snake(dog) ?
2 2 Fail: snake(dog) ?
2 2 Call: animal(dog) ?
2 2 Exit: animal(dog) ?
1 1 Exit: likes(mary,dog) ?
yes
{trace}
| ?- likes(mary,python).
1 1 Call: likes(mary,python) ?
2 2 Call: snake(python) ?
2 2 Exit: snake(python) ?
3 2 Call: fail ?
3 2 Fail: fail ?
1 1 Fail: likes(mary,python) ?
no
{trace}
| ?-
Here we will define two predicates — different and not. The different predicate will check whether two given arguments are same or not. If they are same, it will return false, otherwise it will return true. The not predicate is used to negate some statement, which means, when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.
So the term ‘different’ can be expressed in three different ways as given below −
X and Y are not literally the same
X and Y are not literally the same
X and Y do not match
X and Y do not match
The values of arithmetic expression X and Y are not equal
The values of arithmetic expression X and Y are not equal
So in Prolog, we will try to express the statements as follows −
If X and Y match, then different(X,Y) fails,
If X and Y match, then different(X,Y) fails,
Otherwise different(X,Y) succeeds.
Otherwise different(X,Y) succeeds.
The respective prolog syntax will be as follows −
different(X, X) :- !, fail.
different(X, X) :- !, fail.
different(X, Y).
different(X, Y).
We can also express it using disjunctive clauses as given below −
different(X, Y) :- X = Y, !, fail ; true. % true is goal that always succeeds
different(X, Y) :- X = Y, !, fail ; true. % true is goal that always succeeds
Following example shows how this can be done in prolog −
different(X, X) :- !, fail.
different(X, Y).
| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl:2: warning: singleton variables [X,Y] for different/2
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 2 lines read - 327 bytes written, 11 ms
yes
| ?- different(100,200).
yes
| ?- different(100,100).
no
| ?- different(abc,def).
yes
| ?- different(abc,abc).
no
| ?-
Let us see a program using the disjunctive clauses −
different(X, Y) :- X = Y, !, fail ; true.
| ?- [diff_rel].
compiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 0 lines read - 556 bytes written, 17 ms
yes
| ?- different(100,200).
yes
| ?- different(100,100).
no
| ?- different(abc,def).
yes
| ?- different(abc,abc).
no
| ?-
The not relation is very much useful in different cases. In our traditional programming languages also, we use the logical not operation to negate some statement. So it means that when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true.
In prolog, we can define this as shown below −
not(P) :- P, !, fail ; true.
So if P is true, then cut and fail, this will return false, otherwise it will be true. Now let us see one simple code to understand this concept.
not(P) :- P, !, fail ; true.
| ?- [not_rel].
compiling D:/TP Prolog/Sample_Codes/not_rel.pl for byte code...
D:/TP Prolog/Sample_Codes/not_rel.pl compiled, 0 lines read - 630 bytes written, 17 ms
yes
| ?- not(true).
no
| ?- not(fail).
yes
| ?-
In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques.
Following topics will be discussed in detail −
Handling inputs and outputs
Handling inputs and outputs
File handling using Prolog
File handling using Prolog
Using some external file to read lines and terms
Using some external file to read lines and terms
Character manipulation for input and output
Character manipulation for input and output
Constructing and decomposing atoms
Constructing and decomposing atoms
Consulting prolog files into other prolog program techniques.
Consulting prolog files into other prolog program techniques.
So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques.
To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function.
| ?- write(56).
56
yes
| ?- write('hello').
hello
yes
| ?- write('hello'),nl,write('world').
hello
world
yes
| ?- write("ABCDE")
.
[65,66,67,68,69]
yes
From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values.
The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works.
cube :-
write('Write a number: '),
read(Number),
process(Number).
process(stop) :- !.
process(Number) :-
C is Number * Number * Number,
write('Cube of '),write(Number),write(': '),write(C),nl, cube.
| ?- [read_write].
compiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code...
D:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read - 1226 bytes written, 12 ms
(15 ms) yes
| ?- cube.
Write a number: 2.
Cube of 2: 8
Write a number: 10.
Cube of 10: 1000
Write a number: 12.
Cube of 12: 1728
Write a number: 8.
Cube of 8: 512
Write a number: stop
.
(31 ms) yes
| ?-
The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces.
| ?- write('hello'),tab(15),write('world').
hello world
yes
| ?- write('We'),tab(5),write('will'),tab(5),write('use'),tab(5),write('tabs').
We will use tabs
yes
| ?-
In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it.
If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed.
| ?- told('myFile.txt').
uncaught exception: error(existence_error(procedure,told/1),top_level/0)
| ?- told("myFile.txt").
uncaught exception: error(existence_error(procedure,told/1),top_level/0)
| ?- tell('myFile.txt').
yes
| ?- tell('myFile.txt').
yes
| ?- write('Hello World').
yes
| ?- write(' Writing into a file'),tab(5),write('myFile.txt'),nl.
yes
| ?- write("Write some ASCII values").
yes
| ?- told.
yes
| ?-
Hello World Writing into a file myFile.txt
[87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115]
Similarly, we can also read from files. Let us see some example of reading from file.
When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command.
likes(lili, cat).
likes(jhon,dog).
| ?- see('sample_predicate.txt'),
read(X),
read(Y),
seen,
read(Z).
the_end.
X = end_of_file
Y = end_of_file
Z = the_end
yes
| ?-
So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console.
We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file.
process_file :-
read(Line),
Line \== end_of_file, % when Line is not not end of file, call process.
process(Line).
process_file :- !. % use cut to stop backtracking
process(Line):- %this will print the line into the console
write(Line),nl,
process_file.
likes(lili, cat).
likes(jhon,dog).
domestic(dog).
domestic(cat).
| ?- [process_file].
compiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code...
D:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read - 774 bytes written, 23 ms
yes
| ?- see('sample_predicate.txt'), process_file, seen.
likes(lili,cat)
likes(jhon,dog)
domestic(dog)
domestic(cat)
true ?
(15 ms) yes
| ?-
Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks.
We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value. To use the character instead of ASCII, we can use put_char(C).
| ?- put(97),put(98),put(99),put(100),put(101).
abcde
yes
| ?- put(97),put(66),put(99),put(100),put(101).
aBcde
(15 ms) yes
| ?- put(65),put(66),put(99),put(100),put(101).
ABcde
yes
| ?-put_char('h'),put_char('e'),put_char('l'),put_char('l'),put_char('o').
hello
yes
| ?-
To read a single character from the current input stream, we can use the get_char(C) predicate. This will take the character. if we want the ASCII code, we can use get_code(C).
| ?- get_char(X).
A.
X = 'A'
yes
uncaught exception: error(syntax_error('user_input:6 (char:689) expression expected'),read_term/3)
| ?- get_code(X).
A.
X = 65
yes
uncaught exception: error(syntax_error('user_input:7 (char:14) expression expected'),read_term/3)
| ?-
The atom constructing means from a list of characters, we can make one atom, or from a list of ASCII values also we can make atoms. To do this, we have to use atom_chars() and atom_codes() predicates. In both cases, the first argument will be one variable, and the second argument will be a list. So atom_chars() constructs atom from characters, but atom_codes() construct atoms from ASCII sequence.
| ?- atom_chars(X, ['t','i','g','e','r']).
X = tiger
yes
| ?- atom_chars(A, ['t','o','m']).
A = tom
yes
| ?- atom_codes(X, [97,98,99,100,101]).
X = abcde
yes
| ?- atom_codes(A, [97,98,99]).
A = abc
yes
| ?-
The atom decomposing means from an atom, we can get a sequence of characters, or a sequence ASCII codes. To do this, we have to use the same atom_chars() and atom_codes() predicates. But one difference is that, in both cases, the first argument will be one atom, and the second argument will be a variable. So atom_chars() decomposes atom to characters, but atom_codes() decomposes atoms to ASCII sequence.
| ?- atom_chars(tiger,X).
X = [t,i,g,e,r]
yes
| ?- atom_chars(tom,A).
A = [t,o,m]
yes
| ?- atom_codes(tiger,X).
X = [116,105,103,101,114]
yes
| ?- atom_codes(tom,A).
A = [116,111,109]
(16 ms) yes
| ?-
The consulting is a technique, that is used to merge the predicates from different files. We can use the consult() predicate, and pass the filename to attach the predicates. Let us see one example program to understand this concept.
Suppose we have two files, namely, prog1.pl and prog2.pl.
likes(mary,cat).
likes(joy,rabbit).
likes(tim,duck).
likes(suman,mouse).
likes(angshu,deer).
| ?- [prog1].
compiling D:/TP Prolog/Sample_Codes/prog1.pl for byte code...
D:/TP Prolog/Sample_Codes/prog1.pl compiled, 2 lines read - 443 bytes written, 23 ms
yes
| ?- likes(joy,rabbit).
yes
| ?- likes(suman,mouse).
no
| ?- consult('prog2.pl').
compiling D:/TP Prolog/Sample_Codes/prog2.pl for byte code...
D:/TP Prolog/Sample_Codes/prog2.pl compiled, 1 lines read - 366 bytes written, 20 ms
warning: D:/TP Prolog/Sample_Codes/prog2.pl:1: redefining procedure likes/2
D:/TP Prolog/Sample_Codes/prog1.pl:1: previous definition
yes
| ?- likes(suman,mouse).
yes
| ?- likes(joy,rabbit).
no
| ?-
Now from this output we can understand that this is not as simple as it seems. If two files have completely different clauses, then it will work fine. But if there are same predicates, then while we try to consult the file, it will check the predicates from the second file, when it finds some match, it simply deletes all of the entry of the same predicates from the local database, then load them again from the second file.
In Prolog, we have seen the user defined predicates in most of the cases, but there are some built-in-predicates. There are three types of built-in predicates as given below −
Identifying terms
Identifying terms
Decomposing structures
Decomposing structures
Collecting all solutions
Collecting all solutions
So this is the list of some predicates that are falls under the identifying terms group −
When X is not initialized, then, it will show true, otherwise false. So let us see an example.
| ?- var(X).
yes
| ?- X = 5, var(X).
no
| ?- var([X]).
no
| ?-
When X is not initialized, the, it will show false, otherwise true. So let us see an example.
| ?- nonvar(X).
no
| ?- X = 5,nonvar(X).
X = 5
yes
| ?- nonvar([X]).
yes
| ?-
This will return true, when a non-variable term with 0 argument and a not numeric term is passed as X, otherwise false.
| ?- atom(paul).
yes
| ?- X = paul,atom(X).
X = paul
yes
| ?- atom([]).
yes
| ?- atom([a,b]).
no
| ?-
This will return true, X stands for any number, otherwise false.
| ?- number(X).
no
| ?- X=5,number(X).
X = 5
yes
| ?- number(5.46).
yes
| ?-
This will return true, when X is a positive or negative integer value, otherwise false.
| ?- integer(5).
yes
| ?- integer(5.46).
no
| ?-
This will return true, X is a floating point number, otherwise false.
| ?- float(5).
no
| ?- float(5.46).
yes
| ?-
We have atom(X), that is too specific, it returns false for numeric data, the atomic(X) is like atom(X) but it accepts number.
| ?- atom(5).
no
| ?- atomic(5).
yes
| ?-
If atomic(X) fails, then the terms are either one non-instantiated variable (that can be tested with var(X)) or a compound term. Compound will be true when we pass some compound structure.
| ?- compound([]).
no
| ?- compound([a]).
yes
| ?- compound(b(a)).
yes
| ?-
This will return true, if X does not contain any un-instantiated variables. This also checks inside the compound terms, otherwise returns false.
| ?- ground(X).
no
| ?- ground(a(b,X)).
no
| ?- ground(a).
yes
| ?- ground([a,b,c]).
yes
| ?-
Now we will see, another group of built-in predicates, that is Decomposing structures. We have seen the identifying terms before. So when we are using compound structures we cannot use a variable to check or make a functor. It will return error. So functor name cannot be represented by a variable.
X = tree, Y = X(maple).
Syntax error Y=X<>(maple)
Now, let us see some inbuilt predicates that falls under the Decomposing structures group.
This returns true if F is the principal functor of T, and N is the arity of F.
Note − Arity means the number of attributes.
| ?- functor(t(f(X),a,T),Func,N).
Func = t
N = 3
(15 ms) yes
| ?-
This returns true if A is the Nth argument in Term. Otherwise returns false.
| ?- arg(1,t(t(X),[]),A).
A = t(X)
yes
| ?- arg(2,t(t(X),[]),A).
A = []
yes
| ?-
Now, let us see another example. In this example, we are checking that the first argument of D will be 12, the second argument will be apr and the third argument will be 2020.
| ?- functor(D,date,3), arg(1,D,12), arg(2,D,apr), arg(3,D,2020).
D = date(12,apr,2020)
yes
| ?-
This is another predicate represented as double dot (..). This takes 2 arguments, so ‘/2’ is written. So Term = .. L, this is true if L is a list that contains the functor of Term, followed by its arguments.
| ?- f(a,b) =.. L.
L = [f,a,b]
yes
| ?- T =.. [is_blue,sam,today].
T = is_blue(sam,today)
yes
| ?-
By representing the component of a structure as a list, they can be recursively processed without knowing the functor name. Let us see another example −
| ?- f(2,3)=..[F,N|Y], N1 is N*3, L=..[F,N1|Y].
F = f
L = f(6,3)
N = 2
N1 = 6
Y = [3]
yes
| ?-
Now let us see the third category called the collecting all solutions, that falls under built-in predicates in Prolog.
We have seen that to generate all of the given solutions of a given goal using the semicolon in the prompt. So here is an example of it.
| ?- member(X, [1,2,3,4]).
X = 1 ? ;
X = 2 ? ;
X = 3 ? ;
X = 4
yes
Sometimes, we need to generate all of the solutions to some goal within a program in some AI related applications. So there are three built-in predicates that will help us to get the results. These predicates are as follows −
findall/3
findall/3
setoff/3
setoff/3
bagof/3
bagof/3
These three predicates take three arguments, so we have written ‘/3’ after the name of the predicates.
These are also known as meta-predicates. These are used to manipulate Prolog’s Proof strategy.
findall(X,P,L).
setof(X,P,L)
bagof(X,P,L)
These three predicates a list of all objects X, such that the goal P is satisfied (example: age(X,Age)). They all repeatedly call the goal P, by instantiating variable X within P and adding it to the list L. This stops when there is no more solution.
Here we will see the three different built-in predicates findall/3, setof/3 and the bagof/3, that fall into the category, collecting all solutions.
This predicate is used to make a list of all solutions X, from the predicate P. The returned list will be L. So we will read this as “find all of the Xs, such that X is a solution of predicate P and put the list of results in L”. Here this predicate stores the results in the same order, in which Prolog finds them. And if there are duplicate solutions, then all will come into the resultant list, and if there is infinite solution, then the process will never terminate.
Now we can also do some advancement on them. The second argument, which is the goal, that might be a compound goal. Then the syntax will be as findall(X, (Predicate on X, other goal), L)
And also the first argument can be a term of any complexity. So let us see the examples of these few rules, and check the output.
| ?- findall(X, member(X, [1,2,3,4]), Results).
Results = [1,2,3,4]
yes
| ?- findall(X, (member(X, [1,2,3,4]), X > 2), Results).
Results = [3,4]
yes
| ?- findall(X/Y, (member(X,[1,2,3,4]), Y is X * X), Results).
Results = [1/1,2/4,3/9,4/16]
yes
| ?-
The setof/3 is also like findall/3, but here it removes all of the duplicate outputs, and the answers will be sorted.
If any variable is used in the goal, then that will not appear in the first argument, setof/3 will return a separate result for each possible instantiation of that variable.
Let us see one example to understand this setof/3. Suppose we have a knowledge base as shown below −
age(peter, 7).
age(ann, 5).
age(pat, 8).
age(tom, 5).
age(ann, 5).
Here we can see that age(ann, 5) has two entries in the knowledge base. And the ages are not sorted, and names are not sorted lexicographically in this case. Now let us see one example of setof/3 usage.
| ?- setof(Child, age(Child,Age),Results).
Age = 5
Results = [ann,tom] ? ;
Age = 7
Results = [peter] ? ;
Age = 8
Results = [pat]
(16 ms) yes
| ?-
Here we can see the ages and the names both are coming sorted. For age 5, there is two entries, so the predicate has created one list corresponding to the age value, with two elements. And the duplicate entry is present only once.
We can use the nested call of setof/3, to collect together the individual results. We will see another example, where the first argument will be Age/Children. As the second argument, it will take another setof like before. So this will return a list of (age/Children) pair. Let us see this in the prolog execution −
| ?- setof(Age/Children, setof(Child,age(Child,Age), Children), AllResults).
AllResults = [5/[ann,tom],7/[peter],8/[pat]]
yes
| ?-
Now if we do not care about a variable that does not appear in the first argument, then we can use the following example −
| ?- setof(Child, Age^age(Child,Age), Results).
Results = [ann,pat,peter,tom]
yes
| ?-
Here we are using the upper caret symbol (^), this indicates that the Age is not in the first argument. So we will read this as, “Find the set of all children, such that the child has an Age (whatever it may be), and put the result in Results”.
The bagof/3 is like setof/3, but here it does not remove the duplicate outputs, and the answers may not be sorted.
Let us see one example to understand this bagof/3. Suppose we have a knowledge base as follows −
age(peter, 7).
age(ann, 5).
age(pat, 8).
age(tom, 5).
age(ann, 5).
| ?- bagof(Child, age(Child,Age),Results).
Age = 5
Results = [ann,tom,ann] ? ;
Age = 7
Results = [peter] ? ;
Age = 8
Results = [pat]
(15 ms) yes
| ?-
Here for the Age value 5, the results are [ann, tom, ann]. So the answers are not sorted, and duplicate entries are not removed, so we have got two ‘ann’ values.
The bagof/3 is different from findall/3, as this generates separate results for all the variables in the goal that do not appear in the first argument. We will see this using an example below −
| ?- findall(Child, age(Child,Age),Results).
Results = [peter,ann,pat,tom,ann]
yes
| ?-
Following are the mathematical predicates −
Besides these, there are some other predicates such as sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh, log, log10, exp, pi, etc.
Now let us see these functions in action using a Prolog program.
| ?- random(0,10,X).
X = 0
yes
| ?- random(0,10,X).
X = 5
yes
| ?- random(0,10,X).
X = 1
yes
| ?- between(0,10,X).
X = 0 ? a
X = 1
X = 2
X = 3
X = 4
X = 5
X = 6
X = 7
X = 8
X = 9
X = 10
(31 ms) yes
| ?- succ(2,X).
X = 3
yes
| ?- X is abs(-8).
X = 8
yes
| ?- X is max(10,5).
X = 10
yes
| ?- X is min(10,5).
X = 5
yes
| ?- X is round(10.56).
X = 11
yes
| ?- X is truncate(10.56).
X = 10
yes
| ?- X is floor(10.56).
X = 10
yes
| ?- X is ceiling(10.56).
X = 11
yes
| ?- X is sqrt(144).
X = 12.0
yes
| ?-
So far we have seen different concepts of logic programming in Prolog. Now we will see one case study on Prolog. We will see how to implement a tree data structure using Prolog, and we will create our own operators. So let us start the planning.
Suppose we have a tree as shown below −
We have to implement this tree using prolog. We have some operations as follows −
op(500, xfx, ‘is_parent’).
op(500, xfx, ‘is_parent’).
op(500, xfx, ‘is_sibling_of’).
op(500, xfx, ‘is_sibling_of’).
op(500, xfx, ‘is_at_same_level’).
op(500, xfx, ‘is_at_same_level’).
And another predicate namely leaf_node(Node)
And another predicate namely leaf_node(Node)
In these operators, you have seen some parameters as (500, xfx, <operator_name>). The first argument (here 500) is the priority of that operator. The ‘xfx’ indicates that this is a binary operator and the <operator_name> is the name of the operator.
These operators can be used to define the tree database. We can use these operators as follows −
a is_parent b, or is_parent(a, b). So this indicates that node a is the parent of node b.
a is_parent b, or is_parent(a, b). So this indicates that node a is the parent of node b.
X is_sibling_of Y or is_sibling_of(X,Y). This indicates that X is the sibling of node Y. So the rule is, if another node Z is parent of X and Z is also the parent of Y and X and Y are different, then X and Y are siblings.
X is_sibling_of Y or is_sibling_of(X,Y). This indicates that X is the sibling of node Y. So the rule is, if another node Z is parent of X and Z is also the parent of Y and X and Y are different, then X and Y are siblings.
leaf_node(Node). A node (Node) is said to be a leaf node when a node has no children.
leaf_node(Node). A node (Node) is said to be a leaf node when a node has no children.
X is_at_same_level Y, or is_at_same_level(X,Y). This will check whether X and Y are at the same level or not. So the condition is when X and Y are same, then it returns true, otherwise W is the parent of X, Z is the parent of Y and W and Z are at the same level.
X is_at_same_level Y, or is_at_same_level(X,Y). This will check whether X and Y are at the same level or not. So the condition is when X and Y are same, then it returns true, otherwise W is the parent of X, Z is the parent of Y and W and Z are at the same level.
As shown above, other rules are defined in the code. So let us see the program to get better view.
/* The tree database */
:- op(500,xfx,'is_parent').
a is_parent b. c is_parent g. f is_parent l. j is_parent q.
a is_parent c. c is_parent h. f is_parent m. j is_parent r.
a is_parent d. c is_parent i. h is_parent n. j is_parent s.
b is_parent e. d is_parent j. i is_parent o. m is_parent t.
b is_parent f. e is_parent k. i is_parent p. n is_parent u.
n
is_parent v.
/* X and Y are siblings i.e. child from the same parent */
:- op(500,xfx,'is_sibling_of').
X is_sibling_of Y :- Z is_parent X,
Z is_parent Y,
X \== Y.
leaf_node(Node) :- \+ is_parent(Node,Child). % Node grounded
/* X and Y are on the same level in the tree. */
:-op(500,xfx,'is_at_same_level').
X is_at_same_level X .
X is_at_same_level Y :- W is_parent X,
Z is_parent Y,
W is_at_same_level Z.
| ?- [case_tree].
compiling D:/TP Prolog/Sample_Codes/case_tree.pl for byte code...
D:/TP Prolog/Sample_Codes/case_tree.pl:20: warning: singleton variables [Child] for leaf_node/1
D:/TP Prolog/Sample_Codes/case_tree.pl compiled, 28 lines read - 3244 bytes written, 7 ms
yes
| ?- i is_parent p.
yes
| ?- i is_parent s.
no
| ?- is_parent(i,p).
yes
| ?- e is_sibling_of f.
true ?
yes
| ?- is_sibling_of(e,g).
no
| ?- leaf_node(v).
yes
| ?- leaf_node(a).
no
| ?- is_at_same_level(l,s).
true ?
yes
| ?- l is_at_same_level v.
no
| ?-
Here, we will see some more operations that will be performed on the above given tree data structure.
Let us consider the same tree here −
We will define other operations −
path(Node)
path(Node)
locate(Node)
locate(Node)
As we have created the last database, we will create a new program that will hold these operations, then consult the new file to use these operations on our pre-existing program.
So let us see what is the purpose of these operators −
path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node ‘a’ is reached, it will stop.
path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node ‘a’ is reached, it will stop.
locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node.
locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node.
Let us see the program in execution −
path(a). /* Can start at a. */
path(Node) :- Mother is_parent Node, /* Choose parent, */
path(Mother), /* find path and then */
write(Mother),
write(' --> ').
/* Locate node by finding a path from root down to the node */
locate(Node) :- path(Node),
write(Node),
nl.
| ?- consult('case_tree_more.pl').
compiling D:/TP Prolog/Sample_Codes/case_tree_more.pl for byte code...
D:/TP Prolog/Sample_Codes/case_tree_more.pl compiled, 9 lines read - 866 bytes written, 6 ms
yes
| ?- path(n).
a --> c --> h -->
true ?
yes
| ?- path(s).
a --> d --> j -->
true ?
yes
| ?- path(w).
no
| ?- locate(n).
a --> c --> h --> n
true ?
yes
| ?- locate(s).
a --> d --> j --> s
true ?
yes
| ?- locate(w).
no
| ?-
Now let us define some advanced operations on the same tree data structure.
Here we will see how to find the height of a node, that is, the length of the longest path from that node, using the Prolog built-in predicate setof/3. This predicate takes (Template, Goal, Set). This binds Set to the list of all instances of Template satisfying the goal Goal.
We have already defined the tree before, so we will consult the current code to execute these set of operations without redefining the tree database again.
We will create some predicates as follows −
ht(Node,H). This finds the height. It also checks whether a node is leaf or not, if so, then sets height H as 0, otherwise recursively finds the height of children of Node, and add 1 to them.
max([X|R], M,A). This calculates the max element from the list, and a value M. So if M is maximum, then it returns M, otherwise, it returns the maximum element of list that is greater than M. To solve this, if given list is empty, return M as max element, otherwise check whether Head is greater than M or not, if so, then call max() using the tail part and the value X, otherwise call max() using tail and the value M.
height(N,H). This uses the setof/3 predicate. This will find the set of results using the goal ht(N,Z) for the template Z and stores into the list type variable called Set. Now find the max of Set, and value 0, store the result into H.
Now let us see the program in execution −
height(N,H) :- setof(Z,ht(N,Z),Set),
max(Set,0,H).
ht(Node,0) :- leaf_node(Node),!.
ht(Node,H) :- Node is_parent Child,
ht(Child,H1),
H is H1 + 1.
max([],M,M).
max([X|R],M,A) :- (X > M -> max(R,X,A) ; max(R,M,A)).
| ?- consult('case_tree_adv.pl').
compiling D:/TP Prolog/Sample_Codes/case_tree_adv.pl for byte code...
D:/TP Prolog/Sample_Codes/case_tree_adv.pl compiled, 9 lines read - 2060 bytes written, 9 ms
yes
| ?- ht(c,H).
H = 1 ? a
H = 3
H = 3
H = 2
H = 2
yes
| ?- max([1,5,3,4,2],10,Max).
Max = 10
yes
| ?- max([1,5,3,40,2],10,Max).
Max = 40
yes
| ?- setof(H, ht(c,H),Set).
Set = [1,2,3]
yes
| ?- max([1,2,3],0,H).
H = 3
yes
| ?- height(c,H).
H = 3
yes
| ?- height(a,H).
H = 4
yes
| ?-
In the following chapter, we are going to discuss basic prolog examples to −
Find minimum maximum of two numbers
Find minimum maximum of two numbers
Find the equivalent resistance of a resistive circuit
Find the equivalent resistance of a resistive circuit
Verify whether a line segment is horizontal, vertical or oblique
Verify whether a line segment is horizontal, vertical or oblique
Here we will see one Prolog program, that can find the minimum of two numbers and the maximum of two numbers. First, we will create two predicates, find_max(X,Y,Max). This takes X and Y values, and stores the maximum value into the Max. Similarly find_min(X,Y,Min) takes X and Y values, and store the minimum value into the Min variable.
find_max(X, Y, X) :- X >= Y, !.
find_max(X, Y, Y) :- X < Y.
find_min(X, Y, X) :- X =< Y, !.
find_min(X, Y, Y) :- X > Y.
| ?- find_max(100,200,Max).
Max = 200
yes
| ?- find_max(40,10,Max).
Max = 40
yes
| ?- find_min(40,10,Min).
Min = 10
yes
| ?- find_min(100,200,Min).
Min = 100
yes
| ?-
In this section, we will see how to write a prolog program that will help us find the equivalent resistance of a resistive circuit.
Let us consider the following circuit to understand this concept −
We have to find the equivalent resistance of this network. At first, we will try to get the result by hand, then try to see whether the result is matching with the prolog output or not.
We know that there are two rules −
If R1 and R2 are in Series, then equivalent resistor Re = R1 + R2.
If R1 and R2 are in Series, then equivalent resistor Re = R1 + R2.
If R1 and R2 are in Parallel, then equivalent resistor Re = (R1 * R2)/(R1 + R2).
If R1 and R2 are in Parallel, then equivalent resistor Re = (R1 * R2)/(R1 + R2).
Here 10 Ohm and 40 Ohm resistors are in parallel, then that is in series with 12 Ohm, and the equivalent resistor of the lower half is parallel with 30 Ohm. So let’s try to calculate the equivalent resistance.
R3 = (10 * 40)/(10 + 40) = 400/50 = 8 Ohm
R3 = (10 * 40)/(10 + 40) = 400/50 = 8 Ohm
R4 = R3 + 12 = 8 + 12 = 20 Ohm
R4 = R3 + 12 = 8 + 12 = 20 Ohm
R5 = (20 * 30)/(20 + 30) = 12 Ohm
R5 = (20 * 30)/(20 + 30) = 12 Ohm
series(R1,R2,Re) :- Re is R1 + R2.
parallel(R1,R2,Re) :- Re is ((R1 * R2) / (R1 + R2)).
| ?- [resistance].
compiling D:/TP Prolog/Sample_Codes/resistance.pl for byte code...
D:/TP Prolog/Sample_Codes/resistance.pl compiled, 1 lines read - 804 bytes written, 14 ms
yes
| ?- parallel(10,40,R3).
R3 = 8.0
yes
| ?- series(8,12,R4).
R4 = 20
yes
| ?- parallel(20,30,R5).
R5 = 12.0
yes
| ?- parallel(10,40,R3),series(R3,12,R4),parallel(R4,30,R5).
R3 = 8.0
R4 = 20.0
R5 = 12.0
yes
| ?-
There are three types of line segments, horizontal, vertical or oblique. This example verifies whether a line segment is horizontal, vertical or oblique.
From this diagram we can understand that −
For Horizontal lines, the y coordinate values of two endpoints are same.
For Horizontal lines, the y coordinate values of two endpoints are same.
For Vertical lines, the x coordinate values of two endpoints are same.
For Vertical lines, the x coordinate values of two endpoints are same.
For Oblique lines, the (x,y) coordinates of two endpoints are different.
For Oblique lines, the (x,y) coordinates of two endpoints are different.
Now let us see how to write a program to check this.
vertical(seg(point(X,_),point(X,_))).
horizontal(seg(point(_,Y),point(_,Y))).
oblique(seg(point(X1,Y1),point(X2,Y2)))
:-X1 \== X2,
Y1 \== Y2.
| ?- [line_seg].
compiling D:/TP Prolog/Sample_Codes/line_seg.pl for byte code...
D:/TP Prolog/Sample_Codes/line_seg.pl compiled, 6 lines read - 1276 bytes written, 26 ms
yes
| ?- vertical(seg(point(10,20), point(10,30))).
yes
| ?- vertical(seg(point(10,20), point(15,30))).
no
| ?- oblique(seg(point(10,20), point(15,30))).
yes
| ?- oblique(seg(point(10,20), point(15,20))).
no
| ?- horizontal(seg(point(10,20), point(15,20))).
yes
| ?-
In this section, we will see some examples of cuts in prolog. Let us consider, we want to find the maximum of two elements. So we will check these two conditions.
If X > Y, then Max := X
If X > Y, then Max := X
if X <= Y, then Max := Y
if X <= Y, then Max := Y
Now from these two lines, we can understand that these two statements are mutually exclusive, so when one is true, another one must be false. In such cases we can use the cut. So let us see the program.
We can also define a predicate where we use the two cases using disjunction (OR logic). So when first one satisfies, it does not check for the second one, otherwise, it will check for the second statement.
max(X,Y,X) :- X >= Y,!.
max(X,Y,Y) :- X < Y.
max_find(X,Y,Max) :- X >= Y,!, Max = X; Max = Y.
| ?- [cut_example].
1 1 Call: [cut_example] ?
compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...
D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 3 lines read - 1195 bytes written, 43 ms
1 1 Exit: [cut_example] ?
yes
{trace}
| ?- max(10,20,Max).
1 1 Call: max(10,20,_23) ?
2 2 Call: 10>=20 ?
2 2 Fail: 10>=20 ?
2 2 Call: 10<20 ?
2 2 Exit: 10<20 ?
1 1 Exit: max(10,20,20) ?
Max = 20
yes
{trace}
| ?- max_find(20,10,Max).
1 1 Call: max_find(20,10,_23) ?
2 2 Call: 20>=10 ?
2 2 Exit: 20>=10 ?
1 1 Exit: max_find(20,10,20) ?
Max = 20
yes
{trace}
| ?-
Let us see another example, where we will use list. In this program we will try to insert an element into a list, if it is not present in the list before. And if the list has the element before we will simply cut it. For the membership checking also, if the item is at the head part, we should not check further, so cut it, otherwise check into the tail part.
list_member(X,[X|_]) :- !.
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).
| ?- [cut_example].
compiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...
D:/TP Prolog/Sample_Codes/cut_example.pl compiled, 9 lines read - 1954 bytes written, 15 ms
yes
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- list_append(a,[a,b,c,d,e], L).
1 1 Call: list_append(a,[a,b,c,d,e],_33) ?
2 2 Call: list_member(a,[a,b,c,d,e]) ?
2 2 Exit: list_member(a,[a,b,c,d,e]) ?
1 1 Exit: list_append(a,[a,b,c,d,e],[a,b,c,d,e]) ?
L = [a,b,c,d,e]
yes
{trace}
| ?- list_append(k,[a,b,c,d,e], L).
1 1 Call: list_append(k,[a,b,c,d,e],_33) ?
2 2 Call: list_member(k,[a,b,c,d,e]) ?
3 3 Call: list_member(k,[b,c,d,e]) ?
4 4 Call: list_member(k,[c,d,e]) ?
5 5 Call: list_member(k,[d,e]) ?
6 6 Call: list_member(k,[e]) ?
7 7 Call: list_member(k,[]) ?
7 7 Fail: list_member(k,[]) ?
6 6 Fail: list_member(k,[e]) ?
5 5 Fail: list_member(k,[d,e]) ?
4 4 Fail: list_member(k,[c,d,e]) ?
3 3 Fail: list_member(k,[b,c,d,e]) ?
2 2 Fail: list_member(k,[a,b,c,d,e]) ?
1 1 Exit: list_append(k,[a,b,c,d,e],[k,a,b,c,d,e]) ?
L = [k,a,b,c,d,e]
(16 ms) yes
{trace}
| ?-
Towers of Hanoi Problem is a famous puzzle to move N disks from the source peg/tower to the target peg/tower using the intermediate peg as an auxiliary holding peg. There are two conditions that are to be followed while solving this problem −
A larger disk cannot be placed on a smaller disk.
A larger disk cannot be placed on a smaller disk.
Only one disk can be moved at a time.
Only one disk can be moved at a time.
The following diagram depicts the starting setup for N=3 disks.
To solve this, we have to write one procedure move(N, Source, Target, auxiliary). Here N number of disks will have to be shifted from Source peg to Target peg keeping Auxiliary peg as intermediate.
For example – move(3, source, target, auxiliary).
Move top disk from source to target
Move top disk from source to target
Move top disk from source to auxiliary
Move top disk from source to auxiliary
Move top disk from target to auxiliary
Move top disk from target to auxiliary
Move top disk from source to target
Move top disk from source to target
Move top disk from auxiliary to source
Move top disk from auxiliary to source
Move top disk from auxiliary to target
Move top disk from auxiliary to target
Move top disk from source to target
Move top disk from source to target
move(1,X,Y,_) :-
write('Move top disk from '), write(X), write(' to '), write(Y), nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
| ?- [towersofhanoi].
compiling D:/TP Prolog/Sample_Codes/towersofhanoi.pl for byte code...
D:/TP Prolog/Sample_Codes/towersofhanoi.pl compiled, 8 lines read - 1409 bytes written, 15 ms
yes
| ?- move(4,source,target,auxiliary).
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
Move top disk from source to auxiliary
Move top disk from target to source
Move top disk from target to auxiliary
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
Move top disk from auxiliary to source
Move top disk from target to source
Move top disk from auxiliary to target
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
true ?
(31 ms) yes
Following chapters describe how to generate/create linked lists using recursive structures.
Linked list has two components, the integer part and the link part. The link part will hold another node. End of list will have nil into the link part.
In prolog, we can express this using node(2, node(5, node(6, nil))).
Note − The smallest possible list is nil, and every other list will contain nil as the "next" of the end node. In list terminology, the first element is usually called the head of the list, and the rest of the list is called the tail part. Thus the head of the above list is 2, and its tail is the list node(5, node(6, nil)).
We can also insert elements into front and back side −
add_front(L,E,NList) :- NList = node(E,L).
add_back(nil, E, NList) :-
NList = node(E,nil).
add_back(node(Head,Tail), E, NList) :-
add_back(Tail, E, NewTail),
NList = node(Head,NewTail).
| ?- [linked_list].
compiling D:/TP Prolog/Sample_Codes/linked_list.pl for byte code...
D:/TP Prolog/Sample_Codes/linked_list.pl compiled, 7 lines read - 966 bytes written, 14 ms
(15 ms) yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3).
L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(2,node(5,node(6,nil)))
yes
| ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3).
L1 = node(6,nil)
L2 = node(6,node(5,nil))
L3 = node(6,node(5,node(2,nil)))
yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3).
L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(5,node(6,node(2,nil)))
yes
| ?-
In this prolog example, we will see one very interesting and famous problem, The Monkey and Banana Problem.
Suppose the problem is as given below −
A hungry monkey is in a room, and he is near the door.
A hungry monkey is in a room, and he is near the door.
The monkey is on the floor.
The monkey is on the floor.
Bananas have been hung from the center of the ceiling of the room.
Bananas have been hung from the center of the ceiling of the room.
There is a block (or chair) present in the room near the window.
There is a block (or chair) present in the room near the window.
The monkey wants the banana, but cannot reach it.
The monkey wants the banana, but cannot reach it.
So if the monkey is clever enough, he can come to the block, drag the block to the center, climb on it, and get the banana. Below are few observations in this case −
Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor.
Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor.
If the block position is not at the center, then monkey can drag it to the center.
If the block position is not at the center, then monkey can drag it to the center.
If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed.
If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed.
When the monkey is on the block, and block is at the center, then the monkey can get the bananas.
When the monkey is on the block, and block is at the center, then the monkey can get the bananas.
Now, let us see how we can solve this using Prolog. We will create some predicates as follows −
We have some predicates that will move from one state to another state, by performing action.
When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state.
When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state.
From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb.
From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb.
The push or drag operation moves the block from one place to another.
The push or drag operation moves the block from one place to another.
Monkey can move from one place to another using walk or move clauses.
Monkey can move from one place to another using walk or move clauses.
Another predicate will be canget(). Here we pass a state, so this will perform move predicate from one state to another using different actions, then perform canget() on state 2. When we have reached to the state ‘has>’, this indicates ‘has banana’. We will stop the execution.
move(state(middle,onbox,middle,hasnot),
grasp,
state(middle,onbox,middle,has)).
move(state(P,onfloor,P,H),
climb,
state(P,onbox,P,H)).
move(state(P1,onfloor,P1,H),
drag(P1,P2),
state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),
walk(P1,P2),
state(P2,onfloor,B,H)).
canget(state(_,_,_,has)).
canget(State1) :-
move(State1,_,State2),
canget(State2).
| ?- [monkey_banana].
compiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code...
D:/TP Prolog/Sample_Codes/monkey_banana.pl compiled, 17 lines read - 2167 bytes written, 19 ms
(31 ms) yes
| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).
true ?
yes
| ?- trace
.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).
1 1 Call: canget(state(atdoor,onfloor,atwindow,hasnot)) ?
2 2 Call: move(state(atdoor,onfloor,atwindow,hasnot),_52,_92) ?
2 2 Exit:move(state(atdoor,onfloor,atwindow,hasnot),walk(atdoor,_80),state(_80,onfloor,atwindow,hasnot)) ?
3 2 Call: canget(state(_80,onfloor,atwindow,hasnot)) ?
4 3 Call: move(state(_80,onfloor,atwindow,hasnot),_110,_150) ?
4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ?
5 3 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ?
6 4 Call: move(state(atwindow,onbox,atwindow,hasnot),_165,_205) ?
6 4 Fail: move(state(atwindow,onbox,atwindow,hasnot),_165,_193) ?
5 3 Fail: canget(state(atwindow,onbox,atwindow,hasnot)) ?
4 3 Redo: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ?
4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_138),state(_138,onfloor,_138,hasnot)) ?
5 3 Call: canget(state(_138,onfloor,_138,hasnot)) ?
6 4 Call: move(state(_138,onfloor,_138,hasnot),_168,_208) ?
6 4 Exit: move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasnot)) ?
7 4 Call: canget(state(_138,onbox,_138,hasnot)) ?
8 5 Call: move(state(_138,onbox,_138,hasnot),_223,_263) ?
8 5 Exit: move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has)) ?
9 5 Call: canget(state(middle,onbox,middle,has)) ?
9 5 Exit: canget(state(middle,onbox,middle,has)) ?
7 4 Exit: canget(state(middle,onbox,middle,hasnot)) ?
5 3 Exit: canget(state(middle,onfloor,middle,hasnot)) ?
3 2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ?
1 1 Exit: canget(state(atdoor,onfloor,atwindow,hasnot)) ?
true ?
(78 ms) yes
65 Lectures
5 hours
Arnab Chakraborty
78 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2333,
"s": 2092,
"text": "Prolog as the name itself suggests, is the short form of LOGical PROgramming. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is."
},
{
"code": null,
"e": 2861,
"s": 2333,
"text": "Logic Programming is one of the Computer Programming Paradigm, in which the program statements express the facts and rules about different problems within a system of formal logic. Here, the rules are written in the form of logical clauses, where head and body are present. For example, H is head and B1, B2, B3 are the elements of the body. Now if we state that “H is true, when B1, B2, B3 all are true”, this is a rule. On the other hand, facts are like the rules, but without any body. So, an example of fact is “H is true”."
},
{
"code": null,
"e": 3312,
"s": 2861,
"text": "Some logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely declarative languages. These languages allow statements about what the program should accomplish. There is no such step-by-step instruction on how to perform the task. However, other languages like Prolog, have declarative and also imperative properties. This may also include procedural statements like “To solve the problem H, perform B1, B2 and B3”."
},
{
"code": null,
"e": 3363,
"s": 3312,
"text": "Some logic programming languages are given below −"
},
{
"code": null,
"e": 3418,
"s": 3363,
"text": "ALF (algebraic logic functional programming language)."
},
{
"code": null,
"e": 3473,
"s": 3418,
"text": "ALF (algebraic logic functional programming language)."
},
{
"code": null,
"e": 3502,
"s": 3473,
"text": "ASP (Answer Set Programming)"
},
{
"code": null,
"e": 3531,
"s": 3502,
"text": "ASP (Answer Set Programming)"
},
{
"code": null,
"e": 3536,
"s": 3531,
"text": "CycL"
},
{
"code": null,
"e": 3541,
"s": 3536,
"text": "CycL"
},
{
"code": null,
"e": 3549,
"s": 3541,
"text": "Datalog"
},
{
"code": null,
"e": 3557,
"s": 3549,
"text": "Datalog"
},
{
"code": null,
"e": 3568,
"s": 3557,
"text": "FuzzyCLIPS"
},
{
"code": null,
"e": 3579,
"s": 3568,
"text": "FuzzyCLIPS"
},
{
"code": null,
"e": 3585,
"s": 3579,
"text": "Janus"
},
{
"code": null,
"e": 3591,
"s": 3585,
"text": "Janus"
},
{
"code": null,
"e": 3598,
"s": 3591,
"text": "Parlog"
},
{
"code": null,
"e": 3605,
"s": 3598,
"text": "Parlog"
},
{
"code": null,
"e": 3612,
"s": 3605,
"text": "Prolog"
},
{
"code": null,
"e": 3619,
"s": 3612,
"text": "Prolog"
},
{
"code": null,
"e": 3628,
"s": 3619,
"text": "Prolog++"
},
{
"code": null,
"e": 3637,
"s": 3628,
"text": "Prolog++"
},
{
"code": null,
"e": 3642,
"s": 3637,
"text": "ROOP"
},
{
"code": null,
"e": 3647,
"s": 3642,
"text": "ROOP"
},
{
"code": null,
"e": 3819,
"s": 3647,
"text": "We will discuss about the differences between Logic programming and the traditional functional programming languages. We can illustrate these two using the below diagram −"
},
{
"code": null,
"e": 4261,
"s": 3819,
"text": "From this illustration, we can see that in Functional Programming, we have to define the procedures, and the rule how the procedures work. These procedures work step by step to solve one specific problem based on the algorithm. On the other hand, for the Logic Programming, we will provide knowledge base. Using this knowledge base, the machine can find answers to the given questions, which is totally different from functional programming."
},
{
"code": null,
"e": 4545,
"s": 4261,
"text": "In functional programming, we have to mention how one problem can be solved, but in logic programming we have to specify for which problem we actually want the solution. Then the logic programming automatically finds a suitable solution that will help us solve that specific problem."
},
{
"code": null,
"e": 4590,
"s": 4545,
"text": "Now let us see some more differences below −"
},
{
"code": null,
"e": 5050,
"s": 4590,
"text": "Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. This is the main reason to use Prolog as the programming language in Artificial Intelligence, where symbol manipulation and inference manipulation are the fundamental tasks."
},
{
"code": null,
"e": 5278,
"s": 5050,
"text": "In Prolog, we need not mention the way how one problem can be solved, we just need to mention what the problem is, so that Prolog automatically solves it. However, in Prolog we are supposed to give clues as the solution method."
},
{
"code": null,
"e": 5335,
"s": 5278,
"text": "Prolog language basically has three different elements −"
},
{
"code": null,
"e": 5450,
"s": 5335,
"text": "Facts − The fact is predicate that is true, for example, if we say, “Tom is the son of Jack”, then this is a fact."
},
{
"code": null,
"e": 5611,
"s": 5450,
"text": "Rules − Rules are extinctions of facts that contain conditional clauses. To satisfy a rule these conditions should be met. For example, if we define a rule as −"
},
{
"code": null,
"e": 5660,
"s": 5611,
"text": "grandfather(X, Y) :- father(X, Z), parent(Z, Y)\n"
},
{
"code": null,
"e": 5767,
"s": 5660,
"text": "This implies that for X to be the grandfather of Y, Z should be a parent of Y and X should be father of Z."
},
{
"code": null,
"e": 5898,
"s": 5767,
"text": "Questions − And to run a prolog program, we need some questions, and those questions can be answered by the given facts and rules."
},
{
"code": null,
"e": 6289,
"s": 5898,
"text": "The heritage of prolog includes the research on theorem provers and some other automated deduction system that were developed in 1960s and 1970s. The Inference mechanism of the Prolog is based on Robinson’s Resolution Principle, that was proposed in 1965, and Answer extracting mechanism by Green (1968). These ideas came together forcefully with the advent of linear resolution procedures."
},
{
"code": null,
"e": 6640,
"s": 6289,
"text": "The explicit goal-directed linear resolution procedures, gave impetus to the development of a general purpose logic programming system. The first Prolog was the Marseille Prolog based on the work by Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter (Roussel, 1975) was the first detailed description of the Prolog language."
},
{
"code": null,
"e": 6969,
"s": 6640,
"text": "Prolog is also considered as a fourth generation programming language supporting the declarative programming paradigm. The well-known Japanese Fifth-Generation Computer Project, that was announced in 1981, adopted Prolog as a development language, and thereby grabbed considerable attention on the language and its capabilities."
},
{
"code": null,
"e": 7113,
"s": 6969,
"text": "Prolog is used in various domains. It plays a vital role in automation system. Following are some other important fields where Prolog is used −"
},
{
"code": null,
"e": 7144,
"s": 7113,
"text": "Intelligent Database Retrieval"
},
{
"code": null,
"e": 7175,
"s": 7144,
"text": "Intelligent Database Retrieval"
},
{
"code": null,
"e": 7206,
"s": 7175,
"text": "Natural Language Understanding"
},
{
"code": null,
"e": 7237,
"s": 7206,
"text": "Natural Language Understanding"
},
{
"code": null,
"e": 7260,
"s": 7237,
"text": "Specification Language"
},
{
"code": null,
"e": 7283,
"s": 7260,
"text": "Specification Language"
},
{
"code": null,
"e": 7300,
"s": 7283,
"text": "Machine Learning"
},
{
"code": null,
"e": 7317,
"s": 7300,
"text": "Machine Learning"
},
{
"code": null,
"e": 7332,
"s": 7317,
"text": "Robot Planning"
},
{
"code": null,
"e": 7347,
"s": 7332,
"text": "Robot Planning"
},
{
"code": null,
"e": 7365,
"s": 7347,
"text": "Automation System"
},
{
"code": null,
"e": 7383,
"s": 7365,
"text": "Automation System"
},
{
"code": null,
"e": 7399,
"s": 7383,
"text": "Problem Solving"
},
{
"code": null,
"e": 7415,
"s": 7399,
"text": "Problem Solving"
},
{
"code": null,
"e": 7485,
"s": 7415,
"text": "In this chapter, we will discuss how to install Prolog in our system."
},
{
"code": null,
"e": 7543,
"s": 7485,
"text": "In this tutorial, we are using GNU Prolog, Version: 1.4.5"
},
{
"code": null,
"e": 7676,
"s": 7543,
"text": "This is the official GNU Prolog website where we can see all the necessary details about GNU Prolog, and also get the download link."
},
{
"code": null,
"e": 7700,
"s": 7676,
"text": "http://www.gprolog.org/"
},
{
"code": null,
"e": 7904,
"s": 7700,
"text": "Given below are the direct download links of GNU Prolog for Windows. For other operating systems like Mac or Linux, you can get the download links by visiting the official website (Link is given above) −"
},
{
"code": null,
"e": 7977,
"s": 7904,
"text": "http://www.gprolog.org/setup-gprolog-1.4.5-mingw-x86.exe (32 Bit System)"
},
{
"code": null,
"e": 8049,
"s": 7977,
"text": "http://www.gprolog.org/setup-gprolog-1.4.5-mingw-x64.exe(64 Bit System)"
},
{
"code": null,
"e": 8083,
"s": 8049,
"text": "Download the exe file and run it."
},
{
"code": null,
"e": 8117,
"s": 8083,
"text": "Download the exe file and run it."
},
{
"code": null,
"e": 8178,
"s": 8117,
"text": "You will see the window as shown below, then click on next −"
},
{
"code": null,
"e": 8239,
"s": 8178,
"text": "You will see the window as shown below, then click on next −"
},
{
"code": null,
"e": 8379,
"s": 8239,
"text": "Select proper directory where you want to install the software, otherwise let it be installed on the default directory. Then click on next."
},
{
"code": null,
"e": 8429,
"s": 8379,
"text": "You will get the below screen, simply go to next."
},
{
"code": null,
"e": 8558,
"s": 8429,
"text": "You can verify the below screen, and check/uncheck appropriate boxes, otherwise you can leave it as default. Then click on next."
},
{
"code": null,
"e": 8630,
"s": 8558,
"text": "In the next step, you will see the below screen, then click on Install."
},
{
"code": null,
"e": 8680,
"s": 8630,
"text": "Then wait for the installation process to finish."
},
{
"code": null,
"e": 8725,
"s": 8680,
"text": "Finally click on Finish to start GNU Prolog."
},
{
"code": null,
"e": 8783,
"s": 8725,
"text": "The GNU prolog is installed successfully as shown below −"
},
{
"code": null,
"e": 8934,
"s": 8783,
"text": "In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment."
},
{
"code": null,
"e": 9076,
"s": 8934,
"text": "After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows −"
},
{
"code": null,
"e": 9099,
"s": 9076,
"text": "write('Hello World').\n"
},
{
"code": null,
"e": 9194,
"s": 9099,
"text": "Note − After each line, you have to use one period (.) symbol to show that the line has ended."
},
{
"code": null,
"e": 9244,
"s": 9194,
"text": "The corresponding output will be as shown below −"
},
{
"code": null,
"e": 9338,
"s": 9244,
"text": "Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console."
},
{
"code": null,
"e": 9509,
"s": 9338,
"text": "Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps −"
},
{
"code": null,
"e": 9593,
"s": 9509,
"text": "Step 1 − From the prolog console, go to File > Change Dir, then click on that menu."
},
{
"code": null,
"e": 9641,
"s": 9593,
"text": "Step 2 − Select the proper folder and press OK."
},
{
"code": null,
"e": 9737,
"s": 9641,
"text": "Now we can see in the prolog console, it shows that we have successfully changed the directory."
},
{
"code": null,
"e": 9818,
"s": 9737,
"text": "Step 3 − Now create one file (extension is *.pl) and write the code as follows −"
},
{
"code": null,
"e": 9927,
"s": 9818,
"text": "main :- write('This is sample Prolog program'),\nwrite(' This program is written into hello_world.pl file').\n"
},
{
"code": null,
"e": 10006,
"s": 9927,
"text": "Now let’s run the code. To run it, we have to write the file name as follows −"
},
{
"code": null,
"e": 10021,
"s": 10006,
"text": "[hello_world]\n"
},
{
"code": null,
"e": 10048,
"s": 10021,
"text": "The output is as follows −"
},
{
"code": null,
"e": 10177,
"s": 10048,
"text": "In this chapter, we will gain some basic knowledge about Prolog. So we will move on to the first step of our Prolog Programming."
},
{
"code": null,
"e": 10241,
"s": 10177,
"text": "The different topics that will be covered in this chapter are −"
},
{
"code": null,
"e": 10404,
"s": 10241,
"text": "Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail about the Knowledge Base, and how it helps in logic programming."
},
{
"code": null,
"e": 10616,
"s": 10404,
"text": "Facts, Rules and Queries − These are the building blocks of logic programming. We will get some detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic programming."
},
{
"code": null,
"e": 10752,
"s": 10616,
"text": "Here, we will discuss about the essential building blocks of logic programming. These building blocks are Facts, Rules and the Queries."
},
{
"code": null,
"e": 10946,
"s": 10752,
"text": "We can define fact as an explicit relationship between objects, and properties these objects might have. So facts are unconditionally true in nature. Suppose we have some facts as given below −"
},
{
"code": null,
"e": 10959,
"s": 10946,
"text": "Tom is a cat"
},
{
"code": null,
"e": 10972,
"s": 10959,
"text": "Tom is a cat"
},
{
"code": null,
"e": 10997,
"s": 10972,
"text": "Kunal loves to eat Pasta"
},
{
"code": null,
"e": 11022,
"s": 10997,
"text": "Kunal loves to eat Pasta"
},
{
"code": null,
"e": 11036,
"s": 11022,
"text": "Hair is black"
},
{
"code": null,
"e": 11050,
"s": 11036,
"text": "Hair is black"
},
{
"code": null,
"e": 11076,
"s": 11050,
"text": "Nawaz loves to play games"
},
{
"code": null,
"e": 11102,
"s": 11076,
"text": "Nawaz loves to play games"
},
{
"code": null,
"e": 11121,
"s": 11102,
"text": "Pratyusha is lazy."
},
{
"code": null,
"e": 11140,
"s": 11121,
"text": "Pratyusha is lazy."
},
{
"code": null,
"e": 11261,
"s": 11140,
"text": "So these are some facts, that are unconditionally true. These are actually statements, that we have to consider as true."
},
{
"code": null,
"e": 11308,
"s": 11261,
"text": "Following are some guidelines to write facts −"
},
{
"code": null,
"e": 11373,
"s": 11308,
"text": "Names of properties/relationships begin with lower case letters."
},
{
"code": null,
"e": 11438,
"s": 11373,
"text": "Names of properties/relationships begin with lower case letters."
},
{
"code": null,
"e": 11487,
"s": 11438,
"text": "The relationship name appears as the first term."
},
{
"code": null,
"e": 11536,
"s": 11487,
"text": "The relationship name appears as the first term."
},
{
"code": null,
"e": 11600,
"s": 11536,
"text": "Objects appear as comma-separated arguments within parentheses."
},
{
"code": null,
"e": 11664,
"s": 11600,
"text": "Objects appear as comma-separated arguments within parentheses."
},
{
"code": null,
"e": 11694,
"s": 11664,
"text": "A period \".\" must end a fact."
},
{
"code": null,
"e": 11724,
"s": 11694,
"text": "A period \".\" must end a fact."
},
{
"code": null,
"e": 11892,
"s": 11724,
"text": "Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’)."
},
{
"code": null,
"e": 12060,
"s": 11892,
"text": "Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’)."
},
{
"code": null,
"e": 12128,
"s": 12060,
"text": "phoneno(agnibha, 1122334455). is also called a predicate or clause."
},
{
"code": null,
"e": 12196,
"s": 12128,
"text": "phoneno(agnibha, 1122334455). is also called a predicate or clause."
},
{
"code": null,
"e": 12233,
"s": 12196,
"text": "The syntax for facts is as follows −"
},
{
"code": null,
"e": 12264,
"s": 12233,
"text": "relation(object1,object2...).\n"
},
{
"code": null,
"e": 12311,
"s": 12264,
"text": "Following is an example of the above concept −"
},
{
"code": null,
"e": 12416,
"s": 12311,
"text": "cat(tom).\nloves_to_eat(kunal,pasta).\nof_color(hair,black).\nloves_to_play_games(nawaz).\nlazy(pratyusha).\n"
},
{
"code": null,
"e": 12632,
"s": 12416,
"text": "We can define rule as an implicit relationship between objects. So facts are conditionally true. So when one associated condition is true, then the predicate is also true. Suppose we have some rules as given below −"
},
{
"code": null,
"e": 12661,
"s": 12632,
"text": "Lili is happy if she dances."
},
{
"code": null,
"e": 12690,
"s": 12661,
"text": "Lili is happy if she dances."
},
{
"code": null,
"e": 12733,
"s": 12690,
"text": "Tom is hungry if he is searching for food."
},
{
"code": null,
"e": 12776,
"s": 12733,
"text": "Tom is hungry if he is searching for food."
},
{
"code": null,
"e": 12840,
"s": 12776,
"text": "Jack and Bili are friends if both of them love to play cricket."
},
{
"code": null,
"e": 12904,
"s": 12840,
"text": "Jack and Bili are friends if both of them love to play cricket."
},
{
"code": null,
"e": 12957,
"s": 12904,
"text": "will go to play if school is closed, and he is free."
},
{
"code": null,
"e": 13010,
"s": 12957,
"text": "will go to play if school is closed, and he is free."
},
{
"code": null,
"e": 13138,
"s": 13010,
"text": "So these are some rules that are conditionally true, so when the right hand side is true, then the left hand side is also true."
},
{
"code": null,
"e": 13441,
"s": 13138,
"text": "Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol, the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,) which is known as conjunction, and we can also use semicolon, that is known as disjunction."
},
{
"code": null,
"e": 13721,
"s": 13441,
"text": "rule_name(object1, object2, ...) :- fact/rule(object1,\n object2, ...)\nSuppose a clause is like :\nP :- Q;R.\nThis can also be written as\nP :- Q.\nP :- R.\n\nIf one clause is like :\nP :- Q,R;S,T,U.\n\nIs understood as\nP :- (Q,R);(S,T,U).\nOr can also be written as:\nP :- Q,R.\nP :- S,T,U.\n"
},
{
"code": null,
"e": 13899,
"s": 13721,
"text": "happy(lili) :- dances(lili).\nhungry(tom) :- search_for_food(tom).\nfriends(jack, bili) :- lovesCricket(jack), lovesCricket(bili).\ngoToPlay(ryan) :- isClosed(school), free(ryan).\n"
},
{
"code": null,
"e": 14032,
"s": 13899,
"text": "Queries are some questions on the relationships between objects and object properties. So question can be anything, as given below −"
},
{
"code": null,
"e": 14046,
"s": 14032,
"text": "Is tom a cat?"
},
{
"code": null,
"e": 14060,
"s": 14046,
"text": "Is tom a cat?"
},
{
"code": null,
"e": 14090,
"s": 14060,
"text": "Does Kunal love to eat pasta?"
},
{
"code": null,
"e": 14120,
"s": 14090,
"text": "Does Kunal love to eat pasta?"
},
{
"code": null,
"e": 14135,
"s": 14120,
"text": "Is Lili happy?"
},
{
"code": null,
"e": 14150,
"s": 14135,
"text": "Is Lili happy?"
},
{
"code": null,
"e": 14172,
"s": 14150,
"text": "Will Ryan go to play?"
},
{
"code": null,
"e": 14194,
"s": 14172,
"text": "Will Ryan go to play?"
},
{
"code": null,
"e": 14289,
"s": 14194,
"text": "So according to these queries, Logic programming language can find the answer and return them."
},
{
"code": null,
"e": 14363,
"s": 14289,
"text": "In this section, we will see what knowledge base in logic programming is."
},
{
"code": null,
"e": 14632,
"s": 14363,
"text": "Well, as we know there are three main components in logic programming − Facts, Rules and Queries. Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we can say that the knowledge base is a collection of facts and rules."
},
{
"code": null,
"e": 14872,
"s": 14632,
"text": "Now, we will see how to write some knowledge bases. Suppose we have our very first knowledge base called KB1. Here in the KB1, we have some facts. The facts are used to state things, that are unconditionally true of the domain of interest."
},
{
"code": null,
"e": 15049,
"s": 14872,
"text": "Suppose we have some knowledge, that Priya, Tiyasha, and Jaya are three girls, among them, Priya can cook. Let’s try to write these facts in a more generic way as shown below −"
},
{
"code": null,
"e": 15107,
"s": 15049,
"text": "girl(priya).\ngirl(tiyasha).\ngirl(jaya).\ncan_cook(priya).\n"
},
{
"code": null,
"e": 15247,
"s": 15107,
"text": "Note − Here we have written the name in lowercase letters, because in Prolog, a string starting with uppercase letter indicates a variable."
},
{
"code": null,
"e": 15552,
"s": 15247,
"text": "Now we can use this knowledge base by posing some queries. “Is priya a girl?”, it will reply “yes”, “is jamini a girl?” then it will answer “No”, because it does not know who jamini is. Our next question is “Can Priya cook?”, it will say “yes”, but if we ask the same question for Jaya, it will say “No”."
},
{
"code": null,
"e": 16012,
"s": 15552,
"text": "GNU Prolog 1.4.5 (64 bits)\nCompiled Jul 14 2018, 13:19:42 with x86_64-w64-mingw32-gcc\nBy Daniel Diaz\nCopyright (C) 1999-2018 Daniel Diaz\n| ?- change_directory('D:/TP Prolog/Sample_Codes').\n\nyes\n| ?- [kb1]\n.\ncompiling D:/TP Prolog/Sample_Codes/kb1.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb1.pl compiled, 3 lines read - 489 bytes written, 10 ms\n\nyes\n| ?- girl(priya)\n.\n\nyes\n| ?- girl(jamini).\n\nno\n| ?- can_cook(priya).\n\nyes\n| ?- can_cook(jaya).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 16205,
"s": 16012,
"text": "Let us see another knowledge base, where we have some rules. Rules contain some information that are conditionally true about the domain of interest. Suppose our knowledge base is as follows −"
},
{
"code": null,
"e": 16430,
"s": 16205,
"text": "sing_a_song(ananya).\nlistens_to_music(rohit).\n\nlistens_to_music(ananya) :- sing_a_song(ananya).\nhappy(ananya) :- sing_a_song(ananya).\nhappy(rohit) :- listens_to_music(rohit).\nplayes_guitar(rohit) :- listens_to_music(rohit).\n"
},
{
"code": null,
"e": 16930,
"s": 16430,
"text": "So there are some facts and rules given above. The first two are facts, but the rest are rules. As we know that Ananya sings a song, this implies she also listens to music. So if we ask “Does Ananya listen to music?”, the answer will be true. Similarly, “is Rohit happy?”, this will also be true because he listens to music. But if our question is “does Ananya play guitar?”, then according to the knowledge base, it will say “No”. So these are some examples of queries based on this Knowledge base."
},
{
"code": null,
"e": 17281,
"s": 16930,
"text": "| ?- [kb2].\ncompiling D:/TP Prolog/Sample_Codes/kb2.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb2.pl compiled, 6 lines read - 1066 bytes written, 15 ms\n\nyes\n| ?- happy(rohit).\n\nyes\n| ?- sing_a_song(rohit).\n\nno\n| ?- sing_a_song(ananya).\n\nyes\n| ?- playes_guitar(rohit).\n\nyes\n| ?- playes_guitar(ananya).\n\nno\n| ?- listens_to_music(ananya).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 17338,
"s": 17281,
"text": "The facts and rules of Knowledge Base 3 are as follows −"
},
{
"code": null,
"e": 17472,
"s": 17338,
"text": "can_cook(priya).\ncan_cook(jaya).\ncan_cook(tiyasha).\n\nlikes(priya,jaya) :- can_cook(jaya).\nlikes(priya,tiyasha) :- can_cook(tiyasha).\n"
},
{
"code": null,
"e": 17764,
"s": 17472,
"text": "Suppose we want to see the members who can cook, we can use one variable in our query. The variables should start with uppercase letters. In the result, it will show one by one. If we press enter, then it will come out, otherwise if we press semicolon (;), then it will show the next result."
},
{
"code": null,
"e": 17838,
"s": 17764,
"text": "Let us see one practical demonstration output to understand how it works."
},
{
"code": null,
"e": 18273,
"s": 17838,
"text": "| ?- [kb3].\ncompiling D:/TP Prolog/Sample_Codes/kb3.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb3.pl compiled, 5 lines read - 737 bytes written, 22 ms\nwarning: D:/TP Prolog/Sample_Codes/kb3.pl:1: redefining procedure can_cook/1\n D:/TP Prolog/Sample_Codes/kb1.pl:4: previous definition\n \nyes\n| ?- can_cook(X).\n\nX = priya ? ;\n\nX = jaya ? ;\n\nX = tiyasha\n\nyes\n| ?- likes(priya,X).\n\nX = jaya ? ;\n\nX = tiyasha\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 18583,
"s": 18273,
"text": "Relationship is one of the main features that we have to properly mention in Prolog. These relationships can be expressed as facts and rules. After that we will see about the family relationships, how we can express family based relationships in Prolog, and also see the recursive relationships of the family."
},
{
"code": null,
"e": 18670,
"s": 18583,
"text": "We will create the knowledge base by creating facts and rules, and play query on them."
},
{
"code": null,
"e": 18763,
"s": 18670,
"text": "In Prolog programs, it specifies relationship between objects and properties of the objects."
},
{
"code": null,
"e": 18927,
"s": 18763,
"text": "Suppose, there’s a statement, “Amit has a bike”, then we are actually declaring the ownership relationship between two objects — one is Amit and the other is bike."
},
{
"code": null,
"e": 19033,
"s": 18927,
"text": "If we ask a question, “Does Amit own a bike?”, we are actually trying to find out about one relationship."
},
{
"code": null,
"e": 19214,
"s": 19033,
"text": "There are various kinds of relationships, of which some can be rules as well. A rule can find out about a relationship even if the relationship is not defined explicitly as a fact."
},
{
"code": null,
"e": 19264,
"s": 19214,
"text": "We can define a brother relationship as follows −"
},
{
"code": null,
"e": 19293,
"s": 19264,
"text": "Two person are brothers, if,"
},
{
"code": null,
"e": 19313,
"s": 19293,
"text": "They both are male."
},
{
"code": null,
"e": 19333,
"s": 19313,
"text": "They both are male."
},
{
"code": null,
"e": 19360,
"s": 19333,
"text": "They have the same parent."
},
{
"code": null,
"e": 19387,
"s": 19360,
"text": "They have the same parent."
},
{
"code": null,
"e": 19428,
"s": 19387,
"text": "Now consider we have the below phrases −"
},
{
"code": null,
"e": 19450,
"s": 19428,
"text": "parent(sudip, piyus)."
},
{
"code": null,
"e": 19472,
"s": 19450,
"text": "parent(sudip, piyus)."
},
{
"code": null,
"e": 19492,
"s": 19472,
"text": "parent(sudip, raj)."
},
{
"code": null,
"e": 19512,
"s": 19492,
"text": "parent(sudip, raj)."
},
{
"code": null,
"e": 19525,
"s": 19512,
"text": "male(piyus)."
},
{
"code": null,
"e": 19538,
"s": 19525,
"text": "male(piyus)."
},
{
"code": null,
"e": 19549,
"s": 19538,
"text": "male(raj)."
},
{
"code": null,
"e": 19560,
"s": 19549,
"text": "male(raj)."
},
{
"code": null,
"e": 19618,
"s": 19560,
"text": "brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)"
},
{
"code": null,
"e": 19676,
"s": 19618,
"text": "brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)"
},
{
"code": null,
"e": 20057,
"s": 19676,
"text": "These clauses can give us the answer that piyus and raj are brothers, but we will get three pairs of output here. They are: (piyus, piyus), (piyus, raj), (raj, raj). For these pairs, given conditions are true, but for the pairs (piyus, piyus), (raj, raj), they are not actually brothers, they are the same persons. So we have to create the clauses properly to form a relationship."
},
{
"code": null,
"e": 20102,
"s": 20057,
"text": "The revised relationship can be as follows −"
},
{
"code": null,
"e": 20128,
"s": 20102,
"text": "A and B are brothers if −"
},
{
"code": null,
"e": 20151,
"s": 20128,
"text": "A and B, both are male"
},
{
"code": null,
"e": 20174,
"s": 20151,
"text": "A and B, both are male"
},
{
"code": null,
"e": 20196,
"s": 20174,
"text": "They have same father"
},
{
"code": null,
"e": 20218,
"s": 20196,
"text": "They have same father"
},
{
"code": null,
"e": 20240,
"s": 20218,
"text": "They have same mother"
},
{
"code": null,
"e": 20262,
"s": 20240,
"text": "They have same mother"
},
{
"code": null,
"e": 20283,
"s": 20262,
"text": "A and B are not same"
},
{
"code": null,
"e": 20304,
"s": 20283,
"text": "A and B are not same"
},
{
"code": null,
"e": 20537,
"s": 20304,
"text": "Here we will see the family relationship. This is an example of complex relationship that can be formed using Prolog. We want to make a family tree, and that will be mapped into facts and rules, then we can run some queries on them."
},
{
"code": null,
"e": 20577,
"s": 20537,
"text": "Suppose the family tree is as follows −"
},
{
"code": null,
"e": 20825,
"s": 20577,
"text": "Here from this tree, we can understand that there are few relationships. Here bob is a child of pam and tom, and bob also has two children — ann and pat. Bob has one brother liz, whose parent is also tom. So we want to make predicates as follows −"
},
{
"code": null,
"e": 20843,
"s": 20825,
"text": "parent(pam, bob)."
},
{
"code": null,
"e": 20861,
"s": 20843,
"text": "parent(pam, bob)."
},
{
"code": null,
"e": 20879,
"s": 20861,
"text": "parent(tom, bob)."
},
{
"code": null,
"e": 20897,
"s": 20879,
"text": "parent(tom, bob)."
},
{
"code": null,
"e": 20915,
"s": 20897,
"text": "parent(tom, liz)."
},
{
"code": null,
"e": 20933,
"s": 20915,
"text": "parent(tom, liz)."
},
{
"code": null,
"e": 20951,
"s": 20933,
"text": "parent(bob, ann)."
},
{
"code": null,
"e": 20969,
"s": 20951,
"text": "parent(bob, ann)."
},
{
"code": null,
"e": 20987,
"s": 20969,
"text": "parent(bob, pat)."
},
{
"code": null,
"e": 21005,
"s": 20987,
"text": "parent(bob, pat)."
},
{
"code": null,
"e": 21023,
"s": 21005,
"text": "parent(pat, jim)."
},
{
"code": null,
"e": 21041,
"s": 21023,
"text": "parent(pat, jim)."
},
{
"code": null,
"e": 21061,
"s": 21041,
"text": "parent(bob, peter)."
},
{
"code": null,
"e": 21081,
"s": 21061,
"text": "parent(bob, peter)."
},
{
"code": null,
"e": 21101,
"s": 21081,
"text": "parent(peter, jim)."
},
{
"code": null,
"e": 21121,
"s": 21101,
"text": "parent(peter, jim)."
},
{
"code": null,
"e": 21191,
"s": 21121,
"text": "From our example, it has helped to illustrate some important points −"
},
{
"code": null,
"e": 21302,
"s": 21191,
"text": "We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree."
},
{
"code": null,
"e": 21413,
"s": 21302,
"text": "We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree."
},
{
"code": null,
"e": 21497,
"s": 21413,
"text": "The user can easily query the Prolog system about relations defined in the program."
},
{
"code": null,
"e": 21581,
"s": 21497,
"text": "The user can easily query the Prolog system about relations defined in the program."
},
{
"code": null,
"e": 21645,
"s": 21581,
"text": "A Prolog program consists of clauses terminated by a full stop."
},
{
"code": null,
"e": 21709,
"s": 21645,
"text": "A Prolog program consists of clauses terminated by a full stop."
},
{
"code": null,
"e": 21963,
"s": 21709,
"text": "The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables."
},
{
"code": null,
"e": 22217,
"s": 21963,
"text": "The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables."
},
{
"code": null,
"e": 22271,
"s": 22217,
"text": "Questions to the system consist of one or more goals."
},
{
"code": null,
"e": 22325,
"s": 22271,
"text": "Questions to the system consist of one or more goals."
},
{
"code": null,
"e": 22441,
"s": 22325,
"text": "Some facts can be written in two different ways, like sex of family members can be written in either of the forms −"
},
{
"code": null,
"e": 22454,
"s": 22441,
"text": "female(pam)."
},
{
"code": null,
"e": 22467,
"s": 22454,
"text": "female(pam)."
},
{
"code": null,
"e": 22478,
"s": 22467,
"text": "male(tom)."
},
{
"code": null,
"e": 22489,
"s": 22478,
"text": "male(tom)."
},
{
"code": null,
"e": 22500,
"s": 22489,
"text": "male(bob)."
},
{
"code": null,
"e": 22511,
"s": 22500,
"text": "male(bob)."
},
{
"code": null,
"e": 22524,
"s": 22511,
"text": "female(liz)."
},
{
"code": null,
"e": 22537,
"s": 22524,
"text": "female(liz)."
},
{
"code": null,
"e": 22550,
"s": 22537,
"text": "female(pat)."
},
{
"code": null,
"e": 22563,
"s": 22550,
"text": "female(pat)."
},
{
"code": null,
"e": 22576,
"s": 22563,
"text": "female(ann)."
},
{
"code": null,
"e": 22589,
"s": 22576,
"text": "female(ann)."
},
{
"code": null,
"e": 22600,
"s": 22589,
"text": "male(jim)."
},
{
"code": null,
"e": 22611,
"s": 22600,
"text": "male(jim)."
},
{
"code": null,
"e": 22634,
"s": 22611,
"text": "Or in the below form −"
},
{
"code": null,
"e": 22655,
"s": 22634,
"text": "sex( pam, feminine)."
},
{
"code": null,
"e": 22676,
"s": 22655,
"text": "sex( pam, feminine)."
},
{
"code": null,
"e": 22698,
"s": 22676,
"text": "sex( tom, masculine)."
},
{
"code": null,
"e": 22720,
"s": 22698,
"text": "sex( tom, masculine)."
},
{
"code": null,
"e": 22742,
"s": 22720,
"text": "sex( bob, masculine)."
},
{
"code": null,
"e": 22764,
"s": 22742,
"text": "sex( bob, masculine)."
},
{
"code": null,
"e": 22779,
"s": 22764,
"text": "... and so on."
},
{
"code": null,
"e": 22794,
"s": 22779,
"text": "... and so on."
},
{
"code": null,
"e": 22884,
"s": 22794,
"text": "Now if we want to make mother and sister relationship, then we can write as given below −"
},
{
"code": null,
"e": 22917,
"s": 22884,
"text": "In Prolog syntax, we can write −"
},
{
"code": null,
"e": 22956,
"s": 22917,
"text": "mother(X,Y) :- parent(X,Y), female(X)."
},
{
"code": null,
"e": 22995,
"s": 22956,
"text": "mother(X,Y) :- parent(X,Y), female(X)."
},
{
"code": null,
"e": 23056,
"s": 22995,
"text": "sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \\== Y."
},
{
"code": null,
"e": 23117,
"s": 23056,
"text": "sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \\== Y."
},
{
"code": null,
"e": 23162,
"s": 23117,
"text": "Now let us see the practical demonstration −"
},
{
"code": null,
"e": 23607,
"s": 23162,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\nmother(X,Y):- parent(X,Y),female(X).\nfather(X,Y):- parent(X,Y),male(X).\nhaschild(X):- parent(X,_).\nsister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\\==Y.\nbrother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\\==Y."
},
{
"code": null,
"e": 24160,
"s": 23607,
"text": "| ?- [family].\ncompiling D:/TP Prolog/Sample_Codes/family.pl for byte code...\nD:/TP Prolog/Sample_Codes/family.pl compiled, 23 lines read - 3088 bytes written, 9 ms\n\nyes\n| ?- parent(X,jim).\n\nX = pat ? ;\n\nX = peter\n\nyes\n| ?-\nmother(X,Y).\n\nX = pam\nY = bob ? ;\n\nX = pat\nY = jim ? ;\n\nno\n| ?- haschild(X).\n\nX = pam ? ;\n\nX = tom ? ;\n\nX = tom ? ;\n\nX = bob ? ;\n\nX = bob ? ;\n\nX = pat ? ;\n\nX = bob ? ;\n\nX = peter\n\nyes\n| ?- sister(X,Y).\n\nX = liz\nY = bob ? ;\n\nX = ann\nY = pat ? ;\n\nX = ann\nY = peter ? ;\n\nX = pat\nY = ann ? ;\n\nX = pat\nY = peter ? ;\n\n(16 ms) no\n| ?-\n"
},
{
"code": null,
"e": 24343,
"s": 24160,
"text": "Now let us see some more relationships that we can make from the previous relationships of a family. So if we want to make a grandparent relationship, that can be formed as follows −"
},
{
"code": null,
"e": 24458,
"s": 24343,
"text": "We can also create some other relationships like wife, uncle, etc. We can write the relationships as given below −"
},
{
"code": null,
"e": 24504,
"s": 24458,
"text": "grandparent(X,Y) :- parent(X,Z), parent(Z,Y)."
},
{
"code": null,
"e": 24550,
"s": 24504,
"text": "grandparent(X,Y) :- parent(X,Z), parent(Z,Y)."
},
{
"code": null,
"e": 24596,
"s": 24550,
"text": "grandmother(X,Z) :- mother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 24642,
"s": 24596,
"text": "grandmother(X,Z) :- mother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 24688,
"s": 24642,
"text": "grandfather(X,Z) :- father(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 24734,
"s": 24688,
"text": "grandfather(X,Z) :- father(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 24791,
"s": 24734,
"text": "wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y)."
},
{
"code": null,
"e": 24848,
"s": 24791,
"text": "wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y)."
},
{
"code": null,
"e": 24889,
"s": 24848,
"text": "uncle(X,Z) :- brother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 24930,
"s": 24889,
"text": "uncle(X,Z) :- brother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 25046,
"s": 24930,
"text": "So let us write a prolog program to see this in action. Here we will also see the trace to trace-out the execution."
},
{
"code": null,
"e": 25687,
"s": 25046,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\n\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\n\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\n\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\n\nmother(X,Y):- parent(X,Y),female(X).\nfather(X,Y):-parent(X,Y),male(X).\nsister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\\==Y.\nbrother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\\==Y.\ngrandparent(X,Y):-parent(X,Z),parent(Z,Y).\ngrandmother(X,Z):-mother(X,Y),parent(Y,Z).\ngrandfather(X,Z):-father(X,Y),parent(Y,Z).\nwife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y).\nuncle(X,Z):-brother(X,Y),parent(Y,Z)."
},
{
"code": null,
"e": 26187,
"s": 25687,
"text": "| ?- [family_ext].\ncompiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms\n\n| ?- uncle(X,Y).\n\nX = peter\nY = jim ? ;\n\nno\n| ?- grandparent(X,Y).\n\nX = pam\nY = ann ? ;\n\nX = pam\nY = pat ? ;\n\nX = pam\nY = peter ? ;\n\nX = tom\nY = ann ? ;\n\nX = tom\nY = pat ? ;\n\nX = tom\nY = peter ? ;\n\nX = bob\nY = jim ? ;\n\nX = bob\nY = jim ? ;\n\nno\n| ?- wife(X,Y).\n\nX = pam\nY = tom ? ;\n\nX = pat\nY = peter ? ;\n\n(15 ms) no\n| ?-\n"
},
{
"code": null,
"e": 26530,
"s": 26187,
"text": "In Prolog we can trace the execution. To trace the output, you have to enter into the trace mode by typing “trace.”. Then from the output we can see that we are just tracing “pam is mother of whom?”. See the tracing output by taking X = pam, and Y as variable, there Y will be bob as answer. To come out from the tracing mode press “notrace.”"
},
{
"code": null,
"e": 27154,
"s": 26530,
"text": "| ?- [family_ext].\ncompiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms\n\n(16 ms) yes\n| ?- mother(X,Y).\n\nX = pam\nY = bob ? ;\n\nX = pat\nY = jim ? ;\n\nno\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- mother(pam,Y).\n 1 1 Call: mother(pam,_23) ?\n 2 2 Call: parent(pam,_23) ?\n 2 2 Exit: parent(pam,bob) ?\n 3 2 Call: female(pam) ?\n 3 2 Exit: female(pam) ?\n 1 1 Exit: mother(pam,bob) ?\n \nY = bob\n\n(16 ms) yes\n{trace}\n| ?- notrace.\nThe debugger is switched off\n\nyes\n| ?-"
},
{
"code": null,
"e": 27385,
"s": 27154,
"text": "In the previous section, we have seen that we can define some family relationships. These relationships are static in nature. We can also create some recursive relationships which can be expressed from the following illustration −"
},
{
"code": null,
"e": 27512,
"s": 27385,
"text": "So we can understand that predecessor relationship is recursive. We can express this relationship using the following syntax −"
},
{
"code": null,
"e": 27601,
"s": 27512,
"text": "predecessor(X, Z) :- parent(X, Z).\npredecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).\n"
},
{
"code": null,
"e": 27645,
"s": 27601,
"text": "Now let us see the practical demonstration."
},
{
"code": null,
"e": 27974,
"s": 27645,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\n\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\n\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\n\npredecessor(X, Z) :- parent(X, Z).\npredecessor(X, Z) :- parent(X, Y),predecessor(Y, Z)."
},
{
"code": null,
"e": 29965,
"s": 27974,
"text": "| ?- [family_rec].\ncompiling D:/TP Prolog/Sample_Codes/family_rec.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_rec.pl compiled, 21 lines read - 1851 bytes written, 14 ms\n\nyes\n| ?- predecessor(peter,X).\n\nX = jim ? ;\n\nno\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- predecessor(bob,X).\n 1 1 Call: predecessor(bob,_23) ?\n 2 2 Call: parent(bob,_23) ?\n 2 2 Exit: parent(bob,ann) ?\n 1 1 Exit: predecessor(bob,ann) ?\n \nX = ann ? ;\n 1 1 Redo: predecessor(bob,ann) ?\n 2 2 Redo: parent(bob,ann) ?\n 2 2 Exit: parent(bob,pat) ?\n 1 1 Exit: predecessor(bob,pat) ?\n \nX = pat ? ;\n 1 1 Redo: predecessor(bob,pat) ?\n 2 2 Redo: parent(bob,pat) ?\n 2 2 Exit: parent(bob,peter) ?\n 1 1 Exit: predecessor(bob,peter) ?\n \nX = peter ? ;\n 1 1 Redo: predecessor(bob,peter) ?\n 2 2 Call: parent(bob,_92) ?\n 2 2 Exit: parent(bob,ann) ?\n 3 2 Call: predecessor(ann,_23) ?\n 4 3 Call: parent(ann,_23) ?\n 4 3 Fail: parent(ann,_23) ?\n 4 3 Call: parent(ann,_141) ?\n 4 3 Fail: parent(ann,_129) ?\n 3 2 Fail: predecessor(ann,_23) ?\n 2 2 Redo: parent(bob,ann) ?\n 2 2 Exit: parent(bob,pat) ?\n 3 2 Call: predecessor(pat,_23) ?\n 4 3 Call: parent(pat,_23) ?\n 4 3 Exit: parent(pat,jim) ?\n 3 2 Exit: predecessor(pat,jim) ?\n 1 1 Exit: predecessor(bob,jim) ?\n \nX = jim ? ;\n 1 1 Redo: predecessor(bob,jim) ?\n 3 2 Redo: predecessor(pat,jim) ?\n 4 3 Call: parent(pat,_141) ?\n 4 3 Exit: parent(pat,jim) ?\n 5 3 Call: predecessor(jim,_23) ?\n 6 4 Call: parent(jim,_23) ?\n 6 4 Fail: parent(jim,_23) ?\n 6 4 Call: parent(jim,_190) ?\n 6 4 Fail: parent(jim,_178) ?\n 5 3 Fail: predecessor(jim,_23) ?\n 3 2 Fail: predecessor(pat,_23) ?\n 2 2 Redo: parent(bob,pat) ?\n 2 2 Exit: parent(bob,peter) ?\n 3 2 Call: predecessor(peter,_23) ?\n 4 3 Call: parent(peter,_23) ?\n 4 3 Exit: parent(peter,jim) ?\n 3 2 Exit: predecessor(peter,jim) ?\n 1 1 Exit: predecessor(bob,jim) ?\n \nX = jim ?\n\n(78 ms) yes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 30087,
"s": 29965,
"text": "In this chapter, we will learn data objects in Prolog. They can be divided into few different categories as shown below −"
},
{
"code": null,
"e": 30148,
"s": 30087,
"text": "Below are some examples of different kinds of data objects −"
},
{
"code": null,
"e": 30177,
"s": 30148,
"text": "Atoms − tom, pat, x100, x_45"
},
{
"code": null,
"e": 30206,
"s": 30177,
"text": "Atoms − tom, pat, x100, x_45"
},
{
"code": null,
"e": 30235,
"s": 30206,
"text": "Numbers − 100, 1235, 2000.45"
},
{
"code": null,
"e": 30264,
"s": 30235,
"text": "Numbers − 100, 1235, 2000.45"
},
{
"code": null,
"e": 30291,
"s": 30264,
"text": "Variables − X, Y, Xval, _X"
},
{
"code": null,
"e": 30318,
"s": 30291,
"text": "Variables − X, Y, Xval, _X"
},
{
"code": null,
"e": 30364,
"s": 30318,
"text": "Structures − day(9, jun, 2017), point(10, 25)"
},
{
"code": null,
"e": 30410,
"s": 30364,
"text": "Structures − day(9, jun, 2017), point(10, 25)"
},
{
"code": null,
"e": 30491,
"s": 30410,
"text": "In this section, we will discuss the atoms, numbers and the variables of Prolog."
},
{
"code": null,
"e": 30656,
"s": 30491,
"text": "Atoms are one variation of constants. They can be any names or objects. There are few rules that should be followed when we are trying to use Atoms as given below −"
},
{
"code": null,
"e": 30767,
"s": 30656,
"text": "Strings of letters, digits and the underscore character, ‘_', starting with a lower-case letter. For example −"
},
{
"code": null,
"e": 30774,
"s": 30767,
"text": "azahar"
},
{
"code": null,
"e": 30781,
"s": 30774,
"text": "azahar"
},
{
"code": null,
"e": 30785,
"s": 30781,
"text": "b59"
},
{
"code": null,
"e": 30789,
"s": 30785,
"text": "b59"
},
{
"code": null,
"e": 30794,
"s": 30789,
"text": "b_59"
},
{
"code": null,
"e": 30799,
"s": 30794,
"text": "b_59"
},
{
"code": null,
"e": 30806,
"s": 30799,
"text": "b_59AB"
},
{
"code": null,
"e": 30813,
"s": 30806,
"text": "b_59AB"
},
{
"code": null,
"e": 30819,
"s": 30813,
"text": "b_x25"
},
{
"code": null,
"e": 30825,
"s": 30819,
"text": "b_x25"
},
{
"code": null,
"e": 30839,
"s": 30825,
"text": "antara_sarkar"
},
{
"code": null,
"e": 30853,
"s": 30839,
"text": "antara_sarkar"
},
{
"code": null,
"e": 31027,
"s": 30853,
"text": "We have to keep in mind that when using atoms of this form, some care is necessary as some strings of special characters already have a predefined meaning; for example ':-'."
},
{
"code": null,
"e": 31033,
"s": 31027,
"text": "<--->"
},
{
"code": null,
"e": 31039,
"s": 31033,
"text": "<--->"
},
{
"code": null,
"e": 31048,
"s": 31039,
"text": "=======>"
},
{
"code": null,
"e": 31057,
"s": 31048,
"text": "=======>"
},
{
"code": null,
"e": 31061,
"s": 31057,
"text": "..."
},
{
"code": null,
"e": 31065,
"s": 31061,
"text": "..."
},
{
"code": null,
"e": 31069,
"s": 31065,
"text": ".:."
},
{
"code": null,
"e": 31073,
"s": 31069,
"text": ".:."
},
{
"code": null,
"e": 31077,
"s": 31073,
"text": "::="
},
{
"code": null,
"e": 31081,
"s": 31077,
"text": "::="
},
{
"code": null,
"e": 31229,
"s": 31081,
"text": "This is useful if we want to have an atom that starts with a capital letter. By enclosing it in quotes, we make it distinguishable from variables −"
},
{
"code": null,
"e": 31237,
"s": 31229,
"text": "‘Rubai'"
},
{
"code": null,
"e": 31245,
"s": 31237,
"text": "‘Rubai'"
},
{
"code": null,
"e": 31266,
"s": 31245,
"text": "‘Arindam_Chatterjee'"
},
{
"code": null,
"e": 31287,
"s": 31266,
"text": "‘Arindam_Chatterjee'"
},
{
"code": null,
"e": 31301,
"s": 31287,
"text": "‘Sumit Mitra'"
},
{
"code": null,
"e": 31315,
"s": 31301,
"text": "‘Sumit Mitra'"
},
{
"code": null,
"e": 31487,
"s": 31315,
"text": "Another variation of constants is the Numbers. So integer numbers can be represented as 100, 4, -81, 1202. In Prolog, the normal range of integers is from -16383 to 16383."
},
{
"code": null,
"e": 31794,
"s": 31487,
"text": "Prolog also supports real numbers, but normally the use-case of floating point number is very less in Prolog programs, because Prolog is for symbolic, non-numeric computation. The treatment of real numbers depends on the implementation of Prolog. Example of real numbers are 3.14159, -0.00062, 450.18, etc."
},
{
"code": null,
"e": 31995,
"s": 31794,
"text": "The variables come under the Simple Objects section. Variables can be used in many such cases in our Prolog program, that we have seen earlier. So there are some rules of defining variables in Prolog."
},
{
"code": null,
"e": 32203,
"s": 31995,
"text": "We can define Prolog variables, such that variables are strings of letters, digits and underscore characters. They start with an upper-case letter or an underscore character. Some examples of Variables are −"
},
{
"code": null,
"e": 32205,
"s": 32203,
"text": "X"
},
{
"code": null,
"e": 32207,
"s": 32205,
"text": "X"
},
{
"code": null,
"e": 32211,
"s": 32207,
"text": "Sum"
},
{
"code": null,
"e": 32215,
"s": 32211,
"text": "Sum"
},
{
"code": null,
"e": 32226,
"s": 32215,
"text": "Memer_name"
},
{
"code": null,
"e": 32237,
"s": 32226,
"text": "Memer_name"
},
{
"code": null,
"e": 32250,
"s": 32237,
"text": "Student_list"
},
{
"code": null,
"e": 32263,
"s": 32250,
"text": "Student_list"
},
{
"code": null,
"e": 32276,
"s": 32263,
"text": "Shoppinglist"
},
{
"code": null,
"e": 32289,
"s": 32276,
"text": "Shoppinglist"
},
{
"code": null,
"e": 32294,
"s": 32289,
"text": "_a50"
},
{
"code": null,
"e": 32299,
"s": 32294,
"text": "_a50"
},
{
"code": null,
"e": 32303,
"s": 32299,
"text": "_15"
},
{
"code": null,
"e": 32307,
"s": 32303,
"text": "_15"
},
{
"code": null,
"e": 32536,
"s": 32307,
"text": "Anonymous variables have no names. The anonymous variables in prolog is written by a single underscore character ‘_’. And one important thing is that each individual anonymous variable is treated as different. They are not same."
},
{
"code": null,
"e": 32604,
"s": 32536,
"text": "Now the question is, where should we use these anonymous variables?"
},
{
"code": null,
"e": 32988,
"s": 32604,
"text": "Suppose in our knowledge base we have some facts — “jim hates tom”, “pat hates bob”. So if tom wants to find out who hates him, then he can use variables. However, if he wants to check whether there is someone who hates him, we can use anonymous variables. So when we want to use the variable, but do not want to reveal the value of the variable, then we can use anonymous variables."
},
{
"code": null,
"e": 33033,
"s": 32988,
"text": "So let us see its practical implementation −"
},
{
"code": null,
"e": 33099,
"s": 33033,
"text": "hates(jim,tom).\nhates(pat,bob).\nhates(dog,fox).\nhates(peter,tom)."
},
{
"code": null,
"e": 33441,
"s": 33099,
"text": "| ?- [var_anonymous].\ncompiling D:/TP Prolog/Sample_Codes/var_anonymous.pl for byte code...\nD:/TP Prolog/Sample_Codes/var_anonymous.pl compiled, 3 lines read - 536 bytes written, 16 ms\n\nyes\n| ?- hates(X,tom).\n\nX = jim ? ;\n\nX = peter\n\nyes\n| ?- hates(_,tom).\n\ntrue ? ;\n\n(16 ms) yes\n| ?- hates(_,pat).\n\nno\n| ?- hates(_,fox).\n\ntrue ? ;\n\nno\n| ?-\n"
},
{
"code": null,
"e": 33593,
"s": 33441,
"text": "In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators."
},
{
"code": null,
"e": 33854,
"s": 33593,
"text": "We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators."
},
{
"code": null,
"e": 33967,
"s": 33854,
"text": "Comparison operators are used to compare two equations or states. Following are different comparison operators −"
},
{
"code": null,
"e": 34137,
"s": 33967,
"text": "You can see that the ‘=<’ operator, ‘=:=’ operator and ‘=\\=’ operators are syntactically different from other languages. Let us see some practical demonstration to this."
},
{
"code": null,
"e": 34259,
"s": 34137,
"text": "| ?- 1+2=:=2+1.\n\nyes\n| ?- 1+2=2+1.\n\nno\n| ?- 1+A=B+2.\n\nA = 2\nB = 1\n\nyes\n| ?- 5<10.\n\nyes\n| ?- 5>10.\n\nno\n| ?- 10=\\=100.\n\nyes"
},
{
"code": null,
"e": 34698,
"s": 34259,
"text": "Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern."
},
{
"code": null,
"e": 34829,
"s": 34698,
"text": "Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows −"
},
{
"code": null,
"e": 34903,
"s": 34829,
"text": "Let us see one practical code to understand the usage of these operators."
},
{
"code": null,
"e": 35312,
"s": 34903,
"text": "calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl,\n Y is 400 - 150,write('400 - 150 is '),write(Y),nl,\n Z is 10 * 300,write('10 * 300 is '),write(Z),nl,\n A is 100 / 30,write('100 / 30 is '),write(A),nl,\n B is 100 // 30,write('100 // 30 is '),write(B),nl,\n C is 100 ** 2,write('100 ** 2 is '),write(C),nl,\n D is 100 mod 30,write('100 mod 30 is '),write(D),nl."
},
{
"code": null,
"e": 35354,
"s": 35312,
"text": "Note − The nl is used to create new line."
},
{
"code": null,
"e": 35743,
"s": 35354,
"text": "| ?- change_directory('D:/TP Prolog/Sample_Codes').\n\nyes\n| ?- [op_arith].\ncompiling D:/TP Prolog/Sample_Codes/op_arith.pl for byte code...\nD:/TP Prolog/Sample_Codes/op_arith.pl compiled, 6 lines read - 2390 bytes written, 11 ms\n\nyes\n| ?- calc.\n100 + 200 is 300\n400 - 150 is 250\n10 * 300 is 3000\n100 / 30 is 3.3333333333333335\n100 // 30 is 3\n100 ** 2 is 10000.0\n100 mod 30 is 10\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 35813,
"s": 35743,
"text": "In this chapter, we will discuss loops and decision making in Prolog."
},
{
"code": null,
"e": 35979,
"s": 35813,
"text": "Loop statements are used to execute the code block multiple times. In general, for, while, do-while are loop constructs in programming languages (like Java, C, C++)."
},
{
"code": null,
"e": 36158,
"s": 35979,
"text": "Code block is executed multiple times using recursive predicate logic. There are no direct loops in some other languages, but we can simulate loops with few different techniques."
},
{
"code": null,
"e": 36259,
"s": 36158,
"text": "count_to_10(10) :- write(10),nl.\ncount_to_10(X) :-\n write(X),nl,\n Y is X + 1,\n count_to_10(Y)."
},
{
"code": null,
"e": 36486,
"s": 36259,
"text": "| ?- [loop].\ncompiling D:/TP Prolog/Sample_Codes/loop.pl for byte code...\nD:/TP Prolog/Sample_Codes/loop.pl compiled, 4 lines read - 751 bytes written, 16 ms\n\n(16 ms) yes\n| ?- count_to_10(3).\n3\n4\n5\n6\n7\n8\n9\n10\n\ntrue ?\nyes\n| ?-\n"
},
{
"code": null,
"e": 36590,
"s": 36486,
"text": "Now create a loop that takes lowest and highest values. So, we can use the between() to simulate loops."
},
{
"code": null,
"e": 36622,
"s": 36590,
"text": "Let us see an example program −"
},
{
"code": null,
"e": 36770,
"s": 36622,
"text": "count_down(L, H) :-\n between(L, H, Y),\n Z is H - Y,\n write(Z), nl.\n \ncount_up(L, H) :-\n between(L, H, Y),\n Z is L + Y,\n write(Z), nl."
},
{
"code": null,
"e": 37152,
"s": 36770,
"text": "| ?- [loop].\ncompiling D:/TP Prolog/Sample_Codes/loop.pl for byte code...\nD:/TP Prolog/Sample_Codes/loop.pl compiled, 14 lines read - 1700 bytes written, 16 ms\n\nyes\n| ?- count_down(12,17).\n5\n\ntrue ? ;\n4\n\ntrue ? ;\n3\n\ntrue ? ;\n2\n\ntrue ? ;\n1\n\ntrue ? ;\n0\n\nyes\n| ?- count_up(5,12).\n10\n\ntrue ? ;\n11\n\ntrue ? ;\n12\n\ntrue ? ;\n13\n\ntrue ? ;\n14\n\ntrue ? ;\n15\n\ntrue ? ;\n16\n\ntrue ? ;\n17\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 37344,
"s": 37152,
"text": "The decision statements are If-Then-Else statements. So when we try to match some condition, and perform some task, then we use the decision making statements. The basic usage is as follows −"
},
{
"code": null,
"e": 37391,
"s": 37344,
"text": "If <condition> is true, Then <do this>, Else \n"
},
{
"code": null,
"e": 37585,
"s": 37391,
"text": "In some different programming languages, there are If-Else statements, but in Prolog we have to define our statements in some other manner. Following is an example of decision making in Prolog."
},
{
"code": null,
"e": 37857,
"s": 37585,
"text": "% If-Then-Else statement\n\ngt(X,Y) :- X >= Y,write('X is greater or equal').\ngt(X,Y) :- X < Y,write('X is smaller').\n\n% If-Elif-Else statement\n\ngte(X,Y) :- X > Y,write('X is greater').\ngte(X,Y) :- X =:= Y,write('X and Y are same').\ngte(X,Y) :- X < Y,write('X is smaller')."
},
{
"code": null,
"e": 38250,
"s": 37857,
"text": "| ?- [test].\ncompiling D:/TP Prolog/Sample_Codes/test.pl for byte code...\nD:/TP Prolog/Sample_Codes/test.pl compiled, 3 lines read - 529 bytes written, 15 ms\n\nyes\n| ?- gt(10,100).\nX is smaller\n\nyes\n| ?- gt(150,100).\nX is greater or equal\n\ntrue ?\n\nyes\n| ?- gte(10,20).\nX is smaller\n\n(15 ms) yes\n| ?- gte(100,20).\nX is greater\n\ntrue ?\n\nyes\n| ?- gte(100,100).\nX and Y are same\n\ntrue ?\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 38453,
"s": 38250,
"text": "In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax."
},
{
"code": null,
"e": 38901,
"s": 38453,
"text": "Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male."
},
{
"code": null,
"e": 39342,
"s": 38901,
"text": "Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true."
},
{
"code": null,
"e": 39563,
"s": 39342,
"text": "parent(jhon,bob).\nparent(lili,bob).\n\nmale(jhon).\nfemale(lili).\n\n% Conjunction Logic\nfather(X,Y) :- parent(X,Y),male(X).\nmother(X,Y) :- parent(X,Y),female(X).\n\n% Disjunction Logic\nchild_of(X,Y) :- father(X,Y);mother(X,Y)."
},
{
"code": null,
"e": 39845,
"s": 39563,
"text": "| ?- [conj_disj].\ncompiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code...\nD:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read - 1513 bytes written, 24 ms\n\nyes\n| ?- father(jhon,bob).\n\nyes\n| ?- child_of(jhon,bob).\n\ntrue ?\n\nyes\n| ?- child_of(lili,bob).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 40069,
"s": 39845,
"text": "In this chapter, we will discuss one of the important concepts in Prolog, The Lists. It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection."
},
{
"code": null,
"e": 40136,
"s": 40069,
"text": "In the subsequent sections, we will discuss the following topics −"
},
{
"code": null,
"e": 40170,
"s": 40136,
"text": "Representation of lists in Prolog"
},
{
"code": null,
"e": 40204,
"s": 40170,
"text": "Representation of lists in Prolog"
},
{
"code": null,
"e": 40271,
"s": 40204,
"text": "Basic operations on prolog such as Insert, delete, update, append."
},
{
"code": null,
"e": 40338,
"s": 40271,
"text": "Basic operations on prolog such as Insert, delete, update, append."
},
{
"code": null,
"e": 40401,
"s": 40338,
"text": "Repositioning operators such as permutation, combination, etc."
},
{
"code": null,
"e": 40464,
"s": 40401,
"text": "Repositioning operators such as permutation, combination, etc."
},
{
"code": null,
"e": 40518,
"s": 40464,
"text": "Set operations like set union, set intersection, etc."
},
{
"code": null,
"e": 40572,
"s": 40518,
"text": "Set operations like set union, set intersection, etc."
},
{
"code": null,
"e": 40858,
"s": 40572,
"text": "The list is a simple data structure that is widely used in non-numeric programming. List consists of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with square brackets."
},
{
"code": null,
"e": 41036,
"s": 40858,
"text": "A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom, []. In the second case, the list consists of two things as given below −"
},
{
"code": null,
"e": 41081,
"s": 41036,
"text": "The first item, called the head of the list;"
},
{
"code": null,
"e": 41126,
"s": 41081,
"text": "The first item, called the head of the list;"
},
{
"code": null,
"e": 41175,
"s": 41126,
"text": "The remaining part of the list, called the tail."
},
{
"code": null,
"e": 41224,
"s": 41175,
"text": "The remaining part of the list, called the tail."
},
{
"code": null,
"e": 41376,
"s": 41224,
"text": "Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green, blue, white, dark]. So the tail is another list."
},
{
"code": null,
"e": 41569,
"s": 41376,
"text": "Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts."
},
{
"code": null,
"e": 41624,
"s": 41569,
"text": "So the following list representations are also valid −"
},
{
"code": null,
"e": 41650,
"s": 41624,
"text": "[a, b, c] = [x | [b, c] ]"
},
{
"code": null,
"e": 41676,
"s": 41650,
"text": "[a, b, c] = [x | [b, c] ]"
},
{
"code": null,
"e": 41702,
"s": 41676,
"text": "[a, b, c] = [a, b | [c] ]"
},
{
"code": null,
"e": 41728,
"s": 41702,
"text": "[a, b, c] = [a, b | [c] ]"
},
{
"code": null,
"e": 41757,
"s": 41728,
"text": "[a, b, c] = [a, b, c | [ ] ]"
},
{
"code": null,
"e": 41786,
"s": 41757,
"text": "[a, b, c] = [a, b, c | [ ] ]"
},
{
"code": null,
"e": 41835,
"s": 41786,
"text": "For these properties we can define the list as −"
},
{
"code": null,
"e": 41953,
"s": 41835,
"text": "A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has to be a list."
},
{
"code": null,
"e": 42015,
"s": 41953,
"text": "Following table contains various operations on prolog lists −"
},
{
"code": null,
"e": 42290,
"s": 42015,
"text": "During this operation, we can check whether a member X is present in list L or not? So how to check this? Well, we have to define one predicate to do so. Suppose the predicate name is list_member(X,L). The goal of this predicate is to check whether X is present in L or not."
},
{
"code": null,
"e": 42381,
"s": 42290,
"text": "To design this predicate, we can follow these observations. X is a member of L if either −"
},
{
"code": null,
"e": 42400,
"s": 42381,
"text": "X is head of L, or"
},
{
"code": null,
"e": 42419,
"s": 42400,
"text": "X is head of L, or"
},
{
"code": null,
"e": 42450,
"s": 42419,
"text": "X is a member of the tail of L"
},
{
"code": null,
"e": 42481,
"s": 42450,
"text": "X is a member of the tail of L"
},
{
"code": null,
"e": 42551,
"s": 42481,
"text": "list_member(X,[X|_]).\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL)."
},
{
"code": null,
"e": 42923,
"s": 42551,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 1 lines read - 467 bytes written, 13 ms\n\nyes\n| ?- list_member(b,[a,b,c]).\n\ntrue ?\n\nyes\n| ?- list_member(b,[a,[b,c]]).\n\nno\n| ?- list_member([b,c],[a,[b,c]]).\n\ntrue ?\n\nyes\n| ?- list_member(d,[a,b,c]).\n\nno\n| ?- list_member(d,[a,b,c]).\n"
},
{
"code": null,
"e": 43272,
"s": 42923,
"text": "This is used to find the length of list L. We will define one predicate to do this task. Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This will count the elements in a list L and instantiate N to their number. As was the case with our previous relations involving lists, it is useful to consider two cases −"
},
{
"code": null,
"e": 43308,
"s": 43272,
"text": "If list is empty, then length is 0."
},
{
"code": null,
"e": 43344,
"s": 43308,
"text": "If list is empty, then length is 0."
},
{
"code": null,
"e": 43431,
"s": 43344,
"text": "If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail."
},
{
"code": null,
"e": 43518,
"s": 43431,
"text": "If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail."
},
{
"code": null,
"e": 43599,
"s": 43518,
"text": "list_length([],0).\nlist_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1."
},
{
"code": null,
"e": 43946,
"s": 43599,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 4 lines read - 985 bytes written, 23 ms\n\nyes\n| ?- list_length([a,b,c,d,e,f,g,h,i,j],Len).\n\nLen = 10\n\nyes\n| ?- list_length([],Len).\n\nLen = 0\n\nyes\n| ?- list_length([[a,b],[c,d],[e,f]],Len).\n\nLen = 3\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 44300,
"s": 43946,
"text": "Concatenation of two lists means adding the list items of the second list after the first one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this task we will create one predicate called list_concat(), that will take first list L1, second list L2, and the L3 as resultant list. There are two observations here."
},
{
"code": null,
"e": 44385,
"s": 44300,
"text": "If the first list is empty, and second list is L, then the resultant list will be L."
},
{
"code": null,
"e": 44470,
"s": 44385,
"text": "If the first list is empty, and second list is L, then the resultant list will be L."
},
{
"code": null,
"e": 44626,
"s": 44470,
"text": "If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List]."
},
{
"code": null,
"e": 44782,
"s": 44626,
"text": "If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List]."
},
{
"code": null,
"e": 44861,
"s": 44782,
"text": "list_concat([],L,L).\nlist_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3)."
},
{
"code": null,
"e": 45276,
"s": 44861,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 7 lines read - 1367 bytes written, 19 ms\n\nyes\n| ?- list_concat([1,2],[a,b,c],NewList).\n\nNewList = [1,2,a,b,c]\n\nyes\n| ?- list_concat([],[a,b,c],NewList).\n\nNewList = [a,b,c]\n\nyes\n| ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList).\n\nNewList = [[1,2,3],[p,q,r],a,b,c]\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 45374,
"s": 45276,
"text": "Suppose we have a list L and an element X, we have to delete X from L. So there are three cases −"
},
{
"code": null,
"e": 45451,
"s": 45374,
"text": "If X is the only element, then after deleting it, it will return empty list."
},
{
"code": null,
"e": 45528,
"s": 45451,
"text": "If X is the only element, then after deleting it, it will return empty list."
},
{
"code": null,
"e": 45589,
"s": 45528,
"text": "If X is head of L, the resultant list will be the Tail part."
},
{
"code": null,
"e": 45650,
"s": 45589,
"text": "If X is head of L, the resultant list will be the Tail part."
},
{
"code": null,
"e": 45720,
"s": 45650,
"text": "If X is present in the Tail part, then delete from there recursively."
},
{
"code": null,
"e": 45790,
"s": 45720,
"text": "If X is present in the Tail part, then delete from there recursively."
},
{
"code": null,
"e": 45898,
"s": 45790,
"text": "list_delete(X, [X], []).\nlist_delete(X,[X|L1], L1).\nlist_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1)."
},
{
"code": null,
"e": 46271,
"s": 45898,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 11 lines read - 1923 bytes written, 25 ms\n\nyes\n| ?- list_delete(a,[a,e,i,o,u],NewList).\n\nNewList = [e,i,o,u] ?\n\nyes\n| ?- list_delete(a,[a],NewList).\n\nNewList = [] ?\n\nyes\n| ?- list_delete(X,[a,e,i,o,u],[a,e,o,u]).\n\nX = i ? ;\n\nno\n| ?-\n"
},
{
"code": null,
"e": 46538,
"s": 46271,
"text": "Appending two lists means adding two lists together, or adding one list as an item. Now if the item is present in the list, then the append function will not work. So we will create one predicate namely, list_append(L1, L2, L3). The following are some observations −"
},
{
"code": null,
"e": 46624,
"s": 46538,
"text": "Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already."
},
{
"code": null,
"e": 46710,
"s": 46624,
"text": "Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already."
},
{
"code": null,
"e": 46750,
"s": 46710,
"text": "Otherwise new list will be L2 = [A|L1]."
},
{
"code": null,
"e": 46790,
"s": 46750,
"text": "Otherwise new list will be L2 = [A|L1]."
},
{
"code": null,
"e": 46927,
"s": 46790,
"text": "list_member(X,[X|_]).\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL).\n\nlist_append(A,T,T) :- list_member(A,T),!.\nlist_append(A,T,[A|T])."
},
{
"code": null,
"e": 47096,
"s": 46927,
"text": "In this case, we have used (!) symbol, that is known as cut. So when the first line is executed successfully, then we cut it, so it will not execute the next operation."
},
{
"code": null,
"e": 47503,
"s": 47096,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 14 lines read - 2334 bytes written, 25 ms\n\n(16 ms) yes\n| ?- list_append(a,[e,i,o,u],NewList).\n\nNewList = [a,e,i,o,u]\n\nyes\n| ?- list_append(e,[e,i,o,u],NewList).\n\nNewList = [e,i,o,u]\n\nyes\n| ?- list_append([a,b],[e,i,o,u],NewList).\n\nNewList = [[a,b],e,i,o,u]\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 47757,
"s": 47503,
"text": "This method is used to insert an item X into list L, and the resultant list will be R. So the predicate will be in this form list_insert(X, L, R). So this can insert X into L in all possible positions. If we see closer, then there are some observations."
},
{
"code": null,
"e": 47862,
"s": 47757,
"text": "If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make new list L."
},
{
"code": null,
"e": 47967,
"s": 47862,
"text": "If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make new list L."
},
{
"code": null,
"e": 48118,
"s": 47967,
"text": "list_delete(X, [X], []).\nlist_delete(X,[X|L1], L1).\nlist_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).\n\nlist_insert(X,L,R) :- list_delete(X,R,L)."
},
{
"code": null,
"e": 48511,
"s": 48118,
"text": "| ?- [list_basics].\ncompiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_basics.pl compiled, 16 lines read - 2558 bytes written, 22 ms\n\n(16 ms) yes\n| ?- list_insert(a,[e,i,o,u],NewList).\n\nNewList = [a,e,i,o,u] ? a\n\nNewList = [e,a,i,o,u]\n\nNewList = [e,i,a,o,u]\n\nNewList = [e,i,o,a,u]\n\nNewList = [e,i,o,u,a]\n\nNewList = [e,i,o,u,a]\n\n(15 ms) no\n| ?-\n"
},
{
"code": null,
"e": 48552,
"s": 48511,
"text": "Following are repositioning operations −"
},
{
"code": null,
"e": 48807,
"s": 48552,
"text": "This operation will change the list item positions and generate all possible outcomes. So we will create one predicate as list_perm(L1,L2), This will generate all permutation of L1, and store them into L2. To do this we need list_delete() clause to help."
},
{
"code": null,
"e": 48881,
"s": 48807,
"text": "To design this predicate, we can follow few observations as given below −"
},
{
"code": null,
"e": 48910,
"s": 48881,
"text": "X is member of L if either −"
},
{
"code": null,
"e": 48979,
"s": 48910,
"text": "If the first list is empty, then the second list must also be empty."
},
{
"code": null,
"e": 49048,
"s": 48979,
"text": "If the first list is empty, then the second list must also be empty."
},
{
"code": null,
"e": 49237,
"s": 49048,
"text": "If the first list is not empty then it has the form [X | L], and a permutation of such a list can be constructed as, first permute L obtaining L1 and then insert X at any position into L1."
},
{
"code": null,
"e": 49426,
"s": 49237,
"text": "If the first list is not empty then it has the form [X | L], and a permutation of such a list can be constructed as, first permute L obtaining L1 and then insert X at any position into L1."
},
{
"code": null,
"e": 49587,
"s": 49426,
"text": "list_delete(X,[X|L1], L1).\nlist_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).\n\nlist_perm([],[]).\nlist_perm(L,[X|P]) :- list_delete(X,L,L1),list_perm(L1,P)."
},
{
"code": null,
"e": 50188,
"s": 49587,
"text": "| ?- [list_repos].\ncompiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_repos.pl compiled, 4 lines read - 1060 bytes written, 17 ms\n\n(15 ms) yes\n| ?- list_perm([a,b,c,d],X).\n\nX = [a,b,c,d] ? a\n\nX = [a,b,d,c]\n\nX = [a,c,b,d]\n\nX = [a,c,d,b]\n\nX = [a,d,b,c]\n\nX = [a,d,c,b]\n\nX = [b,a,c,d]\n\nX = [b,a,d,c]\n\nX = [b,c,a,d]\n\nX = [b,c,d,a]\n\nX = [b,d,a,c]\n\nX = [b,d,c,a]\n\nX = [c,a,b,d]\n\nX = [c,a,d,b]\n\nX = [c,b,a,d]\n\nX = [c,b,d,a]\n\nX = [c,d,a,b]\n\nX = [c,d,b,a]\n\nX = [d,a,b,c]\n\nX = [d,a,c,b]\n\nX = [d,b,a,c]\n\nX = [d,b,c,a]\n\nX = [d,c,a,b]\n\nX = [d,c,b,a]\n\n(31 ms) no\n| ?-\n"
},
{
"code": null,
"e": 50405,
"s": 50188,
"text": "Suppose we have a list L = [a,b,c,d,e], and we want to reverse the elements, so the output will be [e,d,c,b,a]. To do this, we will create a clause, list_reverse(List, ReversedList). Following are some observations −"
},
{
"code": null,
"e": 50471,
"s": 50405,
"text": "If the list is empty, then the resultant list will also be empty."
},
{
"code": null,
"e": 50537,
"s": 50471,
"text": "If the list is empty, then the resultant list will also be empty."
},
{
"code": null,
"e": 50658,
"s": 50537,
"text": "Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head."
},
{
"code": null,
"e": 50779,
"s": 50658,
"text": "Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head."
},
{
"code": null,
"e": 50900,
"s": 50779,
"text": "Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head."
},
{
"code": null,
"e": 51021,
"s": 50900,
"text": "Otherwise put the list items namely, [Head|Tail], and reverse the Tail items recursively, and concatenate with the Head."
},
{
"code": null,
"e": 51218,
"s": 51021,
"text": "list_concat([],L,L).\nlist_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).\n\nlist_rev([],[]).\nlist_rev([Head|Tail],Reversed) :-\n list_rev(Tail, RevTail),list_concat(RevTail, [Head],Reversed)."
},
{
"code": null,
"e": 51516,
"s": 51218,
"text": "| ?- [list_repos].\ncompiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_repos.pl compiled, 10 lines read - 1977 bytes written, 19 ms\n\nyes\n| ?- list_rev([a,b,c,d,e],NewList).\n\nNewList = [e,d,c,b,a]\n\nyes\n| ?- list_rev([a,b,c,d,e],[e,d,c,b,a]).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 51724,
"s": 51516,
"text": "Using Shift operation, we can shift one element of a list to the left rotationally. So if the list items are [a,b,c,d], then after shifting, it will be [b,c,d,a]. So we will make a clause list_shift(L1, L2)."
},
{
"code": null,
"e": 51873,
"s": 51724,
"text": "We will express the list as [Head|Tail], then recursively concatenate Head after the Tail, so as a result we can feel that the elements are shifted."
},
{
"code": null,
"e": 52022,
"s": 51873,
"text": "We will express the list as [Head|Tail], then recursively concatenate Head after the Tail, so as a result we can feel that the elements are shifted."
},
{
"code": null,
"e": 52111,
"s": 52022,
"text": "This can also be used to check whether the two lists are shifted at one position or not."
},
{
"code": null,
"e": 52200,
"s": 52111,
"text": "This can also be used to check whether the two lists are shifted at one position or not."
},
{
"code": null,
"e": 52350,
"s": 52200,
"text": "list_concat([],L,L).\nlist_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).\n\nlist_shift([Head|Tail],Shifted) :- list_concat(Tail, [Head],Shifted)."
},
{
"code": null,
"e": 52650,
"s": 52350,
"text": "| ?- [list_repos].\ncompiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_repos.pl compiled, 12 lines read - 2287 bytes written, 10 ms\n\nyes\n| ?- list_shift([a,b,c,d,e],L2).\n\nL2 = [b,c,d,e,a]\n\n(16 ms) yes\n| ?- list_shift([a,b,c,d,e],[b,c,d,e,a]).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 52793,
"s": 52650,
"text": "Here we will define a predicate list_order(L) which checks whether L is ordered or not. So if L = [1,2,3,4,5,6], then the result will be true."
},
{
"code": null,
"e": 52848,
"s": 52793,
"text": "If there is only one element, that is already ordered."
},
{
"code": null,
"e": 52903,
"s": 52848,
"text": "If there is only one element, that is already ordered."
},
{
"code": null,
"e": 53093,
"s": 52903,
"text": "Otherwise take first two elements X and Y as Head, and rest as Tail. If X =< Y, then call the clause again with the parameter [Y|Tail], so this will recursively check from the next element."
},
{
"code": null,
"e": 53283,
"s": 53093,
"text": "Otherwise take first two elements X and Y as Head, and rest as Tail. If X =< Y, then call the clause again with the parameter [Y|Tail], so this will recursively check from the next element."
},
{
"code": null,
"e": 53359,
"s": 53283,
"text": "list_order([X, Y | Tail]) :- X =< Y, list_order([Y|Tail]).\nlist_order([X])."
},
{
"code": null,
"e": 53731,
"s": 53359,
"text": "| ?- [list_repos].\ncompiling D:/TP Prolog/Sample_Codes/list_repos.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_repos.pl:15: warning: singleton variables [X] for list_order/1\nD:/TP Prolog/Sample_Codes/list_repos.pl compiled, 15 lines read - 2805 bytes written, 18 ms\n\nyes\n| ?- list_order([1,2,3,4,5,6,6,7,7,8]).\n\ntrue ?\n\nyes\n| ?- list_order([1,4,2,3,6,5]).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 54026,
"s": 53731,
"text": "We will try to write a clause that will get all possible subsets of a given set. So if the set is [a,b], then the result will be [], [a], [b], [a,b]. To do so, we will create one clause, list_subset(L, X). It will take L and return each subsets into X. So we will proceed in the following way −"
},
{
"code": null,
"e": 54070,
"s": 54026,
"text": "If list is empty, the subset is also empty."
},
{
"code": null,
"e": 54114,
"s": 54070,
"text": "If list is empty, the subset is also empty."
},
{
"code": null,
"e": 54169,
"s": 54114,
"text": "Find the subset recursively by retaining the Head, and"
},
{
"code": null,
"e": 54224,
"s": 54169,
"text": "Find the subset recursively by retaining the Head, and"
},
{
"code": null,
"e": 54279,
"s": 54224,
"text": "Make another recursive call where we will remove Head."
},
{
"code": null,
"e": 54334,
"s": 54279,
"text": "Make another recursive call where we will remove Head."
},
{
"code": null,
"e": 54483,
"s": 54334,
"text": "list_subset([],[]).\nlist_subset([Head|Tail],[Head|Subset]) :- list_subset(Tail,Subset).\nlist_subset([Head|Tail],Subset) :- list_subset(Tail,Subset)."
},
{
"code": null,
"e": 54966,
"s": 54483,
"text": "| ?- [list_set].\ncompiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_set.pl:3: warning: singleton variables [Head] for list_subset/2\nD:/TP Prolog/Sample_Codes/list_set.pl compiled, 2 lines read - 653 bytes written, 7 ms\n\nyes\n| ?- list_subset([a,b],X).\n\nX = [a,b] ? ;\n\nX = [a] ? ;\n\nX = [b] ? ;\n\nX = []\n\n(15 ms) yes\n| ?- list_subset([x,y,z],X).\n\nX = [x,y,z] ? a\n\nX = [x,y]\n\nX = [x,z]\n\nX = [x]\n\nX = [y,z]\n\nX = [y]\n\nX = [z]\n\nX = []\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 55258,
"s": 54966,
"text": "Let us define a clause called list_union(L1,L2,L3), So this will take L1 and L2, and perform Union on them, and store the result into L3. As you know if two lists have the same element twice, then after union, there will be only one. So we need another helper clause to check the membership."
},
{
"code": null,
"e": 55479,
"s": 55258,
"text": "list_member(X,[X|_]).\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL).\n\nlist_union([X|Y],Z,W) :- list_member(X,Z),list_union(Y,Z,W).\nlist_union([X|Y],Z,[X|W]) :- \\+ list_member(X,Z), list_union(Y,Z,W).\nlist_union([],Z,Z)."
},
{
"code": null,
"e": 55561,
"s": 55479,
"text": "Note − In the program, we have used (\\+) operator, this operator is used for NOT."
},
{
"code": null,
"e": 55984,
"s": 55561,
"text": "| ?- [list_set].\ncompiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_set.pl:6: warning: singleton variables [Head] for list_subset/2\nD:/TP Prolog/Sample_Codes/list_set.pl compiled, 9 lines read - 2004 bytes written, 18 ms\n\nyes\n| ?- list_union([a,b,c,d,e],[a,e,i,o,u],L3).\n\nL3 = [b,c,d,a,e,i,o,u] ?\n\n(16 ms) yes\n\n| ?- list_union([a,b,c,d,e],[1,2],L3).\n\nL3 = [a,b,c,d,e,1,2]\n\nyes\n"
},
{
"code": null,
"e": 56362,
"s": 55984,
"text": "Let us define a clause called list_intersection(L1,L2,L3), So this will take L1 and L2, and perform Intersection operation, and store the result into L3. Intersection will return those elements that are present in both lists. So L1 = [a,b,c,d,e], L2 = [a,e,i,o,u], then L3 = [a,e]. Here, we will use the list_member() clause to check if one element is present in a list or not."
},
{
"code": null,
"e": 56611,
"s": 56362,
"text": "list_member(X,[X|_]).\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL).\n\nlist_intersect([X|Y],Z,[X|W]) :-\n list_member(X,Z), list_intersect(Y,Z,W).\nlist_intersect([X|Y],Z,W) :-\n \\+ list_member(X,Z), list_intersect(Y,Z,W).\nlist_intersect([],Z,[])."
},
{
"code": null,
"e": 56923,
"s": 56611,
"text": "| ?- [list_set].\ncompiling D:/TP Prolog/Sample_Codes/list_set.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_set.pl compiled, 13 lines read - 3054 bytes written, 9 ms\n\n(15 ms) yes\n| ?- list_intersect([a,b,c,d,e],[a,e,i,o,u],L3).\n\nL3 = [a,e] ?\n\nyes\n| ?- list_intersect([a,b,c,d,e],[],L3).\n\nL3 = []\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 57000,
"s": 56923,
"text": "Following are some miscellaneous operations that can be performed on lists −"
},
{
"code": null,
"e": 57217,
"s": 57000,
"text": "In this example, we will see two operations using which we can check whether the list has odd number of elements or the even number of elements. We will define predicates namely, list_even_len(L) and list_odd_len(L)."
},
{
"code": null,
"e": 57277,
"s": 57217,
"text": "If the list has no elements, then that is even length list."
},
{
"code": null,
"e": 57337,
"s": 57277,
"text": "If the list has no elements, then that is even length list."
},
{
"code": null,
"e": 57448,
"s": 57337,
"text": "Otherwise we take it as [Head|Tail], then if Tail is of odd length, then the total list is even length string."
},
{
"code": null,
"e": 57559,
"s": 57448,
"text": "Otherwise we take it as [Head|Tail], then if Tail is of odd length, then the total list is even length string."
},
{
"code": null,
"e": 57634,
"s": 57559,
"text": "Similarly, if the list has only one element, then that is odd length list."
},
{
"code": null,
"e": 57709,
"s": 57634,
"text": "Similarly, if the list has only one element, then that is odd length list."
},
{
"code": null,
"e": 57806,
"s": 57709,
"text": "By taking it as [Head|Tail] and Tail is even length string, then entire list is odd length list."
},
{
"code": null,
"e": 57903,
"s": 57806,
"text": "By taking it as [Head|Tail] and Tail is even length string, then entire list is odd length list."
},
{
"code": null,
"e": 58042,
"s": 57903,
"text": "list_even_len([]).\nlist_even_len([Head|Tail]) :- list_odd_len(Tail).\n\nlist_odd_len([_]).\nlist_odd_len([Head|Tail]) :- list_even_len(Tail)."
},
{
"code": null,
"e": 58581,
"s": 58042,
"text": "| ?- [list_misc].\ncompiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl compiled, 4 lines read - 726 bytes written, 20 ms\n\nyes\n| ?- list_odd_len([a,2,b,3,c]).\n\ntrue ?\n\nyes\n| ?- list_odd_len([a,2,b,3]).\n\nno\n| ?- list_even_len([a,2,b,3]).\n\ntrue ?\n\nyes\n| ?- list_even_len([a,2,b,3,c]).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 58933,
"s": 58581,
"text": "This operation divides a list into two lists, and these lists are of approximately same length. So if the given list is [a,b,c,d,e], then the result will be [a,c,e],[b,d]. This will place all of the odd placed elements into one list, and all even placed elements into another list. We will define a predicate, list_divide(L1,L2,L3) to solve this task."
},
{
"code": null,
"e": 58990,
"s": 58933,
"text": "If given list is empty, then it will return empty lists."
},
{
"code": null,
"e": 59047,
"s": 58990,
"text": "If given list is empty, then it will return empty lists."
},
{
"code": null,
"e": 59166,
"s": 59047,
"text": "If there is only one element, then the first list will be a list with that element, and the second list will be empty."
},
{
"code": null,
"e": 59285,
"s": 59166,
"text": "If there is only one element, then the first list will be a list with that element, and the second list will be empty."
},
{
"code": null,
"e": 59438,
"s": 59285,
"text": "Suppose X,Y are two elements from head, and rest are Tail, So make two lists [X|List1], [Y|List2], these List1 and List2 are separated by dividing Tail."
},
{
"code": null,
"e": 59591,
"s": 59438,
"text": "Suppose X,Y are two elements from head, and rest are Tail, So make two lists [X|List1], [Y|List2], these List1 and List2 are separated by dividing Tail."
},
{
"code": null,
"e": 59721,
"s": 59591,
"text": "list_divide([],[],[]).\nlist_divide([X],[X],[]).\nlist_divide([X,Y|Tail], [X|List1],[Y|List2]) :-\n list_divide(Tail,List1,List2)."
},
{
"code": null,
"e": 60248,
"s": 59721,
"text": "| ?- [list_misc].\ncompiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl compiled, 8 lines read - 1432 bytes written, 8 ms\n\nyes\n| ?- list_divide([a,1,b,2,c,3,d,5,e],L1,L2).\n\nL1 = [a,b,c,d,e]\nL2 = [1,2,3,5] ?\n\nyes\n| ?- list_divide([a,b,c,d],L1,L2).\n\nL1 = [a,c]\nL2 = [b,d]\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 60424,
"s": 60248,
"text": "This operation is used to find the maximum element from a list. We will define a predicate, list_max_elem(List, Max), then this will find Max element from the list and return."
},
{
"code": null,
"e": 60487,
"s": 60424,
"text": "If there is only one element, then it will be the max element."
},
{
"code": null,
"e": 60550,
"s": 60487,
"text": "If there is only one element, then it will be the max element."
},
{
"code": null,
"e": 60703,
"s": 60550,
"text": "Divide the list as [X,Y|Tail]. Now recursively find max of [Y|Tail] and store it into MaxRest, and store maximum of X and MaxRest, then store it to Max."
},
{
"code": null,
"e": 60856,
"s": 60703,
"text": "Divide the list as [X,Y|Tail]. Now recursively find max of [Y|Tail] and store it into MaxRest, and store maximum of X and MaxRest, then store it to Max."
},
{
"code": null,
"e": 61034,
"s": 60856,
"text": "max_of_two(X,Y,X) :- X >= Y.\nmax_of_two(X,Y,Y) :- X < Y.\nlist_max_elem([X],X).\nlist_max_elem([X,Y|Rest],Max) :-\n list_max_elem([Y|Rest],MaxRest),\n max_of_two(X,MaxRest,Max)."
},
{
"code": null,
"e": 61536,
"s": 61034,
"text": "| ?- [list_misc].\ncompiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl compiled, 16 lines read - 2385 bytes written, 16 ms\n\nyes\n| ?- list_max_elem([8,5,3,4,7,9,6,1],Max).\n\nMax = 9 ?\n\nyes\n| ?- list_max_elem([5,12,69,112,48,4],Max).\n\nMax = 112 ?\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 61653,
"s": 61536,
"text": "In this example, we will define a clause, list_sum(List, Sum), this will return the sum of the elements of the list."
},
{
"code": null,
"e": 61695,
"s": 61653,
"text": "If the list is empty, then sum will be 0."
},
{
"code": null,
"e": 61737,
"s": 61695,
"text": "If the list is empty, then sum will be 0."
},
{
"code": null,
"e": 61857,
"s": 61737,
"text": "Represent list as [Head|Tail], find sum of tail recursively and store them into SumTemp, then set Sum = Head + SumTemp."
},
{
"code": null,
"e": 61977,
"s": 61857,
"text": "Represent list as [Head|Tail], find sum of tail recursively and store them into SumTemp, then set Sum = Head + SumTemp."
},
{
"code": null,
"e": 62076,
"s": 61977,
"text": "list_sum([],0).\nlist_sum([Head|Tail], Sum) :-\n list_sum(Tail,SumTemp),\n Sum is Head + SumTemp."
},
{
"code": null,
"e": 62577,
"s": 62076,
"text": "yes\n| ?- [list_misc].\ncompiling D:/TP Prolog/Sample_Codes/list_misc.pl for byte code...\nD:/TP Prolog/Sample_Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl:5: warning: singleton variables [Head] for list_odd_len/1\nD:/TP Prolog/Sample_Codes/list_misc.pl compiled, 21 lines read - 2897 bytes written, 21 ms\n\n(32 ms) yes\n| ?- list_sum([5,12,69,112,48,4],Sum).\n\nSum = 250\n\nyes\n| ?- list_sum([8,5,3,4,7,9,6,1],Sum).\n\nSum = 43\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 62703,
"s": 62577,
"text": "If the list is [4,5,3,7,8,1,2], then the result will be [1,2,3,4,5,7,8]. The steps of performing merge sort are shown below −"
},
{
"code": null,
"e": 62794,
"s": 62703,
"text": "Take the list and split them into two sub-lists. This split will be performed recursively."
},
{
"code": null,
"e": 62885,
"s": 62794,
"text": "Take the list and split them into two sub-lists. This split will be performed recursively."
},
{
"code": null,
"e": 62919,
"s": 62885,
"text": "Merge each split in sorted order."
},
{
"code": null,
"e": 62953,
"s": 62919,
"text": "Merge each split in sorted order."
},
{
"code": null,
"e": 62990,
"s": 62953,
"text": "Thus the entire list will be sorted."
},
{
"code": null,
"e": 63027,
"s": 62990,
"text": "Thus the entire list will be sorted."
},
{
"code": null,
"e": 63121,
"s": 63027,
"text": "We will define a predicate called mergesort(L, SL), it will take L and return result into SL."
},
{
"code": null,
"e": 63540,
"s": 63121,
"text": "mergesort([],[]). /* covers special case */\nmergesort([A],[A]).\nmergesort([A,B|R],S) :-\n split([A,B|R],L1,L2),\n mergesort(L1,S1),\n mergesort(L2,S2),\n merge(S1,S2,S).\n \nsplit([],[],[]).\nsplit([A],[A],[]).\nsplit([A,B|R],[A|Ra],[B|Rb]) :-\n split(R,Ra,Rb).\nmerge(A,[],A).\nmerge([],B,B).\nmerge([A|Ra],[B|Rb],[A|M]) :-\n A =< B, merge(Ra,[B|Rb],M).\nmerge([A|Ra],[B|Rb],[B|M]) :-\n A > B, merge([A|Ra],Rb,M)."
},
{
"code": null,
"e": 63859,
"s": 63540,
"text": "| ?- [merge_sort].\ncompiling D:/TP Prolog/Sample_Codes/merge_sort.pl for byte code...\nD:/TP Prolog/Sample_Codes/merge_sort.pl compiled, 17 lines read - 3048 bytes written, 19 ms\n\nyes\n| ?- mergesort([4,5,3,7,8,1,2],L).\n\nL = [1,2,3,4,5,7,8] ?\n\nyes\n| ?- mergesort([8,5,3,4,7,9,6,1],L).\n\nL = [1,3,4,5,6,7,8,9] ?\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 63905,
"s": 63859,
"text": "This chapter covers recursion and structures."
},
{
"code": null,
"e": 64026,
"s": 63905,
"text": "Recursion is a technique in which one predicate uses itself (may be with some other predicates) to find the truth value."
},
{
"code": null,
"e": 64090,
"s": 64026,
"text": "Let us understand this definition with the help of an example −"
},
{
"code": null,
"e": 64126,
"s": 64090,
"text": "is_digesting(X,Y) :- just_ate(X,Y)."
},
{
"code": null,
"e": 64162,
"s": 64126,
"text": "is_digesting(X,Y) :- just_ate(X,Y)."
},
{
"code": null,
"e": 64215,
"s": 64162,
"text": "is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y)."
},
{
"code": null,
"e": 64268,
"s": 64215,
"text": "is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y)."
},
{
"code": null,
"e": 64600,
"s": 64268,
"text": "So this predicate is recursive in nature. Suppose we say that just_ate(deer, grass), it means is_digesting(deer, grass) is true. Now if we say is_digesting(tiger, grass), this will be true if is_digesting(tiger, grass) :- just_ate(tiger, deer), is_digesting(deer, grass), then the statement is_digesting(tiger, grass) is also true."
},
{
"code": null,
"e": 64773,
"s": 64600,
"text": "There may be some other examples also, so let us see one family example. So if we want to express the predecessor logic, that can be expressed using the following diagram −"
},
{
"code": null,
"e": 64899,
"s": 64773,
"text": "So we can understand the predecessor relationship is recursive. We can express this relationship using the following syntax −"
},
{
"code": null,
"e": 64934,
"s": 64899,
"text": "predecessor(X, Z) :- parent(X, Z)."
},
{
"code": null,
"e": 64969,
"s": 64934,
"text": "predecessor(X, Z) :- parent(X, Z)."
},
{
"code": null,
"e": 65022,
"s": 64969,
"text": "predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z)."
},
{
"code": null,
"e": 65075,
"s": 65022,
"text": "predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z)."
},
{
"code": null,
"e": 65137,
"s": 65075,
"text": "Structures are Data Objects that contain multiple components."
},
{
"code": null,
"e": 65302,
"s": 65137,
"text": "For example, the date can be viewed as a structure with three components — day, month and year. Then the date 9th April, 2020 can be written as: date(9, apr, 2020)."
},
{
"code": null,
"e": 65376,
"s": 65302,
"text": "Note − Structure can in turn have another structure as a component in it."
},
{
"code": null,
"e": 65435,
"s": 65376,
"text": "So we can see views as tree structure and Prolog Functors."
},
{
"code": null,
"e": 65562,
"s": 65435,
"text": "Now let us see one example of structures in Prolog. We will define a structure of points, Segments and Triangle as structures."
},
{
"code": null,
"e": 65680,
"s": 65562,
"text": "To represent a point, a line segment and a triangle using structure in Prolog, we can consider following statements −"
},
{
"code": null,
"e": 65697,
"s": 65680,
"text": "p1 − point(1, 1)"
},
{
"code": null,
"e": 65714,
"s": 65697,
"text": "p1 − point(1, 1)"
},
{
"code": null,
"e": 65730,
"s": 65714,
"text": "p2 − point(2,3)"
},
{
"code": null,
"e": 65746,
"s": 65730,
"text": "p2 − point(2,3)"
},
{
"code": null,
"e": 65793,
"s": 65746,
"text": "S − seg( Pl, P2): seg( point(1,1), point(2,3))"
},
{
"code": null,
"e": 65840,
"s": 65793,
"text": "S − seg( Pl, P2): seg( point(1,1), point(2,3))"
},
{
"code": null,
"e": 65891,
"s": 65840,
"text": "T − triangle( point(4,Z), point(6,4), point(7,1) )"
},
{
"code": null,
"e": 65942,
"s": 65891,
"text": "T − triangle( point(4,Z), point(6,4), point(7,1) )"
},
{
"code": null,
"e": 66053,
"s": 65942,
"text": "Note − Structures can be naturally pictured as trees. Prolog can be viewed as a language for processing trees."
},
{
"code": null,
"e": 66231,
"s": 66053,
"text": "Matching is used to check whether two given terms are same (identical) or the variables in both terms can have the same objects after being instantiated. Let us see one example."
},
{
"code": null,
"e": 66354,
"s": 66231,
"text": "Suppose date structure is defined as date(D,M,2020) = date(D1,apr, Y1), this indicates that D = D1, M = feb and Y1 = 2020."
},
{
"code": null,
"e": 66428,
"s": 66354,
"text": "Following rules are to be used to check whether two terms S and T match −"
},
{
"code": null,
"e": 66484,
"s": 66428,
"text": "If S and T are constants, S=T if both are same objects."
},
{
"code": null,
"e": 66540,
"s": 66484,
"text": "If S and T are constants, S=T if both are same objects."
},
{
"code": null,
"e": 66583,
"s": 66540,
"text": "If S is a variable and T is anything, T=S."
},
{
"code": null,
"e": 66626,
"s": 66583,
"text": "If S is a variable and T is anything, T=S."
},
{
"code": null,
"e": 66667,
"s": 66626,
"text": "If T is variable and S is anything, S=T."
},
{
"code": null,
"e": 66708,
"s": 66667,
"text": "If T is variable and S is anything, S=T."
},
{
"code": null,
"e": 66834,
"s": 66708,
"text": "If S and T are structures, S=T if −\n\nS and T have same functor.\nAll their corresponding arguments components have to match.\n\n"
},
{
"code": null,
"e": 66870,
"s": 66834,
"text": "If S and T are structures, S=T if −"
},
{
"code": null,
"e": 66897,
"s": 66870,
"text": "S and T have same functor."
},
{
"code": null,
"e": 66924,
"s": 66897,
"text": "S and T have same functor."
},
{
"code": null,
"e": 66984,
"s": 66924,
"text": "All their corresponding arguments components have to match."
},
{
"code": null,
"e": 67044,
"s": 66984,
"text": "All their corresponding arguments components have to match."
},
{
"code": null,
"e": 67115,
"s": 67044,
"text": "Following is the structure of binary tree using recursive structures −"
},
{
"code": null,
"e": 67163,
"s": 67115,
"text": "The definition of the structure is as follows −"
},
{
"code": null,
"e": 67255,
"s": 67163,
"text": "node(2, node(1,nil,nil), node(6, node(4,node(3,nil,nil), node(5,nil,nil)), node(7,nil,nil))"
},
{
"code": null,
"e": 67598,
"s": 67255,
"text": "Each node has three fields, data and two nodes. One node with no child (leaf node) structure is written as node(value, nil, nil), node with only one left child is written as node(value, left_node, nil), node with only one right child is written as node(value, nil; right_node), and node with both child has node(value, left_node, right_node)."
},
{
"code": null,
"e": 68015,
"s": 67598,
"text": "In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops."
},
{
"code": null,
"e": 68087,
"s": 68015,
"text": "Let us see how backtracking takes place using one tree like structure −"
},
{
"code": null,
"e": 68552,
"s": 68087,
"text": "Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops."
},
{
"code": null,
"e": 68625,
"s": 68552,
"text": "Now we know, what is the backtracking in Prolog. Let us see one example,"
},
{
"code": null,
"e": 68854,
"s": 68625,
"text": "Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop."
},
{
"code": null,
"e": 69071,
"s": 68854,
"text": "Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules −"
},
{
"code": null,
"e": 69146,
"s": 69071,
"text": "boy(tom).\nboy(bob).\ngirl(alice).\ngirl(lili).\n\npay(X,Y) :- boy(X), girl(Y)."
},
{
"code": null,
"e": 69200,
"s": 69146,
"text": "Following is the illustration of the above scenario −"
},
{
"code": null,
"e": 69357,
"s": 69200,
"text": "As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working."
},
{
"code": null,
"e": 70452,
"s": 69357,
"text": "| ?- [backtrack].\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read - 703 bytes written, 22 ms\n\nyes\n| ?- pay(X,Y).\n\nX = tom\nY = alice ?\n\n(15 ms) yes\n| ?- pay(X,Y).\n\nX = tom\nY = alice ? ;\n\nX = tom\nY = lili ? ;\n\nX = bob\nY = alice ? ;\n\nX = bob\nY = lili\n\nyes\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\n(16 ms) yes\n{trace}\n| ?- pay(X,Y).\n 1 1 Call: pay(_23,_24) ?\n 2 2 Call: boy(_23) ?\n 2 2 Exit: boy(tom) ?\n 3 2 Call: girl(_24) ?\n 3 2 Exit: girl(alice) ?\n 1 1 Exit: pay(tom,alice) ?\n \nX = tom\nY = alice ? ;\n 1 1 Redo: pay(tom,alice) ?\n 3 2 Redo: girl(alice) ?\n 3 2 Exit: girl(lili) ?\n 1 1 Exit: pay(tom,lili) ?\n \nX = tom\nY = lili ? ;\n 1 1 Redo: pay(tom,lili) ?\n 2 2 Redo: boy(tom) ?\n 2 2 Exit: boy(bob) ?\n 3 2 Call: girl(_24) ?\n 3 2 Exit: girl(alice) ?\n 1 1 Exit: pay(bob,alice) ?\n \nX = bob\nY = alice ? ;\n 1 1 Redo: pay(bob,alice) ?\n 3 2 Redo: girl(alice) ?\n 3 2 Exit: girl(lili) ?\n 1 1 Exit: pay(bob,lili) ?\nX = bob\nY = lili\n\nyes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 70833,
"s": 70452,
"text": "So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog."
},
{
"code": null,
"e": 70873,
"s": 70833,
"text": "Suppose we have some rules as follows −"
},
{
"code": null,
"e": 70909,
"s": 70873,
"text": "Rule 1 &minnus; if X < 3 then Y = 0"
},
{
"code": null,
"e": 70945,
"s": 70909,
"text": "Rule 1 &minnus; if X < 3 then Y = 0"
},
{
"code": null,
"e": 70992,
"s": 70945,
"text": "Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2"
},
{
"code": null,
"e": 71039,
"s": 70992,
"text": "Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2"
},
{
"code": null,
"e": 71076,
"s": 71039,
"text": "Rule 3 &minnus; if 6 <= X then Y = 4"
},
{
"code": null,
"e": 71113,
"s": 71076,
"text": "Rule 3 &minnus; if 6 <= X then Y = 4"
},
{
"code": null,
"e": 71144,
"s": 71113,
"text": "In Prolog syntax we can write,"
},
{
"code": null,
"e": 71182,
"s": 71144,
"text": "f(X,0) :- X < 3. % Rule 1"
},
{
"code": null,
"e": 71220,
"s": 71182,
"text": "f(X,0) :- X < 3. % Rule 1"
},
{
"code": null,
"e": 71255,
"s": 71220,
"text": "f(X,2) :- 3 =< X, X < 6. % Rule 2"
},
{
"code": null,
"e": 71290,
"s": 71255,
"text": "f(X,2) :- 3 =< X, X < 6. % Rule 2"
},
{
"code": null,
"e": 71328,
"s": 71290,
"text": "f(X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 71366,
"s": 71328,
"text": "f(X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 71414,
"s": 71366,
"text": "Now if we ask for a question as f (1,Y), 2 < Y."
},
{
"code": null,
"e": 71623,
"s": 71414,
"text": "The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that −"
},
{
"code": null,
"e": 71700,
"s": 71623,
"text": "The three rules are mutually exclusive and one of them at most will succeed."
},
{
"code": null,
"e": 71777,
"s": 71700,
"text": "The three rules are mutually exclusive and one of them at most will succeed."
},
{
"code": null,
"e": 71882,
"s": 71777,
"text": "As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail."
},
{
"code": null,
"e": 71987,
"s": 71882,
"text": "As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail."
},
{
"code": null,
"e": 72107,
"s": 71987,
"text": "So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows −"
},
{
"code": null,
"e": 72148,
"s": 72107,
"text": "f (X,0) :- X < 3, !. % Rule 1"
},
{
"code": null,
"e": 72189,
"s": 72148,
"text": "f (X,0) :- X < 3, !. % Rule 1"
},
{
"code": null,
"e": 72227,
"s": 72189,
"text": "f (X,2) :- 3 =< X, X < 6, !. % Rule 2"
},
{
"code": null,
"e": 72265,
"s": 72227,
"text": "f (X,2) :- 3 =< X, X < 6, !. % Rule 2"
},
{
"code": null,
"e": 72306,
"s": 72265,
"text": "f (X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 72347,
"s": 72306,
"text": "f (X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 72585,
"s": 72347,
"text": "Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated."
},
{
"code": null,
"e": 72622,
"s": 72585,
"text": "Let us see this in below execution −"
},
{
"code": null,
"e": 72736,
"s": 72622,
"text": "f(X,0) :- X < 3. % Rule 1\nf(X,2) :- 3 =< X, X < 6. % Rule 2\nf(X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 73319,
"s": 72736,
"text": "| ?- [backtrack].\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1224 bytes written, 17 ms\n\nyes\n| ?- f(1,Y), 2<Y.\n\nno\n| ?- trace\n.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- f(1,Y), 2<Y.\n 1 1 Call: f(1,_23) ?\n 2 2 Call: 1<3 ?\n 2 2 Exit: 1<3 ?\n 1 1 Exit: f(1,0) ?\n 3 1 Call: 2<0 ?\n 3 1 Fail: 2<0 ?\n 1 1 Redo: f(1,0) ?\n 2 2 Call: 3=<1 ?\n 2 2 Fail: 3=<1 ?\n 2 2 Call: 6=<1 ?\n 2 2 Fail: 6=<1 ?\n 1 1 Fail: f(1,_23) ?\n \n(46 ms) no\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 73350,
"s": 73319,
"text": "Let us see the same using cut."
},
{
"code": null,
"e": 73464,
"s": 73350,
"text": "f(X,0) :- X < 3,!. % Rule 1\nf(X,2) :- 3 =< X, X < 6,!. % Rule 2\nf(X,4) :- 6 =< X. % Rule 3"
},
{
"code": null,
"e": 73870,
"s": 73464,
"text": "| ?- [backtrack].\n 1 1 Call: [backtrack] ?\ncompiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code...\nD:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read - 1373 bytes written, 15 ms\n 1 1 Exit: [backtrack] ?\n(16 ms) yes\n{trace}\n| ?- f(1,Y), 2<Y.\n 1 1 Call: f(1,_23) ?\n 2 2 Call: 1<3 ?\n 2 2 Exit: 1<3 ?\n 1 1 Exit: f(1,0) ?\n 3 1 Call: 2<0 ?\n 3 1 Fail: 2<0 ?\nno\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 74030,
"s": 73870,
"text": "Here we will perform failure when condition does not satisfy. Suppose we have a statement, “Mary likes all animals but snakes”, we will express this in Prolog."
},
{
"code": null,
"e": 74255,
"s": 74030,
"text": "It would be very easy and straight forward, if the statement is “Mary likes all animals”. In that case we can write “Mary likes X if X is an animal”. And in prolog we can write this statement as, likes(mary, X) := animal(X)."
},
{
"code": null,
"e": 74298,
"s": 74255,
"text": "Our actual statement can be expressed as −"
},
{
"code": null,
"e": 74345,
"s": 74298,
"text": "If X is snake, then “Mary likes X” is not true"
},
{
"code": null,
"e": 74392,
"s": 74345,
"text": "If X is snake, then “Mary likes X” is not true"
},
{
"code": null,
"e": 74440,
"s": 74392,
"text": "Otherwise if X is an animal, then Mary likes X."
},
{
"code": null,
"e": 74488,
"s": 74440,
"text": "Otherwise if X is an animal, then Mary likes X."
},
{
"code": null,
"e": 74521,
"s": 74488,
"text": "In prolog we can write this as −"
},
{
"code": null,
"e": 74557,
"s": 74521,
"text": "likes(mary,X) :- snake(X), !, fail."
},
{
"code": null,
"e": 74593,
"s": 74557,
"text": "likes(mary,X) :- snake(X), !, fail."
},
{
"code": null,
"e": 74622,
"s": 74593,
"text": "likes(mary, X) :- animal(X)."
},
{
"code": null,
"e": 74651,
"s": 74622,
"text": "likes(mary, X) :- animal(X)."
},
{
"code": null,
"e": 74731,
"s": 74651,
"text": "The ‘fail’ statement causes the failure. Now let us see how it works in Prolog."
},
{
"code": null,
"e": 74918,
"s": 74731,
"text": "animal(dog).\nanimal(cat).\nanimal(elephant).\nanimal(tiger).\nanimal(cobra).\nanimal(python).\n\nsnake(cobra).\nsnake(python).\n\nlikes(mary, X) :- snake(X), !, fail.\nlikes(mary, X) :- animal(X)."
},
{
"code": null,
"e": 75726,
"s": 74918,
"text": "| ?- [negate_fail].\ncompiling D:/TP Prolog/Sample_Codes/negate_fail.pl for byte code...\nD:/TP Prolog/Sample_Codes/negate_fail.pl compiled, 11 lines read - 1118 bytes written, 17 ms\n\nyes\n| ?- likes(mary,elephant).\n\nyes\n| ?- likes(mary,tiger).\n\nyes\n| ?- likes(mary,python).\n\nno\n| ?- likes(mary,cobra).\n\nno\n| ?- trace\n.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- likes(mary,dog).\n 1 1 Call: likes(mary,dog) ?\n 2 2 Call: snake(dog) ?\n 2 2 Fail: snake(dog) ?\n 2 2 Call: animal(dog) ?\n 2 2 Exit: animal(dog) ?\n 1 1 Exit: likes(mary,dog) ?\n \nyes\n{trace}\n| ?- likes(mary,python).\n 1 1 Call: likes(mary,python) ?\n 2 2 Call: snake(python) ?\n 2 2 Exit: snake(python) ?\n 3 2 Call: fail ?\n 3 2 Fail: fail ?\n 1 1 Fail: likes(mary,python) ?\n \nno\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 76130,
"s": 75726,
"text": "Here we will define two predicates — different and not. The different predicate will check whether two given arguments are same or not. If they are same, it will return false, otherwise it will return true. The not predicate is used to negate some statement, which means, when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true."
},
{
"code": null,
"e": 76212,
"s": 76130,
"text": "So the term ‘different’ can be expressed in three different ways as given below −"
},
{
"code": null,
"e": 76247,
"s": 76212,
"text": "X and Y are not literally the same"
},
{
"code": null,
"e": 76282,
"s": 76247,
"text": "X and Y are not literally the same"
},
{
"code": null,
"e": 76303,
"s": 76282,
"text": "X and Y do not match"
},
{
"code": null,
"e": 76324,
"s": 76303,
"text": "X and Y do not match"
},
{
"code": null,
"e": 76382,
"s": 76324,
"text": "The values of arithmetic expression X and Y are not equal"
},
{
"code": null,
"e": 76440,
"s": 76382,
"text": "The values of arithmetic expression X and Y are not equal"
},
{
"code": null,
"e": 76505,
"s": 76440,
"text": "So in Prolog, we will try to express the statements as follows −"
},
{
"code": null,
"e": 76550,
"s": 76505,
"text": "If X and Y match, then different(X,Y) fails,"
},
{
"code": null,
"e": 76595,
"s": 76550,
"text": "If X and Y match, then different(X,Y) fails,"
},
{
"code": null,
"e": 76630,
"s": 76595,
"text": "Otherwise different(X,Y) succeeds."
},
{
"code": null,
"e": 76665,
"s": 76630,
"text": "Otherwise different(X,Y) succeeds."
},
{
"code": null,
"e": 76715,
"s": 76665,
"text": "The respective prolog syntax will be as follows −"
},
{
"code": null,
"e": 76743,
"s": 76715,
"text": "different(X, X) :- !, fail."
},
{
"code": null,
"e": 76771,
"s": 76743,
"text": "different(X, X) :- !, fail."
},
{
"code": null,
"e": 76788,
"s": 76771,
"text": "different(X, Y)."
},
{
"code": null,
"e": 76805,
"s": 76788,
"text": "different(X, Y)."
},
{
"code": null,
"e": 76871,
"s": 76805,
"text": "We can also express it using disjunctive clauses as given below −"
},
{
"code": null,
"e": 76951,
"s": 76871,
"text": "different(X, Y) :- X = Y, !, fail ; true. % true is goal that always succeeds"
},
{
"code": null,
"e": 77031,
"s": 76951,
"text": "different(X, Y) :- X = Y, !, fail ; true. % true is goal that always succeeds"
},
{
"code": null,
"e": 77088,
"s": 77031,
"text": "Following example shows how this can be done in prolog −"
},
{
"code": null,
"e": 77133,
"s": 77088,
"text": "different(X, X) :- !, fail.\ndifferent(X, Y)."
},
{
"code": null,
"e": 77524,
"s": 77133,
"text": "| ?- [diff_rel].\ncompiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...\nD:/TP Prolog/Sample_Codes/diff_rel.pl:2: warning: singleton variables [X,Y] for different/2\nD:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 2 lines read - 327 bytes written, 11 ms\n\nyes\n| ?- different(100,200).\n\nyes\n| ?- different(100,100).\n\nno\n| ?- different(abc,def).\n\nyes\n| ?- different(abc,abc).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 77577,
"s": 77524,
"text": "Let us see a program using the disjunctive clauses −"
},
{
"code": null,
"e": 77619,
"s": 77577,
"text": "different(X, Y) :- X = Y, !, fail ; true."
},
{
"code": null,
"e": 77918,
"s": 77619,
"text": "| ?- [diff_rel].\ncompiling D:/TP Prolog/Sample_Codes/diff_rel.pl for byte code...\nD:/TP Prolog/Sample_Codes/diff_rel.pl compiled, 0 lines read - 556 bytes written, 17 ms\n\nyes\n| ?- different(100,200).\n\nyes\n| ?- different(100,100).\n\nno\n| ?- different(abc,def).\n\nyes\n| ?- different(abc,abc).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 78230,
"s": 77918,
"text": "The not relation is very much useful in different cases. In our traditional programming languages also, we use the logical not operation to negate some statement. So it means that when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true."
},
{
"code": null,
"e": 78277,
"s": 78230,
"text": "In prolog, we can define this as shown below −"
},
{
"code": null,
"e": 78307,
"s": 78277,
"text": "not(P) :- P, !, fail ; true.\n"
},
{
"code": null,
"e": 78453,
"s": 78307,
"text": "So if P is true, then cut and fail, this will return false, otherwise it will be true. Now let us see one simple code to understand this concept."
},
{
"code": null,
"e": 78482,
"s": 78453,
"text": "not(P) :- P, !, fail ; true."
},
{
"code": null,
"e": 78701,
"s": 78482,
"text": "| ?- [not_rel].\ncompiling D:/TP Prolog/Sample_Codes/not_rel.pl for byte code...\nD:/TP Prolog/Sample_Codes/not_rel.pl compiled, 0 lines read - 630 bytes written, 17 ms\n\nyes\n| ?- not(true).\n\nno\n| ?- not(fail).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 78886,
"s": 78701,
"text": "In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques."
},
{
"code": null,
"e": 78933,
"s": 78886,
"text": "Following topics will be discussed in detail −"
},
{
"code": null,
"e": 78961,
"s": 78933,
"text": "Handling inputs and outputs"
},
{
"code": null,
"e": 78989,
"s": 78961,
"text": "Handling inputs and outputs"
},
{
"code": null,
"e": 79016,
"s": 78989,
"text": "File handling using Prolog"
},
{
"code": null,
"e": 79043,
"s": 79016,
"text": "File handling using Prolog"
},
{
"code": null,
"e": 79092,
"s": 79043,
"text": "Using some external file to read lines and terms"
},
{
"code": null,
"e": 79141,
"s": 79092,
"text": "Using some external file to read lines and terms"
},
{
"code": null,
"e": 79185,
"s": 79141,
"text": "Character manipulation for input and output"
},
{
"code": null,
"e": 79229,
"s": 79185,
"text": "Character manipulation for input and output"
},
{
"code": null,
"e": 79264,
"s": 79229,
"text": "Constructing and decomposing atoms"
},
{
"code": null,
"e": 79299,
"s": 79264,
"text": "Constructing and decomposing atoms"
},
{
"code": null,
"e": 79361,
"s": 79299,
"text": "Consulting prolog files into other prolog program techniques."
},
{
"code": null,
"e": 79423,
"s": 79361,
"text": "Consulting prolog files into other prolog program techniques."
},
{
"code": null,
"e": 79737,
"s": 79423,
"text": "So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques."
},
{
"code": null,
"e": 79967,
"s": 79737,
"text": "To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function."
},
{
"code": null,
"e": 80123,
"s": 79967,
"text": "| ?- write(56).\n56\n\nyes\n| ?- write('hello').\nhello\n\nyes\n| ?- write('hello'),nl,write('world').\nhello\nworld\n\nyes\n| ?- write(\"ABCDE\")\n.\n[65,66,67,68,69]\n\nyes"
},
{
"code": null,
"e": 80477,
"s": 80123,
"text": "From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values."
},
{
"code": null,
"e": 80761,
"s": 80477,
"text": "The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works."
},
{
"code": null,
"e": 80975,
"s": 80761,
"text": "cube :-\n write('Write a number: '),\n read(Number),\n process(Number).\nprocess(stop) :- !.\nprocess(Number) :-\n C is Number * Number * Number,\n write('Cube of '),write(Number),write(': '),write(C),nl, cube."
},
{
"code": null,
"e": 81358,
"s": 80975,
"text": "| ?- [read_write].\ncompiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code...\nD:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read - 1226 bytes written, 12 ms\n\n(15 ms) yes\n| ?- cube.\nWrite a number: 2.\nCube of 2: 8\nWrite a number: 10.\nCube of 10: 1000\nWrite a number: 12.\nCube of 12: 1728\nWrite a number: 8.\nCube of 8: 512\nWrite a number: stop\n.\n\n(31 ms) yes\n| ?-\n"
},
{
"code": null,
"e": 81547,
"s": 81358,
"text": "The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces."
},
{
"code": null,
"e": 81730,
"s": 81547,
"text": "| ?- write('hello'),tab(15),write('world').\nhello world\n\nyes\n| ?- write('We'),tab(5),write('will'),tab(5),write('use'),tab(5),write('tabs').\nWe will use tabs\n\nyes\n| ?-"
},
{
"code": null,
"e": 81910,
"s": 81730,
"text": "In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it."
},
{
"code": null,
"e": 82269,
"s": 81910,
"text": "If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed."
},
{
"code": null,
"e": 82693,
"s": 82269,
"text": "| ?- told('myFile.txt').\nuncaught exception: error(existence_error(procedure,told/1),top_level/0)\n| ?- told(\"myFile.txt\").\nuncaught exception: error(existence_error(procedure,told/1),top_level/0)\n| ?- tell('myFile.txt').\n\nyes\n| ?- tell('myFile.txt').\n\nyes\n| ?- write('Hello World').\n\nyes\n| ?- write(' Writing into a file'),tab(5),write('myFile.txt'),nl.\n\nyes\n| ?- write(\"Write some ASCII values\").\n\nyes\n| ?- told.\n\nyes\n| ?-"
},
{
"code": null,
"e": 82825,
"s": 82693,
"text": "Hello World Writing into a file myFile.txt\n[87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115]\n"
},
{
"code": null,
"e": 82911,
"s": 82825,
"text": "Similarly, we can also read from files. Let us see some example of reading from file."
},
{
"code": null,
"e": 83140,
"s": 82911,
"text": "When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command."
},
{
"code": null,
"e": 83175,
"s": 83140,
"text": "likes(lili, cat).\nlikes(jhon,dog)."
},
{
"code": null,
"e": 83307,
"s": 83175,
"text": "| ?- see('sample_predicate.txt'),\nread(X),\nread(Y),\nseen,\nread(Z).\nthe_end.\n\nX = end_of_file\nY = end_of_file\nZ = the_end\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 83512,
"s": 83307,
"text": "So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console."
},
{
"code": null,
"e": 83731,
"s": 83512,
"text": "We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file."
},
{
"code": null,
"e": 84001,
"s": 83731,
"text": "process_file :-\n read(Line),\n Line \\== end_of_file, % when Line is not not end of file, call process.\n process(Line).\nprocess_file :- !. % use cut to stop backtracking\n\nprocess(Line):- %this will print the line into the console\n write(Line),nl,\n process_file."
},
{
"code": null,
"e": 84066,
"s": 84001,
"text": "likes(lili, cat).\nlikes(jhon,dog).\ndomestic(dog).\ndomestic(cat)."
},
{
"code": null,
"e": 84394,
"s": 84066,
"text": "| ?- [process_file].\ncompiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code...\nD:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read - 774 bytes written, 23 ms\n\nyes\n| ?- see('sample_predicate.txt'), process_file, seen.\nlikes(lili,cat)\nlikes(jhon,dog)\ndomestic(dog)\ndomestic(cat)\n\ntrue ?\n\n(15 ms) yes\n| ?-\n"
},
{
"code": null,
"e": 84682,
"s": 84394,
"text": "Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks."
},
{
"code": null,
"e": 85016,
"s": 84682,
"text": "We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value. To use the character instead of ASCII, we can use put_char(C)."
},
{
"code": null,
"e": 85292,
"s": 85016,
"text": "| ?- put(97),put(98),put(99),put(100),put(101).\nabcde\n\nyes\n| ?- put(97),put(66),put(99),put(100),put(101).\naBcde\n\n(15 ms) yes\n| ?- put(65),put(66),put(99),put(100),put(101).\nABcde\n\nyes\n| ?-put_char('h'),put_char('e'),put_char('l'),put_char('l'),put_char('o').\nhello\n\nyes\n| ?-"
},
{
"code": null,
"e": 85469,
"s": 85292,
"text": "To read a single character from the current input stream, we can use the get_char(C) predicate. This will take the character. if we want the ASCII code, we can use get_code(C)."
},
{
"code": null,
"e": 85740,
"s": 85469,
"text": "| ?- get_char(X).\nA.\n\nX = 'A'\n\nyes\nuncaught exception: error(syntax_error('user_input:6 (char:689) expression expected'),read_term/3)\n| ?- get_code(X).\nA.\n\nX = 65\n\nyes\nuncaught exception: error(syntax_error('user_input:7 (char:14) expression expected'),read_term/3)\n| ?-"
},
{
"code": null,
"e": 86140,
"s": 85740,
"text": "The atom constructing means from a list of characters, we can make one atom, or from a list of ASCII values also we can make atoms. To do this, we have to use atom_chars() and atom_codes() predicates. In both cases, the first argument will be one variable, and the second argument will be a list. So atom_chars() constructs atom from characters, but atom_codes() construct atoms from ASCII sequence."
},
{
"code": null,
"e": 86355,
"s": 86140,
"text": "| ?- atom_chars(X, ['t','i','g','e','r']).\n\nX = tiger\n\nyes\n| ?- atom_chars(A, ['t','o','m']).\n\nA = tom\n\nyes\n| ?- atom_codes(X, [97,98,99,100,101]).\n\nX = abcde\n\nyes\n| ?- atom_codes(A, [97,98,99]).\n\nA = abc\n\nyes\n| ?-"
},
{
"code": null,
"e": 86762,
"s": 86355,
"text": "The atom decomposing means from an atom, we can get a sequence of characters, or a sequence ASCII codes. To do this, we have to use the same atom_chars() and atom_codes() predicates. But one difference is that, in both cases, the first argument will be one atom, and the second argument will be a variable. So atom_chars() decomposes atom to characters, but atom_codes() decomposes atoms to ASCII sequence."
},
{
"code": null,
"e": 86971,
"s": 86762,
"text": "| ?- atom_chars(tiger,X).\n\nX = [t,i,g,e,r]\n\nyes\n| ?- atom_chars(tom,A).\n\nA = [t,o,m]\n\nyes\n| ?- atom_codes(tiger,X).\n\nX = [116,105,103,101,114]\n\nyes\n| ?- atom_codes(tom,A).\n\nA = [116,111,109]\n\n(16 ms) yes\n| ?-"
},
{
"code": null,
"e": 87204,
"s": 86971,
"text": "The consulting is a technique, that is used to merge the predicates from different files. We can use the consult() predicate, and pass the filename to attach the predicates. Let us see one example program to understand this concept."
},
{
"code": null,
"e": 87262,
"s": 87204,
"text": "Suppose we have two files, namely, prog1.pl and prog2.pl."
},
{
"code": null,
"e": 87315,
"s": 87262,
"text": "likes(mary,cat).\nlikes(joy,rabbit).\nlikes(tim,duck)."
},
{
"code": null,
"e": 87355,
"s": 87315,
"text": "likes(suman,mouse).\nlikes(angshu,deer)."
},
{
"code": null,
"e": 87973,
"s": 87355,
"text": "| ?- [prog1].\ncompiling D:/TP Prolog/Sample_Codes/prog1.pl for byte code...\nD:/TP Prolog/Sample_Codes/prog1.pl compiled, 2 lines read - 443 bytes written, 23 ms\n\nyes\n| ?- likes(joy,rabbit).\n\nyes\n| ?- likes(suman,mouse).\n\nno\n| ?- consult('prog2.pl').\ncompiling D:/TP Prolog/Sample_Codes/prog2.pl for byte code...\nD:/TP Prolog/Sample_Codes/prog2.pl compiled, 1 lines read - 366 bytes written, 20 ms\nwarning: D:/TP Prolog/Sample_Codes/prog2.pl:1: redefining procedure likes/2\n D:/TP Prolog/Sample_Codes/prog1.pl:1: previous definition\n \nyes\n| ?- likes(suman,mouse).\n\nyes\n| ?- likes(joy,rabbit).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 88400,
"s": 87973,
"text": "Now from this output we can understand that this is not as simple as it seems. If two files have completely different clauses, then it will work fine. But if there are same predicates, then while we try to consult the file, it will check the predicates from the second file, when it finds some match, it simply deletes all of the entry of the same predicates from the local database, then load them again from the second file."
},
{
"code": null,
"e": 88576,
"s": 88400,
"text": "In Prolog, we have seen the user defined predicates in most of the cases, but there are some built-in-predicates. There are three types of built-in predicates as given below −"
},
{
"code": null,
"e": 88594,
"s": 88576,
"text": "Identifying terms"
},
{
"code": null,
"e": 88612,
"s": 88594,
"text": "Identifying terms"
},
{
"code": null,
"e": 88635,
"s": 88612,
"text": "Decomposing structures"
},
{
"code": null,
"e": 88658,
"s": 88635,
"text": "Decomposing structures"
},
{
"code": null,
"e": 88683,
"s": 88658,
"text": "Collecting all solutions"
},
{
"code": null,
"e": 88708,
"s": 88683,
"text": "Collecting all solutions"
},
{
"code": null,
"e": 88798,
"s": 88708,
"text": "So this is the list of some predicates that are falls under the identifying terms group −"
},
{
"code": null,
"e": 88893,
"s": 88798,
"text": "When X is not initialized, then, it will show true, otherwise false. So let us see an example."
},
{
"code": null,
"e": 88959,
"s": 88893,
"text": "| ?- var(X).\n\nyes\n| ?- X = 5, var(X).\n\nno\n| ?- var([X]).\n\nno\n| ?-"
},
{
"code": null,
"e": 89053,
"s": 88959,
"text": "When X is not initialized, the, it will show false, otherwise true. So let us see an example."
},
{
"code": null,
"e": 89135,
"s": 89053,
"text": "| ?- nonvar(X).\n\nno\n| ?- X = 5,nonvar(X).\n\nX = 5\n\nyes\n| ?- nonvar([X]).\n\nyes\n| ?-"
},
{
"code": null,
"e": 89255,
"s": 89135,
"text": "This will return true, when a non-variable term with 0 argument and a not numeric term is passed as X, otherwise false."
},
{
"code": null,
"e": 89362,
"s": 89255,
"text": "| ?- atom(paul).\n\nyes\n| ?- X = paul,atom(X).\n\nX = paul\n\nyes\n| ?- atom([]).\n\nyes\n| ?- atom([a,b]).\n\nno\n| ?-"
},
{
"code": null,
"e": 89427,
"s": 89362,
"text": "This will return true, X stands for any number, otherwise false."
},
{
"code": null,
"e": 89508,
"s": 89427,
"text": "| ?- number(X).\n\nno\n| ?- X=5,number(X).\n\nX = 5\n\nyes\n| ?- number(5.46).\n\nyes\n| ?-"
},
{
"code": null,
"e": 89596,
"s": 89508,
"text": "This will return true, when X is a positive or negative integer value, otherwise false."
},
{
"code": null,
"e": 89647,
"s": 89596,
"text": "| ?- integer(5).\n\nyes\n| ?- integer(5.46).\n\nno\n| ?-"
},
{
"code": null,
"e": 89717,
"s": 89647,
"text": "This will return true, X is a floating point number, otherwise false."
},
{
"code": null,
"e": 89764,
"s": 89717,
"text": "| ?- float(5).\n\nno\n| ?- float(5.46).\n\nyes\n| ?-"
},
{
"code": null,
"e": 89891,
"s": 89764,
"text": "We have atom(X), that is too specific, it returns false for numeric data, the atomic(X) is like atom(X) but it accepts number."
},
{
"code": null,
"e": 89935,
"s": 89891,
"text": "| ?- atom(5).\n\nno\n| ?- atomic(5).\n\nyes\n| ?-"
},
{
"code": null,
"e": 90124,
"s": 89935,
"text": "If atomic(X) fails, then the terms are either one non-instantiated variable (that can be tested with var(X)) or a compound term. Compound will be true when we pass some compound structure."
},
{
"code": null,
"e": 90203,
"s": 90124,
"text": "| ?- compound([]).\n\nno\n| ?- compound([a]).\n\nyes\n| ?- compound(b(a)).\n\nyes\n| ?-"
},
{
"code": null,
"e": 90348,
"s": 90203,
"text": "This will return true, if X does not contain any un-instantiated variables. This also checks inside the compound terms, otherwise returns false."
},
{
"code": null,
"e": 90446,
"s": 90348,
"text": "| ?- ground(X).\n\nno\n| ?- ground(a(b,X)).\n\nno\n| ?- ground(a).\n\nyes\n| ?- ground([a,b,c]).\n\nyes\n| ?-"
},
{
"code": null,
"e": 90745,
"s": 90446,
"text": "Now we will see, another group of built-in predicates, that is Decomposing structures. We have seen the identifying terms before. So when we are using compound structures we cannot use a variable to check or make a functor. It will return error. So functor name cannot be represented by a variable."
},
{
"code": null,
"e": 90795,
"s": 90745,
"text": "X = tree, Y = X(maple).\nSyntax error Y=X<>(maple)"
},
{
"code": null,
"e": 90886,
"s": 90795,
"text": "Now, let us see some inbuilt predicates that falls under the Decomposing structures group."
},
{
"code": null,
"e": 90965,
"s": 90886,
"text": "This returns true if F is the principal functor of T, and N is the arity of F."
},
{
"code": null,
"e": 91010,
"s": 90965,
"text": "Note − Arity means the number of attributes."
},
{
"code": null,
"e": 91078,
"s": 91010,
"text": "| ?- functor(t(f(X),a,T),Func,N).\n\nFunc = t\nN = 3\n\n(15 ms) yes\n| ?-"
},
{
"code": null,
"e": 91155,
"s": 91078,
"text": "This returns true if A is the Nth argument in Term. Otherwise returns false."
},
{
"code": null,
"e": 91240,
"s": 91155,
"text": "| ?- arg(1,t(t(X),[]),A).\n\nA = t(X)\n\nyes\n| ?- arg(2,t(t(X),[]),A).\n\nA = []\n\nyes\n| ?-"
},
{
"code": null,
"e": 91416,
"s": 91240,
"text": "Now, let us see another example. In this example, we are checking that the first argument of D will be 12, the second argument will be apr and the third argument will be 2020."
},
{
"code": null,
"e": 91515,
"s": 91416,
"text": "| ?- functor(D,date,3), arg(1,D,12), arg(2,D,apr), arg(3,D,2020).\n\nD = date(12,apr,2020)\n\nyes\n| ?-"
},
{
"code": null,
"e": 91723,
"s": 91515,
"text": "This is another predicate represented as double dot (..). This takes 2 arguments, so ‘/2’ is written. So Term = .. L, this is true if L is a list that contains the functor of Term, followed by its arguments."
},
{
"code": null,
"e": 91826,
"s": 91723,
"text": "| ?- f(a,b) =.. L.\n\nL = [f,a,b]\n\nyes\n| ?- T =.. [is_blue,sam,today].\n\nT = is_blue(sam,today)\n\nyes\n| ?-"
},
{
"code": null,
"e": 91979,
"s": 91826,
"text": "By representing the component of a structure as a list, they can be recursively processed without knowing the functor name. Let us see another example −"
},
{
"code": null,
"e": 92076,
"s": 91979,
"text": "| ?- f(2,3)=..[F,N|Y], N1 is N*3, L=..[F,N1|Y].\n\nF = f\nL = f(6,3)\nN = 2\nN1 = 6\nY = [3]\n\nyes\n| ?-"
},
{
"code": null,
"e": 92195,
"s": 92076,
"text": "Now let us see the third category called the collecting all solutions, that falls under built-in predicates in Prolog."
},
{
"code": null,
"e": 92332,
"s": 92195,
"text": "We have seen that to generate all of the given solutions of a given goal using the semicolon in the prompt. So here is an example of it."
},
{
"code": null,
"e": 92404,
"s": 92332,
"text": "| ?- member(X, [1,2,3,4]).\n\nX = 1 ? ;\n\nX = 2 ? ;\n\nX = 3 ? ;\n\nX = 4\n\nyes"
},
{
"code": null,
"e": 92630,
"s": 92404,
"text": "Sometimes, we need to generate all of the solutions to some goal within a program in some AI related applications. So there are three built-in predicates that will help us to get the results. These predicates are as follows −"
},
{
"code": null,
"e": 92640,
"s": 92630,
"text": "findall/3"
},
{
"code": null,
"e": 92650,
"s": 92640,
"text": "findall/3"
},
{
"code": null,
"e": 92659,
"s": 92650,
"text": "setoff/3"
},
{
"code": null,
"e": 92668,
"s": 92659,
"text": "setoff/3"
},
{
"code": null,
"e": 92676,
"s": 92668,
"text": "bagof/3"
},
{
"code": null,
"e": 92684,
"s": 92676,
"text": "bagof/3"
},
{
"code": null,
"e": 92787,
"s": 92684,
"text": "These three predicates take three arguments, so we have written ‘/3’ after the name of the predicates."
},
{
"code": null,
"e": 92882,
"s": 92787,
"text": "These are also known as meta-predicates. These are used to manipulate Prolog’s Proof strategy."
},
{
"code": null,
"e": 92925,
"s": 92882,
"text": "findall(X,P,L).\nsetof(X,P,L)\nbagof(X,P,L)\n"
},
{
"code": null,
"e": 93176,
"s": 92925,
"text": "These three predicates a list of all objects X, such that the goal P is satisfied (example: age(X,Age)). They all repeatedly call the goal P, by instantiating variable X within P and adding it to the list L. This stops when there is no more solution."
},
{
"code": null,
"e": 93324,
"s": 93176,
"text": "Here we will see the three different built-in predicates findall/3, setof/3 and the bagof/3, that fall into the category, collecting all solutions."
},
{
"code": null,
"e": 93796,
"s": 93324,
"text": "This predicate is used to make a list of all solutions X, from the predicate P. The returned list will be L. So we will read this as “find all of the Xs, such that X is a solution of predicate P and put the list of results in L”. Here this predicate stores the results in the same order, in which Prolog finds them. And if there are duplicate solutions, then all will come into the resultant list, and if there is infinite solution, then the process will never terminate."
},
{
"code": null,
"e": 93983,
"s": 93796,
"text": "Now we can also do some advancement on them. The second argument, which is the goal, that might be a compound goal. Then the syntax will be as findall(X, (Predicate on X, other goal), L)"
},
{
"code": null,
"e": 94113,
"s": 93983,
"text": "And also the first argument can be a term of any complexity. So let us see the examples of these few rules, and check the output."
},
{
"code": null,
"e": 94369,
"s": 94113,
"text": "| ?- findall(X, member(X, [1,2,3,4]), Results).\n\nResults = [1,2,3,4]\n\nyes\n| ?- findall(X, (member(X, [1,2,3,4]), X > 2), Results).\n\nResults = [3,4]\n\nyes\n| ?- findall(X/Y, (member(X,[1,2,3,4]), Y is X * X), Results).\n\nResults = [1/1,2/4,3/9,4/16]\n\nyes\n| ?-"
},
{
"code": null,
"e": 94487,
"s": 94369,
"text": "The setof/3 is also like findall/3, but here it removes all of the duplicate outputs, and the answers will be sorted."
},
{
"code": null,
"e": 94661,
"s": 94487,
"text": "If any variable is used in the goal, then that will not appear in the first argument, setof/3 will return a separate result for each possible instantiation of that variable."
},
{
"code": null,
"e": 94762,
"s": 94661,
"text": "Let us see one example to understand this setof/3. Suppose we have a knowledge base as shown below −"
},
{
"code": null,
"e": 94829,
"s": 94762,
"text": "age(peter, 7).\nage(ann, 5).\nage(pat, 8).\nage(tom, 5).\nage(ann, 5)."
},
{
"code": null,
"e": 95032,
"s": 94829,
"text": "Here we can see that age(ann, 5) has two entries in the knowledge base. And the ages are not sorted, and names are not sorted lexicographically in this case. Now let us see one example of setof/3 usage."
},
{
"code": null,
"e": 95182,
"s": 95032,
"text": "| ?- setof(Child, age(Child,Age),Results).\n\nAge = 5\nResults = [ann,tom] ? ;\n\nAge = 7\nResults = [peter] ? ;\n\nAge = 8\nResults = [pat]\n\n(16 ms) yes\n| ?-"
},
{
"code": null,
"e": 95413,
"s": 95182,
"text": "Here we can see the ages and the names both are coming sorted. For age 5, there is two entries, so the predicate has created one list corresponding to the age value, with two elements. And the duplicate entry is present only once."
},
{
"code": null,
"e": 95729,
"s": 95413,
"text": "We can use the nested call of setof/3, to collect together the individual results. We will see another example, where the first argument will be Age/Children. As the second argument, it will take another setof like before. So this will return a list of (age/Children) pair. Let us see this in the prolog execution −"
},
{
"code": null,
"e": 95862,
"s": 95729,
"text": "| ?- setof(Age/Children, setof(Child,age(Child,Age), Children), AllResults).\n\nAllResults = [5/[ann,tom],7/[peter],8/[pat]]\n\nyes\n| ?-"
},
{
"code": null,
"e": 95985,
"s": 95862,
"text": "Now if we do not care about a variable that does not appear in the first argument, then we can use the following example −"
},
{
"code": null,
"e": 96074,
"s": 95985,
"text": "| ?- setof(Child, Age^age(Child,Age), Results).\n\nResults = [ann,pat,peter,tom]\n\nyes\n| ?-"
},
{
"code": null,
"e": 96319,
"s": 96074,
"text": "Here we are using the upper caret symbol (^), this indicates that the Age is not in the first argument. So we will read this as, “Find the set of all children, such that the child has an Age (whatever it may be), and put the result in Results”."
},
{
"code": null,
"e": 96434,
"s": 96319,
"text": "The bagof/3 is like setof/3, but here it does not remove the duplicate outputs, and the answers may not be sorted."
},
{
"code": null,
"e": 96531,
"s": 96434,
"text": "Let us see one example to understand this bagof/3. Suppose we have a knowledge base as follows −"
},
{
"code": null,
"e": 96599,
"s": 96531,
"text": "age(peter, 7).\nage(ann, 5).\nage(pat, 8).\nage(tom, 5).\nage(ann, 5).\n"
},
{
"code": null,
"e": 96753,
"s": 96599,
"text": "| ?- bagof(Child, age(Child,Age),Results).\n\nAge = 5\nResults = [ann,tom,ann] ? ;\n\nAge = 7\nResults = [peter] ? ;\n\nAge = 8\nResults = [pat]\n\n(15 ms) yes\n| ?-"
},
{
"code": null,
"e": 96915,
"s": 96753,
"text": "Here for the Age value 5, the results are [ann, tom, ann]. So the answers are not sorted, and duplicate entries are not removed, so we have got two ‘ann’ values."
},
{
"code": null,
"e": 97109,
"s": 96915,
"text": "The bagof/3 is different from findall/3, as this generates separate results for all the variables in the goal that do not appear in the first argument. We will see this using an example below −"
},
{
"code": null,
"e": 97199,
"s": 97109,
"text": "| ?- findall(Child, age(Child,Age),Results).\n\nResults = [peter,ann,pat,tom,ann]\n\nyes\n| ?-"
},
{
"code": null,
"e": 97243,
"s": 97199,
"text": "Following are the mathematical predicates −"
},
{
"code": null,
"e": 97403,
"s": 97243,
"text": "Besides these, there are some other predicates such as sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh, log, log10, exp, pi, etc."
},
{
"code": null,
"e": 97468,
"s": 97403,
"text": "Now let us see these functions in action using a Prolog program."
},
{
"code": null,
"e": 98004,
"s": 97468,
"text": "| ?- random(0,10,X).\n\nX = 0\n\nyes\n| ?- random(0,10,X).\n\nX = 5\n\nyes\n| ?- random(0,10,X).\n\nX = 1\n\nyes\n| ?- between(0,10,X).\n\nX = 0 ? a\n\nX = 1\n\nX = 2\n\nX = 3\n\nX = 4\n\nX = 5\n\nX = 6\n\nX = 7\n\nX = 8\n\nX = 9\n\nX = 10\n\n(31 ms) yes\n| ?- succ(2,X).\n\nX = 3\n\nyes\n| ?- X is abs(-8).\n\nX = 8\n\nyes\n| ?- X is max(10,5).\n\nX = 10\n\nyes\n| ?- X is min(10,5).\n\nX = 5\n\nyes\n| ?- X is round(10.56).\n\nX = 11\n\nyes\n| ?- X is truncate(10.56).\n\nX = 10\n\nyes\n| ?- X is floor(10.56).\n\nX = 10\n\nyes\n| ?- X is ceiling(10.56).\n\nX = 11\n\nyes\n| ?- X is sqrt(144).\n\nX = 12.0\n\nyes\n| ?-"
},
{
"code": null,
"e": 98250,
"s": 98004,
"text": "So far we have seen different concepts of logic programming in Prolog. Now we will see one case study on Prolog. We will see how to implement a tree data structure using Prolog, and we will create our own operators. So let us start the planning."
},
{
"code": null,
"e": 98290,
"s": 98250,
"text": "Suppose we have a tree as shown below −"
},
{
"code": null,
"e": 98372,
"s": 98290,
"text": "We have to implement this tree using prolog. We have some operations as follows −"
},
{
"code": null,
"e": 98399,
"s": 98372,
"text": "op(500, xfx, ‘is_parent’)."
},
{
"code": null,
"e": 98426,
"s": 98399,
"text": "op(500, xfx, ‘is_parent’)."
},
{
"code": null,
"e": 98457,
"s": 98426,
"text": "op(500, xfx, ‘is_sibling_of’)."
},
{
"code": null,
"e": 98488,
"s": 98457,
"text": "op(500, xfx, ‘is_sibling_of’)."
},
{
"code": null,
"e": 98522,
"s": 98488,
"text": "op(500, xfx, ‘is_at_same_level’)."
},
{
"code": null,
"e": 98556,
"s": 98522,
"text": "op(500, xfx, ‘is_at_same_level’)."
},
{
"code": null,
"e": 98601,
"s": 98556,
"text": "And another predicate namely leaf_node(Node)"
},
{
"code": null,
"e": 98646,
"s": 98601,
"text": "And another predicate namely leaf_node(Node)"
},
{
"code": null,
"e": 98896,
"s": 98646,
"text": "In these operators, you have seen some parameters as (500, xfx, <operator_name>). The first argument (here 500) is the priority of that operator. The ‘xfx’ indicates that this is a binary operator and the <operator_name> is the name of the operator."
},
{
"code": null,
"e": 98993,
"s": 98896,
"text": "These operators can be used to define the tree database. We can use these operators as follows −"
},
{
"code": null,
"e": 99083,
"s": 98993,
"text": "a is_parent b, or is_parent(a, b). So this indicates that node a is the parent of node b."
},
{
"code": null,
"e": 99173,
"s": 99083,
"text": "a is_parent b, or is_parent(a, b). So this indicates that node a is the parent of node b."
},
{
"code": null,
"e": 99395,
"s": 99173,
"text": "X is_sibling_of Y or is_sibling_of(X,Y). This indicates that X is the sibling of node Y. So the rule is, if another node Z is parent of X and Z is also the parent of Y and X and Y are different, then X and Y are siblings."
},
{
"code": null,
"e": 99617,
"s": 99395,
"text": "X is_sibling_of Y or is_sibling_of(X,Y). This indicates that X is the sibling of node Y. So the rule is, if another node Z is parent of X and Z is also the parent of Y and X and Y are different, then X and Y are siblings."
},
{
"code": null,
"e": 99703,
"s": 99617,
"text": "leaf_node(Node). A node (Node) is said to be a leaf node when a node has no children."
},
{
"code": null,
"e": 99789,
"s": 99703,
"text": "leaf_node(Node). A node (Node) is said to be a leaf node when a node has no children."
},
{
"code": null,
"e": 100052,
"s": 99789,
"text": "X is_at_same_level Y, or is_at_same_level(X,Y). This will check whether X and Y are at the same level or not. So the condition is when X and Y are same, then it returns true, otherwise W is the parent of X, Z is the parent of Y and W and Z are at the same level."
},
{
"code": null,
"e": 100315,
"s": 100052,
"text": "X is_at_same_level Y, or is_at_same_level(X,Y). This will check whether X and Y are at the same level or not. So the condition is when X and Y are same, then it returns true, otherwise W is the parent of X, Z is the parent of Y and W and Z are at the same level."
},
{
"code": null,
"e": 100414,
"s": 100315,
"text": "As shown above, other rules are defined in the code. So let us see the program to get better view."
},
{
"code": null,
"e": 101272,
"s": 100414,
"text": "/* The tree database */\n\n:- op(500,xfx,'is_parent').\n\na is_parent b. c is_parent g. f is_parent l. j is_parent q.\na is_parent c. c is_parent h. f is_parent m. j is_parent r.\na is_parent d. c is_parent i. h is_parent n. j is_parent s.\nb is_parent e. d is_parent j. i is_parent o. m is_parent t.\nb is_parent f. e is_parent k. i is_parent p. n is_parent u.\nn \nis_parent v.\n/* X and Y are siblings i.e. child from the same parent */\n\n:- op(500,xfx,'is_sibling_of').\n\nX is_sibling_of Y :- Z is_parent X,\n Z is_parent Y,\n X \\== Y.\nleaf_node(Node) :- \\+ is_parent(Node,Child). % Node grounded\n\n/* X and Y are on the same level in the tree. */\n\n:-op(500,xfx,'is_at_same_level').\nX is_at_same_level X .\nX is_at_same_level Y :- W is_parent X,\n Z is_parent Y,\n W is_at_same_level Z."
},
{
"code": null,
"e": 101813,
"s": 101272,
"text": "| ?- [case_tree].\ncompiling D:/TP Prolog/Sample_Codes/case_tree.pl for byte code...\nD:/TP Prolog/Sample_Codes/case_tree.pl:20: warning: singleton variables [Child] for leaf_node/1\nD:/TP Prolog/Sample_Codes/case_tree.pl compiled, 28 lines read - 3244 bytes written, 7 ms\n\nyes\n| ?- i is_parent p.\n\nyes\n| ?- i is_parent s.\n\nno\n| ?- is_parent(i,p).\n\nyes\n| ?- e is_sibling_of f.\n\ntrue ?\n\nyes\n| ?- is_sibling_of(e,g).\n\nno\n| ?- leaf_node(v).\n\nyes\n| ?- leaf_node(a).\n\nno\n| ?- is_at_same_level(l,s).\n\ntrue ?\n\nyes\n| ?- l is_at_same_level v.\n\nno\n| ?-\n"
},
{
"code": null,
"e": 101915,
"s": 101813,
"text": "Here, we will see some more operations that will be performed on the above given tree data structure."
},
{
"code": null,
"e": 101952,
"s": 101915,
"text": "Let us consider the same tree here −"
},
{
"code": null,
"e": 101986,
"s": 101952,
"text": "We will define other operations −"
},
{
"code": null,
"e": 101997,
"s": 101986,
"text": "path(Node)"
},
{
"code": null,
"e": 102008,
"s": 101997,
"text": "path(Node)"
},
{
"code": null,
"e": 102021,
"s": 102008,
"text": "locate(Node)"
},
{
"code": null,
"e": 102034,
"s": 102021,
"text": "locate(Node)"
},
{
"code": null,
"e": 102213,
"s": 102034,
"text": "As we have created the last database, we will create a new program that will hold these operations, then consult the new file to use these operations on our pre-existing program."
},
{
"code": null,
"e": 102268,
"s": 102213,
"text": "So let us see what is the purpose of these operators −"
},
{
"code": null,
"e": 102468,
"s": 102268,
"text": "path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node ‘a’ is reached, it will stop."
},
{
"code": null,
"e": 102668,
"s": 102468,
"text": "path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node ‘a’ is reached, it will stop."
},
{
"code": null,
"e": 102803,
"s": 102668,
"text": "locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node."
},
{
"code": null,
"e": 102938,
"s": 102803,
"text": "locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node."
},
{
"code": null,
"e": 102976,
"s": 102938,
"text": "Let us see the program in execution −"
},
{
"code": null,
"e": 103370,
"s": 102976,
"text": "path(a). /* Can start at a. */\npath(Node) :- Mother is_parent Node, /* Choose parent, */\n path(Mother), /* find path and then */ \n write(Mother),\n write(' --> ').\n \n/* Locate node by finding a path from root down to the node */\nlocate(Node) :- path(Node),\n write(Node),\n nl."
},
{
"code": null,
"e": 103806,
"s": 103370,
"text": "| ?- consult('case_tree_more.pl').\ncompiling D:/TP Prolog/Sample_Codes/case_tree_more.pl for byte code...\nD:/TP Prolog/Sample_Codes/case_tree_more.pl compiled, 9 lines read - 866 bytes written, 6 ms\n\nyes\n| ?- path(n).\na --> c --> h -->\n\ntrue ?\n\nyes\n| ?- path(s).\na --> d --> j -->\n\ntrue ?\n\nyes\n| ?- path(w).\n\nno\n| ?- locate(n).\na --> c --> h --> n\n\ntrue ?\n\nyes\n| ?- locate(s).\na --> d --> j --> s\n\ntrue ?\n\nyes\n| ?- locate(w).\n\nno\n| ?-\n"
},
{
"code": null,
"e": 103882,
"s": 103806,
"text": "Now let us define some advanced operations on the same tree data structure."
},
{
"code": null,
"e": 104160,
"s": 103882,
"text": "Here we will see how to find the height of a node, that is, the length of the longest path from that node, using the Prolog built-in predicate setof/3. This predicate takes (Template, Goal, Set). This binds Set to the list of all instances of Template satisfying the goal Goal."
},
{
"code": null,
"e": 104316,
"s": 104160,
"text": "We have already defined the tree before, so we will consult the current code to execute these set of operations without redefining the tree database again."
},
{
"code": null,
"e": 104360,
"s": 104316,
"text": "We will create some predicates as follows −"
},
{
"code": null,
"e": 104552,
"s": 104360,
"text": "ht(Node,H). This finds the height. It also checks whether a node is leaf or not, if so, then sets height H as 0, otherwise recursively finds the height of children of Node, and add 1 to them."
},
{
"code": null,
"e": 104972,
"s": 104552,
"text": "max([X|R], M,A). This calculates the max element from the list, and a value M. So if M is maximum, then it returns M, otherwise, it returns the maximum element of list that is greater than M. To solve this, if given list is empty, return M as max element, otherwise check whether Head is greater than M or not, if so, then call max() using the tail part and the value X, otherwise call max() using tail and the value M."
},
{
"code": null,
"e": 105208,
"s": 104972,
"text": "height(N,H). This uses the setof/3 predicate. This will find the set of results using the goal ht(N,Z) for the template Z and stores into the list type variable called Set. Now find the max of Set, and value 0, store the result into H."
},
{
"code": null,
"e": 105250,
"s": 105208,
"text": "Now let us see the program in execution −"
},
{
"code": null,
"e": 105523,
"s": 105250,
"text": "height(N,H) :- setof(Z,ht(N,Z),Set),\n max(Set,0,H).\n \nht(Node,0) :- leaf_node(Node),!.\nht(Node,H) :- Node is_parent Child,\n ht(Child,H1),\n H is H1 + 1.\nmax([],M,M).\nmax([X|R],M,A) :- (X > M -> max(R,X,A) ; max(R,M,A))."
},
{
"code": null,
"e": 106023,
"s": 105523,
"text": "| ?- consult('case_tree_adv.pl').\ncompiling D:/TP Prolog/Sample_Codes/case_tree_adv.pl for byte code...\nD:/TP Prolog/Sample_Codes/case_tree_adv.pl compiled, 9 lines read - 2060 bytes written, 9 ms\n\nyes\n| ?- ht(c,H).\n\nH = 1 ? a\n\nH = 3\n\nH = 3\n\nH = 2\n\nH = 2\n\nyes\n| ?- max([1,5,3,4,2],10,Max).\n\nMax = 10\n\nyes\n| ?- max([1,5,3,40,2],10,Max).\n\nMax = 40\n\nyes\n| ?- setof(H, ht(c,H),Set).\n\nSet = [1,2,3]\n\nyes\n| ?- max([1,2,3],0,H).\n\nH = 3\n\nyes\n| ?- height(c,H).\n\nH = 3\n\nyes\n| ?- height(a,H).\n\nH = 4\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 106100,
"s": 106023,
"text": "In the following chapter, we are going to discuss basic prolog examples to −"
},
{
"code": null,
"e": 106136,
"s": 106100,
"text": "Find minimum maximum of two numbers"
},
{
"code": null,
"e": 106172,
"s": 106136,
"text": "Find minimum maximum of two numbers"
},
{
"code": null,
"e": 106226,
"s": 106172,
"text": "Find the equivalent resistance of a resistive circuit"
},
{
"code": null,
"e": 106280,
"s": 106226,
"text": "Find the equivalent resistance of a resistive circuit"
},
{
"code": null,
"e": 106345,
"s": 106280,
"text": "Verify whether a line segment is horizontal, vertical or oblique"
},
{
"code": null,
"e": 106410,
"s": 106345,
"text": "Verify whether a line segment is horizontal, vertical or oblique"
},
{
"code": null,
"e": 106748,
"s": 106410,
"text": "Here we will see one Prolog program, that can find the minimum of two numbers and the maximum of two numbers. First, we will create two predicates, find_max(X,Y,Max). This takes X and Y values, and stores the maximum value into the Max. Similarly find_min(X,Y,Min) takes X and Y values, and store the minimum value into the Min variable."
},
{
"code": null,
"e": 106869,
"s": 106748,
"text": "find_max(X, Y, X) :- X >= Y, !.\nfind_max(X, Y, Y) :- X < Y.\n\nfind_min(X, Y, X) :- X =< Y, !.\nfind_min(X, Y, Y) :- X > Y."
},
{
"code": null,
"e": 107045,
"s": 106869,
"text": "| ?- find_max(100,200,Max).\n\nMax = 200\n\nyes\n| ?- find_max(40,10,Max).\n\nMax = 40\n\nyes\n| ?- find_min(40,10,Min).\n\nMin = 10\n\nyes\n| ?- find_min(100,200,Min).\n\nMin = 100\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 107177,
"s": 107045,
"text": "In this section, we will see how to write a prolog program that will help us find the equivalent resistance of a resistive circuit."
},
{
"code": null,
"e": 107244,
"s": 107177,
"text": "Let us consider the following circuit to understand this concept −"
},
{
"code": null,
"e": 107430,
"s": 107244,
"text": "We have to find the equivalent resistance of this network. At first, we will try to get the result by hand, then try to see whether the result is matching with the prolog output or not."
},
{
"code": null,
"e": 107465,
"s": 107430,
"text": "We know that there are two rules −"
},
{
"code": null,
"e": 107532,
"s": 107465,
"text": "If R1 and R2 are in Series, then equivalent resistor Re = R1 + R2."
},
{
"code": null,
"e": 107599,
"s": 107532,
"text": "If R1 and R2 are in Series, then equivalent resistor Re = R1 + R2."
},
{
"code": null,
"e": 107680,
"s": 107599,
"text": "If R1 and R2 are in Parallel, then equivalent resistor Re = (R1 * R2)/(R1 + R2)."
},
{
"code": null,
"e": 107761,
"s": 107680,
"text": "If R1 and R2 are in Parallel, then equivalent resistor Re = (R1 * R2)/(R1 + R2)."
},
{
"code": null,
"e": 107971,
"s": 107761,
"text": "Here 10 Ohm and 40 Ohm resistors are in parallel, then that is in series with 12 Ohm, and the equivalent resistor of the lower half is parallel with 30 Ohm. So let’s try to calculate the equivalent resistance."
},
{
"code": null,
"e": 108013,
"s": 107971,
"text": "R3 = (10 * 40)/(10 + 40) = 400/50 = 8 Ohm"
},
{
"code": null,
"e": 108055,
"s": 108013,
"text": "R3 = (10 * 40)/(10 + 40) = 400/50 = 8 Ohm"
},
{
"code": null,
"e": 108086,
"s": 108055,
"text": "R4 = R3 + 12 = 8 + 12 = 20 Ohm"
},
{
"code": null,
"e": 108117,
"s": 108086,
"text": "R4 = R3 + 12 = 8 + 12 = 20 Ohm"
},
{
"code": null,
"e": 108151,
"s": 108117,
"text": "R5 = (20 * 30)/(20 + 30) = 12 Ohm"
},
{
"code": null,
"e": 108185,
"s": 108151,
"text": "R5 = (20 * 30)/(20 + 30) = 12 Ohm"
},
{
"code": null,
"e": 108273,
"s": 108185,
"text": "series(R1,R2,Re) :- Re is R1 + R2.\nparallel(R1,R2,Re) :- Re is ((R1 * R2) / (R1 + R2))."
},
{
"code": null,
"e": 108673,
"s": 108273,
"text": "| ?- [resistance].\ncompiling D:/TP Prolog/Sample_Codes/resistance.pl for byte code...\nD:/TP Prolog/Sample_Codes/resistance.pl compiled, 1 lines read - 804 bytes written, 14 ms\n\nyes\n| ?- parallel(10,40,R3).\n\nR3 = 8.0\n\nyes\n| ?- series(8,12,R4).\n\nR4 = 20\n\nyes\n| ?- parallel(20,30,R5).\n\nR5 = 12.0\n\nyes\n| ?- parallel(10,40,R3),series(R3,12,R4),parallel(R4,30,R5).\n\nR3 = 8.0\nR4 = 20.0\nR5 = 12.0\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 108827,
"s": 108673,
"text": "There are three types of line segments, horizontal, vertical or oblique. This example verifies whether a line segment is horizontal, vertical or oblique."
},
{
"code": null,
"e": 108870,
"s": 108827,
"text": "From this diagram we can understand that −"
},
{
"code": null,
"e": 108943,
"s": 108870,
"text": "For Horizontal lines, the y coordinate values of two endpoints are same."
},
{
"code": null,
"e": 109016,
"s": 108943,
"text": "For Horizontal lines, the y coordinate values of two endpoints are same."
},
{
"code": null,
"e": 109087,
"s": 109016,
"text": "For Vertical lines, the x coordinate values of two endpoints are same."
},
{
"code": null,
"e": 109158,
"s": 109087,
"text": "For Vertical lines, the x coordinate values of two endpoints are same."
},
{
"code": null,
"e": 109231,
"s": 109158,
"text": "For Oblique lines, the (x,y) coordinates of two endpoints are different."
},
{
"code": null,
"e": 109304,
"s": 109231,
"text": "For Oblique lines, the (x,y) coordinates of two endpoints are different."
},
{
"code": null,
"e": 109357,
"s": 109304,
"text": "Now let us see how to write a program to check this."
},
{
"code": null,
"e": 109510,
"s": 109357,
"text": "vertical(seg(point(X,_),point(X,_))).\n\nhorizontal(seg(point(_,Y),point(_,Y))).\n\noblique(seg(point(X1,Y1),point(X2,Y2)))\n :-X1 \\== X2,\n Y1 \\== Y2."
},
{
"code": null,
"e": 109955,
"s": 109510,
"text": "| ?- [line_seg].\ncompiling D:/TP Prolog/Sample_Codes/line_seg.pl for byte code...\nD:/TP Prolog/Sample_Codes/line_seg.pl compiled, 6 lines read - 1276 bytes written, 26 ms\n\nyes\n| ?- vertical(seg(point(10,20), point(10,30))).\n\nyes\n| ?- vertical(seg(point(10,20), point(15,30))).\n\nno\n| ?- oblique(seg(point(10,20), point(15,30))).\n\nyes\n| ?- oblique(seg(point(10,20), point(15,20))).\n\nno\n| ?- horizontal(seg(point(10,20), point(15,20))).\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 110118,
"s": 109955,
"text": "In this section, we will see some examples of cuts in prolog. Let us consider, we want to find the maximum of two elements. So we will check these two conditions."
},
{
"code": null,
"e": 110142,
"s": 110118,
"text": "If X > Y, then Max := X"
},
{
"code": null,
"e": 110166,
"s": 110142,
"text": "If X > Y, then Max := X"
},
{
"code": null,
"e": 110191,
"s": 110166,
"text": "if X <= Y, then Max := Y"
},
{
"code": null,
"e": 110216,
"s": 110191,
"text": "if X <= Y, then Max := Y"
},
{
"code": null,
"e": 110419,
"s": 110216,
"text": "Now from these two lines, we can understand that these two statements are mutually exclusive, so when one is true, another one must be false. In such cases we can use the cut. So let us see the program."
},
{
"code": null,
"e": 110625,
"s": 110419,
"text": "We can also define a predicate where we use the two cases using disjunction (OR logic). So when first one satisfies, it does not check for the second one, otherwise, it will check for the second statement."
},
{
"code": null,
"e": 110720,
"s": 110625,
"text": "max(X,Y,X) :- X >= Y,!.\nmax(X,Y,Y) :- X < Y.\n\nmax_find(X,Y,Max) :- X >= Y,!, Max = X; Max = Y."
},
{
"code": null,
"e": 111361,
"s": 110720,
"text": "| ?- [cut_example].\n 1 1 Call: [cut_example] ?\ncompiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...\nD:/TP Prolog/Sample_Codes/cut_example.pl compiled, 3 lines read - 1195 bytes written, 43 ms\n 1 1 Exit: [cut_example] ?\nyes\n{trace}\n| ?- max(10,20,Max).\n 1 1 Call: max(10,20,_23) ?\n 2 2 Call: 10>=20 ?\n 2 2 Fail: 10>=20 ?\n 2 2 Call: 10<20 ?\n 2 2 Exit: 10<20 ?\n 1 1 Exit: max(10,20,20) ?\nMax = 20\n\nyes\n{trace}\n| ?- max_find(20,10,Max).\n 1 1 Call: max_find(20,10,_23) ?\n 2 2 Call: 20>=10 ?\n 2 2 Exit: 20>=10 ?\n 1 1 Exit: max_find(20,10,20) ?\nMax = 20\n\nyes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 111721,
"s": 111361,
"text": "Let us see another example, where we will use list. In this program we will try to insert an element into a list, if it is not present in the list before. And if the list has the element before we will simply cut it. For the membership checking also, if the item is at the head part, we should not check further, so cut it, otherwise check into the tail part."
},
{
"code": null,
"e": 111863,
"s": 111721,
"text": "list_member(X,[X|_]) :- !.\nlist_member(X,[_|TAIL]) :- list_member(X,TAIL).\n\nlist_append(A,T,T) :- list_member(A,T),!.\nlist_append(A,T,[A|T])."
},
{
"code": null,
"e": 113079,
"s": 111863,
"text": "| ?- [cut_example].\ncompiling D:/TP Prolog/Sample_Codes/cut_example.pl for byte code...\nD:/TP Prolog/Sample_Codes/cut_example.pl compiled, 9 lines read - 1954 bytes written, 15 ms\n\nyes\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- list_append(a,[a,b,c,d,e], L).\n 1 1 Call: list_append(a,[a,b,c,d,e],_33) ?\n 2 2 Call: list_member(a,[a,b,c,d,e]) ?\n 2 2 Exit: list_member(a,[a,b,c,d,e]) ?\n 1 1 Exit: list_append(a,[a,b,c,d,e],[a,b,c,d,e]) ?\n \nL = [a,b,c,d,e]\n\nyes\n{trace}\n| ?- list_append(k,[a,b,c,d,e], L).\n 1 1 Call: list_append(k,[a,b,c,d,e],_33) ?\n 2 2 Call: list_member(k,[a,b,c,d,e]) ?\n 3 3 Call: list_member(k,[b,c,d,e]) ?\n 4 4 Call: list_member(k,[c,d,e]) ?\n 5 5 Call: list_member(k,[d,e]) ?\n 6 6 Call: list_member(k,[e]) ?\n 7 7 Call: list_member(k,[]) ?\n 7 7 Fail: list_member(k,[]) ?\n 6 6 Fail: list_member(k,[e]) ?\n 5 5 Fail: list_member(k,[d,e]) ?\n 4 4 Fail: list_member(k,[c,d,e]) ?\n 3 3 Fail: list_member(k,[b,c,d,e]) ?\n 2 2 Fail: list_member(k,[a,b,c,d,e]) ?\n 1 1 Exit: list_append(k,[a,b,c,d,e],[k,a,b,c,d,e]) ?\n \nL = [k,a,b,c,d,e]\n\n(16 ms) yes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 113322,
"s": 113079,
"text": "Towers of Hanoi Problem is a famous puzzle to move N disks from the source peg/tower to the target peg/tower using the intermediate peg as an auxiliary holding peg. There are two conditions that are to be followed while solving this problem −"
},
{
"code": null,
"e": 113372,
"s": 113322,
"text": "A larger disk cannot be placed on a smaller disk."
},
{
"code": null,
"e": 113422,
"s": 113372,
"text": "A larger disk cannot be placed on a smaller disk."
},
{
"code": null,
"e": 113460,
"s": 113422,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 113498,
"s": 113460,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 113562,
"s": 113498,
"text": "The following diagram depicts the starting setup for N=3 disks."
},
{
"code": null,
"e": 113760,
"s": 113562,
"text": "To solve this, we have to write one procedure move(N, Source, Target, auxiliary). Here N number of disks will have to be shifted from Source peg to Target peg keeping Auxiliary peg as intermediate."
},
{
"code": null,
"e": 113810,
"s": 113760,
"text": "For example – move(3, source, target, auxiliary)."
},
{
"code": null,
"e": 113846,
"s": 113810,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 113882,
"s": 113846,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 113921,
"s": 113882,
"text": "Move top disk from source to auxiliary"
},
{
"code": null,
"e": 113960,
"s": 113921,
"text": "Move top disk from source to auxiliary"
},
{
"code": null,
"e": 113999,
"s": 113960,
"text": "Move top disk from target to auxiliary"
},
{
"code": null,
"e": 114038,
"s": 113999,
"text": "Move top disk from target to auxiliary"
},
{
"code": null,
"e": 114074,
"s": 114038,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 114110,
"s": 114074,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 114149,
"s": 114110,
"text": "Move top disk from auxiliary to source"
},
{
"code": null,
"e": 114188,
"s": 114149,
"text": "Move top disk from auxiliary to source"
},
{
"code": null,
"e": 114227,
"s": 114188,
"text": "Move top disk from auxiliary to target"
},
{
"code": null,
"e": 114266,
"s": 114227,
"text": "Move top disk from auxiliary to target"
},
{
"code": null,
"e": 114302,
"s": 114266,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 114338,
"s": 114302,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 114519,
"s": 114338,
"text": "move(1,X,Y,_) :-\n write('Move top disk from '), write(X), write(' to '), write(Y), nl.\nmove(N,X,Y,Z) :-\n N>1,\n M is N-1,\n move(M,X,Z,Y),\n move(1,X,Y,_),\n move(M,Z,Y,X)."
},
{
"code": null,
"e": 115340,
"s": 114519,
"text": "| ?- [towersofhanoi].\ncompiling D:/TP Prolog/Sample_Codes/towersofhanoi.pl for byte code...\nD:/TP Prolog/Sample_Codes/towersofhanoi.pl compiled, 8 lines read - 1409 bytes written, 15 ms\n\nyes\n| ?- move(4,source,target,auxiliary).\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\nMove top disk from source to auxiliary\nMove top disk from target to source\nMove top disk from target to auxiliary\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\nMove top disk from auxiliary to source\nMove top disk from target to source\nMove top disk from auxiliary to target\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\n\ntrue ?\n\n(31 ms) yes\n"
},
{
"code": null,
"e": 115432,
"s": 115340,
"text": "Following chapters describe how to generate/create linked lists using recursive structures."
},
{
"code": null,
"e": 115584,
"s": 115432,
"text": "Linked list has two components, the integer part and the link part. The link part will hold another node. End of list will have nil into the link part."
},
{
"code": null,
"e": 115653,
"s": 115584,
"text": "In prolog, we can express this using node(2, node(5, node(6, nil)))."
},
{
"code": null,
"e": 115979,
"s": 115653,
"text": "Note − The smallest possible list is nil, and every other list will contain nil as the \"next\" of the end node. In list terminology, the first element is usually called the head of the list, and the rest of the list is called the tail part. Thus the head of the above list is 2, and its tail is the list node(5, node(6, nil))."
},
{
"code": null,
"e": 116034,
"s": 115979,
"text": "We can also insert elements into front and back side −"
},
{
"code": null,
"e": 116234,
"s": 116034,
"text": "add_front(L,E,NList) :- NList = node(E,L).\n\nadd_back(nil, E, NList) :-\n NList = node(E,nil).\n \nadd_back(node(Head,Tail), E, NList) :-\n add_back(Tail, E, NewTail),\n NList = node(Head,NewTail)."
},
{
"code": null,
"e": 116887,
"s": 116234,
"text": "| ?- [linked_list].\ncompiling D:/TP Prolog/Sample_Codes/linked_list.pl for byte code...\nD:/TP Prolog/Sample_Codes/linked_list.pl compiled, 7 lines read - 966 bytes written, 14 ms\n\n(15 ms) yes\n| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(5,node(6,nil))\nL3 = node(2,node(5,node(6,nil)))\n\nyes\n| ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(6,node(5,nil))\nL3 = node(6,node(5,node(2,nil)))\n\nyes\n| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(5,node(6,nil))\nL3 = node(5,node(6,node(2,nil)))\n\nyes\n| ?-\n"
},
{
"code": null,
"e": 116995,
"s": 116887,
"text": "In this prolog example, we will see one very interesting and famous problem, The Monkey and Banana Problem."
},
{
"code": null,
"e": 117035,
"s": 116995,
"text": "Suppose the problem is as given below −"
},
{
"code": null,
"e": 117090,
"s": 117035,
"text": "A hungry monkey is in a room, and he is near the door."
},
{
"code": null,
"e": 117145,
"s": 117090,
"text": "A hungry monkey is in a room, and he is near the door."
},
{
"code": null,
"e": 117173,
"s": 117145,
"text": "The monkey is on the floor."
},
{
"code": null,
"e": 117201,
"s": 117173,
"text": "The monkey is on the floor."
},
{
"code": null,
"e": 117268,
"s": 117201,
"text": "Bananas have been hung from the center of the ceiling of the room."
},
{
"code": null,
"e": 117335,
"s": 117268,
"text": "Bananas have been hung from the center of the ceiling of the room."
},
{
"code": null,
"e": 117400,
"s": 117335,
"text": "There is a block (or chair) present in the room near the window."
},
{
"code": null,
"e": 117465,
"s": 117400,
"text": "There is a block (or chair) present in the room near the window."
},
{
"code": null,
"e": 117515,
"s": 117465,
"text": "The monkey wants the banana, but cannot reach it."
},
{
"code": null,
"e": 117565,
"s": 117515,
"text": "The monkey wants the banana, but cannot reach it."
},
{
"code": null,
"e": 117731,
"s": 117565,
"text": "So if the monkey is clever enough, he can come to the block, drag the block to the center, climb on it, and get the banana. Below are few observations in this case −"
},
{
"code": null,
"e": 117884,
"s": 117731,
"text": "Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor."
},
{
"code": null,
"e": 118037,
"s": 117884,
"text": "Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor."
},
{
"code": null,
"e": 118120,
"s": 118037,
"text": "If the block position is not at the center, then monkey can drag it to the center."
},
{
"code": null,
"e": 118203,
"s": 118120,
"text": "If the block position is not at the center, then monkey can drag it to the center."
},
{
"code": null,
"e": 118377,
"s": 118203,
"text": "If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed."
},
{
"code": null,
"e": 118551,
"s": 118377,
"text": "If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed."
},
{
"code": null,
"e": 118649,
"s": 118551,
"text": "When the monkey is on the block, and block is at the center, then the monkey can get the bananas."
},
{
"code": null,
"e": 118747,
"s": 118649,
"text": "When the monkey is on the block, and block is at the center, then the monkey can get the bananas."
},
{
"code": null,
"e": 118843,
"s": 118747,
"text": "Now, let us see how we can solve this using Prolog. We will create some predicates as follows −"
},
{
"code": null,
"e": 118937,
"s": 118843,
"text": "We have some predicates that will move from one state to another state, by performing action."
},
{
"code": null,
"e": 119141,
"s": 118937,
"text": "When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state."
},
{
"code": null,
"e": 119345,
"s": 119141,
"text": "When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state."
},
{
"code": null,
"e": 119450,
"s": 119345,
"text": "From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb."
},
{
"code": null,
"e": 119555,
"s": 119450,
"text": "From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb."
},
{
"code": null,
"e": 119625,
"s": 119555,
"text": "The push or drag operation moves the block from one place to another."
},
{
"code": null,
"e": 119695,
"s": 119625,
"text": "The push or drag operation moves the block from one place to another."
},
{
"code": null,
"e": 119765,
"s": 119695,
"text": "Monkey can move from one place to another using walk or move clauses."
},
{
"code": null,
"e": 119835,
"s": 119765,
"text": "Monkey can move from one place to another using walk or move clauses."
},
{
"code": null,
"e": 120113,
"s": 119835,
"text": "Another predicate will be canget(). Here we pass a state, so this will perform move predicate from one state to another using different actions, then perform canget() on state 2. When we have reached to the state ‘has>’, this indicates ‘has banana’. We will stop the execution."
},
{
"code": null,
"e": 120493,
"s": 120113,
"text": "move(state(middle,onbox,middle,hasnot),\n grasp,\n state(middle,onbox,middle,has)).\nmove(state(P,onfloor,P,H),\n climb,\n state(P,onbox,P,H)).\nmove(state(P1,onfloor,P1,H),\n drag(P1,P2),\n state(P2,onfloor,P2,H)).\nmove(state(P1,onfloor,B,H),\n walk(P1,P2),\n state(P2,onfloor,B,H)).\ncanget(state(_,_,_,has)).\ncanget(State1) :-\n move(State1,_,State2),\n canget(State2)."
},
{
"code": null,
"e": 122710,
"s": 120493,
"text": "| ?- [monkey_banana].\ncompiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code...\nD:/TP Prolog/Sample_Codes/monkey_banana.pl compiled, 17 lines read - 2167 bytes written, 19 ms\n\n(31 ms) yes\n| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).\n\ntrue ?\n\nyes\n| ?- trace\n.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- canget(state(atdoor, onfloor, atwindow, hasnot)).\n 1 1 Call: canget(state(atdoor,onfloor,atwindow,hasnot)) ?\n 2 2 Call: move(state(atdoor,onfloor,atwindow,hasnot),_52,_92) ?\n 2 2 Exit:move(state(atdoor,onfloor,atwindow,hasnot),walk(atdoor,_80),state(_80,onfloor,atwindow,hasnot)) ?\n 3 2 Call: canget(state(_80,onfloor,atwindow,hasnot)) ?\n 4 3 Call: move(state(_80,onfloor,atwindow,hasnot),_110,_150) ?\n 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ?\n 5 3 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ?\n 6 4 Call: move(state(atwindow,onbox,atwindow,hasnot),_165,_205) ?\n 6 4 Fail: move(state(atwindow,onbox,atwindow,hasnot),_165,_193) ?\n 5 3 Fail: canget(state(atwindow,onbox,atwindow,hasnot)) ?\n 4 3 Redo: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ?\n 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_138),state(_138,onfloor,_138,hasnot)) ?\n 5 3 Call: canget(state(_138,onfloor,_138,hasnot)) ?\n 6 4 Call: move(state(_138,onfloor,_138,hasnot),_168,_208) ?\n 6 4 Exit: move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasnot)) ?\n 7 4 Call: canget(state(_138,onbox,_138,hasnot)) ?\n 8 5 Call: move(state(_138,onbox,_138,hasnot),_223,_263) ?\n 8 5 Exit: move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has)) ?\n 9 5 Call: canget(state(middle,onbox,middle,has)) ?\n 9 5 Exit: canget(state(middle,onbox,middle,has)) ?\n 7 4 Exit: canget(state(middle,onbox,middle,hasnot)) ?\n 5 3 Exit: canget(state(middle,onfloor,middle,hasnot)) ?\n 3 2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ?\n 1 1 Exit: canget(state(atdoor,onfloor,atwindow,hasnot)) ?\n \ntrue ?\n\n(78 ms) yes\n"
},
{
"code": null,
"e": 122743,
"s": 122710,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 122762,
"s": 122743,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 122795,
"s": 122762,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 122814,
"s": 122795,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 122821,
"s": 122814,
"text": " Print"
},
{
"code": null,
"e": 122832,
"s": 122821,
"text": " Add Notes"
}
] |
Java 8 Interview Questions
|
Dear readers, these Java 8 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Java 8 Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
There are dozens of features added to Java 8, the most significant ones are mentioned below −
Lambda expression − Adds functional processing capability to Java.
Lambda expression − Adds functional processing capability to Java.
Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.
Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.
Default method − Interface to have default method implementation.
Default method − Interface to have default method implementation.
New tools − New compiler tools and utilities are added like 'jdeps' to figure out dependencies.
New tools − New compiler tools and utilities are added like 'jdeps' to figure out dependencies.
Stream API − New stream API to facilitate pipeline processing.
Stream API − New stream API to facilitate pipeline processing.
Date Time API − Improved date time API.
Date Time API − Improved date time API.
Optional − Emphasis on best practices to handle null values properly.
Optional − Emphasis on best practices to handle null values properly.
Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.
Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.
Along with these new featuers, lots of feature enhancements are done under-the-hood, at both compiler and JVM level.
Following code sorts a list of string using Java 8 lambda expression:
//sort using java 8
private void sortUsingJava8(List<String> names) {
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}
A lambda expression is characterized by the following syntax -
parameter −> expression body
Following are the important characteristics of a lambda expression −
Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.
Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.
Method references help to point to methods by their names. A method reference is described using :: (double colon) symbol. A method reference can be used to point the following types of methods −
Static methods
Static methods
Instance methods
Instance methods
Constructors using new operator (TreeSet::new)
Constructors using new operator (TreeSet::new)
System.out::println method is a static method reference to println method of out object of System class.
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions.
It represents an operation that accepts two input arguments, and returns no result.
It represents a function that accepts two arguments and produces a result.
It represents an operation upon two operands of the same type, producing a result of the same type as the operands.
It represents a predicate (Boolean-valued function) of two arguments.
It represents a supplier of Boolean-valued results.
It represents an operation that accepts a single input argument and returns no result.
It represents an operation upon two double-valued operands and producing a double-valued result.
It represents an operation that accepts a single double-valued argument and returns no result.
It represents a function that accepts a double-valued argument and produces a result.
It represents a predicate (Boolean-valued function) of one double-valued argument.
It represents a supplier of double-valued results.
It represents a function that accepts a double-valued argument and produces an int-valued result.
It represents a function that accepts a double-valued argument and produces a long-valued result.
It represents an operation on a single double-valued operand that produces a double-valued result.
It represents a function that accepts one argument and produces a result.
It represents an operation upon two int-valued operands and produces an int-valued result.
It represents an operation that accepts a single int-valued argument and returns no result.
It represents a function that accepts an int-valued argument and produces a result.
It represents a predicate (Boolean-valued function) of one int-valued argument.
It represents a supplier of int-valued results.
It represents a function that accepts an int-valued argument and produces a double-valued result.
It represents a function that accepts an int-valued argument and produces a long-valued result.
It represents an operation on a single int-valued operand that produces an int-valued result.
It represents an operation upon two long-valued operands and produces a long-valued result.
It represents an operation that accepts a single long-valued argument and returns no result.
It represents a function that accepts a long-valued argument and produces a result.
It represents a predicate (Boolean-valued function) of one long-valued argument.
It represents a supplier of long-valued results.
It represents a function that accepts a long-valued argument and produces a double-valued result.
It represents a function that accepts a long-valued argument and produces an int-valued result.
It represents an operation on a single long-valued operand that produces a long-valued result.
It represents an operation that accepts an object-valued and a double-valued argument, and returns no result.
It represents an operation that accepts an object-valued and an int-valued argument, and returns no result.
It represents an operation that accepts an object-valued and a long-valued argument, and returns no result.
It represents a predicate (Boolean-valued function) of one argument.
It represents a supplier of results.
It represents a function that accepts two arguments and produces a double-valued result.
It represents a function that produces a double-valued result.
It represents a function that accepts two arguments and produces an int-valued result.
It represents a function that produces an int-valued result.
It represents a function that accepts two arguments and produces a long-valued result.
It represents a function that produces a long-valued result.
It represents an operation on a single operand that produces a result of the same type as its operand.
With java 8, an interface can have default implementation of a function in interfaces.
An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
Using super keyword along with interface name.
interface Vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
}
class Car implements Vehicle {
public void print() {
Vehicle.super.print();
}
}
Using name of the interface.
interface Vehicle {
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
class Car implements Vehicle {
public void print() {
Vehicle.blowHorn();
}
}
Stream represents a sequence of objects from a source, which supports aggregate operations.
Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.
Stream has provided a new method 'forEach' to iterate each element of the stream.
The following code segment shows how to print 10 random numbers using forEach.
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
The 'map' method is used to map each element to its corresponding result.
The following code segment prints unique squares of numbers using map.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
The 'filter' method is used to eliminate elements based on a criteria.
The following code segment prints a count of empty strings using filter.
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.stream().filter(string −> string.isEmpty()).count();
The 'limit' method is used to reduce the size of the stream.
The following code segment shows how to print 10 random numbers.
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
The 'sorted' method is used to sort the stream.
The following code segment shows how to print 10 random numbers in a sorted order.
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream.
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.parallelStream().filter(string −> string.isEmpty()).count();
//It is very easy to switch between sequential and parallel streams.
Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string.
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);
With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done.
Following code will print the highest number present in a list.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();
System.out.println("Highest number in List : " + stats.getMax());
Following code will print the highest number present in a list.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();
System.out.println("Lowest number in List : " + stats.getMin());
Following code will print the sum of all numbers present in a list.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();
System.out.println("Sum of all numbers : " + stats.getSum());
Following code will print the average of all numbers present in a list.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();
System.out.println("Average of all numbers : " + stats.getAverage());
Optional is a container object which is used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.
With Java 8, Nashorn, a much improved javascript engine is introduced, to replace the existing Rhino. Nashorn provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invokedynamics feature, introduced in Java 7 to improve performance.
For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console.
Yes! Using ScriptEngineManager, JavaScript code can be called and interpreted in Java.
Local − Simplified date-time API with no complexity of timezone handling.
Zoned − Specialized date-time API to deal with various timezones.
java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values used in old API to represent day, month, etc.
Following code gets the current date using local datetime api −
//Get the current date
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
Following code adds 1 week to current date using local datetime api −
//add 1 week to the current date
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Next week: " + nextWeek);
Following code adds 1 month to current date using local datetime api:
//add 1 month to the current date
LocalDate today = LocalDate.now();
LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + nextMonth);
Following code adds 1 year to current date using local datetime api −
//add 1 year to the current date
LocalDate today = LocalDate.now();
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("Next year: " + nextYear);
Following code adds 10 years to current date using local datetime api −
//add 10 years to the current date
LocalDate today = LocalDate.now();
LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
System.out.println("Date after ten year: " + nextDecade);
Following code gets next tuesday using java8 −
//get the next tuesday
LocalDate today = LocalDate.now();
LocalDate nextTuesday = today.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
System.out.println("Next Tuesday on : " + nextTuesday);
Following code gets second saturday of next month using java8 −
//get the second saturday of next month
LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);
LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
System.out.println("Second Saturday on : " + secondSaturday);
Following code gets the instant of current date in terms of milliseconds −
//Get the instant of current date in terms of milliseconds
Instant now = currentDate.toInstant();
Following code gets the instant of local date time using time in of milliseconds −
Instant now = currentDate.toInstant();
ZoneId currentZone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
System.out.println("Local date: " + localDateTime);
Following code gets the instant of zoned date time using time in of milliseconds −
Instant now = currentDate.toInstant();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
System.out.println("Zoned date: " + zonedDateTime);
static class Base64.Decoder − This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
static class Base64.Encoder − This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
getDecoder() method of Base64 class returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme.
getEncoder() method of Base64 class returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme.
getMimeDecoder() method of Base64 class returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.
getMimeEncoder() method of Base64 class returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme.
getUrlDecoder() method of Base64 class returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.
getUrlEncoder() method of Base64 class returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
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": 2320,
"s": 1874,
"text": "Dear readers, these Java 8 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Java 8 Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 2414,
"s": 2320,
"text": "There are dozens of features added to Java 8, the most significant ones are mentioned below −"
},
{
"code": null,
"e": 2481,
"s": 2414,
"text": "Lambda expression − Adds functional processing capability to Java."
},
{
"code": null,
"e": 2548,
"s": 2481,
"text": "Lambda expression − Adds functional processing capability to Java."
},
{
"code": null,
"e": 2670,
"s": 2548,
"text": "Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter."
},
{
"code": null,
"e": 2792,
"s": 2670,
"text": "Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter."
},
{
"code": null,
"e": 2858,
"s": 2792,
"text": "Default method − Interface to have default method implementation."
},
{
"code": null,
"e": 2924,
"s": 2858,
"text": "Default method − Interface to have default method implementation."
},
{
"code": null,
"e": 3020,
"s": 2924,
"text": "New tools − New compiler tools and utilities are added like 'jdeps' to figure out dependencies."
},
{
"code": null,
"e": 3116,
"s": 3020,
"text": "New tools − New compiler tools and utilities are added like 'jdeps' to figure out dependencies."
},
{
"code": null,
"e": 3179,
"s": 3116,
"text": "Stream API − New stream API to facilitate pipeline processing."
},
{
"code": null,
"e": 3242,
"s": 3179,
"text": "Stream API − New stream API to facilitate pipeline processing."
},
{
"code": null,
"e": 3282,
"s": 3242,
"text": "Date Time API − Improved date time API."
},
{
"code": null,
"e": 3322,
"s": 3282,
"text": "Date Time API − Improved date time API."
},
{
"code": null,
"e": 3392,
"s": 3322,
"text": "Optional − Emphasis on best practices to handle null values properly."
},
{
"code": null,
"e": 3462,
"s": 3392,
"text": "Optional − Emphasis on best practices to handle null values properly."
},
{
"code": null,
"e": 3539,
"s": 3462,
"text": "Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code."
},
{
"code": null,
"e": 3616,
"s": 3539,
"text": "Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code."
},
{
"code": null,
"e": 3733,
"s": 3616,
"text": "Along with these new featuers, lots of feature enhancements are done under-the-hood, at both compiler and JVM level."
},
{
"code": null,
"e": 3803,
"s": 3733,
"text": "Following code sorts a list of string using Java 8 lambda expression:"
},
{
"code": null,
"e": 3932,
"s": 3803,
"text": "//sort using java 8\nprivate void sortUsingJava8(List<String> names) {\n Collections.sort(names, (s1, s2) -> s1.compareTo(s2));\n}"
},
{
"code": null,
"e": 3995,
"s": 3932,
"text": "A lambda expression is characterized by the following syntax -"
},
{
"code": null,
"e": 4024,
"s": 3995,
"text": "parameter −> expression body"
},
{
"code": null,
"e": 4093,
"s": 4024,
"text": "Following are the important characteristics of a lambda expression −"
},
{
"code": null,
"e": 4234,
"s": 4093,
"text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter."
},
{
"code": null,
"e": 4375,
"s": 4234,
"text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter."
},
{
"code": null,
"e": 4520,
"s": 4375,
"text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required."
},
{
"code": null,
"e": 4665,
"s": 4520,
"text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required."
},
{
"code": null,
"e": 4777,
"s": 4665,
"text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement."
},
{
"code": null,
"e": 4889,
"s": 4777,
"text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement."
},
{
"code": null,
"e": 5088,
"s": 4889,
"text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value."
},
{
"code": null,
"e": 5287,
"s": 5088,
"text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value."
},
{
"code": null,
"e": 5632,
"s": 5287,
"text": "Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService."
},
{
"code": null,
"e": 5769,
"s": 5632,
"text": "Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java."
},
{
"code": null,
"e": 5984,
"s": 5769,
"text": "Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time."
},
{
"code": null,
"e": 6180,
"s": 5984,
"text": "Method references help to point to methods by their names. A method reference is described using :: (double colon) symbol. A method reference can be used to point the following types of methods −"
},
{
"code": null,
"e": 6195,
"s": 6180,
"text": "Static methods"
},
{
"code": null,
"e": 6210,
"s": 6195,
"text": "Static methods"
},
{
"code": null,
"e": 6227,
"s": 6210,
"text": "Instance methods"
},
{
"code": null,
"e": 6244,
"s": 6227,
"text": "Instance methods"
},
{
"code": null,
"e": 6291,
"s": 6244,
"text": "Constructors using new operator (TreeSet::new)"
},
{
"code": null,
"e": 6338,
"s": 6291,
"text": "Constructors using new operator (TreeSet::new)"
},
{
"code": null,
"e": 6443,
"s": 6338,
"text": "System.out::println method is a static method reference to println method of out object of System class."
},
{
"code": null,
"e": 6702,
"s": 6443,
"text": "Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions."
},
{
"code": null,
"e": 6786,
"s": 6702,
"text": "It represents an operation that accepts two input arguments, and returns no result."
},
{
"code": null,
"e": 6861,
"s": 6786,
"text": "It represents a function that accepts two arguments and produces a result."
},
{
"code": null,
"e": 6977,
"s": 6861,
"text": "It represents an operation upon two operands of the same type, producing a result of the same type as the operands."
},
{
"code": null,
"e": 7047,
"s": 6977,
"text": "It represents a predicate (Boolean-valued function) of two arguments."
},
{
"code": null,
"e": 7099,
"s": 7047,
"text": "It represents a supplier of Boolean-valued results."
},
{
"code": null,
"e": 7186,
"s": 7099,
"text": "It represents an operation that accepts a single input argument and returns no result."
},
{
"code": null,
"e": 7283,
"s": 7186,
"text": "It represents an operation upon two double-valued operands and producing a double-valued result."
},
{
"code": null,
"e": 7378,
"s": 7283,
"text": "It represents an operation that accepts a single double-valued argument and returns no result."
},
{
"code": null,
"e": 7464,
"s": 7378,
"text": "It represents a function that accepts a double-valued argument and produces a result."
},
{
"code": null,
"e": 7547,
"s": 7464,
"text": "It represents a predicate (Boolean-valued function) of one double-valued argument."
},
{
"code": null,
"e": 7598,
"s": 7547,
"text": "It represents a supplier of double-valued results."
},
{
"code": null,
"e": 7696,
"s": 7598,
"text": "It represents a function that accepts a double-valued argument and produces an int-valued result."
},
{
"code": null,
"e": 7794,
"s": 7696,
"text": "It represents a function that accepts a double-valued argument and produces a long-valued result."
},
{
"code": null,
"e": 7893,
"s": 7794,
"text": "It represents an operation on a single double-valued operand that produces a double-valued result."
},
{
"code": null,
"e": 7967,
"s": 7893,
"text": "It represents a function that accepts one argument and produces a result."
},
{
"code": null,
"e": 8058,
"s": 7967,
"text": "It represents an operation upon two int-valued operands and produces an int-valued result."
},
{
"code": null,
"e": 8150,
"s": 8058,
"text": "It represents an operation that accepts a single int-valued argument and returns no result."
},
{
"code": null,
"e": 8234,
"s": 8150,
"text": "It represents a function that accepts an int-valued argument and produces a result."
},
{
"code": null,
"e": 8314,
"s": 8234,
"text": "It represents a predicate (Boolean-valued function) of one int-valued argument."
},
{
"code": null,
"e": 8362,
"s": 8314,
"text": "It represents a supplier of int-valued results."
},
{
"code": null,
"e": 8460,
"s": 8362,
"text": "It represents a function that accepts an int-valued argument and produces a double-valued result."
},
{
"code": null,
"e": 8556,
"s": 8460,
"text": "It represents a function that accepts an int-valued argument and produces a long-valued result."
},
{
"code": null,
"e": 8650,
"s": 8556,
"text": "It represents an operation on a single int-valued operand that produces an int-valued result."
},
{
"code": null,
"e": 8742,
"s": 8650,
"text": "It represents an operation upon two long-valued operands and produces a long-valued result."
},
{
"code": null,
"e": 8835,
"s": 8742,
"text": "It represents an operation that accepts a single long-valued argument and returns no result."
},
{
"code": null,
"e": 8919,
"s": 8835,
"text": "It represents a function that accepts a long-valued argument and produces a result."
},
{
"code": null,
"e": 9000,
"s": 8919,
"text": "It represents a predicate (Boolean-valued function) of one long-valued argument."
},
{
"code": null,
"e": 9049,
"s": 9000,
"text": "It represents a supplier of long-valued results."
},
{
"code": null,
"e": 9147,
"s": 9049,
"text": "It represents a function that accepts a long-valued argument and produces a double-valued result."
},
{
"code": null,
"e": 9243,
"s": 9147,
"text": "It represents a function that accepts a long-valued argument and produces an int-valued result."
},
{
"code": null,
"e": 9338,
"s": 9243,
"text": "It represents an operation on a single long-valued operand that produces a long-valued result."
},
{
"code": null,
"e": 9448,
"s": 9338,
"text": "It represents an operation that accepts an object-valued and a double-valued argument, and returns no result."
},
{
"code": null,
"e": 9556,
"s": 9448,
"text": "It represents an operation that accepts an object-valued and an int-valued argument, and returns no result."
},
{
"code": null,
"e": 9664,
"s": 9556,
"text": "It represents an operation that accepts an object-valued and a long-valued argument, and returns no result."
},
{
"code": null,
"e": 9733,
"s": 9664,
"text": "It represents a predicate (Boolean-valued function) of one argument."
},
{
"code": null,
"e": 9770,
"s": 9733,
"text": "It represents a supplier of results."
},
{
"code": null,
"e": 9859,
"s": 9770,
"text": "It represents a function that accepts two arguments and produces a double-valued result."
},
{
"code": null,
"e": 9922,
"s": 9859,
"text": "It represents a function that produces a double-valued result."
},
{
"code": null,
"e": 10009,
"s": 9922,
"text": "It represents a function that accepts two arguments and produces an int-valued result."
},
{
"code": null,
"e": 10070,
"s": 10009,
"text": "It represents a function that produces an int-valued result."
},
{
"code": null,
"e": 10157,
"s": 10070,
"text": "It represents a function that accepts two arguments and produces a long-valued result."
},
{
"code": null,
"e": 10218,
"s": 10157,
"text": "It represents a function that produces a long-valued result."
},
{
"code": null,
"e": 10321,
"s": 10218,
"text": "It represents an operation on a single operand that produces a result of the same type as its operand."
},
{
"code": null,
"e": 10408,
"s": 10321,
"text": "With java 8, an interface can have default implementation of a function in interfaces."
},
{
"code": null,
"e": 10478,
"s": 10408,
"text": "An interface can also have static helper methods from Java 8 onwards."
},
{
"code": null,
"e": 10663,
"s": 10478,
"text": "public interface vehicle {\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n \n static void blowHorn() {\n System.out.println(\"Blowing horn!!!\");\n }\n}"
},
{
"code": null,
"e": 10710,
"s": 10663,
"text": "Using super keyword along with interface name."
},
{
"code": null,
"e": 10918,
"s": 10710,
"text": "interface Vehicle {\n default void print() {\n System.out.println(\"I am a vehicle!\");\n }\n}\nclass Car implements Vehicle {\n public void print() {\n Vehicle.super.print(); \n }\n}"
},
{
"code": null,
"e": 10947,
"s": 10918,
"text": "Using name of the interface."
},
{
"code": null,
"e": 11154,
"s": 10947,
"text": "interface Vehicle {\n static void blowHorn() {\n System.out.println(\"Blowing horn!!!\");\n }\n}\nclass Car implements Vehicle {\n public void print() {\n Vehicle.blowHorn(); \n }\n}"
},
{
"code": null,
"e": 11246,
"s": 11154,
"text": "Stream represents a sequence of objects from a source, which supports aggregate operations."
},
{
"code": null,
"e": 11609,
"s": 11246,
"text": "Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream."
},
{
"code": null,
"e": 11756,
"s": 11609,
"text": "Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required."
},
{
"code": null,
"e": 11838,
"s": 11756,
"text": "Stream has provided a new method 'forEach' to iterate each element of the stream."
},
{
"code": null,
"e": 11917,
"s": 11838,
"text": "The following code segment shows how to print 10 random numbers using forEach."
},
{
"code": null,
"e": 12001,
"s": 11917,
"text": "Random random = new Random();\nrandom.ints().limit(10).forEach(System.out::println);"
},
{
"code": null,
"e": 12075,
"s": 12001,
"text": "The 'map' method is used to map each element to its corresponding result."
},
{
"code": null,
"e": 12146,
"s": 12075,
"text": "The following code segment prints unique squares of numbers using map."
},
{
"code": null,
"e": 12336,
"s": 12146,
"text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\n//get list of unique squares\nList<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());"
},
{
"code": null,
"e": 12408,
"s": 12336,
"text": "The 'filter' method is used to eliminate elements based on a criteria. "
},
{
"code": null,
"e": 12481,
"s": 12408,
"text": "The following code segment prints a count of empty strings using filter."
},
{
"code": null,
"e": 12661,
"s": 12481,
"text": "List<String>strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n//get count of empty string\nint count = strings.stream().filter(string −> string.isEmpty()).count();"
},
{
"code": null,
"e": 12723,
"s": 12661,
"text": "The 'limit' method is used to reduce the size of the stream. "
},
{
"code": null,
"e": 12788,
"s": 12723,
"text": "The following code segment shows how to print 10 random numbers."
},
{
"code": null,
"e": 12872,
"s": 12788,
"text": "Random random = new Random();\nrandom.ints().limit(10).forEach(System.out::println);"
},
{
"code": null,
"e": 12921,
"s": 12872,
"text": "The 'sorted' method is used to sort the stream. "
},
{
"code": null,
"e": 13004,
"s": 12921,
"text": "The following code segment shows how to print 10 random numbers in a sorted order."
},
{
"code": null,
"e": 13097,
"s": 13004,
"text": "Random random = new Random();\nrandom.ints().limit(10).sorted().forEach(System.out::println);"
},
{
"code": null,
"e": 13267,
"s": 13097,
"text": "parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream."
},
{
"code": null,
"e": 13525,
"s": 13267,
"text": "List<String> strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n//get count of empty string\nint count = strings.parallelStream().filter(string −> string.isEmpty()).count();\n//It is very easy to switch between sequential and parallel streams."
},
{
"code": null,
"e": 13663,
"s": 13525,
"text": "Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string."
},
{
"code": null,
"e": 14063,
"s": 13663,
"text": "List<String>strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\nList<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());\nSystem.out.println(\"Filtered List: \" + filtered);\nString mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(\", \"));\nSystem.out.println(\"Merged String: \" + mergedString);"
},
{
"code": null,
"e": 14179,
"s": 14063,
"text": "With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done."
},
{
"code": null,
"e": 14243,
"s": 14179,
"text": "Following code will print the highest number present in a list."
},
{
"code": null,
"e": 14456,
"s": 14243,
"text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\nIntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();\nSystem.out.println(\"Highest number in List : \" + stats.getMax());"
},
{
"code": null,
"e": 14520,
"s": 14456,
"text": "Following code will print the highest number present in a list."
},
{
"code": null,
"e": 14734,
"s": 14520,
"text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\nIntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();\nSystem.out.println(\"Lowest number in List : \" + stats.getMin());\n\n"
},
{
"code": null,
"e": 14802,
"s": 14734,
"text": "Following code will print the sum of all numbers present in a list."
},
{
"code": null,
"e": 15011,
"s": 14802,
"text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\nIntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();\nSystem.out.println(\"Sum of all numbers : \" + stats.getSum());"
},
{
"code": null,
"e": 15083,
"s": 15011,
"text": "Following code will print the average of all numbers present in a list."
},
{
"code": null,
"e": 15300,
"s": 15083,
"text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\nIntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();\nSystem.out.println(\"Average of all numbers : \" + stats.getAverage());"
},
{
"code": null,
"e": 15649,
"s": 15300,
"text": "Optional is a container object which is used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava."
},
{
"code": null,
"e": 15959,
"s": 15649,
"text": "With Java 8, Nashorn, a much improved javascript engine is introduced, to replace the existing Rhino. Nashorn provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invokedynamics feature, introduced in Java 7 to improve performance."
},
{
"code": null,
"e": 16067,
"s": 15959,
"text": "For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console."
},
{
"code": null,
"e": 16154,
"s": 16067,
"text": "Yes! Using ScriptEngineManager, JavaScript code can be called and interpreted in Java."
},
{
"code": null,
"e": 16228,
"s": 16154,
"text": "Local − Simplified date-time API with no complexity of timezone handling."
},
{
"code": null,
"e": 16294,
"s": 16228,
"text": "Zoned − Specialized date-time API to deal with various timezones."
},
{
"code": null,
"e": 16424,
"s": 16294,
"text": "java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values used in old API to represent day, month, etc."
},
{
"code": null,
"e": 16488,
"s": 16424,
"text": "Following code gets the current date using local datetime api −"
},
{
"code": null,
"e": 16592,
"s": 16488,
"text": "//Get the current date\nLocalDate today = LocalDate.now();\nSystem.out.println(\"Current date: \" + today);"
},
{
"code": null,
"e": 16662,
"s": 16592,
"text": "Following code adds 1 week to current date using local datetime api −"
},
{
"code": null,
"e": 16830,
"s": 16662,
"text": "//add 1 week to the current date\nLocalDate today = LocalDate.now();\nLocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);\nSystem.out.println(\"Next week: \" + nextWeek);"
},
{
"code": null,
"e": 16900,
"s": 16830,
"text": "Following code adds 1 month to current date using local datetime api:"
},
{
"code": null,
"e": 17073,
"s": 16900,
"text": "//add 1 month to the current date\nLocalDate today = LocalDate.now();\nLocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);\nSystem.out.println(\"Next month: \" + nextMonth);"
},
{
"code": null,
"e": 17143,
"s": 17073,
"text": "Following code adds 1 year to current date using local datetime api −"
},
{
"code": null,
"e": 17311,
"s": 17143,
"text": "//add 1 year to the current date\nLocalDate today = LocalDate.now();\nLocalDate nextYear = today.plus(1, ChronoUnit.YEARS);\nSystem.out.println(\"Next year: \" + nextYear);"
},
{
"code": null,
"e": 17383,
"s": 17311,
"text": "Following code adds 10 years to current date using local datetime api −"
},
{
"code": null,
"e": 17569,
"s": 17383,
"text": "//add 10 years to the current date\nLocalDate today = LocalDate.now();\nLocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);\nSystem.out.println(\"Date after ten year: \" + nextDecade);"
},
{
"code": null,
"e": 17616,
"s": 17569,
"text": "Following code gets next tuesday using java8 −"
},
{
"code": null,
"e": 17809,
"s": 17616,
"text": "//get the next tuesday\nLocalDate today = LocalDate.now();\nLocalDate nextTuesday = today.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));\nSystem.out.println(\"Next Tuesday on : \" + nextTuesday);"
},
{
"code": null,
"e": 17873,
"s": 17809,
"text": "Following code gets second saturday of next month using java8 −"
},
{
"code": null,
"e": 18194,
"s": 17873,
"text": "//get the second saturday of next month\nLocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);\nLocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(TemporalAdjusters.next(DayOfWeek.SATURDAY));\nSystem.out.println(\"Second Saturday on : \" + secondSaturday);"
},
{
"code": null,
"e": 18269,
"s": 18194,
"text": "Following code gets the instant of current date in terms of milliseconds −"
},
{
"code": null,
"e": 18367,
"s": 18269,
"text": "//Get the instant of current date in terms of milliseconds\nInstant now = currentDate.toInstant();"
},
{
"code": null,
"e": 18450,
"s": 18367,
"text": "Following code gets the instant of local date time using time in of milliseconds −"
},
{
"code": null,
"e": 18659,
"s": 18450,
"text": "Instant now = currentDate.toInstant();\nZoneId currentZone = ZoneId.systemDefault();\nLocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);\nSystem.out.println(\"Local date: \" + localDateTime);"
},
{
"code": null,
"e": 18742,
"s": 18659,
"text": "Following code gets the instant of zoned date time using time in of milliseconds −"
},
{
"code": null,
"e": 18951,
"s": 18742,
"text": "Instant now = currentDate.toInstant();\nZoneId currentZone = ZoneId.systemDefault();\nZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);\nSystem.out.println(\"Zoned date: \" + zonedDateTime);"
},
{
"code": null,
"e": 19108,
"s": 18951,
"text": "static class Base64.Decoder − This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045."
},
{
"code": null,
"e": 19266,
"s": 19108,
"text": "static class Base64.Encoder − This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045."
},
{
"code": null,
"e": 19385,
"s": 19266,
"text": "getDecoder() method of Base64 class returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme."
},
{
"code": null,
"e": 19504,
"s": 19385,
"text": "getEncoder() method of Base64 class returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme."
},
{
"code": null,
"e": 19626,
"s": 19504,
"text": "getMimeDecoder() method of Base64 class returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme."
},
{
"code": null,
"e": 19748,
"s": 19626,
"text": "getMimeEncoder() method of Base64 class returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme."
},
{
"code": null,
"e": 19886,
"s": 19748,
"text": "getUrlDecoder() method of Base64 class returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme."
},
{
"code": null,
"e": 20024,
"s": 19886,
"text": "getUrlEncoder() method of Base64 class returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme."
},
{
"code": null,
"e": 20311,
"s": 20024,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 20641,
"s": 20311,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 20674,
"s": 20641,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 20690,
"s": 20674,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 20723,
"s": 20690,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 20739,
"s": 20723,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 20774,
"s": 20739,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 20788,
"s": 20774,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 20822,
"s": 20788,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 20836,
"s": 20822,
"text": " Tushar Kale"
},
{
"code": null,
"e": 20873,
"s": 20836,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 20888,
"s": 20873,
"text": " Monica Mittal"
},
{
"code": null,
"e": 20921,
"s": 20888,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 20940,
"s": 20921,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 20947,
"s": 20940,
"text": " Print"
},
{
"code": null,
"e": 20958,
"s": 20947,
"text": " Add Notes"
}
] |
MATLAB - Plotting
|
To plot the graph of a function, you need to take the following steps −
Define x, by specifying the range of values for the variable x, for which the function is to be plotted
Define x, by specifying the range of values for the variable x, for which the function is to be plotted
Define the function, y = f(x)
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y = x for the range of values for x from 0 to 100, with an increment of 5.
Create a script file and type the following code −
x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Let us take one more example to plot the function y = x2. In this example, we will draw two graphs with the same function, but in second time, we will reduce the value of increment. Please note that as we decrease the increment, the graph becomes smoother.
Create a script file and type the following code −
x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Change the code file a little, reduce the increment to 5 −
x = [-100:5:100];
y = x.^2;
plot(x, y)
MATLAB draws a smoother graph −
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The title command allows you to put a title on the graph.
The title command allows you to put a title on the graph.
The grid on command allows you to put the grid lines on the graph.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale factors and the spaces on both axes.
The axis equal command allows generating the plot with the same scale factors and the spaces on both axes.
The axis square command generates a square plot.
The axis square command generates a square plot.
Create a script file and type the following code −
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
MATLAB generates the following graph −
You can draw multiple graphs on the same plot. The following example demonstrates the concept −
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
MATLAB generates the following graph −
MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes −
Let us draw the graph of two polynomials
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
g(x) = 5x3 + 9x + 2
g(x) = 5x3 + 9x + 2
Create a script file and type the following code −
x = [-10 : 0.01: 10];
y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')
When you run the file, MATLAB generates the following graph −
The axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way −
axis ( [xmin xmax ymin ymax] )
The following example shows this −
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
When you run the file, MATLAB generates the following graph −
When you create an array of plots in the same figure, each of these plots is called a subplot. The subplot command is used for creating subplots.
Syntax for the command is −
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies where to put a particular plot.
Each plot created with the subplot command can have its own characteristics. Following example demonstrates the concept −
Let us generate two plots −
y = e−1.5xsin(10x)
y = e−2xsin(10x)
Create a script file and type the following code −
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])
When you run the file, MATLAB generates the following graph −
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2213,
"s": 2141,
"text": "To plot the graph of a function, you need to take the following steps −"
},
{
"code": null,
"e": 2317,
"s": 2213,
"text": "Define x, by specifying the range of values for the variable x, for which the function is to be plotted"
},
{
"code": null,
"e": 2421,
"s": 2317,
"text": "Define x, by specifying the range of values for the variable x, for which the function is to be plotted"
},
{
"code": null,
"e": 2451,
"s": 2421,
"text": "Define the function, y = f(x)"
},
{
"code": null,
"e": 2481,
"s": 2451,
"text": "Define the function, y = f(x)"
},
{
"code": null,
"e": 2518,
"s": 2481,
"text": "Call the plot command, as plot(x, y)"
},
{
"code": null,
"e": 2555,
"s": 2518,
"text": "Call the plot command, as plot(x, y)"
},
{
"code": null,
"e": 2711,
"s": 2555,
"text": "Following example would demonstrate the concept. Let us plot the simple function y = x for the range of values for x from 0 to 100, with an increment of 5."
},
{
"code": null,
"e": 2762,
"s": 2711,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 2795,
"s": 2762,
"text": "x = [0:5:100];\ny = x;\nplot(x, y)"
},
{
"code": null,
"e": 2855,
"s": 2795,
"text": "When you run the file, MATLAB displays the following plot −"
},
{
"code": null,
"e": 3112,
"s": 2855,
"text": "Let us take one more example to plot the function y = x2. In this example, we will draw two graphs with the same function, but in second time, we will reduce the value of increment. Please note that as we decrease the increment, the graph becomes smoother."
},
{
"code": null,
"e": 3163,
"s": 3112,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 3231,
"s": 3163,
"text": "x = [1 2 3 4 5 6 7 8 9 10];\nx = [-100:20:100];\ny = x.^2;\nplot(x, y)"
},
{
"code": null,
"e": 3291,
"s": 3231,
"text": "When you run the file, MATLAB displays the following plot −"
},
{
"code": null,
"e": 3350,
"s": 3291,
"text": "Change the code file a little, reduce the increment to 5 −"
},
{
"code": null,
"e": 3389,
"s": 3350,
"text": "x = [-100:5:100];\ny = x.^2;\nplot(x, y)"
},
{
"code": null,
"e": 3421,
"s": 3389,
"text": "MATLAB draws a smoother graph −"
},
{
"code": null,
"e": 3552,
"s": 3421,
"text": "MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph."
},
{
"code": null,
"e": 3624,
"s": 3552,
"text": "The xlabel and ylabel commands generate labels along x-axis and y-axis."
},
{
"code": null,
"e": 3696,
"s": 3624,
"text": "The xlabel and ylabel commands generate labels along x-axis and y-axis."
},
{
"code": null,
"e": 3754,
"s": 3696,
"text": "The title command allows you to put a title on the graph."
},
{
"code": null,
"e": 3812,
"s": 3754,
"text": "The title command allows you to put a title on the graph."
},
{
"code": null,
"e": 3879,
"s": 3812,
"text": "The grid on command allows you to put the grid lines on the graph."
},
{
"code": null,
"e": 3946,
"s": 3879,
"text": "The grid on command allows you to put the grid lines on the graph."
},
{
"code": null,
"e": 4053,
"s": 3946,
"text": "The axis equal command allows generating the plot with the same scale factors and the spaces on both axes."
},
{
"code": null,
"e": 4160,
"s": 4053,
"text": "The axis equal command allows generating the plot with the same scale factors and the spaces on both axes."
},
{
"code": null,
"e": 4209,
"s": 4160,
"text": "The axis square command generates a square plot."
},
{
"code": null,
"e": 4258,
"s": 4209,
"text": "The axis square command generates a square plot."
},
{
"code": null,
"e": 4309,
"s": 4258,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 4424,
"s": 4309,
"text": "x = [0:0.01:10];\ny = sin(x);\nplot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),\ngrid on, axis equal"
},
{
"code": null,
"e": 4463,
"s": 4424,
"text": "MATLAB generates the following graph −"
},
{
"code": null,
"e": 4559,
"s": 4463,
"text": "You can draw multiple graphs on the same plot. The following example demonstrates the concept −"
},
{
"code": null,
"e": 4610,
"s": 4559,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 4705,
"s": 4610,
"text": "x = [0 : 0.01: 10];\ny = sin(x);\ng = cos(x);\nplot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')"
},
{
"code": null,
"e": 4744,
"s": 4705,
"text": "MATLAB generates the following graph −"
},
{
"code": null,
"e": 4861,
"s": 4744,
"text": "MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes −"
},
{
"code": null,
"e": 4902,
"s": 4861,
"text": "Let us draw the graph of two polynomials"
},
{
"code": null,
"e": 4937,
"s": 4902,
"text": "f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and"
},
{
"code": null,
"e": 4972,
"s": 4937,
"text": "f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and"
},
{
"code": null,
"e": 4992,
"s": 4972,
"text": "g(x) = 5x3 + 9x + 2"
},
{
"code": null,
"e": 5012,
"s": 4992,
"text": "g(x) = 5x3 + 9x + 2"
},
{
"code": null,
"e": 5063,
"s": 5012,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 5184,
"s": 5063,
"text": "x = [-10 : 0.01: 10];\ny = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;\ng = 5 * x.^3 + 9 * x + 2;\nplot(x, y, 'r', x, g, 'g')"
},
{
"code": null,
"e": 5246,
"s": 5184,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 5404,
"s": 5246,
"text": "The axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way −"
},
{
"code": null,
"e": 5436,
"s": 5404,
"text": "axis ( [xmin xmax ymin ymax] )\n"
},
{
"code": null,
"e": 5471,
"s": 5436,
"text": "The following example shows this −"
},
{
"code": null,
"e": 5522,
"s": 5471,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 5600,
"s": 5522,
"text": "x = [0 : 0.01: 10];\ny = exp(-x).* sin(2*x + 3);\nplot(x, y), axis([0 10 -1 1])"
},
{
"code": null,
"e": 5662,
"s": 5600,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 5808,
"s": 5662,
"text": "When you create an array of plots in the same figure, each of these plots is called a subplot. The subplot command is used for creating subplots."
},
{
"code": null,
"e": 5836,
"s": 5808,
"text": "Syntax for the command is −"
},
{
"code": null,
"e": 5854,
"s": 5836,
"text": "subplot(m, n, p)\n"
},
{
"code": null,
"e": 5970,
"s": 5854,
"text": "where, m and n are the number of rows and columns of the plot array and p specifies where to put a particular plot."
},
{
"code": null,
"e": 6092,
"s": 5970,
"text": "Each plot created with the subplot command can have its own characteristics. Following example demonstrates the concept −"
},
{
"code": null,
"e": 6120,
"s": 6092,
"text": "Let us generate two plots −"
},
{
"code": null,
"e": 6139,
"s": 6120,
"text": "y = e−1.5xsin(10x)"
},
{
"code": null,
"e": 6156,
"s": 6139,
"text": "y = e−2xsin(10x)"
},
{
"code": null,
"e": 6207,
"s": 6156,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 6444,
"s": 6207,
"text": "x = [0:0.01:5];\ny = exp(-1.5*x).*sin(10*x);\nsubplot(1,2,1)\nplot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])\ny = exp(-2*x).*sin(10*x);\nsubplot(1,2,2)\nplot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])"
},
{
"code": null,
"e": 6506,
"s": 6444,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 6539,
"s": 6506,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6552,
"s": 6539,
"text": " Nouman Azam"
},
{
"code": null,
"e": 6587,
"s": 6552,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 6600,
"s": 6587,
"text": " Nouman Azam"
},
{
"code": null,
"e": 6633,
"s": 6600,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6642,
"s": 6633,
"text": " Sanjeev"
},
{
"code": null,
"e": 6675,
"s": 6642,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6691,
"s": 6675,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6724,
"s": 6691,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6740,
"s": 6724,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6773,
"s": 6740,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6790,
"s": 6773,
"text": " Phinite Academy"
},
{
"code": null,
"e": 6797,
"s": 6790,
"text": " Print"
},
{
"code": null,
"e": 6808,
"s": 6797,
"text": " Add Notes"
}
] |
Sum of the Series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... in C++
|
In this problem, we are given a number n which is the nth term of the series 1/(1*2) + 1/(2*3) +...+ 1/(n*(n+1)). Our task is to create a program to find the sum of the series.
Input
n = 3
Output
0.75
Explanation − sum = 1/(1*2) + 1/(2*3) + 1/(3*4) = 1⁄2 + 1⁄6+ 1/12 = (6+2+1)/12 = 9/12 = 3⁄4 = 0.75
A simple solution to the problem is using the loop. And commuting value for each element of the series. Then add them to the sum value.
Initialize sum = 0
Step 1: Iterate from i = 1 to n. And follow :
Step 1.1: Update sum, sum += 1/ ( i*(i+1) )
Step 2: Print sum.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
double sum = 0.0;
for (int i = 1; i <= n; i++)
sum += ((double)1/(i*(i+1)));
return sum;
}
int main() {
int n = 5;
cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
return 0;
}
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333
This solution is not much effective as it uses loops.
An effective approach to solve the problem is using the general formula for the sum of series.
The series is 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...
n-th terms is 1/n(n+1).
an = 1/n(n+1)
an = ((n+1) - n) /n(n+1)
an = (n+1)/n(n+1) - n/ n(n+1)
an = 1/n - 1/(n+1)
sum of the series is
sum = 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...
Changing each term as in above formula,
sum = 1/1 - 1⁄2 + 1⁄2 - 1⁄3 + 1⁄3 - 1⁄4 + 1⁄4 -1⁄5 + .... 1/n - 1/(n+1)
sum = 1 - 1/(n+1)
sum = (n+1 -1) / (n+1) = n/(n+1)
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
return ((double)n/ (n+1));
}
int main() {
int n = 5;
cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
return 0;
}
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "In this problem, we are given a number n which is the nth term of the series 1/(1*2) + 1/(2*3) +...+ 1/(n*(n+1)). Our task is to create a program to find the sum of the series."
},
{
"code": null,
"e": 1246,
"s": 1239,
"text": "Input "
},
{
"code": null,
"e": 1252,
"s": 1246,
"text": "n = 3"
},
{
"code": null,
"e": 1260,
"s": 1252,
"text": "Output "
},
{
"code": null,
"e": 1265,
"s": 1260,
"text": "0.75"
},
{
"code": null,
"e": 1364,
"s": 1265,
"text": "Explanation − sum = 1/(1*2) + 1/(2*3) + 1/(3*4) = 1⁄2 + 1⁄6+ 1/12 = (6+2+1)/12 = 9/12 = 3⁄4 = 0.75"
},
{
"code": null,
"e": 1500,
"s": 1364,
"text": "A simple solution to the problem is using the loop. And commuting value for each element of the series. Then add them to the sum value."
},
{
"code": null,
"e": 1631,
"s": 1500,
"text": "Initialize sum = 0\nStep 1: Iterate from i = 1 to n. And follow :\n Step 1.1: Update sum, sum += 1/ ( i*(i+1) )\nStep 2: Print sum."
},
{
"code": null,
"e": 1682,
"s": 1631,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 1693,
"s": 1682,
"text": " Live Demo"
},
{
"code": null,
"e": 2005,
"s": 1693,
"text": "#include <iostream>\nusing namespace std;\ndouble calcSeriesSum(int n) {\n double sum = 0.0;\n for (int i = 1; i <= n; i++)\n sum += ((double)1/(i*(i+1)));\n return sum;\n}\nint main() {\n int n = 5;\n cout<<\"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is \"<<calcSeriesSum(n);\n return 0;\n}"
},
{
"code": null,
"e": 2079,
"s": 2005,
"text": "Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333"
},
{
"code": null,
"e": 2133,
"s": 2079,
"text": "This solution is not much effective as it uses loops."
},
{
"code": null,
"e": 2228,
"s": 2133,
"text": "An effective approach to solve the problem is using the general formula for the sum of series."
},
{
"code": null,
"e": 2632,
"s": 2228,
"text": "The series is 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...\nn-th terms is 1/n(n+1).\nan = 1/n(n+1)\nan = ((n+1) - n) /n(n+1)\nan = (n+1)/n(n+1) - n/ n(n+1)\nan = 1/n - 1/(n+1)\nsum of the series is\nsum = 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...\nChanging each term as in above formula,\nsum = 1/1 - 1⁄2 + 1⁄2 - 1⁄3 + 1⁄3 - 1⁄4 + 1⁄4 -1⁄5 + .... 1/n - 1/(n+1)\nsum = 1 - 1/(n+1)\nsum = (n+1 -1) / (n+1) = n/(n+1)"
},
{
"code": null,
"e": 2683,
"s": 2632,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2694,
"s": 2683,
"text": " Live Demo"
},
{
"code": null,
"e": 2935,
"s": 2694,
"text": "#include <iostream>\nusing namespace std;\ndouble calcSeriesSum(int n) {\n return ((double)n/ (n+1));\n}\nint main() {\n int n = 5;\n cout<<\"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is \"<<calcSeriesSum(n);\n return 0;\n}"
},
{
"code": null,
"e": 3009,
"s": 2935,
"text": "Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333"
}
] |
Spring MVC Login Form Example Tutorials - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Spring MVC Login Form is a basic example for all spring based applications. We can hardly imagine any web application without forms in it because forms have their own importance in web application development.
In this tutorial, we are going to see how forms are used in Spring Framework, and how spring forms are different from normal HTML forms.
As part of this tutorial, I am going to implement a simple Spring-based Login Form. Though it is a simple login form, it requires more understanding about each and every newer thing init.
Spring offers different types of annotations to handling forms. Here are the typical annotations that every spring developer should know.
@Controller is an annotation, used in Spring MVC Framework.
@Controller annotation is a sub annotation of @Cmponent annotation.
We can use @Controller annotation on top of the class only.
It indicates that a particular class serves the role of controller in the MVC pattern.
@Controller annotation acts as a stereotype for the annotated class, indicating its roles.
Like @Controller annotation, @RequestMapping annotation is also used in Spring MVC Framework.
@RequestMapping annotation can be applied on top of the class and/or methods, and it should be used along with the @Controller annotation.
It is used to bind an HTTP request to spring components or handler methods.
Class level mapping binds a specific request to the Spring component (class), whereas method level mapping binds a specific request to a specific handler method.
@ModelAttribute annotation can be used on top of a method or method argument.
An @ModelAttribute on a method is used to populate the model with commonly needed attributes for example to fill a drop-down with states.
@ModelAttribute on method arguments refers to a specific property in Model class (MVC).
Used to bind the data from form to controller
It should be used along with @RequestMapping in Controllers
@ModelAttribute is invoked before the actual controller method starts execution along with @RequestMapping
Recommended: Spring with Hibernate Integration Complete Example
Here we are going to implement the Spring MVC Login form step by step.
Download Example : Spring MVC Login Form Example with STS (NEW)
Project Structure:
Follow below project structure to add described files below.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@taglib
uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring Login Form</title>
</head>
<body>
<form:form name="submitForm" method="POST">
<div align="center">
<table>
<tr>
<td>User Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
<div style="color: red">${error}</div>
</div>
</form:form>
</body>
</html>
On the above login form, we used <form:form> tag. Which is given by the spring framework. To use this tag, we need to include the below taglib directory on top of the jsp page.
<%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%>
The main advantage of using the <form: form> is, spring automatically binds the form data to the model bean whenever we submit this form. To make it work, the properties in the model class should be equal to the name of form data elements.
For instance, we have created a text box field with the name userName and password field with the name password. The same names should be used as part of the Model class attributes.
Create a Login Model :
package com.spring.controller;
public class LoginBean {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Recommended: Spring Boot MVC Login Form Example
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.spring.controller" />
</beans:beans>
Points To Note :
<annotation-driven />, informs Spring container that we are going to use annotations in this application and can be used to identify annotations and to perform respective functions.
Created a ViewResolver bean and mapped with the folder name where our actual views (JSP) are present as prefix and extension as a suffix
Component scanning with <context:component-scan base-package=”com.spring.controller” />, is telling spring that it should search the classpath for all the classes under com.spring.controller and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class=”...” /> in the XML configuration files.
Configure the web.xml File :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Points To Note :
Define DispatcherServlet, which will act as a front controller to route the requests
Create a Spring Controller :
package com.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String init(Model model) {
model.addAttribute("msg", "Please Enter Your Login Details");
return "login";
}
@RequestMapping(method = RequestMethod.POST)
public String submit(Model model, @ModelAttribute("loginBean") LoginBean loginBean) {
if (loginBean != null && loginBean.getUserName() != null & loginBean.getPassword() != null) {
if (loginBean.getUserName().equals("chandra") && loginBean.getPassword().equals("chandra123")) {
model.addAttribute("msg", loginBean.getUserName());
return "success";
} else {
model.addAttribute("error", "Invalid Details");
return "login";
}
} else {
model.addAttribute("error", "Please enter Details");
return "login";
}
}
}
Points To Note :
We have created two handler methods
init
This is a default handler method for HTTP GET requests. The RequestMapping url is “/login”.
submit
This method is called whenever the form get submitted because the HTTP type for this method is POST.
All the form elements are fed into the LoginBean object and we retrieve them using @ModelAttribute annotation
To run this application, we can make use of the below URL.
http://localhost:8080/Spring-MVC-LoginForm/login
Error Response :
Giving Valid credentials :
Success Page :
The complete Example is available for download : Spring MVC Login Form Example with STS (NEW)
Happy Learning 🙂
Spring MVC Login Form Example with STS (NEW)
File size: 28 KB
Downloads: 22653
Spring MVC Login Form Example With Netbeans
File size: 18 MB
Downloads: 33337
Spring Boot MVC Example Tutorials
Spring MVC Form Validation Example
Spring Boot Validation Login Form Example
Spring Web MVC Framework Flow
Python Selenium Automate the Login Form
Spring MVC HelloWorld
Spring Form Custom Validation Example
Spring MVC Tiles Example (Apache Tiles)
Python – Flask Login Form Example
Spring Hibernate Example
Basic Android Login Form Example
AngularJs Directive Example Tutorials
How to Get All Spring Beans Details Loaded in ICO
@Component,@Service,@Repository,@Controller in spring
Spring Boot FileUpload Ajax Example
Spring Boot MVC Example Tutorials
Spring MVC Form Validation Example
Spring Boot Validation Login Form Example
Spring Web MVC Framework Flow
Python Selenium Automate the Login Form
Spring MVC HelloWorld
Spring Form Custom Validation Example
Spring MVC Tiles Example (Apache Tiles)
Python – Flask Login Form Example
Spring Hibernate Example
Basic Android Login Form Example
AngularJs Directive Example Tutorials
How to Get All Spring Beans Details Loaded in ICO
@Component,@Service,@Repository,@Controller in spring
Spring Boot FileUpload Ajax Example
vishwanath
December 29, 2015 at 8:02 am - Reply
good one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples.
chandrashekhar
December 30, 2015 at 4:34 pm - Reply
Hi Vishwanath,
Thank you for your comment. Can you please explain your query in detail, so that I can help you better.
Thankyou,
Chandrashekhar
Virendra
February 7, 2016 at 8:17 am - Reply
Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂
Ravichandra
March 14, 2017 at 5:34 am - Reply
Hi Chandra....
Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....
Virendra
February 7, 2016 at 8:34 am - Reply
@Vishwanath
I think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.
For such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,
Step 1: Retrieve user roles from DB as per authentication from your DAO layer.
Step 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.
if(users.getUserRole.equals("amin"))
{
return "Admin";
}
if(users.getUserRole.equals("client"))
{
return "Client";
}
Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.
Step4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.
Where all users will have their respective permissions to work in your system.
pradeep
March 28, 2016 at 4:42 am - Reply
i am getting Error-The request sent by the client was syntactically incorrect.
jagriti
May 31, 2016 at 11:21 am - Reply
why you added applicationcontext. xml in web.xml param name
Tejeswar
September 4, 2016 at 11:14 am - Reply
I just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.
Thank you for your help.
chandrashekhar
September 4, 2016 at 2:54 pm - Reply
Hi Tejeswar,
Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build.
For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven.
Please don’t hesitate to write comment us, if you find any problem.
Thanks.
kanchan
November 3, 2016 at 3:58 am - Reply
can u please give example first register then login and then CRUD operation in single project
satya prakash
December 9, 2016 at 10:47 am - Reply
When i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.
Please explain exception ..
Venkatesh
December 13, 2016 at 8:14 am - Reply
Hey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven
Surendra
January 19, 2017 at 6:42 am - Reply
Very Well explained..
Thank you @chandrashekhar
Obireddy
January 22, 2017 at 6:24 am - Reply
I want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly
Thiyagarajan
April 11, 2017 at 5:27 pm - Reply
Hi,
I am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse.
Sheeja
May 3, 2017 at 10:08 am - Reply
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?
Prasanta
May 9, 2017 at 1:20 pm - Reply
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone explain why?
raza
November 19, 2017 at 10:21 am - Reply
Hi !
I just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere
Umesh
December 16, 2017 at 8:40 am - Reply
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone help me please.
prasanna
December 20, 2017 at 10:14 am - Reply
nice tutorial what i have to do to handle the session
suresh
December 21, 2017 at 6:35 am - Reply
Hello Sir,....Your tutorial is really Good....
But Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email...
Bhavesh
March 1, 2018 at 8:49 am - Reply
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
maha
July 12, 2018 at 5:27 pm - Reply
hello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse
Arpit
July 28, 2019 at 6:25 pm - Reply
Hi,
Nice tutorial.
Nehal Raju
August 12, 2020 at 12:54 pm - Reply
Can u send the link for login page using spring mvc and hibernate through NetBeans. share me to my email id
vishwanath
December 29, 2015 at 8:02 am - Reply
good one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples.
chandrashekhar
December 30, 2015 at 4:34 pm - Reply
Hi Vishwanath,
Thank you for your comment. Can you please explain your query in detail, so that I can help you better.
Thankyou,
Chandrashekhar
Virendra
February 7, 2016 at 8:17 am - Reply
Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂
Ravichandra
March 14, 2017 at 5:34 am - Reply
Hi Chandra....
Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....
Virendra
February 7, 2016 at 8:34 am - Reply
@Vishwanath
I think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.
For such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,
Step 1: Retrieve user roles from DB as per authentication from your DAO layer.
Step 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.
if(users.getUserRole.equals("amin"))
{
return "Admin";
}
if(users.getUserRole.equals("client"))
{
return "Client";
}
Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.
Step4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.
Where all users will have their respective permissions to work in your system.
good one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples.
chandrashekhar
December 30, 2015 at 4:34 pm - Reply
Hi Vishwanath,
Thank you for your comment. Can you please explain your query in detail, so that I can help you better.
Thankyou,
Chandrashekhar
Virendra
February 7, 2016 at 8:17 am - Reply
Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂
Ravichandra
March 14, 2017 at 5:34 am - Reply
Hi Chandra....
Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....
Hi Vishwanath,
Thank you for your comment. Can you please explain your query in detail, so that I can help you better.
Thankyou,
Chandrashekhar
Virendra
February 7, 2016 at 8:17 am - Reply
Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂
Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂
Ravichandra
March 14, 2017 at 5:34 am - Reply
Hi Chandra....
Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....
Hi Chandra....
Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....
Virendra
February 7, 2016 at 8:34 am - Reply
@Vishwanath
I think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.
For such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,
Step 1: Retrieve user roles from DB as per authentication from your DAO layer.
Step 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.
if(users.getUserRole.equals("amin"))
{
return "Admin";
}
if(users.getUserRole.equals("client"))
{
return "Client";
}
Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.
Step4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.
Where all users will have their respective permissions to work in your system.
@Vishwanath
I think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.
For such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,
Step 1: Retrieve user roles from DB as per authentication from your DAO layer.
Step 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.
if(users.getUserRole.equals("amin"))
{
return "Admin";
}
if(users.getUserRole.equals("client"))
{
return "Client";
}
Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.
Step4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.
Where all users will have their respective permissions to work in your system.
pradeep
March 28, 2016 at 4:42 am - Reply
i am getting Error-The request sent by the client was syntactically incorrect.
i am getting Error-The request sent by the client was syntactically incorrect.
jagriti
May 31, 2016 at 11:21 am - Reply
why you added applicationcontext. xml in web.xml param name
why you added applicationcontext. xml in web.xml param name
Tejeswar
September 4, 2016 at 11:14 am - Reply
I just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.
Thank you for your help.
chandrashekhar
September 4, 2016 at 2:54 pm - Reply
Hi Tejeswar,
Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build.
For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven.
Please don’t hesitate to write comment us, if you find any problem.
Thanks.
I just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.
Thank you for your help.
chandrashekhar
September 4, 2016 at 2:54 pm - Reply
Hi Tejeswar,
Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build.
For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven.
Please don’t hesitate to write comment us, if you find any problem.
Thanks.
Hi Tejeswar,
Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build.
For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven.
Please don’t hesitate to write comment us, if you find any problem.
Thanks.
kanchan
November 3, 2016 at 3:58 am - Reply
can u please give example first register then login and then CRUD operation in single project
can u please give example first register then login and then CRUD operation in single project
satya prakash
December 9, 2016 at 10:47 am - Reply
When i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.
Please explain exception ..
When i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.
Please explain exception ..
Venkatesh
December 13, 2016 at 8:14 am - Reply
Hey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven
Hey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven
Surendra
January 19, 2017 at 6:42 am - Reply
Very Well explained..
Thank you @chandrashekhar
Very Well explained..
Thank you @chandrashekhar
Obireddy
January 22, 2017 at 6:24 am - Reply
I want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly
I want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly
Thiyagarajan
April 11, 2017 at 5:27 pm - Reply
Hi,
I am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse.
Hi,
I am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse.
Sheeja
May 3, 2017 at 10:08 am - Reply
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?
Prasanta
May 9, 2017 at 1:20 pm - Reply
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone explain why?
I am getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone explain why?
raza
November 19, 2017 at 10:21 am - Reply
Hi !
I just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere
Hi !
I just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere
Umesh
December 16, 2017 at 8:40 am - Reply
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone help me please.
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
can anyone help me please.
prasanna
December 20, 2017 at 10:14 am - Reply
nice tutorial what i have to do to handle the session
nice tutorial what i have to do to handle the session
suresh
December 21, 2017 at 6:35 am - Reply
Hello Sir,....Your tutorial is really Good....
But Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email...
Hello Sir,....Your tutorial is really Good....
But Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email...
Bhavesh
March 1, 2018 at 8:49 am - Reply
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”
maha
July 12, 2018 at 5:27 pm - Reply
hello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse
Arpit
July 28, 2019 at 6:25 pm - Reply
Hi,
Nice tutorial.
hello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse
Arpit
July 28, 2019 at 6:25 pm - Reply
Hi,
Nice tutorial.
Hi,
Nice tutorial.
Nehal Raju
August 12, 2020 at 12:54 pm - Reply
Can u send the link for login page using spring mvc and hibernate through NetBeans. share me to my email id
Can u send the link for login page using spring mvc and hibernate through NetBeans. share me to my email id
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 608,
"s": 398,
"text": "Spring MVC Login Form is a basic example for all spring based applications. We can hardly imagine any web application without forms in it because forms have their own importance in web application development."
},
{
"code": null,
"e": 745,
"s": 608,
"text": "In this tutorial, we are going to see how forms are used in Spring Framework, and how spring forms are different from normal HTML forms."
},
{
"code": null,
"e": 933,
"s": 745,
"text": "As part of this tutorial, I am going to implement a simple Spring-based Login Form. Though it is a simple login form, it requires more understanding about each and every newer thing init."
},
{
"code": null,
"e": 1071,
"s": 933,
"text": "Spring offers different types of annotations to handling forms. Here are the typical annotations that every spring developer should know."
},
{
"code": null,
"e": 1131,
"s": 1071,
"text": "@Controller is an annotation, used in Spring MVC Framework."
},
{
"code": null,
"e": 1199,
"s": 1131,
"text": "@Controller annotation is a sub annotation of @Cmponent annotation."
},
{
"code": null,
"e": 1259,
"s": 1199,
"text": "We can use @Controller annotation on top of the class only."
},
{
"code": null,
"e": 1346,
"s": 1259,
"text": "It indicates that a particular class serves the role of controller in the MVC pattern."
},
{
"code": null,
"e": 1437,
"s": 1346,
"text": "@Controller annotation acts as a stereotype for the annotated class, indicating its roles."
},
{
"code": null,
"e": 1531,
"s": 1437,
"text": "Like @Controller annotation, @RequestMapping annotation is also used in Spring MVC Framework."
},
{
"code": null,
"e": 1670,
"s": 1531,
"text": "@RequestMapping annotation can be applied on top of the class and/or methods, and it should be used along with the @Controller annotation."
},
{
"code": null,
"e": 1746,
"s": 1670,
"text": "It is used to bind an HTTP request to spring components or handler methods."
},
{
"code": null,
"e": 1908,
"s": 1746,
"text": "Class level mapping binds a specific request to the Spring component (class), whereas method level mapping binds a specific request to a specific handler method."
},
{
"code": null,
"e": 1986,
"s": 1908,
"text": "@ModelAttribute annotation can be used on top of a method or method argument."
},
{
"code": null,
"e": 2124,
"s": 1986,
"text": "An @ModelAttribute on a method is used to populate the model with commonly needed attributes for example to fill a drop-down with states."
},
{
"code": null,
"e": 2212,
"s": 2124,
"text": "@ModelAttribute on method arguments refers to a specific property in Model class (MVC)."
},
{
"code": null,
"e": 2258,
"s": 2212,
"text": "Used to bind the data from form to controller"
},
{
"code": null,
"e": 2318,
"s": 2258,
"text": "It should be used along with @RequestMapping in Controllers"
},
{
"code": null,
"e": 2425,
"s": 2318,
"text": "@ModelAttribute is invoked before the actual controller method starts execution along with @RequestMapping"
},
{
"code": null,
"e": 2489,
"s": 2425,
"text": "Recommended: Spring with Hibernate Integration Complete Example"
},
{
"code": null,
"e": 2560,
"s": 2489,
"text": "Here we are going to implement the Spring MVC Login form step by step."
},
{
"code": null,
"e": 2624,
"s": 2560,
"text": "Download Example : Spring MVC Login Form Example with STS (NEW)"
},
{
"code": null,
"e": 2643,
"s": 2624,
"text": "Project Structure:"
},
{
"code": null,
"e": 2704,
"s": 2643,
"text": "Follow below project structure to add described files below."
},
{
"code": null,
"e": 3483,
"s": 2704,
"text": "\n<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"\npageEncoding=\"UTF-8\"%> <%@taglib\nuri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>Spring Login Form</title>\n</head>\n<body>\n<form:form name=\"submitForm\" method=\"POST\">\n<div align=\"center\">\n<table>\n<tr>\n<td>User Name</td>\n<td><input type=\"text\" name=\"userName\" /></td>\n</tr>\n<tr>\n<td>Password</td>\n<td><input type=\"password\" name=\"password\" /></td>\n</tr>\n<tr>\n<td></td>\n<td><input type=\"submit\" value=\"Submit\" /></td>\n</tr>\n</table>\n<div style=\"color: red\">${error}</div>\n\n</div>\n</form:form>\n</body>\n</html>\n"
},
{
"code": null,
"e": 3733,
"s": 3483,
"text": "On the above login form, we used <form:form> tag. Which is given by the spring framework. To use this tag, we need to include the below taglib directory on top of the jsp page.\n<%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%>"
},
{
"code": null,
"e": 3974,
"s": 3733,
"text": "The main advantage of using the <form: form> is, spring automatically binds the form data to the model bean whenever we submit this form. To make it work, the properties in the model class should be equal to the name of form data elements."
},
{
"code": null,
"e": 4156,
"s": 3974,
"text": "For instance, we have created a text box field with the name userName and password field with the name password. The same names should be used as part of the Model class attributes."
},
{
"code": null,
"e": 4179,
"s": 4156,
"text": "Create a Login Model :"
},
{
"code": null,
"e": 4571,
"s": 4179,
"text": "package com.spring.controller;\n\npublic class LoginBean {\n\n private String userName;\n private String password;\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}\n"
},
{
"code": null,
"e": 4619,
"s": 4571,
"text": "Recommended: Spring Boot MVC Login Form Example"
},
{
"code": null,
"e": 6009,
"s": 4619,
"text": "\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans:beans xmlns=\"http://www.springframework.org/schema/mvc\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:beans=\"http://www.springframework.org/schema/beans\"\nxmlns:context=\"http://www.springframework.org/schema/context\"\nxsi:schemaLocation=\"http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\nhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n\n<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->\n\n<!-- Enables the Spring MVC @Controller programming model -->\n<annotation-driven />\n\n<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->\n<resources mapping=\"/resources/**\" location=\"/resources/\" />\n\n<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->\n<beans:bean class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n<beans:property name=\"prefix\" value=\"/WEB-INF/views/\" />\n<beans:property name=\"suffix\" value=\".jsp\" />\n</beans:bean>\n<context:component-scan base-package=\"com.spring.controller\" />\n</beans:beans>\n"
},
{
"code": null,
"e": 6026,
"s": 6009,
"text": "Points To Note :"
},
{
"code": null,
"e": 6209,
"s": 6026,
"text": " <annotation-driven />, informs Spring container that we are going to use annotations in this application and can be used to identify annotations and to perform respective functions."
},
{
"code": null,
"e": 6346,
"s": 6209,
"text": "Created a ViewResolver bean and mapped with the folder name where our actual views (JSP) are present as prefix and extension as a suffix"
},
{
"code": null,
"e": 6781,
"s": 6346,
"text": "Component scanning with <context:component-scan base-package=”com.spring.controller” />, is telling spring that it should search the classpath for all the classes under com.spring.controller and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class=”...” /> in the XML configuration files."
},
{
"code": null,
"e": 6810,
"s": 6781,
"text": "Configure the web.xml File :"
},
{
"code": null,
"e": 7770,
"s": 6810,
"text": "\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns=\"http://java.sun.com/xml/ns/javaee\"\nxsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\nversion=\"2.5\">\n<context-param>\n<param-name>contextConfigLocation</param-name>\n<param-value>/WEB-INF/spring/root-context.xml</param-value>\n</context-param>\n<listener>\n<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n</listener>\n<servlet>\n<servlet-name>appServlet</servlet-name>\n<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\n<init-param>\n<param-name>contextConfigLocation</param-name>\n<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>\n</init-param>\n<load-on-startup>1</load-on-startup>\n</servlet>\n<servlet-mapping>\n<servlet-name>appServlet</servlet-name>\n<url-pattern>/</url-pattern>\n</servlet-mapping>\n</web-app>\n"
},
{
"code": null,
"e": 7787,
"s": 7770,
"text": "Points To Note :"
},
{
"code": null,
"e": 7872,
"s": 7787,
"text": "Define DispatcherServlet, which will act as a front controller to route the requests"
},
{
"code": null,
"e": 7902,
"s": 7872,
"text": "Create a Spring Controller :\n"
},
{
"code": null,
"e": 9077,
"s": 7902,
"text": "\npackage com.spring.controller;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class LoginController {\n @RequestMapping(value = \"/login\", method = RequestMethod.GET)\n public String init(Model model) {\n model.addAttribute(\"msg\", \"Please Enter Your Login Details\");\n return \"login\";\n }\n\n @RequestMapping(method = RequestMethod.POST)\n public String submit(Model model, @ModelAttribute(\"loginBean\") LoginBean loginBean) {\n if (loginBean != null && loginBean.getUserName() != null & loginBean.getPassword() != null) {\n if (loginBean.getUserName().equals(\"chandra\") && loginBean.getPassword().equals(\"chandra123\")) {\n model.addAttribute(\"msg\", loginBean.getUserName());\n return \"success\";\n } else {\n model.addAttribute(\"error\", \"Invalid Details\");\n return \"login\";\n }\n } else {\n model.addAttribute(\"error\", \"Please enter Details\");\n return \"login\";\n }\n }\n}\n"
},
{
"code": null,
"e": 9094,
"s": 9077,
"text": "Points To Note :"
},
{
"code": null,
"e": 9130,
"s": 9094,
"text": "We have created two handler methods"
},
{
"code": null,
"e": 9227,
"s": 9130,
"text": "init\nThis is a default handler method for HTTP GET requests. The RequestMapping url is “/login”."
},
{
"code": null,
"e": 9445,
"s": 9227,
"text": "submit\nThis method is called whenever the form get submitted because the HTTP type for this method is POST.\nAll the form elements are fed into the LoginBean object and we retrieve them using @ModelAttribute annotation"
},
{
"code": null,
"e": 9504,
"s": 9445,
"text": "To run this application, we can make use of the below URL."
},
{
"code": null,
"e": 9553,
"s": 9504,
"text": "http://localhost:8080/Spring-MVC-LoginForm/login"
},
{
"code": null,
"e": 9570,
"s": 9553,
"text": "Error Response :"
},
{
"code": null,
"e": 9598,
"s": 9570,
"text": "Giving Valid credentials :\n"
},
{
"code": null,
"e": 9613,
"s": 9598,
"text": "Success Page :"
},
{
"code": null,
"e": 9707,
"s": 9613,
"text": "The complete Example is available for download : Spring MVC Login Form Example with STS (NEW)"
},
{
"code": null,
"e": 9724,
"s": 9707,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 9807,
"s": 9724,
"text": "\n\nSpring MVC Login Form Example with STS (NEW)\n\nFile size: 28 KB\nDownloads: 22653\n"
},
{
"code": null,
"e": 9889,
"s": 9807,
"text": "\n\nSpring MVC Login Form Example With Netbeans\n\nFile size: 18 MB\nDownloads: 33337\n"
},
{
"code": null,
"e": 10442,
"s": 9889,
"text": "\nSpring Boot MVC Example Tutorials\nSpring MVC Form Validation Example\nSpring Boot Validation Login Form Example\nSpring Web MVC Framework Flow\nPython Selenium Automate the Login Form\nSpring MVC HelloWorld\nSpring Form Custom Validation Example\nSpring MVC Tiles Example (Apache Tiles)\nPython – Flask Login Form Example\nSpring Hibernate Example\nBasic Android Login Form Example\nAngularJs Directive Example Tutorials\nHow to Get All Spring Beans Details Loaded in ICO\n@Component,@Service,@Repository,@Controller in spring\nSpring Boot FileUpload Ajax Example\n"
},
{
"code": null,
"e": 10476,
"s": 10442,
"text": "Spring Boot MVC Example Tutorials"
},
{
"code": null,
"e": 10511,
"s": 10476,
"text": "Spring MVC Form Validation Example"
},
{
"code": null,
"e": 10553,
"s": 10511,
"text": "Spring Boot Validation Login Form Example"
},
{
"code": null,
"e": 10583,
"s": 10553,
"text": "Spring Web MVC Framework Flow"
},
{
"code": null,
"e": 10623,
"s": 10583,
"text": "Python Selenium Automate the Login Form"
},
{
"code": null,
"e": 10645,
"s": 10623,
"text": "Spring MVC HelloWorld"
},
{
"code": null,
"e": 10683,
"s": 10645,
"text": "Spring Form Custom Validation Example"
},
{
"code": null,
"e": 10723,
"s": 10683,
"text": "Spring MVC Tiles Example (Apache Tiles)"
},
{
"code": null,
"e": 10757,
"s": 10723,
"text": "Python – Flask Login Form Example"
},
{
"code": null,
"e": 10782,
"s": 10757,
"text": "Spring Hibernate Example"
},
{
"code": null,
"e": 10815,
"s": 10782,
"text": "Basic Android Login Form Example"
},
{
"code": null,
"e": 10853,
"s": 10815,
"text": "AngularJs Directive Example Tutorials"
},
{
"code": null,
"e": 10903,
"s": 10853,
"text": "How to Get All Spring Beans Details Loaded in ICO"
},
{
"code": null,
"e": 10957,
"s": 10903,
"text": "@Component,@Service,@Repository,@Controller in spring"
},
{
"code": null,
"e": 10993,
"s": 10957,
"text": "Spring Boot FileUpload Ajax Example"
},
{
"code": null,
"e": 16715,
"s": 10993,
"text": "\n\n\n\n\n\nvishwanath\nDecember 29, 2015 at 8:02 am - Reply \n\ngood one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nDecember 30, 2015 at 4:34 pm - Reply \n\nHi Vishwanath,\nThank you for your comment. Can you please explain your query in detail, so that I can help you better.\nThankyou,\nChandrashekhar\n\n\n\n\n\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:17 am - Reply \n\nVery well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂\n\n\n\n\n\n\n\n\n\nRavichandra\nMarch 14, 2017 at 5:34 am - Reply \n\nHi Chandra....\nVery good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....\n\n\n\n\n\n\n\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:34 am - Reply \n\n@Vishwanath\nI think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.\nFor such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,\nStep 1: Retrieve user roles from DB as per authentication from your DAO layer.\nStep 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.\n\nif(users.getUserRole.equals(\"amin\"))\n{\nreturn \"Admin\";\n}\nif(users.getUserRole.equals(\"client\"))\n{\nreturn \"Client\";\n}\n\nStep 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.\nStep4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.\nWhere all users will have their respective permissions to work in your system.\n\n\n\n\n\n\n\n\n\n\n\npradeep\nMarch 28, 2016 at 4:42 am - Reply \n\ni am getting Error-The request sent by the client was syntactically incorrect.\n\n\n\n\n\n\n\n\n\njagriti\nMay 31, 2016 at 11:21 am - Reply \n\nwhy you added applicationcontext. xml in web.xml param name\n\n\n\n\n\n\n\n\n\nTejeswar\nSeptember 4, 2016 at 11:14 am - Reply \n\nI just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.\nThank you for your help.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nSeptember 4, 2016 at 2:54 pm - Reply \n\nHi Tejeswar,\nThanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build. \nFor maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven. \nPlease don’t hesitate to write comment us, if you find any problem.\nThanks.\n\n\n\n\n\n\n\n\n\n\n\nkanchan\nNovember 3, 2016 at 3:58 am - Reply \n\ncan u please give example first register then login and then CRUD operation in single project\n\n\n\n\n\n\n\n\n\nsatya prakash\nDecember 9, 2016 at 10:47 am - Reply \n\nWhen i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.\nPlease explain exception ..\n\n\n\n\n\n\n\n\n\nVenkatesh\nDecember 13, 2016 at 8:14 am - Reply \n\nHey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven\n\n\n\n\n\n\n\n\n\nSurendra\nJanuary 19, 2017 at 6:42 am - Reply \n\nVery Well explained..\nThank you @chandrashekhar\n\n\n\n\n\n\n\n\n\nObireddy\nJanuary 22, 2017 at 6:24 am - Reply \n\nI want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly\n\n\n\n\n\n\n\n\n\nThiyagarajan\nApril 11, 2017 at 5:27 pm - Reply \n\nHi,\nI am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse.\n\n\n\n\n\n\n\n\n\nSheeja\nMay 3, 2017 at 10:08 am - Reply \n\nI am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?\n\n\n\n\n\n\n\n\n\nPrasanta\nMay 9, 2017 at 1:20 pm - Reply \n\nI am getting an error HTTP status 405 “Request method ‘GET’ not supported”\ncan anyone explain why?\n\n\n\n\n\n\n\n\n\nraza\nNovember 19, 2017 at 10:21 am - Reply \n\nHi !\nI just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere\n\n\n\n\n\n\n\n\n\nUmesh\nDecember 16, 2017 at 8:40 am - Reply \n\nI am also getting an error HTTP status 405 “Request method ‘GET’ not supported”\ncan anyone help me please.\n\n\n\n\n\n\n\n\n\nprasanna\nDecember 20, 2017 at 10:14 am - Reply \n\nnice tutorial what i have to do to handle the session\n\n\n\n\n\n\n\n\n\nsuresh\nDecember 21, 2017 at 6:35 am - Reply \n\nHello Sir,....Your tutorial is really Good....\nBut Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email...\n\n\n\n\n\n\n\n\n\nBhavesh\nMarch 1, 2018 at 8:49 am - Reply \n\nI am also getting an error HTTP status 405 “Request method ‘GET’ not supported”\n\n\n\n\n\n\n\n\n\nmaha\nJuly 12, 2018 at 5:27 pm - Reply \n\nhello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse\n\n\n\n\n\n\n\n\n\nArpit\nJuly 28, 2019 at 6:25 pm - Reply \n\nHi,\nNice tutorial.\n\n\n\n\n\n\n\n\n\n\n\nNehal Raju\nAugust 12, 2020 at 12:54 pm - Reply \n\nCan u send the link for login page using spring mvc and hibernate through NetBeans. share me to my email id\n\n\n\n\n"
},
{
"code": null,
"e": 18662,
"s": 16715,
"text": "\n\n\n\n\nvishwanath\nDecember 29, 2015 at 8:02 am - Reply \n\ngood one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nDecember 30, 2015 at 4:34 pm - Reply \n\nHi Vishwanath,\nThank you for your comment. Can you please explain your query in detail, so that I can help you better.\nThankyou,\nChandrashekhar\n\n\n\n\n\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:17 am - Reply \n\nVery well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂\n\n\n\n\n\n\n\n\n\nRavichandra\nMarch 14, 2017 at 5:34 am - Reply \n\nHi Chandra....\nVery good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....\n\n\n\n\n\n\n\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:34 am - Reply \n\n@Vishwanath\nI think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.\nFor such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,\nStep 1: Retrieve user roles from DB as per authentication from your DAO layer.\nStep 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.\n\nif(users.getUserRole.equals(\"amin\"))\n{\nreturn \"Admin\";\n}\nif(users.getUserRole.equals(\"client\"))\n{\nreturn \"Client\";\n}\n\nStep 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.\nStep4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.\nWhere all users will have their respective permissions to work in your system.\n\n\n\n\n\n"
},
{
"code": null,
"e": 18892,
"s": 18662,
"text": "good one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples."
},
{
"code": null,
"e": 19503,
"s": 18892,
"text": "\n\n\n\n\nchandrashekhar\nDecember 30, 2015 at 4:34 pm - Reply \n\nHi Vishwanath,\nThank you for your comment. Can you please explain your query in detail, so that I can help you better.\nThankyou,\nChandrashekhar\n\n\n\n\n\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:17 am - Reply \n\nVery well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂\n\n\n\n\n\n\n\n\n\nRavichandra\nMarch 14, 2017 at 5:34 am - Reply \n\nHi Chandra....\nVery good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....\n\n\n\n\n\n"
},
{
"code": null,
"e": 19518,
"s": 19503,
"text": "Hi Vishwanath,"
},
{
"code": null,
"e": 19622,
"s": 19518,
"text": "Thank you for your comment. Can you please explain your query in detail, so that I can help you better."
},
{
"code": null,
"e": 19647,
"s": 19622,
"text": "Thankyou,\nChandrashekhar"
},
{
"code": null,
"e": 19774,
"s": 19647,
"text": "\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:17 am - Reply \n\nVery well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂\n\n\n\n"
},
{
"code": null,
"e": 19845,
"s": 19774,
"text": "Very well demonstrated by you Mr. Chandrashekhar... Nice to have it. 🙂"
},
{
"code": null,
"e": 20120,
"s": 19845,
"text": "\n\n\n\n\nRavichandra\nMarch 14, 2017 at 5:34 am - Reply \n\nHi Chandra....\nVery good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects....\n\n\n\n"
},
{
"code": null,
"e": 20135,
"s": 20120,
"text": "Hi Chandra...."
},
{
"code": null,
"e": 20338,
"s": 20135,
"text": "Very good example for beginners to understand spring MVC.... but can you explain us how to connect it with data base like HSQLDB like that.... because working with data base is necessary in projects...."
},
{
"code": null,
"e": 21383,
"s": 20338,
"text": "\n\n\n\n\nVirendra\nFebruary 7, 2016 at 8:34 am - Reply \n\n@Vishwanath\nI think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.\nFor such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,\nStep 1: Retrieve user roles from DB as per authentication from your DAO layer.\nStep 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.\n\nif(users.getUserRole.equals(\"amin\"))\n{\nreturn \"Admin\";\n}\nif(users.getUserRole.equals(\"client\"))\n{\nreturn \"Client\";\n}\n\nStep 3: And eventually, just return that same view name to ViewResolver which you received from Service layer.\nStep4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.\nWhere all users will have their respective permissions to work in your system.\n\n\n\n"
},
{
"code": null,
"e": 22022,
"s": 21383,
"text": "@Vishwanath\nI think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example.\nFor such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as,\nStep 1: Retrieve user roles from DB as per authentication from your DAO layer.\nStep 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g.\n\nif(users.getUserRole.equals(\"amin\"))\n{\nreturn \"Admin\";\n}\nif(users.getUserRole.equals(\"client\"))\n{\nreturn \"Client\";\n}\n"
},
{
"code": null,
"e": 22133,
"s": 22022,
"text": "Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer."
},
{
"code": null,
"e": 22372,
"s": 22133,
"text": "Step4; DONE... ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc.\nWhere all users will have their respective permissions to work in your system."
},
{
"code": null,
"e": 22504,
"s": 22372,
"text": "\n\n\n\n\npradeep\nMarch 28, 2016 at 4:42 am - Reply \n\ni am getting Error-The request sent by the client was syntactically incorrect.\n\n\n\n"
},
{
"code": null,
"e": 22583,
"s": 22504,
"text": "i am getting Error-The request sent by the client was syntactically incorrect."
},
{
"code": null,
"e": 22695,
"s": 22583,
"text": "\n\n\n\n\njagriti\nMay 31, 2016 at 11:21 am - Reply \n\nwhy you added applicationcontext. xml in web.xml param name\n\n\n\n"
},
{
"code": null,
"e": 22755,
"s": 22695,
"text": "why you added applicationcontext. xml in web.xml param name"
},
{
"code": null,
"e": 23460,
"s": 22755,
"text": "\n\n\n\n\nTejeswar\nSeptember 4, 2016 at 11:14 am - Reply \n\nI just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.\nThank you for your help.\n\n\n\n\n\n\n\n\n\nchandrashekhar\nSeptember 4, 2016 at 2:54 pm - Reply \n\nHi Tejeswar,\nThanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build. \nFor maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven. \nPlease don’t hesitate to write comment us, if you find any problem.\nThanks.\n\n\n\n\n\n"
},
{
"code": null,
"e": 23687,
"s": 23460,
"text": "I just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here.\nThank you for your help."
},
{
"code": null,
"e": 24105,
"s": 23687,
"text": "\n\n\n\n\nchandrashekhar\nSeptember 4, 2016 at 2:54 pm - Reply \n\nHi Tejeswar,\nThanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build. \nFor maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven. \nPlease don’t hesitate to write comment us, if you find any problem.\nThanks.\n\n\n\n"
},
{
"code": null,
"e": 24118,
"s": 24105,
"text": "Hi Tejeswar,"
},
{
"code": null,
"e": 24254,
"s": 24118,
"text": "Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build. "
},
{
"code": null,
"e": 24384,
"s": 24254,
"text": "For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven. "
},
{
"code": null,
"e": 24452,
"s": 24384,
"text": "Please don’t hesitate to write comment us, if you find any problem."
},
{
"code": null,
"e": 24460,
"s": 24452,
"text": "Thanks."
},
{
"code": null,
"e": 24609,
"s": 24460,
"text": "\n\n\n\n\nkanchan\nNovember 3, 2016 at 3:58 am - Reply \n\ncan u please give example first register then login and then CRUD operation in single project\n\n\n\n"
},
{
"code": null,
"e": 24703,
"s": 24609,
"text": "can u please give example first register then login and then CRUD operation in single project"
},
{
"code": null,
"e": 25016,
"s": 24703,
"text": "\n\n\n\n\nsatya prakash\nDecember 9, 2016 at 10:47 am - Reply \n\nWhen i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.\nPlease explain exception ..\n\n\n\n"
},
{
"code": null,
"e": 25267,
"s": 25016,
"text": "When i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page.\nPlease explain exception .."
},
{
"code": null,
"e": 25439,
"s": 25267,
"text": "\n\n\n\n\nVenkatesh\nDecember 13, 2016 at 8:14 am - Reply \n\nHey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven\n\n\n\n"
},
{
"code": null,
"e": 25553,
"s": 25439,
"text": "Hey i am not finding source file for root-context.xml.... can please send the code .. I am doing project in Maven"
},
{
"code": null,
"e": 25657,
"s": 25553,
"text": "\n\n\n\n\nSurendra\nJanuary 19, 2017 at 6:42 am - Reply \n\nVery Well explained..\nThank you @chandrashekhar\n\n\n\n"
},
{
"code": null,
"e": 25679,
"s": 25657,
"text": "Very Well explained.."
},
{
"code": null,
"e": 25705,
"s": 25679,
"text": "Thank you @chandrashekhar"
},
{
"code": null,
"e": 25917,
"s": 25705,
"text": "\n\n\n\n\nObireddy\nJanuary 22, 2017 at 6:24 am - Reply \n\nI want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly\n\n\n\n"
},
{
"code": null,
"e": 26073,
"s": 25917,
"text": "I want login and registration example with spring +hibernate in with explanation... Your explaining way is very impressed me if possible please send fastly"
},
{
"code": null,
"e": 26338,
"s": 26073,
"text": "\n\n\n\n\nThiyagarajan\nApril 11, 2017 at 5:27 pm - Reply \n\nHi,\nI am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse.\n\n\n\n"
},
{
"code": null,
"e": 26545,
"s": 26338,
"text": "Hi,\nI am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse."
},
{
"code": null,
"e": 26693,
"s": 26545,
"text": "\n\n\n\n\nSheeja\nMay 3, 2017 at 10:08 am - Reply \n\nI am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?\n\n\n\n"
},
{
"code": null,
"e": 26791,
"s": 26693,
"text": "I am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this?"
},
{
"code": null,
"e": 26941,
"s": 26791,
"text": "\n\n\n\n\nPrasanta\nMay 9, 2017 at 1:20 pm - Reply \n\nI am getting an error HTTP status 405 “Request method ‘GET’ not supported”\ncan anyone explain why?\n\n\n\n"
},
{
"code": null,
"e": 27016,
"s": 26941,
"text": "I am getting an error HTTP status 405 “Request method ‘GET’ not supported”"
},
{
"code": null,
"e": 27040,
"s": 27016,
"text": "can anyone explain why?"
},
{
"code": null,
"e": 27328,
"s": 27040,
"text": "\n\n\n\n\nraza\nNovember 19, 2017 at 10:21 am - Reply \n\nHi !\nI just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere\n\n\n\n"
},
{
"code": null,
"e": 27562,
"s": 27328,
"text": "Hi !\nI just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere"
},
{
"code": null,
"e": 27723,
"s": 27562,
"text": "\n\n\n\n\nUmesh\nDecember 16, 2017 at 8:40 am - Reply \n\nI am also getting an error HTTP status 405 “Request method ‘GET’ not supported”\ncan anyone help me please.\n\n\n\n"
},
{
"code": null,
"e": 27803,
"s": 27723,
"text": "I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”"
},
{
"code": null,
"e": 27830,
"s": 27803,
"text": "can anyone help me please."
},
{
"code": null,
"e": 27942,
"s": 27830,
"text": "\n\n\n\n\nprasanna\nDecember 20, 2017 at 10:14 am - Reply \n\nnice tutorial what i have to do to handle the session\n\n\n\n"
},
{
"code": null,
"e": 27996,
"s": 27942,
"text": "nice tutorial what i have to do to handle the session"
},
{
"code": null,
"e": 28204,
"s": 27996,
"text": "\n\n\n\n\nsuresh\nDecember 21, 2017 at 6:35 am - Reply \n\nHello Sir,....Your tutorial is really Good....\nBut Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email...\n\n\n\n"
},
{
"code": null,
"e": 28251,
"s": 28204,
"text": "Hello Sir,....Your tutorial is really Good...."
},
{
"code": null,
"e": 28357,
"s": 28251,
"text": "But Netbeans project size is 0 bytes...Please share the login form using netbeans zip file to my email..."
},
{
"code": null,
"e": 28489,
"s": 28357,
"text": "\n\n\n\n\nBhavesh\nMarch 1, 2018 at 8:49 am - Reply \n\nI am also getting an error HTTP status 405 “Request method ‘GET’ not supported”\n\n\n\n"
},
{
"code": null,
"e": 28569,
"s": 28489,
"text": "I am also getting an error HTTP status 405 “Request method ‘GET’ not supported”"
},
{
"code": null,
"e": 28813,
"s": 28569,
"text": "\n\n\n\n\nmaha\nJuly 12, 2018 at 5:27 pm - Reply \n\nhello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse\n\n\n\n\n\n\n\n\n\nArpit\nJuly 28, 2019 at 6:25 pm - Reply \n\nHi,\nNice tutorial.\n\n\n\n\n\n"
},
{
"code": null,
"e": 28937,
"s": 28813,
"text": "hello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse"
},
{
"code": null,
"e": 29006,
"s": 28937,
"text": "\n\n\n\n\nArpit\nJuly 28, 2019 at 6:25 pm - Reply \n\nHi,\nNice tutorial.\n\n\n\n"
},
{
"code": null,
"e": 29025,
"s": 29006,
"text": "Hi,\nNice tutorial."
},
{
"code": null,
"e": 29191,
"s": 29025,
"text": "\n\n\n\n\nNehal Raju\nAugust 12, 2020 at 12:54 pm - Reply \n\nCan u send the link for login page using spring mvc and hibernate through NetBeans. share me to my email id\n\n\n\n"
}
] |
Image Processing in Java - Colored Image to Grayscale Image Conversion - GeeksforGeeks
|
14 Nov, 2021
Prerequisites:
Image Processing in Java – Read and Write
Image Processing In Java – Get and set Pixels
In this article, we will be converting a colored image to a grayscale image.
RGB Color Model – The RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors.
Grayscale Images – Grayscale images, a kind of black-and-white or gray monochrome, are composed exclusively of shades of gray. The contrast ranges from black at the weakest intensity to white at the strongest.
Generally, a grayscale image uses an 8-bit representation for each pixel. By using 8-bits, we can represent values from 0 to 255. So a grayscale image in 8-bit representation will be a matrix, and the values can be anything from 0 to 255. 0 indicates black pixels, and 255 indicates white pixels, and in between different shades from black to white will come.
Note: In a grayscale image, the Alpha component of the image will be the same as the original image, but the RGB will be changed i.e, all three RGB components will have the same value for each pixel.
Get the RGB value of the pixel.Find the average of RGB, i.e., Avg = (R+G+B)/3Replace the R, G, and B values of the pixel with the average (Avg) calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image.
Get the RGB value of the pixel.
Find the average of RGB, i.e., Avg = (R+G+B)/3
Replace the R, G, and B values of the pixel with the average (Avg) calculated in step 2.
Repeat Step 1 to Step 3 for each pixel of the image.
Java
// Java program to demonstrate// colored to grayscale conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class Grayscale { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get image's width and height int width = img.getWidth(); int height = img.getHeight(); // convert to grayscale for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Here (x,y)denotes the coordinate of image // for modifying the pixel value. int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; int g = (p >> 8) & 0xff; int b = p & 0xff; // calculate average int avg = (r + g + b) / 3; // replace RGB value with avg p = (a << 24) | (avg << 16) | (avg << 8) | avg; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(img, "png", f); } catch (IOException e) { System.out.println(e); } }}
Note: This code will not run on an online IDE as it needs an image on disk.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
sooda367
nishkarshgandhi
Image-Processing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n14 Nov, 2021"
},
{
"code": null,
"e": 24921,
"s": 24906,
"text": "Prerequisites:"
},
{
"code": null,
"e": 24963,
"s": 24921,
"text": "Image Processing in Java – Read and Write"
},
{
"code": null,
"e": 25009,
"s": 24963,
"text": "Image Processing In Java – Get and set Pixels"
},
{
"code": null,
"e": 25087,
"s": 25009,
"text": "In this article, we will be converting a colored image to a grayscale image. "
},
{
"code": null,
"e": 25263,
"s": 25087,
"text": "RGB Color Model – The RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. "
},
{
"code": null,
"e": 25473,
"s": 25263,
"text": "Grayscale Images – Grayscale images, a kind of black-and-white or gray monochrome, are composed exclusively of shades of gray. The contrast ranges from black at the weakest intensity to white at the strongest."
},
{
"code": null,
"e": 25833,
"s": 25473,
"text": "Generally, a grayscale image uses an 8-bit representation for each pixel. By using 8-bits, we can represent values from 0 to 255. So a grayscale image in 8-bit representation will be a matrix, and the values can be anything from 0 to 255. 0 indicates black pixels, and 255 indicates white pixels, and in between different shades from black to white will come."
},
{
"code": null,
"e": 26033,
"s": 25833,
"text": "Note: In a grayscale image, the Alpha component of the image will be the same as the original image, but the RGB will be changed i.e, all three RGB components will have the same value for each pixel."
},
{
"code": null,
"e": 26251,
"s": 26033,
"text": "Get the RGB value of the pixel.Find the average of RGB, i.e., Avg = (R+G+B)/3Replace the R, G, and B values of the pixel with the average (Avg) calculated in step 2.Repeat Step 1 to Step 3 for each pixel of the image."
},
{
"code": null,
"e": 26283,
"s": 26251,
"text": "Get the RGB value of the pixel."
},
{
"code": null,
"e": 26330,
"s": 26283,
"text": "Find the average of RGB, i.e., Avg = (R+G+B)/3"
},
{
"code": null,
"e": 26419,
"s": 26330,
"text": "Replace the R, G, and B values of the pixel with the average (Avg) calculated in step 2."
},
{
"code": null,
"e": 26472,
"s": 26419,
"text": "Repeat Step 1 to Step 3 for each pixel of the image."
},
{
"code": null,
"e": 26477,
"s": 26472,
"text": "Java"
},
{
"code": "// Java program to demonstrate// colored to grayscale conversion import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class Grayscale { public static void main(String args[]) throws IOException { BufferedImage img = null; File f = null; // read image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get image's width and height int width = img.getWidth(); int height = img.getHeight(); // convert to grayscale for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Here (x,y)denotes the coordinate of image // for modifying the pixel value. int p = img.getRGB(x, y); int a = (p >> 24) & 0xff; int r = (p >> 16) & 0xff; int g = (p >> 8) & 0xff; int b = p & 0xff; // calculate average int avg = (r + g + b) / 3; // replace RGB value with avg p = (a << 24) | (avg << 16) | (avg << 8) | avg; img.setRGB(x, y, p); } } // write image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(img, \"png\", f); } catch (IOException e) { System.out.println(e); } }}",
"e": 28154,
"s": 26477,
"text": null
},
{
"code": null,
"e": 28231,
"s": 28154,
"text": "Note: This code will not run on an online IDE as it needs an image on disk. "
},
{
"code": null,
"e": 28654,
"s": 28231,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 28663,
"s": 28654,
"text": "sooda367"
},
{
"code": null,
"e": 28679,
"s": 28663,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 28696,
"s": 28679,
"text": "Image-Processing"
},
{
"code": null,
"e": 28701,
"s": 28696,
"text": "Java"
},
{
"code": null,
"e": 28706,
"s": 28701,
"text": "Java"
},
{
"code": null,
"e": 28804,
"s": 28706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28836,
"s": 28804,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28887,
"s": 28836,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28917,
"s": 28887,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28936,
"s": 28917,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28967,
"s": 28936,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28985,
"s": 28967,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29017,
"s": 28985,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29032,
"s": 29017,
"text": "Stream In Java"
},
{
"code": null,
"e": 29052,
"s": 29032,
"text": "Stack Class in Java"
}
] |
PHP Exercises With Solutions
|
Theory of Computation
$str1 = "00004";
$str2 = "008";
$str3 = "00007-STR";
$a = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';
[
{
"name" : "John Garg",
"age" : "15",
"school" : "Ahlcon Public school"
},
{
"name" : "Smith Soy",
"age" : "16",
"school" : "St. Marie school"
},
{
"name" : "Charle Rena",
"age" : "16",
"school" : "St. Columba school"
}
]
$a = array('one' => 'I', 'two' => 'II', 'three' =>'III', 'four' => 'IV');
$quantity1 = 70;
$quantity2 = 100;
$price1 = 35;
$price2 = 30;
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 165,
"s": 112,
"text": "$str1 = \"00004\";\n$str2 = \"008\";\n$str3 = \"00007-STR\";"
},
{
"code": null,
"e": 268,
"s": 165,
"text": "$a = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';"
},
{
"code": null,
"e": 512,
"s": 268,
"text": "\n[\n\t{\n\t\"name\" : \"John Garg\",\n\t\"age\" : \"15\",\n\t\"school\" : \"Ahlcon Public school\"\n\t},\n\t{\n\t\"name\" : \"Smith Soy\",\n\t\"age\" : \"16\",\n\t\"school\" : \"St. Marie school\"\n\t},\n\t{\n\t\"name\" : \"Charle Rena\",\n\t\"age\" : \"16\",\n\t\"school\" : \"St. Columba school\"\n\t}\n]\n"
},
{
"code": null,
"e": 586,
"s": 512,
"text": "$a = array('one' => 'I', 'two' => 'II', 'three' =>'III', 'four' => 'IV');"
}
] |
How to validate a form using jQuery?
|
At first you have to make a html form like.
<html>
<body>
<h2>Validation of a form</h2>
<form id="form" method="post" action="">
First name:<br>
<input type="text" name="firstname" value="john">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br>
Email:<br>
<input type="email" name="u_email" value="johndoe@gmail.com">
<br>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now use jQuery validation plugin to validate forms' data in easier way.
first,add jQuery library in your file.
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
then add javascript code:
$(document).ready(function() {
$("#form").validate();
});
</script>
Then to define rules use simple syntax.
jQuery(document).ready(function() {
jQuery("#forms).validate({
rules: {
firstname: 'required',
lastname: 'required',
u_email: {
required: true,
email: true,//add an email rule that will ensure the value entered is valid email id.
maxlength: 255,
},
}
});
});
To define error messages.
messages: {
firstname: 'This field is required',
lastname: 'This field is required',
u_email: 'Enter a valid email',
},
Now finally to submit the form.
submitHandler: function(form) {
form.submit();
}
|
[
{
"code": null,
"e": 1106,
"s": 1062,
"text": "At first you have to make a html form like."
},
{
"code": null,
"e": 1478,
"s": 1106,
"text": "<html>\n<body>\n<h2>Validation of a form</h2>\n<form id=\"form\" method=\"post\" action=\"\">\nFirst name:<br>\n<input type=\"text\" name=\"firstname\" value=\"john\">\n<br>\nLast name:<br>\n<input type=\"text\" name=\"lastname\" value=\"Doe\">\n<br>\nEmail:<br>\n<input type=\"email\" name=\"u_email\" value=\"johndoe@gmail.com\">\n<br>\n<br><br>\n<input type=\"submit\" value=\"Submit\">\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 1550,
"s": 1478,
"text": "Now use jQuery validation plugin to validate forms' data in easier way."
},
{
"code": null,
"e": 1589,
"s": 1550,
"text": "first,add jQuery library in your file."
},
{
"code": null,
"e": 1783,
"s": 1589,
"text": "<script src=\"https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js\"></script>\nthen add javascript code:\n$(document).ready(function() {\n $(\"#form\").validate();\n});\n</script>"
},
{
"code": null,
"e": 1823,
"s": 1783,
"text": "Then to define rules use simple syntax."
},
{
"code": null,
"e": 2172,
"s": 1823,
"text": "jQuery(document).ready(function() {\n jQuery(\"#forms).validate({\n rules: {\n firstname: 'required',\n lastname: 'required',\n u_email: {\n required: true,\n email: true,//add an email rule that will ensure the value entered is valid email id.\n maxlength: 255,\n },\n }\n });\n});"
},
{
"code": null,
"e": 2198,
"s": 2172,
"text": "To define error messages."
},
{
"code": null,
"e": 2327,
"s": 2198,
"text": "messages: {\n firstname: 'This field is required',\n lastname: 'This field is required',\n u_email: 'Enter a valid email',\n},"
},
{
"code": null,
"e": 2359,
"s": 2327,
"text": "Now finally to submit the form."
},
{
"code": null,
"e": 2411,
"s": 2359,
"text": "submitHandler: function(form) {\n form.submit();\n}"
}
] |
Maximum frequency of any array element possible by at most K increments - GeeksforGeeks
|
13 Jul, 2021
Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments.
Examples:
Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5 Output: 2 Explanation: Incrementing arr[0] twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2. Incrementing arr[1] four times modifies arr[] to {1, 8, 8, 13}. Maximum frequency = 2. Incrementing arr[2] five times modifies arr[] to {1, 4, 13, 13}. Maximum frequency = 2. Therefore, the maximum possible frequency of any array element that can be obtained by at most 5 increments is 2.
Input: arr[] = {2, 4, 5}, N = 3, K = 4 Output: 3
Approach: This problem can be solved by using Sliding Window Technique and Sorting. Follow the steps to solve this problem.
Sort the array arr[].
Initialize variables sum = 0, start = 0 and resultant frequency res = 0.
Traverse the array over the range of indices [0, N – 1] and perform the following steps:
Increment sum by arr[end].
Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn:
Decrement the value of sum by arr[start].
Increment the value of start by 1.
After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).
Increment sum by arr[end].
Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn:
Decrement the value of sum by arr[start].
Increment the value of start by 1.
Decrement the value of sum by arr[start].
Increment the value of start by 1.
After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).
Finally, print the value of res as frequency of most frequent element after performing Koperations.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum possible
// frequency of a most frequent element
// after at most K increment operations
void maxFrequency(int arr[], int N, int K)
{
// Sort the input array
sort(arr, arr + N);
int start = 0, end = 0;
// Stores the sum of sliding
// window and the maximum possible
// frequency of any array element
int sum = 0, res = 0;
// Traverse the array
for (end = 0; end < N; end++) {
// Add the current element
// to the window
sum += arr[end];
// Decrease the window size
// If it is not possible to make the
// array elements in the window equal
while ((end - start + 1) * arr[end] - sum > K) {
// Update the value of sum
sum -= arr[start];
// Increment the value of start
start++;
}
// Update the maximum possible frequency
res = max(res, end - start + 1);
}
// Print the frequency of
// the most frequent array
// element after K increments
cout << res << endl;
}
// Driver code
int main()
{
int arr[] = { 1, 4, 8, 13 };
int N = 4;
int K = 5;
maxFrequency(arr, N, K);
return 0;
}
// Java program for the above approach
import java.util.Arrays;
class GFG{
// Function to find the maximum possible
// frequency of a most frequent element
// after at most K increment operations
static void maxFrequency(int arr[], int N, int K)
{
// Sort the input array
Arrays.sort(arr);
int start = 0, end = 0;
// Stores the sum of sliding
// window and the maximum possible
// frequency of any array element
int sum = 0, res = 0;
// Traverse the array
for(end = 0; end < N; end++)
{
// Add the current element
// to the window
sum += arr[end];
// Decrease the window size
// If it is not possible to make the
// array elements in the window equal
while ((end - start + 1) *
arr[end] - sum > K)
{
// Update the value of sum
sum -= arr[start];
// Increment the value of start
start++;
}
// Update the maximum possible frequency
res = Math.max(res, end - start + 1);
}
// Print the frequency of
// the most frequent array
// element after K increments
System.out.println(res);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 4, 8, 13 };
int N = 4;
int K = 5;
maxFrequency(arr, N, K);
}
}
// This code is contributed by abhinavjain194
# Python3 program for the above approach
# Function to find the maximum possible
# frequency of a most frequent element
# after at most K increment operations
def maxFrequency(arr, N, K):
# Sort the input array
arr.sort()
start = 0
end = 0
# Stores the sum of sliding
# window and the maximum possible
# frequency of any array element
sum = 0
res = 0
# Traverse the array
for end in range(N):
# Add the current element
# to the window
sum += arr[end]
# Decrease the window size
# If it is not possible to make the
# array elements in the window equal
while ((end - start + 1) * arr[end] - sum > K):
# Update the value of sum
sum -= arr[start]
# Increment the value of start
start += 1
# Update the maximum possible frequency
res = max(res, end - start + 1)
# Print the frequency of
# the most frequent array
# element after K increments
print(res)
# Driver code
if __name__ == '__main__':
arr = [ 1, 4, 8, 13 ]
N = 4
K = 5
maxFrequency(arr, N, K)
# This code is contributed by ipg2016107
// C# program for the above approach
using System;
class GFG{
// Function to find the maximum possible
// frequency of a most frequent element
// after at most K increment operations
static void maxFrequency(int[] arr, int N, int K)
{
// Sort the input array
Array.Sort(arr);
int start = 0, end = 0;
// Stores the sum of sliding
// window and the maximum possible
// frequency of any array element
int sum = 0, res = 0;
// Traverse the array
for(end = 0; end < N; end++)
{
// Add the current element
// to the window
sum += arr[end];
// Decrease the window size
// If it is not possible to make the
// array elements in the window equal
while ((end - start + 1) *
arr[end] - sum > K)
{
// Update the value of sum
sum -= arr[start];
// Increment the value of start
start++;
}
// Update the maximum possible frequency
res = Math.Max(res, end - start + 1);
}
// Print the frequency of
// the most frequent array
// element after K increments
Console.WriteLine(res);
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 4, 8, 13 };
int N = 4;
int K = 5;
maxFrequency(arr, N, K);
}
}
// This code is contributed by code_hunt
<script>
// JavaScript program for the above approach
// Function to find the maximum possible
// frequency of a most frequent element
// after at most K increment operations
function maxFrequency(arr, N, K) {
// Sort the input array
arr.sort((a, b) => a - b);
let start = 0, end = 0;
// Stores the sum of sliding
// window and the maximum possible
// frequency of any array element
let sum = 0, res = 0;
// Traverse the array
for (end = 0; end < N; end++) {
// Add the current element
// to the window
sum += arr[end];
// Decrease the window size
// If it is not possible to make the
// array elements in the window equal
while ((end - start + 1) * arr[end] - sum > K) {
// Update the value of sum
sum -= arr[start];
// Increment the value of start
start++;
}
// Update the maximum possible frequency
res = Math.max(res, end - start + 1);
}
// Print the frequency of
// the most frequent array
// element after K increments
document.write(res + "<br>");
}
// Driver code
let arr = [1, 4, 8, 13];
let N = 4;
let K = 5;
maxFrequency(arr, N, K);
</script>
2
Time Complexity: O(NlogN) Auxiliary Space: O(1)
abhinavjain194
code_hunt
ipg2016107
_saurabh_jaiswal
frequency-counting
Picked
sliding-window
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linear Search
Multidimensional Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
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)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 25366,
"s": 25335,
"text": " \n13 Jul, 2021\n"
},
{
"code": null,
"e": 25512,
"s": 25366,
"text": "Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments."
},
{
"code": null,
"e": 25522,
"s": 25512,
"text": "Examples:"
},
{
"code": null,
"e": 25959,
"s": 25522,
"text": "Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5 Output: 2 Explanation: Incrementing arr[0] twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2. Incrementing arr[1] four times modifies arr[] to {1, 8, 8, 13}. Maximum frequency = 2. Incrementing arr[2] five times modifies arr[] to {1, 4, 13, 13}. Maximum frequency = 2. Therefore, the maximum possible frequency of any array element that can be obtained by at most 5 increments is 2."
},
{
"code": null,
"e": 26008,
"s": 25959,
"text": "Input: arr[] = {2, 4, 5}, N = 3, K = 4 Output: 3"
},
{
"code": null,
"e": 26132,
"s": 26008,
"text": "Approach: This problem can be solved by using Sliding Window Technique and Sorting. Follow the steps to solve this problem."
},
{
"code": null,
"e": 26154,
"s": 26132,
"text": "Sort the array arr[]."
},
{
"code": null,
"e": 26227,
"s": 26154,
"text": "Initialize variables sum = 0, start = 0 and resultant frequency res = 0."
},
{
"code": null,
"e": 26759,
"s": 26227,
"text": "Traverse the array over the range of indices [0, N – 1] and perform the following steps:\n\nIncrement sum by arr[end].\nIterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: \n\nDecrement the value of sum by arr[start].\nIncrement the value of start by 1.\n\n\nAfter completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).\n\n"
},
{
"code": null,
"e": 26786,
"s": 26759,
"text": "Increment sum by arr[end]."
},
{
"code": null,
"e": 26991,
"s": 26786,
"text": "Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: \n\nDecrement the value of sum by arr[start].\nIncrement the value of start by 1.\n\n"
},
{
"code": null,
"e": 27033,
"s": 26991,
"text": "Decrement the value of sum by arr[start]."
},
{
"code": null,
"e": 27068,
"s": 27033,
"text": "Increment the value of start by 1."
},
{
"code": null,
"e": 27276,
"s": 27068,
"text": "After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1)."
},
{
"code": null,
"e": 27376,
"s": 27276,
"text": "Finally, print the value of res as frequency of most frequent element after performing Koperations."
},
{
"code": null,
"e": 27427,
"s": 27376,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27431,
"s": 27427,
"text": "C++"
},
{
"code": null,
"e": 27436,
"s": 27431,
"text": "Java"
},
{
"code": null,
"e": 27444,
"s": 27436,
"text": "Python3"
},
{
"code": null,
"e": 27447,
"s": 27444,
"text": "C#"
},
{
"code": null,
"e": 27458,
"s": 27447,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program for the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to find the maximum possible\n// frequency of a most frequent element\n// after at most K increment operations\nvoid maxFrequency(int arr[], int N, int K)\n{\n // Sort the input array\n sort(arr, arr + N);\n \n int start = 0, end = 0;\n \n // Stores the sum of sliding\n // window and the maximum possible\n // frequency of any array element\n int sum = 0, res = 0;\n \n // Traverse the array\n for (end = 0; end < N; end++) {\n \n // Add the current element\n // to the window\n sum += arr[end];\n \n // Decrease the window size\n \n // If it is not possible to make the\n // array elements in the window equal\n while ((end - start + 1) * arr[end] - sum > K) {\n \n // Update the value of sum\n sum -= arr[start];\n \n // Increment the value of start\n start++;\n }\n \n // Update the maximum possible frequency\n res = max(res, end - start + 1);\n }\n \n // Print the frequency of\n // the most frequent array\n // element after K increments\n cout << res << endl;\n}\n \n// Driver code\nint main()\n{\n int arr[] = { 1, 4, 8, 13 };\n int N = 4;\n int K = 5;\n maxFrequency(arr, N, K);\n return 0;\n}\n\n\n\n\n\n",
"e": 28801,
"s": 27468,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.util.Arrays;\n \nclass GFG{\n \n// Function to find the maximum possible\n// frequency of a most frequent element\n// after at most K increment operations\nstatic void maxFrequency(int arr[], int N, int K)\n{\n \n // Sort the input array\n Arrays.sort(arr);\n \n int start = 0, end = 0;\n \n // Stores the sum of sliding\n // window and the maximum possible\n // frequency of any array element\n int sum = 0, res = 0;\n \n // Traverse the array\n for(end = 0; end < N; end++)\n {\n \n // Add the current element\n // to the window\n sum += arr[end];\n \n // Decrease the window size\n \n // If it is not possible to make the\n // array elements in the window equal\n while ((end - start + 1) * \n arr[end] - sum > K)\n {\n \n // Update the value of sum\n sum -= arr[start];\n \n // Increment the value of start\n start++;\n }\n \n // Update the maximum possible frequency\n res = Math.max(res, end - start + 1);\n }\n \n // Print the frequency of\n // the most frequent array\n // element after K increments\n System.out.println(res);\n}\n \n// Driver code\npublic static void main(String[] args)\n{\n int arr[] = { 1, 4, 8, 13 };\n int N = 4;\n int K = 5;\n \n maxFrequency(arr, N, K);\n}\n}\n \n// This code is contributed by abhinavjain194\n\n\n\n\n\n",
"e": 30278,
"s": 28811,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 program for the above approach\n \n# Function to find the maximum possible\n# frequency of a most frequent element\n# after at most K increment operations\ndef maxFrequency(arr, N, K):\n \n # Sort the input array\n arr.sort()\n \n start = 0\n end = 0\n \n # Stores the sum of sliding\n # window and the maximum possible\n # frequency of any array element\n sum = 0\n res = 0\n \n # Traverse the array\n for end in range(N):\n \n # Add the current element\n # to the window\n sum += arr[end]\n \n # Decrease the window size\n \n # If it is not possible to make the\n # array elements in the window equal\n while ((end - start + 1) * arr[end] - sum > K):\n \n # Update the value of sum\n sum -= arr[start]\n \n # Increment the value of start\n start += 1\n \n # Update the maximum possible frequency\n res = max(res, end - start + 1)\n \n # Print the frequency of\n # the most frequent array\n # element after K increments\n print(res)\n \n# Driver code\nif __name__ == '__main__':\n \n arr = [ 1, 4, 8, 13 ]\n N = 4\n K = 5\n \n maxFrequency(arr, N, K)\n \n# This code is contributed by ipg2016107\n\n\n\n\n\n",
"e": 31533,
"s": 30288,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\n \nclass GFG{\n \n// Function to find the maximum possible\n// frequency of a most frequent element\n// after at most K increment operations\nstatic void maxFrequency(int[] arr, int N, int K)\n{\n \n // Sort the input array\n Array.Sort(arr);\n \n int start = 0, end = 0;\n \n // Stores the sum of sliding\n // window and the maximum possible\n // frequency of any array element\n int sum = 0, res = 0;\n \n // Traverse the array\n for(end = 0; end < N; end++)\n {\n \n // Add the current element\n // to the window\n sum += arr[end];\n \n // Decrease the window size\n \n // If it is not possible to make the\n // array elements in the window equal\n while ((end - start + 1) * \n arr[end] - sum > K)\n {\n \n // Update the value of sum\n sum -= arr[start];\n \n // Increment the value of start\n start++;\n }\n \n // Update the maximum possible frequency\n res = Math.Max(res, end - start + 1);\n }\n \n // Print the frequency of\n // the most frequent array\n // element after K increments\n Console.WriteLine(res);\n}\n \n// Driver Code\npublic static void Main()\n{\n int[] arr = { 1, 4, 8, 13 };\n int N = 4;\n int K = 5;\n \n maxFrequency(arr, N, K);\n}\n}\n \n// This code is contributed by code_hunt\n\n\n\n\n\n",
"e": 32981,
"s": 31543,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n// JavaScript program for the above approach\n \n \n// Function to find the maximum possible\n// frequency of a most frequent element\n// after at most K increment operations\nfunction maxFrequency(arr, N, K) {\n // Sort the input array\n arr.sort((a, b) => a - b);\n \n let start = 0, end = 0;\n \n // Stores the sum of sliding\n // window and the maximum possible\n // frequency of any array element\n let sum = 0, res = 0;\n \n // Traverse the array\n for (end = 0; end < N; end++) {\n \n // Add the current element\n // to the window\n sum += arr[end];\n \n // Decrease the window size\n \n // If it is not possible to make the\n // array elements in the window equal\n while ((end - start + 1) * arr[end] - sum > K) {\n \n // Update the value of sum\n sum -= arr[start];\n \n // Increment the value of start\n start++;\n }\n \n // Update the maximum possible frequency\n res = Math.max(res, end - start + 1);\n }\n \n // Print the frequency of\n // the most frequent array\n // element after K increments\n document.write(res + \"<br>\");\n}\n \n// Driver code\n \nlet arr = [1, 4, 8, 13];\nlet N = 4;\nlet K = 5;\nmaxFrequency(arr, N, K);\n \n</script>\n\n\n\n\n\n",
"e": 34274,
"s": 32991,
"text": null
},
{
"code": null,
"e": 34276,
"s": 34274,
"text": "2"
},
{
"code": null,
"e": 34326,
"s": 34278,
"text": "Time Complexity: O(NlogN) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34341,
"s": 34326,
"text": "abhinavjain194"
},
{
"code": null,
"e": 34351,
"s": 34341,
"text": "code_hunt"
},
{
"code": null,
"e": 34362,
"s": 34351,
"text": "ipg2016107"
},
{
"code": null,
"e": 34379,
"s": 34362,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34400,
"s": 34379,
"text": "\nfrequency-counting\n"
},
{
"code": null,
"e": 34409,
"s": 34400,
"text": "\nPicked\n"
},
{
"code": null,
"e": 34426,
"s": 34409,
"text": "\nsliding-window\n"
},
{
"code": null,
"e": 34435,
"s": 34426,
"text": "\nArrays\n"
},
{
"code": null,
"e": 34450,
"s": 34435,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 34655,
"s": 34450,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 34678,
"s": 34655,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34692,
"s": 34678,
"text": "Linear Search"
},
{
"code": null,
"e": 34724,
"s": 34692,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34792,
"s": 34724,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34837,
"s": 34792,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 34867,
"s": 34837,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34882,
"s": 34867,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34943,
"s": 34882,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34986,
"s": 34943,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to open a file in append mode with Python?
|
To open files in append mode, specify 'a' as the mode(a=append). For example,
f = open('my_file.txt', 'a')
file_content = f.read()
f.write('Hello World')
f.close()
Above code opens my_file.txt in append mode and appends the file to contain "Hello World" at the end.
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To open files in append mode, specify 'a' as the mode(a=append). For example,"
},
{
"code": null,
"e": 1226,
"s": 1140,
"text": "f = open('my_file.txt', 'a')\nfile_content = f.read()\nf.write('Hello World')\nf.close()"
},
{
"code": null,
"e": 1328,
"s": 1226,
"text": "Above code opens my_file.txt in append mode and appends the file to contain \"Hello World\" at the end."
}
] |
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) - GeeksforGeeks
|
19 Feb, 2020
Decision-making statements in programming languages decide the direction of the flow of program execution. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Decision-making statements available in Julia are:
if statement
if..else statements
nested if statements
if-elseif ladder
if statement
if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if condition
# Statements to execute if
# condition is true
end
Here, conditions after evaluation will be either true or false. if-statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.Statements written within the if-statement and the end statement are considered as a block and are executed if the condition is satisfied.
Flowchart:-
# Julia program to illustrate If statement i = 10if (i > 15) println("10 is greater than 15")endprintln("I am Not in if")
Output:In the above code, the condition present in the if-statement is false. So, the block below the if-statement is not executed.
if- else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.Syntax:
if (condition)
# Executes this block if
# condition is true
else
# Executes this block if
# condition is false
end
Flow Chart:-
# Julia program to illustrate If-else statement i = 20;if (i < 15) println("$i is smaller than 15") println("I'm in if Block")else println("$i is greater than 15") println("I'm in else Block")endprintln("I'm not in if and not in else Block")
In the above code, the condition given in the if-statement is false. Hence, the block of code written in the else-statement is executed. Afterwards, when the execution of the else block is over, the compiler executes the statement written outside of the If-else statement.
nested-if
A nested-if is an if-statement that is the target of another if-statement. Nested-if statements means an if-statement written inside another if-statement. Yes, Julia allows us to nest if-statements within if-statements. i.e, we can place an if-statement inside another if-statement and so on multiple if-statements can be used as per the need.
Syntax:
if (condition1)
# Executes when condition1 is true
if (condition2)
# Executes when condition2 is true
# if Block ends here
end
# if Block ends here
end
Flow chart:-
# Julia program to illustrate nested-If statement i = 14 # First if statementif (i == 14) # First Nested-if statement if (i < 15) println("$i is smaller than 15") # This Nested statement # will only be executed if # the first Nested-if statement is true if (i < 12) println("$i is smaller than 12 too") else println("$i lies between 12 and 15") end else println("$i is greater than 15") endend
Output:
if-elseif-else ladder
Here, a user can decide among multiple options. The if-statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement
elseif (condition)
statement
.
.
else
statement
end
Flow Chart:-
# Julia program to illustrate if-elseif-else ladder i = 20if (i == 10) println("Value of i is 10")elseif(i == 15) println("Value of i is 15")elseif(i == 20) println("Value of i is 20")else println("Value of i is not defined")end
Output:
Julia-Decision Making
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Formatting of Strings in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Storing Output on a File in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Creating array with repeated elements in Julia - repeat() Method
Comments in Julia
Convert an Integer to a String in Julia - string() Function
while loop in Julia
|
[
{
"code": null,
"e": 24184,
"s": 24156,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 24576,
"s": 24184,
"text": "Decision-making statements in programming languages decide the direction of the flow of program execution. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Decision-making statements available in Julia are:"
},
{
"code": null,
"e": 24589,
"s": 24576,
"text": "if statement"
},
{
"code": null,
"e": 24609,
"s": 24589,
"text": "if..else statements"
},
{
"code": null,
"e": 24630,
"s": 24609,
"text": "nested if statements"
},
{
"code": null,
"e": 24647,
"s": 24630,
"text": "if-elseif ladder"
},
{
"code": null,
"e": 24660,
"s": 24647,
"text": "if statement"
},
{
"code": null,
"e": 24903,
"s": 24660,
"text": "if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not."
},
{
"code": null,
"e": 24911,
"s": 24903,
"text": "Syntax:"
},
{
"code": null,
"e": 24991,
"s": 24911,
"text": "if condition \n # Statements to execute if\n # condition is true\nend\n"
},
{
"code": null,
"e": 25369,
"s": 24991,
"text": "Here, conditions after evaluation will be either true or false. if-statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.Statements written within the if-statement and the end statement are considered as a block and are executed if the condition is satisfied."
},
{
"code": null,
"e": 25381,
"s": 25369,
"text": "Flowchart:-"
},
{
"code": "# Julia program to illustrate If statement i = 10if (i > 15) println(\"10 is greater than 15\")endprintln(\"I am Not in if\")",
"e": 25506,
"s": 25381,
"text": null
},
{
"code": null,
"e": 25638,
"s": 25506,
"text": "Output:In the above code, the condition present in the if-statement is false. So, the block below the if-statement is not executed."
},
{
"code": null,
"e": 25647,
"s": 25638,
"text": "if- else"
},
{
"code": null,
"e": 25995,
"s": 25647,
"text": "The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.Syntax:"
},
{
"code": null,
"e": 26127,
"s": 25995,
"text": "if (condition)\n # Executes this block if\n # condition is true\nelse\n # Executes this block if\n # condition is false\nend\n"
},
{
"code": null,
"e": 26140,
"s": 26127,
"text": "Flow Chart:-"
},
{
"code": "# Julia program to illustrate If-else statement i = 20;if (i < 15) println(\"$i is smaller than 15\") println(\"I'm in if Block\")else println(\"$i is greater than 15\") println(\"I'm in else Block\")endprintln(\"I'm not in if and not in else Block\")",
"e": 26395,
"s": 26140,
"text": null
},
{
"code": null,
"e": 26668,
"s": 26395,
"text": "In the above code, the condition given in the if-statement is false. Hence, the block of code written in the else-statement is executed. Afterwards, when the execution of the else block is over, the compiler executes the statement written outside of the If-else statement."
},
{
"code": null,
"e": 26678,
"s": 26668,
"text": "nested-if"
},
{
"code": null,
"e": 27022,
"s": 26678,
"text": "A nested-if is an if-statement that is the target of another if-statement. Nested-if statements means an if-statement written inside another if-statement. Yes, Julia allows us to nest if-statements within if-statements. i.e, we can place an if-statement inside another if-statement and so on multiple if-statements can be used as per the need."
},
{
"code": null,
"e": 27030,
"s": 27022,
"text": "Syntax:"
},
{
"code": null,
"e": 27201,
"s": 27030,
"text": "if (condition1)\n # Executes when condition1 is true\n if (condition2)\n # Executes when condition2 is true\n # if Block ends here\n end\n# if Block ends here\nend\n"
},
{
"code": null,
"e": 27214,
"s": 27201,
"text": "Flow chart:-"
},
{
"code": "# Julia program to illustrate nested-If statement i = 14 # First if statementif (i == 14) # First Nested-if statement if (i < 15) println(\"$i is smaller than 15\") # This Nested statement # will only be executed if # the first Nested-if statement is true if (i < 12) println(\"$i is smaller than 12 too\") else println(\"$i lies between 12 and 15\") end else println(\"$i is greater than 15\") endend",
"e": 27705,
"s": 27214,
"text": null
},
{
"code": null,
"e": 27713,
"s": 27705,
"text": "Output:"
},
{
"code": null,
"e": 27735,
"s": 27713,
"text": "if-elseif-else ladder"
},
{
"code": null,
"e": 28068,
"s": 27735,
"text": "Here, a user can decide among multiple options. The if-statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed."
},
{
"code": null,
"e": 28076,
"s": 28068,
"text": "Syntax:"
},
{
"code": null,
"e": 28166,
"s": 28076,
"text": "if (condition)\n statement\nelseif (condition)\n statement\n.\n.\nelse\n statement\nend\n"
},
{
"code": null,
"e": 28179,
"s": 28166,
"text": "Flow Chart:-"
},
{
"code": "# Julia program to illustrate if-elseif-else ladder i = 20if (i == 10) println(\"Value of i is 10\")elseif(i == 15) println(\"Value of i is 15\")elseif(i == 20) println(\"Value of i is 20\")else println(\"Value of i is not defined\")end",
"e": 28421,
"s": 28179,
"text": null
},
{
"code": null,
"e": 28429,
"s": 28421,
"text": "Output:"
},
{
"code": null,
"e": 28451,
"s": 28429,
"text": "Julia-Decision Making"
},
{
"code": null,
"e": 28457,
"s": 28451,
"text": "Julia"
},
{
"code": null,
"e": 28555,
"s": 28457,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28564,
"s": 28555,
"text": "Comments"
},
{
"code": null,
"e": 28577,
"s": 28564,
"text": "Old Comments"
},
{
"code": null,
"e": 28594,
"s": 28577,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 28625,
"s": 28594,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 28685,
"s": 28625,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 28746,
"s": 28685,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 28780,
"s": 28746,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 28850,
"s": 28780,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 28915,
"s": 28850,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 28933,
"s": 28915,
"text": "Comments in Julia"
},
{
"code": null,
"e": 28993,
"s": 28933,
"text": "Convert an Integer to a String in Julia - string() Function"
}
] |
How to multiply two Arrays in JavaScript?
|
Following is the code to multiply two arrays in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>Multiply two Arrays in JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to multiply the above two arrays</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let arr = [1, 2, 3, 4, 5];
let arr1 = [11, 12, 13, 14, 15, 22];
let multArray = [];
sampleEle.innerHTML = arr + "<br>" + arr1 + "<br>";
BtnEle.addEventListener("click", () => {
for (let i = 0; i < Math.min(arr.length, arr1.length); i++) {
multArray[i] = arr[i] * arr1[i];
}
resEle.innerHTML = "Multiplied array = " + multArray;
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "Following is the code to multiply two arrays in JavaScript −"
},
{
"code": null,
"e": 1134,
"s": 1123,
"text": " Live Demo"
},
{
"code": null,
"e": 2315,
"s": 1134,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,.sample {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n .result {\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>Multiply two Arrays in JavaScript</h1>\n<div class=\"sample\"></div>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click the above button to multiply the above two arrays</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n let sampleEle = document.querySelector(\".sample\");\n let arr = [1, 2, 3, 4, 5];\n let arr1 = [11, 12, 13, 14, 15, 22];\n let multArray = [];\n sampleEle.innerHTML = arr + \"<br>\" + arr1 + \"<br>\";\n BtnEle.addEventListener(\"click\", () => {\n for (let i = 0; i < Math.min(arr.length, arr1.length); i++) {\n multArray[i] = arr[i] * arr1[i];\n }\n resEle.innerHTML = \"Multiplied array = \" + multArray;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2366,
"s": 2315,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2404,
"s": 2366,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
How to add Days to a Date in Python?
|
29 Dec, 2020
Python provides an in-built module datetime which allows easy manipulation and modification of date and time values. It allows arithmetic operations as well as formatting the output obtained from the DateTime module. The module contains various classes like date, time, timedelta, etc. that simulate the easy implementation of dates and time (month, years, and days).
Date and time objects are created using the DateTime module which is immutable and hashable. The following classes of the DateTime module are used to add days to a date in python :
datetime – DateTime objects give date along with time in hours, minutes, seconds. The DateTime library provides manipulation to a combination of both date and time objects (month, day, year, seconds and microseconds).timedelta – Timedelta class represents the duration. The DateTime library provides timedelta method to carry out date-related manipulation and also calculate differences in time objects. It can be majorly used to perform arithmetic operations like addition, subtraction, and multiplication. By specifying the days attribute value, we can add days to the date specified.
datetime – DateTime objects give date along with time in hours, minutes, seconds. The DateTime library provides manipulation to a combination of both date and time objects (month, day, year, seconds and microseconds).
timedelta – Timedelta class represents the duration. The DateTime library provides timedelta method to carry out date-related manipulation and also calculate differences in time objects. It can be majorly used to perform arithmetic operations like addition, subtraction, and multiplication. By specifying the days attribute value, we can add days to the date specified.
Syntax: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example 1: The following Python code is used to add days to a date in Python
Python3
from datetime import datetimefrom datetime import timedelta # taking input as the dateBegindatestring = "2020-10-11" # carry out conversion between string # to datetime objectBegindate = datetime.strptime(Begindatestring, "%Y-%m-%d") # print begin dateprint("Beginning date")print(Begindate) # calculating end date by adding 10 daysEnddate = Begindate + timedelta(days=10) # printing end dateprint("Ending date")print(Enddate)
Output:
Beginning date
2020-10-11 00:00:00
Ending date
2020-10-21 00:00:00
Example 2: The program adds 10 days to the beginning date in yyyy-mm-dd format
Python3
from datetime import datetimefrom datetime import timedeltafrom datetime import date # taking input as the current date# today() method is supported by date # class in datetime moduleBegindatestring = date.today() # print begin dateprint("Beginning date")print(Begindatestring) # calculating end date by adding 4 daysEnddate = Begindatestring + timedelta(days=4) # printing end dateprint("Ending date")print(Enddate)
Output:
Beginning date
2020-12-05
Ending date
2020-12-09
Python datetime-program
Python-datetime
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "Python provides an in-built module datetime which allows easy manipulation and modification of date and time values. It allows arithmetic operations as well as formatting the output obtained from the DateTime module. The module contains various classes like date, time, timedelta, etc. that simulate the easy implementation of dates and time (month, years, and days). "
},
{
"code": null,
"e": 578,
"s": 397,
"text": "Date and time objects are created using the DateTime module which is immutable and hashable. The following classes of the DateTime module are used to add days to a date in python :"
},
{
"code": null,
"e": 1165,
"s": 578,
"text": "datetime – DateTime objects give date along with time in hours, minutes, seconds. The DateTime library provides manipulation to a combination of both date and time objects (month, day, year, seconds and microseconds).timedelta – Timedelta class represents the duration. The DateTime library provides timedelta method to carry out date-related manipulation and also calculate differences in time objects. It can be majorly used to perform arithmetic operations like addition, subtraction, and multiplication. By specifying the days attribute value, we can add days to the date specified."
},
{
"code": null,
"e": 1383,
"s": 1165,
"text": "datetime – DateTime objects give date along with time in hours, minutes, seconds. The DateTime library provides manipulation to a combination of both date and time objects (month, day, year, seconds and microseconds)."
},
{
"code": null,
"e": 1753,
"s": 1383,
"text": "timedelta – Timedelta class represents the duration. The DateTime library provides timedelta method to carry out date-related manipulation and also calculate differences in time objects. It can be majorly used to perform arithmetic operations like addition, subtraction, and multiplication. By specifying the days attribute value, we can add days to the date specified."
},
{
"code": null,
"e": 1860,
"s": 1753,
"text": "Syntax: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)"
},
{
"code": null,
"e": 1937,
"s": 1860,
"text": "Example 1: The following Python code is used to add days to a date in Python"
},
{
"code": null,
"e": 1945,
"s": 1937,
"text": "Python3"
},
{
"code": "from datetime import datetimefrom datetime import timedelta # taking input as the dateBegindatestring = \"2020-10-11\" # carry out conversion between string # to datetime objectBegindate = datetime.strptime(Begindatestring, \"%Y-%m-%d\") # print begin dateprint(\"Beginning date\")print(Begindate) # calculating end date by adding 10 daysEnddate = Begindate + timedelta(days=10) # printing end dateprint(\"Ending date\")print(Enddate)",
"e": 2377,
"s": 1945,
"text": null
},
{
"code": null,
"e": 2385,
"s": 2377,
"text": "Output:"
},
{
"code": null,
"e": 2452,
"s": 2385,
"text": "Beginning date\n2020-10-11 00:00:00\nEnding date\n2020-10-21 00:00:00"
},
{
"code": null,
"e": 2531,
"s": 2452,
"text": "Example 2: The program adds 10 days to the beginning date in yyyy-mm-dd format"
},
{
"code": null,
"e": 2539,
"s": 2531,
"text": "Python3"
},
{
"code": "from datetime import datetimefrom datetime import timedeltafrom datetime import date # taking input as the current date# today() method is supported by date # class in datetime moduleBegindatestring = date.today() # print begin dateprint(\"Beginning date\")print(Begindatestring) # calculating end date by adding 4 daysEnddate = Begindatestring + timedelta(days=4) # printing end dateprint(\"Ending date\")print(Enddate)",
"e": 2960,
"s": 2539,
"text": null
},
{
"code": null,
"e": 2968,
"s": 2960,
"text": "Output:"
},
{
"code": null,
"e": 3017,
"s": 2968,
"text": "Beginning date\n2020-12-05\nEnding date\n2020-12-09"
},
{
"code": null,
"e": 3041,
"s": 3017,
"text": "Python datetime-program"
},
{
"code": null,
"e": 3057,
"s": 3041,
"text": "Python-datetime"
},
{
"code": null,
"e": 3064,
"s": 3057,
"text": "Python"
},
{
"code": null,
"e": 3162,
"s": 3064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3180,
"s": 3162,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3222,
"s": 3180,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3244,
"s": 3222,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3270,
"s": 3244,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3302,
"s": 3270,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3331,
"s": 3302,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3361,
"s": 3331,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3388,
"s": 3361,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3424,
"s": 3388,
"text": "Convert integer to string in Python"
}
] |
Django Models | Set – 1
|
21 Jun, 2019
Prerequisites : Django Creating apps
According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
The basics:
Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
With all of this, Django gives you an automatically-generated database-access API.
Django models are used as a structure to define fields and their types which will be saved in the database. Whatever changes we want to make in the database and want to store them in the database permanently are done using Django Models. A table for a phone in the database can be imagined as:
We need to create a new app named product so that we can define all properties of phone described in the above-provided image. Open your terminal and run following command:
python manage.py startapp product
Now, our directory will be:After creating the app, don’t forget to mention it in geeks_site/settings.py under INSTALLED_APPS.
Also, register it with admin by adding following line of code to product/admin.py. By registering it with admin, you make sure that admin of the site will be aware that new table schema for database has been prepared.
from django.contrib import admin # Register your models here.from product.models import Phone admin.site.register(Phone)
Now, navigate to product/models.py. You will see a file with following lines:
from django.db import models # Create your models here.
We use a python class to define models which inherit parent class named Model defined in django.db.models package.
Add the following lines of code to this file:
from django.db import models # Create your models here.class Phone(models.Model): Price = models.IntegerField() RAM = models.IntegerField() ROM = models.IntegerField() Front_camera = models.IntegerField() Rear_camera = models.IntegerField() Battery = models.IntegerField() Screen_size = models.DecimalField(max_digits = 2, decimal_places = 1) Color = models.CharField(max_length = 120) Quantity = models.IntegerField()
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 65,
"s": 28,
"text": "Prerequisites : Django Creating apps"
},
{
"code": null,
"e": 296,
"s": 65,
"text": "According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table."
},
{
"code": null,
"e": 308,
"s": 296,
"text": "The basics:"
},
{
"code": null,
"e": 377,
"s": 308,
"text": "Each model is a Python class that subclasses django.db.models.Model."
},
{
"code": null,
"e": 434,
"s": 377,
"text": "Each attribute of the model represents a database field."
},
{
"code": null,
"e": 517,
"s": 434,
"text": "With all of this, Django gives you an automatically-generated database-access API."
},
{
"code": null,
"e": 811,
"s": 517,
"text": "Django models are used as a structure to define fields and their types which will be saved in the database. Whatever changes we want to make in the database and want to store them in the database permanently are done using Django Models. A table for a phone in the database can be imagined as:"
},
{
"code": null,
"e": 984,
"s": 811,
"text": "We need to create a new app named product so that we can define all properties of phone described in the above-provided image. Open your terminal and run following command:"
},
{
"code": null,
"e": 1018,
"s": 984,
"text": "python manage.py startapp product"
},
{
"code": null,
"e": 1144,
"s": 1018,
"text": "Now, our directory will be:After creating the app, don’t forget to mention it in geeks_site/settings.py under INSTALLED_APPS."
},
{
"code": null,
"e": 1362,
"s": 1144,
"text": "Also, register it with admin by adding following line of code to product/admin.py. By registering it with admin, you make sure that admin of the site will be aware that new table schema for database has been prepared."
},
{
"code": " from django.contrib import admin # Register your models here.from product.models import Phone admin.site.register(Phone)",
"e": 1488,
"s": 1362,
"text": null
},
{
"code": null,
"e": 1566,
"s": 1488,
"text": "Now, navigate to product/models.py. You will see a file with following lines:"
},
{
"code": " from django.db import models # Create your models here.",
"e": 1626,
"s": 1566,
"text": null
},
{
"code": null,
"e": 1741,
"s": 1626,
"text": "We use a python class to define models which inherit parent class named Model defined in django.db.models package."
},
{
"code": null,
"e": 1787,
"s": 1741,
"text": "Add the following lines of code to this file:"
},
{
"code": " from django.db import models # Create your models here.class Phone(models.Model): Price = models.IntegerField() RAM = models.IntegerField() ROM = models.IntegerField() Front_camera = models.IntegerField() Rear_camera = models.IntegerField() Battery = models.IntegerField() Screen_size = models.DecimalField(max_digits = 2, decimal_places = 1) Color = models.CharField(max_length = 120) Quantity = models.IntegerField()",
"e": 2239,
"s": 1787,
"text": null
},
{
"code": null,
"e": 2253,
"s": 2239,
"text": "Python Django"
},
{
"code": null,
"e": 2260,
"s": 2253,
"text": "Python"
}
] |
Python | Pandas DataFrame.values
|
20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.values attribute return a Numpy representation of the given DataFrame.
Syntax: DataFrame.values
Parameter : None
Returns : array
Example #1: Use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# return the numpy representation of # this dataframeresult = df.values # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame. Example #2: Use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# return the numpy representation of # this dataframeresult = df.values # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas."
},
{
"code": null,
"e": 430,
"s": 342,
"text": "Pandas DataFrame.values attribute return a Numpy representation of the given DataFrame."
},
{
"code": null,
"e": 455,
"s": 430,
"text": "Syntax: DataFrame.values"
},
{
"code": null,
"e": 472,
"s": 455,
"text": "Parameter : None"
},
{
"code": null,
"e": 488,
"s": 472,
"text": "Returns : array"
},
{
"code": null,
"e": 590,
"s": 488,
"text": "Example #1: Use DataFrame.values attribute to return the numpy representation of the given DataFrame."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Print the DataFrameprint(df)",
"e": 855,
"s": 590,
"text": null
},
{
"code": null,
"e": 864,
"s": 855,
"text": "Output :"
},
{
"code": null,
"e": 966,
"s": 864,
"text": "Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame."
},
{
"code": "# return the numpy representation of # this dataframeresult = df.values # Print the resultprint(result)",
"e": 1071,
"s": 966,
"text": null
},
{
"code": null,
"e": 1080,
"s": 1071,
"text": "Output :"
},
{
"code": null,
"e": 1317,
"s": 1080,
"text": "As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame. Example #2: Use DataFrame.values attribute to return the numpy representation of the given DataFrame."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Print the DataFrameprint(df)",
"e": 1595,
"s": 1317,
"text": null
},
{
"code": null,
"e": 1604,
"s": 1595,
"text": "Output :"
},
{
"code": null,
"e": 1706,
"s": 1604,
"text": "Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame."
},
{
"code": "# return the numpy representation of # this dataframeresult = df.values # Print the resultprint(result)",
"e": 1811,
"s": 1706,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1811,
"text": "Output :As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame."
},
{
"code": null,
"e": 1978,
"s": 1954,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2010,
"s": 1978,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2024,
"s": 2010,
"text": "Python-pandas"
},
{
"code": null,
"e": 2031,
"s": 2024,
"text": "Python"
}
] |
How to create a bootstrap tooltip using jQuery ?
|
02 Dec, 2021
Tooltip is like a balloon or also a small screen tip that displays text descriptions to any object in a webpage. A tooltip is displayed when the user hovers over an object using the cursor. It is a very useful part of a website and now can be found in almost all websites including some web applications like Adobe Photoshop, Adobe Illustrator, and many more. A tooltip is very helpful for new users, where the user can learn about the object by reading the tooltip text.
Now, having understood the basic concept of the tooltip, let’s learn how to create a tooltip using the Bootstrap framework and jQuery.
What is jQuery ?
jQuery is a JavaScript library that makes the manipulation of the HTML DOM (Document Object Model) properties very easily. So let’s start.
Step 1: First import all the Bootstrap CDN for Bootstrap CSS from the Bootstrap official website.
Bootstrap CSS:
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css” rel=”stylesheet” integrity=”sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU” crossorigin=”anonymous”>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js” integrity=”sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ” crossorigin=”anonymous”></script>
Step 2: Import the jQuery link to the HTML file from the official jQuery CDN website.
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”> </script>
Step 3: To create a tooltip, we have to add the ‘data-bs-toggle’ attribute to any element and to add the text that needs to be displayed when the tooltip hovers, we have to add the ‘title’ attribute to the HTML element.
<button type=”button” id=”tooltip” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”Tooltip on bottom”>Tooltip on bottom</button>
(Here we have used buttons to show the tooltips effect, but, you can use tooltips with other bootstrap components too. The process is very same.)
Step 4: After that, add the jQuery piece of code to the HTML file given below inside the script tag:
<script>
var tool = $("#tooltip");
var tooltip = new bootstrap.Tooltip(tool, {
boundary: $("body")
})
</script>
Here in the above code, we use the Tooltip() function to make the tooltip trigger on mouse hover.
Note: Here we have made the tooltip text placement in the bottom, you can place it on left, right or top using the “data-bs-placement” attribute. Here, we have set it to “bottom”.
Step 5: Thus, we have successfully created the tooltip in Bootstrap using jQuery.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous" /> <style> button { margin: 4em; } </style> <title>Document</title> </head> <body> <button type="button" id="tooltip" class="tool btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Tooltip on bottom" > Tooltip on bottom </button> <!-- Bootstrap Javascript --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous" ></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" ></script> <script> var tool = $("#tooltip"); var tooltip = new bootstrap.Tooltip(tool, { boundary: $("body"), }); </script> </body></html>
Tooltip using Bootstrap and jQuery
Now, after that, we can also define the direction of the tooltip message on different directions like bottom, top, left, right, etc.
To align the tooltip to different positions, we need the ‘data-bs-placement’ attribute to the bootstrap object. There are four placement options available with it. They are:
1. Top – to place the tooltip on the top of the object.
Syntax:
<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”top” title=”...”>...</button>
2. Bottom – to place the tooltip on the bottom of the object.
Syntax:
<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”...”>...</button>
3. Left – to place the tooltip on the left of the object.
Syntax:
<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”left” title=”...”>...</button>
4. Right – to place the tooltip on the right of the object.
Syntax:
<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”...”>...</button>
Bootstrap-Questions
HTML-Questions
jQuery-Questions
Picked
Bootstrap
HTML
JQuery
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to set vertical alignment in Bootstrap ?
How to toggle password visibility in forms using Bootstrap-icons ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Tooltip is like a balloon or also a small screen tip that displays text descriptions to any object in a webpage. A tooltip is displayed when the user hovers over an object using the cursor. It is a very useful part of a website and now can be found in almost all websites including some web applications like Adobe Photoshop, Adobe Illustrator, and many more. A tooltip is very helpful for new users, where the user can learn about the object by reading the tooltip text. "
},
{
"code": null,
"e": 637,
"s": 502,
"text": "Now, having understood the basic concept of the tooltip, let’s learn how to create a tooltip using the Bootstrap framework and jQuery."
},
{
"code": null,
"e": 654,
"s": 637,
"text": "What is jQuery ?"
},
{
"code": null,
"e": 793,
"s": 654,
"text": "jQuery is a JavaScript library that makes the manipulation of the HTML DOM (Document Object Model) properties very easily. So let’s start."
},
{
"code": null,
"e": 892,
"s": 793,
"text": "Step 1: First import all the Bootstrap CDN for Bootstrap CSS from the Bootstrap official website."
},
{
"code": null,
"e": 907,
"s": 892,
"text": "Bootstrap CSS:"
},
{
"code": null,
"e": 1118,
"s": 907,
"text": "<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css” rel=”stylesheet” integrity=”sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU” crossorigin=”anonymous”>"
},
{
"code": null,
"e": 1327,
"s": 1118,
"text": "<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js” integrity=”sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ” crossorigin=”anonymous”></script>"
},
{
"code": null,
"e": 1413,
"s": 1327,
"text": "Step 2: Import the jQuery link to the HTML file from the official jQuery CDN website."
},
{
"code": null,
"e": 1526,
"s": 1413,
"text": "<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”> </script>"
},
{
"code": null,
"e": 1746,
"s": 1526,
"text": "Step 3: To create a tooltip, we have to add the ‘data-bs-toggle’ attribute to any element and to add the text that needs to be displayed when the tooltip hovers, we have to add the ‘title’ attribute to the HTML element."
},
{
"code": null,
"e": 1912,
"s": 1746,
"text": "<button type=”button” id=”tooltip” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”Tooltip on bottom”>Tooltip on bottom</button>"
},
{
"code": null,
"e": 2058,
"s": 1912,
"text": "(Here we have used buttons to show the tooltips effect, but, you can use tooltips with other bootstrap components too. The process is very same.)"
},
{
"code": null,
"e": 2159,
"s": 2058,
"text": "Step 4: After that, add the jQuery piece of code to the HTML file given below inside the script tag:"
},
{
"code": null,
"e": 2292,
"s": 2159,
"text": "<script>\n var tool = $(\"#tooltip\");\n var tooltip = new bootstrap.Tooltip(tool, {\n boundary: $(\"body\")\n })\n</script>\n"
},
{
"code": null,
"e": 2392,
"s": 2292,
"text": "Here in the above code, we use the Tooltip() function to make the tooltip trigger on mouse hover. "
},
{
"code": null,
"e": 2572,
"s": 2392,
"text": "Note: Here we have made the tooltip text placement in the bottom, you can place it on left, right or top using the “data-bs-placement” attribute. Here, we have set it to “bottom”."
},
{
"code": null,
"e": 2654,
"s": 2572,
"text": "Step 5: Thus, we have successfully created the tooltip in Bootstrap using jQuery."
},
{
"code": null,
"e": 2659,
"s": 2654,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU\" crossorigin=\"anonymous\" /> <style> button { margin: 4em; } </style> <title>Document</title> </head> <body> <button type=\"button\" id=\"tooltip\" class=\"tool btn btn-secondary\" data-bs-toggle=\"tooltip\" data-bs-placement=\"bottom\" title=\"Tooltip on bottom\" > Tooltip on bottom </button> <!-- Bootstrap Javascript --> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ\" crossorigin=\"anonymous\" ></script> <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\" ></script> <script> var tool = $(\"#tooltip\"); var tooltip = new bootstrap.Tooltip(tool, { boundary: $(\"body\"), }); </script> </body></html>",
"e": 4247,
"s": 2659,
"text": null
},
{
"code": null,
"e": 4282,
"s": 4247,
"text": "Tooltip using Bootstrap and jQuery"
},
{
"code": null,
"e": 4417,
"s": 4282,
"text": "Now, after that, we can also define the direction of the tooltip message on different directions like bottom, top, left, right, etc. "
},
{
"code": null,
"e": 4591,
"s": 4417,
"text": "To align the tooltip to different positions, we need the ‘data-bs-placement’ attribute to the bootstrap object. There are four placement options available with it. They are:"
},
{
"code": null,
"e": 4647,
"s": 4591,
"text": "1. Top – to place the tooltip on the top of the object."
},
{
"code": null,
"e": 4655,
"s": 4647,
"text": "Syntax:"
},
{
"code": null,
"e": 4777,
"s": 4655,
"text": "<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”top” title=”...”>...</button>"
},
{
"code": null,
"e": 4839,
"s": 4777,
"text": "2. Bottom – to place the tooltip on the bottom of the object."
},
{
"code": null,
"e": 4847,
"s": 4839,
"text": "Syntax:"
},
{
"code": null,
"e": 4972,
"s": 4847,
"text": "<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”...”>...</button>"
},
{
"code": null,
"e": 5030,
"s": 4972,
"text": "3. Left – to place the tooltip on the left of the object."
},
{
"code": null,
"e": 5038,
"s": 5030,
"text": "Syntax:"
},
{
"code": null,
"e": 5161,
"s": 5038,
"text": "<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”left” title=”...”>...</button>"
},
{
"code": null,
"e": 5221,
"s": 5161,
"text": "4. Right – to place the tooltip on the right of the object."
},
{
"code": null,
"e": 5229,
"s": 5221,
"text": "Syntax:"
},
{
"code": null,
"e": 5354,
"s": 5229,
"text": "<button type=”button” class=”btn btn-secondary” data-bs-toggle=”tooltip” data-bs-placement=”bottom” title=”...”>...</button>"
},
{
"code": null,
"e": 5374,
"s": 5354,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 5389,
"s": 5374,
"text": "HTML-Questions"
},
{
"code": null,
"e": 5406,
"s": 5389,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 5413,
"s": 5406,
"text": "Picked"
},
{
"code": null,
"e": 5423,
"s": 5413,
"text": "Bootstrap"
},
{
"code": null,
"e": 5428,
"s": 5423,
"text": "HTML"
},
{
"code": null,
"e": 5435,
"s": 5428,
"text": "JQuery"
},
{
"code": null,
"e": 5440,
"s": 5435,
"text": "HTML"
},
{
"code": null,
"e": 5538,
"s": 5440,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5579,
"s": 5538,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5612,
"s": 5579,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 5638,
"s": 5612,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 5683,
"s": 5638,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 5750,
"s": 5683,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 5798,
"s": 5750,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5860,
"s": 5798,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5910,
"s": 5860,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5934,
"s": 5910,
"text": "REST API (Introduction)"
}
] |
PHP | array_filter() Function
|
08 Mar, 2018
This built-in function in PHP is used to filter the elements of an array using a user-defined function which is also called a callback function. The array_filter() function iterates over each value in the array, passing them to the user-defined function or the callback function. If the callback function returns true then the current value of the array is returned into the result array otherwise not. This way the keys of the array gets preserved, i.e. the key of element in the original array and output array are same.
Syntax:
array array_filter($array, $callback_function, $flag)
Parameters: The function takes three parameters, out of which one is mandatory and the other two are optional.
$array (mandatory): This refers to the input array on which the filter operation is to be performed.$callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed.$flag (optional): Refers to the arguments passed to the callback function.ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value.
$array (mandatory): This refers to the input array on which the filter operation is to be performed.
$callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed.
$flag (optional): Refers to the arguments passed to the callback function.ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value.
ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.
ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value.
Return Value: The function returns a filtered array.
Below is a program showing how to return or filter out even elements from an array using array_filter() function.
<?php // PHP function to check for even elements in an arrayfunction Even($array){ // returns if the input integer is even if($array%2==0) return TRUE; else return FALSE; } $array = array(12, 0, 0, 18, 27, 0, 46);print_r(array_filter($array, "Even")); ?>
Output:
Array
(
[0] => 12
[1] => 0
[2] => 0
[3] => 18
[5] => 0
[6] => 46
)
In this example, we will not pass the callback function and let’s see the output. We will see that the 0 or false elements are not printed:
<?php // PHP function to check for even elements in an arrayfunction Even($array){ // returns if the input integer is even if($array%2==0) return TRUE; else return FALSE; } $array = array(12, 0, 0, 18, 27, 0, 46);print_r(array_filter($array)); ?>
Output:
Array
(
[0] => 12
[3] => 18
[4] => 27
[6] => 46
)
Reference: http://php.net/manual/en/function.array-filter.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 576,
"s": 53,
"text": "This built-in function in PHP is used to filter the elements of an array using a user-defined function which is also called a callback function. The array_filter() function iterates over each value in the array, passing them to the user-defined function or the callback function. If the callback function returns true then the current value of the array is returned into the result array otherwise not. This way the keys of the array gets preserved, i.e. the key of element in the original array and output array are same."
},
{
"code": null,
"e": 584,
"s": 576,
"text": "Syntax:"
},
{
"code": null,
"e": 638,
"s": 584,
"text": "array array_filter($array, $callback_function, $flag)"
},
{
"code": null,
"e": 749,
"s": 638,
"text": "Parameters: The function takes three parameters, out of which one is mandatory and the other two are optional."
},
{
"code": null,
"e": 1296,
"s": 749,
"text": "$array (mandatory): This refers to the input array on which the filter operation is to be performed.$callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed.$flag (optional): Refers to the arguments passed to the callback function.ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value."
},
{
"code": null,
"e": 1397,
"s": 1296,
"text": "$array (mandatory): This refers to the input array on which the filter operation is to be performed."
},
{
"code": null,
"e": 1561,
"s": 1397,
"text": "$callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed."
},
{
"code": null,
"e": 1845,
"s": 1561,
"text": "$flag (optional): Refers to the arguments passed to the callback function.ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value."
},
{
"code": null,
"e": 1959,
"s": 1845,
"text": "ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array."
},
{
"code": null,
"e": 2056,
"s": 1959,
"text": "ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value."
},
{
"code": null,
"e": 2109,
"s": 2056,
"text": "Return Value: The function returns a filtered array."
},
{
"code": null,
"e": 2223,
"s": 2109,
"text": "Below is a program showing how to return or filter out even elements from an array using array_filter() function."
},
{
"code": "<?php // PHP function to check for even elements in an arrayfunction Even($array){ // returns if the input integer is even if($array%2==0) return TRUE; else return FALSE; } $array = array(12, 0, 0, 18, 27, 0, 46);print_r(array_filter($array, \"Even\")); ?>",
"e": 2503,
"s": 2223,
"text": null
},
{
"code": null,
"e": 2511,
"s": 2503,
"text": "Output:"
},
{
"code": null,
"e": 2603,
"s": 2511,
"text": "Array\n(\n [0] => 12\n [1] => 0\n [2] => 0\n [3] => 18\n [5] => 0\n [6] => 46\n)\n"
},
{
"code": null,
"e": 2743,
"s": 2603,
"text": "In this example, we will not pass the callback function and let’s see the output. We will see that the 0 or false elements are not printed:"
},
{
"code": "<?php // PHP function to check for even elements in an arrayfunction Even($array){ // returns if the input integer is even if($array%2==0) return TRUE; else return FALSE; } $array = array(12, 0, 0, 18, 27, 0, 46);print_r(array_filter($array)); ?>",
"e": 3015,
"s": 2743,
"text": null
},
{
"code": null,
"e": 3023,
"s": 3015,
"text": "Output:"
},
{
"code": null,
"e": 3090,
"s": 3023,
"text": "Array\n(\n [0] => 12\n [3] => 18\n [4] => 27\n [6] => 46\n)\n"
},
{
"code": null,
"e": 3152,
"s": 3090,
"text": "Reference: http://php.net/manual/en/function.array-filter.php"
},
{
"code": null,
"e": 3162,
"s": 3152,
"text": "PHP-array"
},
{
"code": null,
"e": 3175,
"s": 3162,
"text": "PHP-function"
},
{
"code": null,
"e": 3179,
"s": 3175,
"text": "PHP"
},
{
"code": null,
"e": 3196,
"s": 3179,
"text": "Web Technologies"
},
{
"code": null,
"e": 3200,
"s": 3196,
"text": "PHP"
},
{
"code": null,
"e": 3298,
"s": 3200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3338,
"s": 3298,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3383,
"s": 3338,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3431,
"s": 3383,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3483,
"s": 3431,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3516,
"s": 3483,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 3578,
"s": 3516,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3611,
"s": 3578,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3672,
"s": 3611,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3722,
"s": 3672,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
cpio command in Linux with Examples
|
15 May, 2019
cpio stands for “copy in, copy out“. It is used for processing the archive files like *.cpio or *.tar. This command can copy files to and from archives.
Synopsis:
Copy-out Mode: Copy files named in name-list to the archiveSyntax:cpio -o < name-list > archive
Syntax:
cpio -o < name-list > archive
Copy-in Mode: Extract files from the archiveSyntax:cpio -i < archive
Syntax:
cpio -i < archive
Copy-pass Mode: Copy files named in name-list to destination-directorySyntax:cpio -p destination-directory < name-list
Syntax:
cpio -p destination-directory < name-list
Policy Options:
-i, –extract: Extract files from an archive and it runs only in copy-in mode.
-o, –create: Create the archive and it runs only in copy-out mode.
-p, –pass-through: Run in copy-pass mode.
-t, –list: Print a table of contents of all the inputs present.
Operation modifiers valid in any Mode:
-B: Changes the I/O block size to 5120 bytes.
-c: Use the old portable (ASCII) archive format.
-C, –io-size=NUMBER: Set the I/O block size to the given particular NUMBER of bytes.
-D, –directory=DIR: Changes to Directory DIR.
-H, –format=FORMAT: Use given arc.
-v, –verbose: List the files processed in a particular task.
-V, –dot: Print “.” for each file processed in a particular task.
-W, –warning=FLAG: Control warning display. Currently FLAG is one of ‘none‘, ‘truncate‘, ‘all‘.
Examples:
To create a *.cpio file : We can create *.cpio files containing files and directory with the help of cpio command.Syntax:cpio -ov < name-list > archiveHere -ov is used as -o create the new archive and -v list the files processed.
Syntax:
cpio -ov < name-list > archive
Here -ov is used as -o create the new archive and -v list the files processed.
To extract a *.cpio file: We can extract *.cpio files containing files and directory with the help of cpio command.Syntax:cpio -iv < archive
Syntax:
cpio -iv < archive
To create *.tar archive file using cpio: The cpio helps to create a *.tar archive.Syntax:cpio -ov -H tar > archive
Syntax:
cpio -ov -H tar > archive
To extract *.tar archive file using cpio: The cpio helps to extract *.tar files containing files and directory.Syntax:cpio -iv -F < archive
Syntax:
cpio -iv -F < archive
To create a *.cpio archive with selected files: We can create *.cpio files containing specific files with the help of cpio command. In the example we are using .txt files.Syntax:find . -iname "*.txt" | cpio -ov > archive
Syntax:
find . -iname "*.txt" | cpio -ov > archive
To create a *.tar archive with selected files: We can create *.tar files containing specific files with the help of cpio command. In the example we are using .txt files.Syntax:find . -iname "*.txt" | cpio -ov -H tar > archive
Syntax:
find . -iname "*.txt" | cpio -ov -H tar > archive
To only view *.tar archive file using cpio: The cpio helps to view *.tar files containing files and directory.Syntax:cpio -it -F < archive
Syntax:
cpio -it -F < archive
Note:
To check for the manual page of cpio command, use the following command: man cpio
man cpio
To check the help page of cpio command, use the following command: cpio --help
cpio --help
linux-command
Linux-file-commands
Picked
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
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 207,
"s": 54,
"text": "cpio stands for “copy in, copy out“. It is used for processing the archive files like *.cpio or *.tar. This command can copy files to and from archives."
},
{
"code": null,
"e": 217,
"s": 207,
"text": "Synopsis:"
},
{
"code": null,
"e": 313,
"s": 217,
"text": "Copy-out Mode: Copy files named in name-list to the archiveSyntax:cpio -o < name-list > archive"
},
{
"code": null,
"e": 321,
"s": 313,
"text": "Syntax:"
},
{
"code": null,
"e": 351,
"s": 321,
"text": "cpio -o < name-list > archive"
},
{
"code": null,
"e": 420,
"s": 351,
"text": "Copy-in Mode: Extract files from the archiveSyntax:cpio -i < archive"
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Syntax:"
},
{
"code": null,
"e": 446,
"s": 428,
"text": "cpio -i < archive"
},
{
"code": null,
"e": 565,
"s": 446,
"text": "Copy-pass Mode: Copy files named in name-list to destination-directorySyntax:cpio -p destination-directory < name-list"
},
{
"code": null,
"e": 573,
"s": 565,
"text": "Syntax:"
},
{
"code": null,
"e": 615,
"s": 573,
"text": "cpio -p destination-directory < name-list"
},
{
"code": null,
"e": 631,
"s": 615,
"text": "Policy Options:"
},
{
"code": null,
"e": 709,
"s": 631,
"text": "-i, –extract: Extract files from an archive and it runs only in copy-in mode."
},
{
"code": null,
"e": 776,
"s": 709,
"text": "-o, –create: Create the archive and it runs only in copy-out mode."
},
{
"code": null,
"e": 818,
"s": 776,
"text": "-p, –pass-through: Run in copy-pass mode."
},
{
"code": null,
"e": 882,
"s": 818,
"text": "-t, –list: Print a table of contents of all the inputs present."
},
{
"code": null,
"e": 921,
"s": 882,
"text": "Operation modifiers valid in any Mode:"
},
{
"code": null,
"e": 967,
"s": 921,
"text": "-B: Changes the I/O block size to 5120 bytes."
},
{
"code": null,
"e": 1016,
"s": 967,
"text": "-c: Use the old portable (ASCII) archive format."
},
{
"code": null,
"e": 1101,
"s": 1016,
"text": "-C, –io-size=NUMBER: Set the I/O block size to the given particular NUMBER of bytes."
},
{
"code": null,
"e": 1147,
"s": 1101,
"text": "-D, –directory=DIR: Changes to Directory DIR."
},
{
"code": null,
"e": 1182,
"s": 1147,
"text": "-H, –format=FORMAT: Use given arc."
},
{
"code": null,
"e": 1243,
"s": 1182,
"text": "-v, –verbose: List the files processed in a particular task."
},
{
"code": null,
"e": 1309,
"s": 1243,
"text": "-V, –dot: Print “.” for each file processed in a particular task."
},
{
"code": null,
"e": 1405,
"s": 1309,
"text": "-W, –warning=FLAG: Control warning display. Currently FLAG is one of ‘none‘, ‘truncate‘, ‘all‘."
},
{
"code": null,
"e": 1415,
"s": 1405,
"text": "Examples:"
},
{
"code": null,
"e": 1645,
"s": 1415,
"text": "To create a *.cpio file : We can create *.cpio files containing files and directory with the help of cpio command.Syntax:cpio -ov < name-list > archiveHere -ov is used as -o create the new archive and -v list the files processed."
},
{
"code": null,
"e": 1653,
"s": 1645,
"text": "Syntax:"
},
{
"code": null,
"e": 1684,
"s": 1653,
"text": "cpio -ov < name-list > archive"
},
{
"code": null,
"e": 1763,
"s": 1684,
"text": "Here -ov is used as -o create the new archive and -v list the files processed."
},
{
"code": null,
"e": 1904,
"s": 1763,
"text": "To extract a *.cpio file: We can extract *.cpio files containing files and directory with the help of cpio command.Syntax:cpio -iv < archive"
},
{
"code": null,
"e": 1912,
"s": 1904,
"text": "Syntax:"
},
{
"code": null,
"e": 1931,
"s": 1912,
"text": "cpio -iv < archive"
},
{
"code": null,
"e": 2046,
"s": 1931,
"text": "To create *.tar archive file using cpio: The cpio helps to create a *.tar archive.Syntax:cpio -ov -H tar > archive"
},
{
"code": null,
"e": 2054,
"s": 2046,
"text": "Syntax:"
},
{
"code": null,
"e": 2080,
"s": 2054,
"text": "cpio -ov -H tar > archive"
},
{
"code": null,
"e": 2220,
"s": 2080,
"text": "To extract *.tar archive file using cpio: The cpio helps to extract *.tar files containing files and directory.Syntax:cpio -iv -F < archive"
},
{
"code": null,
"e": 2228,
"s": 2220,
"text": "Syntax:"
},
{
"code": null,
"e": 2250,
"s": 2228,
"text": "cpio -iv -F < archive"
},
{
"code": null,
"e": 2471,
"s": 2250,
"text": "To create a *.cpio archive with selected files: We can create *.cpio files containing specific files with the help of cpio command. In the example we are using .txt files.Syntax:find . -iname \"*.txt\" | cpio -ov > archive"
},
{
"code": null,
"e": 2479,
"s": 2471,
"text": "Syntax:"
},
{
"code": null,
"e": 2522,
"s": 2479,
"text": "find . -iname \"*.txt\" | cpio -ov > archive"
},
{
"code": null,
"e": 2748,
"s": 2522,
"text": "To create a *.tar archive with selected files: We can create *.tar files containing specific files with the help of cpio command. In the example we are using .txt files.Syntax:find . -iname \"*.txt\" | cpio -ov -H tar > archive"
},
{
"code": null,
"e": 2756,
"s": 2748,
"text": "Syntax:"
},
{
"code": null,
"e": 2806,
"s": 2756,
"text": "find . -iname \"*.txt\" | cpio -ov -H tar > archive"
},
{
"code": null,
"e": 2945,
"s": 2806,
"text": "To only view *.tar archive file using cpio: The cpio helps to view *.tar files containing files and directory.Syntax:cpio -it -F < archive"
},
{
"code": null,
"e": 2953,
"s": 2945,
"text": "Syntax:"
},
{
"code": null,
"e": 2975,
"s": 2953,
"text": "cpio -it -F < archive"
},
{
"code": null,
"e": 2981,
"s": 2975,
"text": "Note:"
},
{
"code": null,
"e": 3063,
"s": 2981,
"text": "To check for the manual page of cpio command, use the following command: man cpio"
},
{
"code": null,
"e": 3073,
"s": 3063,
"text": " man cpio"
},
{
"code": null,
"e": 3152,
"s": 3073,
"text": "To check the help page of cpio command, use the following command: cpio --help"
},
{
"code": null,
"e": 3165,
"s": 3152,
"text": " cpio --help"
},
{
"code": null,
"e": 3179,
"s": 3165,
"text": "linux-command"
},
{
"code": null,
"e": 3199,
"s": 3179,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 3206,
"s": 3199,
"text": "Picked"
},
{
"code": null,
"e": 3217,
"s": 3206,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3315,
"s": 3217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3341,
"s": 3315,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3376,
"s": 3341,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3413,
"s": 3376,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3452,
"s": 3413,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3481,
"s": 3452,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3518,
"s": 3481,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3558,
"s": 3518,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3592,
"s": 3558,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3629,
"s": 3592,
"text": "chmod command in Linux with examples"
}
] |
How to open web cam in JavaScript ?
|
31 Mar, 2021
In this article, we will see how to open a webcam and show a live video using JavaScript. For this we are going to use Navigator media Devices.
Navigator Media Devices: It is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like camera and microphone.
Syntax :
var mediaDevices = navigator.mediaDevices;
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Web Cam</title> <script> document.addEventListener("DOMContentLoaded", () => { var but = document.getElementById("but"); var video = document.getElementById("vid"); var mediaDevices = navigator.mediaDevices; vid.muted = true; but.addEventListener("click", () => { // Accessing the user camera and video. mediaDevices .getUserMedia({ video: true, audio: true, }) .then((stream) => { // Changing the source of video to current stream. video.srcObject = stream; video.addEventListener("loadedmetadata", () => { video.play(); }); }) .catch(alert); }); }); </script> </head> <style> div { width: 500px; height: 400px; border: 2px solid black; position: relative; } video { width: 500px; height: 400px; object-fit: cover; } </style> <body> <center> <div> <video id="vid"></video> </div> <br /> <button id="but" autoplay> Open WebCam </button> </center> </body></html>
Output :
Before clicking the button :
Before clicking the button :
After clicking the button :
After clicking the button :
JavaScript-Questions
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 ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "In this article, we will see how to open a webcam and show a live video using JavaScript. For this we are going to use Navigator media Devices."
},
{
"code": null,
"e": 348,
"s": 172,
"text": "Navigator Media Devices: It is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like camera and microphone."
},
{
"code": null,
"e": 357,
"s": 348,
"text": "Syntax :"
},
{
"code": null,
"e": 400,
"s": 357,
"text": "var mediaDevices = navigator.mediaDevices;"
},
{
"code": null,
"e": 409,
"s": 400,
"text": "Example:"
},
{
"code": null,
"e": 414,
"s": 409,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Web Cam</title> <script> document.addEventListener(\"DOMContentLoaded\", () => { var but = document.getElementById(\"but\"); var video = document.getElementById(\"vid\"); var mediaDevices = navigator.mediaDevices; vid.muted = true; but.addEventListener(\"click\", () => { // Accessing the user camera and video. mediaDevices .getUserMedia({ video: true, audio: true, }) .then((stream) => { // Changing the source of video to current stream. video.srcObject = stream; video.addEventListener(\"loadedmetadata\", () => { video.play(); }); }) .catch(alert); }); }); </script> </head> <style> div { width: 500px; height: 400px; border: 2px solid black; position: relative; } video { width: 500px; height: 400px; object-fit: cover; } </style> <body> <center> <div> <video id=\"vid\"></video> </div> <br /> <button id=\"but\" autoplay> Open WebCam </button> </center> </body></html>",
"e": 1828,
"s": 414,
"text": null
},
{
"code": null,
"e": 1837,
"s": 1828,
"text": "Output :"
},
{
"code": null,
"e": 1867,
"s": 1837,
"text": "Before clicking the button : "
},
{
"code": null,
"e": 1897,
"s": 1867,
"text": "Before clicking the button : "
},
{
"code": null,
"e": 1926,
"s": 1897,
"text": "After clicking the button : "
},
{
"code": null,
"e": 1955,
"s": 1926,
"text": "After clicking the button : "
},
{
"code": null,
"e": 1976,
"s": 1955,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 1980,
"s": 1976,
"text": "CSS"
},
{
"code": null,
"e": 1985,
"s": 1980,
"text": "HTML"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": "JavaScript"
},
{
"code": null,
"e": 2013,
"s": 1996,
"text": "Web Technologies"
},
{
"code": null,
"e": 2018,
"s": 2013,
"text": "HTML"
},
{
"code": null,
"e": 2116,
"s": 2018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2155,
"s": 2116,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2194,
"s": 2155,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2233,
"s": 2194,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2262,
"s": 2233,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2299,
"s": 2262,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2323,
"s": 2299,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2376,
"s": 2323,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2436,
"s": 2376,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2497,
"s": 2436,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Xamarin - Andriod Views
|
A Listview is a user interface element that displays lists of items that are scrollable.
In this example, you are going to create a listView that displays the days of the week. To start with, let us create a new XML file and name it listViewTemplate.xml.
In listViewTemplate.xml, we add a new textview as shown below.
<?xml version = "1.0" encoding = "utf-8" ?>
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/textItem"
android:textSize ="20sp"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"/>
Next, go to Main.axml and create a new listview inside the Linear Layout.
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView1" />
Open MainActivity.cs and type the following code to bind the data to the listview we created. The code must be written inside the OnCreate() method.
SetContentView(Resource.Layout.Main);
var listView = FindViewById<ListView>(Resource.Id.listView1);
var data = new string[] {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
};
listView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewTemplate, data);
Var data = new string[] simply holds our items as an array.
Array Adapter returns the items in our collection as a view. By default, the Array Adapter uses a default textView to display each item. In the above code, we created our own textview in ListViewTemplate.xml and referenced it using the constructor shown below.
ArrayAdapter(this, Resource.Layout.ListViewTemplate, data);
Finally, build and run your application to view the output.
A gridView is a view group that allows applications to lay out content in a two-dimensional way, scrollable grid.
To add a GridView, create a new project and call it gridViewApp. Go to Main.axml and add a grid as shown below.
<?xml version = "1.0" encoding="utf-8"?>
<GridView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/gridview"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:columnWidth = "90dp"
android:numColumns = "auto_fit"
android:verticalSpacing = "10dp"
android:horizontalSpacing = "10dp"
android:stretchMode = "columnWidth"
android:gravity = "center" />
Next, create a new class and name it ImageAdpter.cs. This class will contain the adapter classes for all items which will be shown in the grid.
Inside ImageAdapter, add the following code −
public class ImageAdapter : BaseAdapter {
Context context;
public ImageAdapter(Context ch) {
context = ch;
}
public override int Count {
get {
return cars.Length;
}
}
public override long GetItemId(int position) {
return 0;
}
public override Java.Lang.Object GetItem(int position) {
return null;
}
public override View GetView(int position,
View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.LayoutParameters = new GridView.LayoutParams(100, 100);
imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
imageView.SetPadding(8, 8, 8, 8);
} else {
imageView = (ImageView)convertView;
}
imageView.SetImageResource(cars[position]);
return imageView;
}
int[] cars = {
Resource.Drawable.img1, Resource.Drawable.img2,
Resource.Drawable.img3, Resource.Drawable.img4,
Resource.Drawable.img5, Resource.Drawable.img6,
};
}
In the above code, we have simply bound our car images to the image adapters. Next, open MainActivity.cs and add the following code after setContentView().
var gridview = FindViewById<GridView>(Resource.Id.gridview);
gridview.Adapter = new ImageAdapter(this);
gridview.ItemClick += delegate(object sender,
AdapterView.ItemClickEventArgs args) {
Toast.MakeText(this,
args.Position.ToString(), ToastLength.Short).Show();
};
The above code finds the gridView in main.axml and binds it to the imageAdapter class. Gridview.ItemClick creates an onClick event which returns the position of the selected image when a user clicks on an image.
Now, build and run your application to view the output.
|
[
{
"code": null,
"e": 2187,
"s": 2098,
"text": "A Listview is a user interface element that displays lists of items that are scrollable."
},
{
"code": null,
"e": 2353,
"s": 2187,
"text": "In this example, you are going to create a listView that displays the days of the week. To start with, let us create a new XML file and name it listViewTemplate.xml."
},
{
"code": null,
"e": 2416,
"s": 2353,
"text": "In listViewTemplate.xml, we add a new textview as shown below."
},
{
"code": null,
"e": 2670,
"s": 2416,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<TextView xmlns:android = \"http://schemas.android.com/apk/res/android\" \nandroid:id = \"@+id/textItem\" \nandroid:textSize =\"20sp\" \nandroid:layout_width = \"fill_parent\" \nandroid:layout_height = \"wrap_content\"/>"
},
{
"code": null,
"e": 2744,
"s": 2670,
"text": "Next, go to Main.axml and create a new listview inside the Linear Layout."
},
{
"code": null,
"e": 2927,
"s": 2744,
"text": "<ListView \n android:minWidth=\"25px\" \n android:minHeight=\"25px\" \n android:layout_width=\"match_parent\" \n android:layout_height=\"match_parent\" \n android:id=\"@+id/listView1\" />"
},
{
"code": null,
"e": 3076,
"s": 2927,
"text": "Open MainActivity.cs and type the following code to bind the data to the listview we created. The code must be written inside the OnCreate() method."
},
{
"code": null,
"e": 3374,
"s": 3076,
"text": "SetContentView(Resource.Layout.Main); \nvar listView = FindViewById<ListView>(Resource.Id.listView1); \nvar data = new string[] { \n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\" \n}; \nlistView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); "
},
{
"code": null,
"e": 3434,
"s": 3374,
"text": "Var data = new string[] simply holds our items as an array."
},
{
"code": null,
"e": 3695,
"s": 3434,
"text": "Array Adapter returns the items in our collection as a view. By default, the Array Adapter uses a default textView to display each item. In the above code, we created our own textview in ListViewTemplate.xml and referenced it using the constructor shown below."
},
{
"code": null,
"e": 3757,
"s": 3695,
"text": "ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); \n"
},
{
"code": null,
"e": 3817,
"s": 3757,
"text": "Finally, build and run your application to view the output."
},
{
"code": null,
"e": 3931,
"s": 3817,
"text": "A gridView is a view group that allows applications to lay out content in a two-dimensional way, scrollable grid."
},
{
"code": null,
"e": 4043,
"s": 3931,
"text": "To add a GridView, create a new project and call it gridViewApp. Go to Main.axml and add a grid as shown below."
},
{
"code": null,
"e": 4491,
"s": 4043,
"text": "<?xml version = \"1.0\" encoding=\"utf-8\"?> \n<GridView xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:id = \"@+id/gridview\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\" \n android:columnWidth = \"90dp\" \n android:numColumns = \"auto_fit\" \n android:verticalSpacing = \"10dp\" \n android:horizontalSpacing = \"10dp\" \n android:stretchMode = \"columnWidth\" \n android:gravity = \"center\" />"
},
{
"code": null,
"e": 4635,
"s": 4491,
"text": "Next, create a new class and name it ImageAdpter.cs. This class will contain the adapter classes for all items which will be shown in the grid."
},
{
"code": null,
"e": 4681,
"s": 4635,
"text": "Inside ImageAdapter, add the following code −"
},
{
"code": null,
"e": 5851,
"s": 4681,
"text": "public class ImageAdapter : BaseAdapter { \n Context context; \n public ImageAdapter(Context ch) { \n context = ch; \n } \n \n public override int Count { \n get { \n return cars.Length; \n } \n } \n \n public override long GetItemId(int position) { \n return 0; \n } \n \n public override Java.Lang.Object GetItem(int position) { \n return null; \n } \n \n public override View GetView(int position, \n View convertView, ViewGroup parent) { \n ImageView imageView; \n if (convertView == null) { \n imageView = new ImageView(context); \n imageView.LayoutParameters = new GridView.LayoutParams(100, 100); \n imageView.SetScaleType(ImageView.ScaleType.CenterCrop); \n imageView.SetPadding(8, 8, 8, 8); \n } else { \n imageView = (ImageView)convertView; \n } \n \n imageView.SetImageResource(cars[position]); \n return imageView; \n } \n \n int[] cars = { \n Resource.Drawable.img1, Resource.Drawable.img2, \n Resource.Drawable.img3, Resource.Drawable.img4, \n Resource.Drawable.img5, Resource.Drawable.img6, \n }; \n} "
},
{
"code": null,
"e": 6007,
"s": 5851,
"text": "In the above code, we have simply bound our car images to the image adapters. Next, open MainActivity.cs and add the following code after setContentView()."
},
{
"code": null,
"e": 6297,
"s": 6007,
"text": "var gridview = FindViewById<GridView>(Resource.Id.gridview); \ngridview.Adapter = new ImageAdapter(this); \ngridview.ItemClick += delegate(object sender, \n AdapterView.ItemClickEventArgs args) { \n Toast.MakeText(this, \n args.Position.ToString(), ToastLength.Short).Show(); \n};"
},
{
"code": null,
"e": 6509,
"s": 6297,
"text": "The above code finds the gridView in main.axml and binds it to the imageAdapter class. Gridview.ItemClick creates an onClick event which returns the position of the selected image when a user clicks on an image."
}
] |
Kotlin labelled break
|
28 Mar, 2022
While working with loops say you want to stop the execution of loop immediately if a certain condition is satisfied. In this case you can use either break or return expression to exit from the loop. In this article, we are going to learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to nearest enclosing loop.There are two types of break expression in Kotlin: As we all know, Unlabelled break is used to terminate to the closest enclosing loop when certain condition is satisfied. But labelled break is used to terminate to a desired loop when certain condition is satisfied. It can be done with the help of labels. An identifier followed by @ sign is called label e.g.- inner@, outer@, first@, second@ etc. You can use label with any expression and it should be written in front of it.We are going to learn how to use labelled break expression in while, do-while and for loop.
Labelled break is used to exit to the desired block when it satisfy a specific condition without checking the condition in while loop. Then, transfers the control to following statement of while block. If you mark the outer loop using the label outer@ then you can easily break the outer loop using break@outer in the break condition block.Syntax of labelled break in while loop-
outer@ while(condition) {
// code
inner@ while(condition) {
// code
if(break condition) {
break @outer
}
}
}
Kotlin program of using labelled break in while loop –
Kotlin
fun main(args: Array<String>) { var num1 = 4 outer@ while (num1 > 0) { var num2 = 4 inner@ while (num2 > 0) { if (num1==2) break@outer println("num1 = $num1, num2 = $num2") num2-- } num1-- }}
Output:
num1 = 4, num2 = 4
num1 = 4, num2 = 3
num1 = 4, num2 = 2
num1 = 4, num2 = 1
num1 = 3, num2 = 4
num1 = 3, num2 = 3
num1 = 3, num2 = 2
num1 = 3, num2 = 1
When (num1 == 2) expression is evaluated to be true, the break@outer is executed which terminates the desired loop marked with outer@.
In do-while loop also the labelled break is executed to terminate the desired loop. Here we have used outer@ for the outer do-while and inner@ for the inner do-while loop.Syntax of labelled break in do-while loop –
outer@ do {
// code
inner@ do {
// code
if(break condition) {
break@outer
}
} while(condition)
} while(condition)
Kotlin program of using labelled break in do-while loop-
Kotlin
fun main(args: Array<String>) { var num1 = 4 outer@ do { var num2 = 4 inner@ do { if (num1 == 2) break@outer println("num1 = $num1; num2 = $num2") num2-- } while (num2 > 0) num1-- } while (num1 > 0)}
Output:
num1 = 4; num2 = 4
num1 = 4; num2 = 3
num1 = 4; num2 = 2
num1 = 4; num2 = 1
num1 = 3; num2 = 4
num1 = 3; num2 = 3
num1 = 3; num2 = 2
num1 = 3; num2 = 1
Here, we print the same output as while loop. When (num1 == 2) expression is evaluated to be true, the break@outer is executed which terminates the desired loop marked with outer@.
In for loop also we can use the labelled break to terminate the desired loop for certain condition. We have labelled the outer for loop as outer@ and inner for loop as inner@. In for loop, iteration is to be done through iterator. Syntax of labelled break in for loop –
outer@ for(iteration through iterator) {
// code
inner@ for(iteration through iterator)
// code
if(break condition) {
break@outer
}
}
}
Kotlin program of using labelled break in for-loop-
Kotlin
fun main(args: Array<String>) { outer@ for (num1 in 4 downTo 1) { inner@ for (num2 in 4 downTo 1) { if (num1 == 2) break@outer println("num1 = $num1; num2 = $num2") } }}
Output:
num1 = 4; num2 = 4
num1 = 4; num2 = 3
num1 = 4; num2 = 2
num1 = 4; num2 = 1
num1 = 3; num2 = 4
num1 = 3; num2 = 3
num1 = 3; num2 = 2
num1 = 3; num2 = 1
sooda367
ayushpandey3july
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Higher-Order Functions
Suspend Function In Kotlin Coroutines
Spinner in Kotlin
MVP (Model View Presenter) Architecture Pattern in Android with Example
Android Menus
How to Get Current Location in Android?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 966,
"s": 28,
"text": "While working with loops say you want to stop the execution of loop immediately if a certain condition is satisfied. In this case you can use either break or return expression to exit from the loop. In this article, we are going to learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to nearest enclosing loop.There are two types of break expression in Kotlin: As we all know, Unlabelled break is used to terminate to the closest enclosing loop when certain condition is satisfied. But labelled break is used to terminate to a desired loop when certain condition is satisfied. It can be done with the help of labels. An identifier followed by @ sign is called label e.g.- inner@, outer@, first@, second@ etc. You can use label with any expression and it should be written in front of it.We are going to learn how to use labelled break expression in while, do-while and for loop. "
},
{
"code": null,
"e": 1348,
"s": 966,
"text": "Labelled break is used to exit to the desired block when it satisfy a specific condition without checking the condition in while loop. Then, transfers the control to following statement of while block. If you mark the outer loop using the label outer@ then you can easily break the outer loop using break@outer in the break condition block.Syntax of labelled break in while loop- "
},
{
"code": null,
"e": 1527,
"s": 1348,
"text": "outer@ while(condition) {\n // code\n inner@ while(condition) {\n // code\n if(break condition) {\n break @outer\n } \n }\n}"
},
{
"code": null,
"e": 1584,
"s": 1527,
"text": "Kotlin program of using labelled break in while loop – "
},
{
"code": null,
"e": 1591,
"s": 1584,
"text": "Kotlin"
},
{
"code": "fun main(args: Array<String>) { var num1 = 4 outer@ while (num1 > 0) { var num2 = 4 inner@ while (num2 > 0) { if (num1==2) break@outer println(\"num1 = $num1, num2 = $num2\") num2-- } num1-- }}",
"e": 1868,
"s": 1591,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1868,
"text": "Output: "
},
{
"code": null,
"e": 2030,
"s": 1878,
"text": "num1 = 4, num2 = 4\nnum1 = 4, num2 = 3\nnum1 = 4, num2 = 2\nnum1 = 4, num2 = 1\nnum1 = 3, num2 = 4\nnum1 = 3, num2 = 3\nnum1 = 3, num2 = 2\nnum1 = 3, num2 = 1"
},
{
"code": null,
"e": 2166,
"s": 2030,
"text": "When (num1 == 2) expression is evaluated to be true, the break@outer is executed which terminates the desired loop marked with outer@. "
},
{
"code": null,
"e": 2383,
"s": 2166,
"text": "In do-while loop also the labelled break is executed to terminate the desired loop. Here we have used outer@ for the outer do-while and inner@ for the inner do-while loop.Syntax of labelled break in do-while loop – "
},
{
"code": null,
"e": 2565,
"s": 2383,
"text": "outer@ do {\n // code\n inner@ do {\n // code\n if(break condition) {\n break@outer\n }\n } while(condition)\n} while(condition)"
},
{
"code": null,
"e": 2624,
"s": 2565,
"text": "Kotlin program of using labelled break in do-while loop- "
},
{
"code": null,
"e": 2631,
"s": 2624,
"text": "Kotlin"
},
{
"code": "fun main(args: Array<String>) { var num1 = 4 outer@ do { var num2 = 4 inner@ do { if (num1 == 2) break@outer println(\"num1 = $num1; num2 = $num2\") num2-- } while (num2 > 0) num1-- } while (num1 > 0)}",
"e": 2917,
"s": 2631,
"text": null
},
{
"code": null,
"e": 2927,
"s": 2917,
"text": "Output: "
},
{
"code": null,
"e": 3079,
"s": 2927,
"text": "num1 = 4; num2 = 4\nnum1 = 4; num2 = 3\nnum1 = 4; num2 = 2\nnum1 = 4; num2 = 1\nnum1 = 3; num2 = 4\nnum1 = 3; num2 = 3\nnum1 = 3; num2 = 2\nnum1 = 3; num2 = 1"
},
{
"code": null,
"e": 3261,
"s": 3079,
"text": "Here, we print the same output as while loop. When (num1 == 2) expression is evaluated to be true, the break@outer is executed which terminates the desired loop marked with outer@. "
},
{
"code": null,
"e": 3533,
"s": 3261,
"text": "In for loop also we can use the labelled break to terminate the desired loop for certain condition. We have labelled the outer for loop as outer@ and inner for loop as inner@. In for loop, iteration is to be done through iterator. Syntax of labelled break in for loop – "
},
{
"code": null,
"e": 3726,
"s": 3533,
"text": "outer@ for(iteration through iterator) {\n // code\n inner@ for(iteration through iterator)\n // code\n if(break condition) {\n break@outer\n }\n }\n}"
},
{
"code": null,
"e": 3780,
"s": 3726,
"text": "Kotlin program of using labelled break in for-loop- "
},
{
"code": null,
"e": 3787,
"s": 3780,
"text": "Kotlin"
},
{
"code": "fun main(args: Array<String>) { outer@ for (num1 in 4 downTo 1) { inner@ for (num2 in 4 downTo 1) { if (num1 == 2) break@outer println(\"num1 = $num1; num2 = $num2\") } }}",
"e": 4015,
"s": 3787,
"text": null
},
{
"code": null,
"e": 4025,
"s": 4015,
"text": "Output: "
},
{
"code": null,
"e": 4177,
"s": 4025,
"text": "num1 = 4; num2 = 4\nnum1 = 4; num2 = 3\nnum1 = 4; num2 = 2\nnum1 = 4; num2 = 1\nnum1 = 3; num2 = 4\nnum1 = 3; num2 = 3\nnum1 = 3; num2 = 2\nnum1 = 3; num2 = 1"
},
{
"code": null,
"e": 4188,
"s": 4179,
"text": "sooda367"
},
{
"code": null,
"e": 4205,
"s": 4188,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 4212,
"s": 4205,
"text": "Kotlin"
},
{
"code": null,
"e": 4310,
"s": 4212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4379,
"s": 4310,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 4428,
"s": 4379,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 4470,
"s": 4428,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 4489,
"s": 4470,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 4519,
"s": 4489,
"text": "Kotlin Higher-Order Functions"
},
{
"code": null,
"e": 4557,
"s": 4519,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 4575,
"s": 4557,
"text": "Spinner in Kotlin"
},
{
"code": null,
"e": 4647,
"s": 4575,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
},
{
"code": null,
"e": 4661,
"s": 4647,
"text": "Android Menus"
}
] |
Image Classification with Web App
|
12 Apr, 2022
Detecting Emergency Vehicles Using CNNs
Motivation: Recently I participated in JanataHack: Computer Vision Hackathon hosted by Analytics Vidhya. The aim of the competition was to create a binary image classifier that could differentiate the Non?-?Emergency Vehicles eg. private owned vehicles. from the emergency vehicles (police vehicles, ambulances, etc).
Problem Statement: We need to create a classifier which is able to differentiate between Emergency and Non- Emergency vehicles. The Emergency vehicles are labelled 1 and Non- Emergency vehicles are labeled 0. In this article I am going to show the approach I followed to create a models that got be in the 147 place out of 10000.
The models shows in this article are Convolution Neural Networks. I have tried to make the code as simple as I can. Readers are required to have some knowledge of neural networks.
Problem Solving Steps:
Loading and Visualizing the dataData CleaningModelingTransfer LearningParameter TuningFinal Model.
Loading and Visualizing the data
Data Cleaning
Modeling
Transfer Learning
Parameter Tuning
Final Model.
Code: Loading And Visualizing Data
Python3
# importsimport numpy as npimport osimport matplotlib.pyplot as pltfrom PIL import Image, ImageOps, ImageFilter, ImageEnhanceimport pandas as pd # importing pytorch library.import torchvision.transforms as transformsimport torch.nn.functional as Fimport torch.nn as nnfrom torch.utils.data import Dataset, random_split, DataLoader
We will be using:
numpy: to store the images into arrays,
matplotlib: to visualize the images,
PILLOW or(PIL): library to load and transform images
Pytorch: For our deep learning framework.
Data Loading: The above image shows the datasets provided to us all the images the train and test set are present in the images folder, the train and test CVS files contains the name of images.
Code:
Python3
# name of the image folderimagePaths = 'images' # reading the train.csv file using pandastrainImages = pd.read_csv('train.csv')# reading the test.csv file using pandastestImages = pd.read_csv('test.csv')# reading the submission file using pandassamples = pd.read_csv('sample_submission.csv')
Code: Loading the images into numpy arrays
Python3
# defining train and labels list to store images and labels respectively.train = []labels = [] for image, label in zip(trainImages.iloc[:, 0], trainImages.iloc[:, 1]): # create a image path and store in img_path variable imgPath = os.path.join(imagePaths, image) # Use PIl Image class to load the image img = Image.open(imgPath) # apply median filter to the image this helps in reducing noise img = img.filter(ImageFilter.MedianFilter) # convert the image to numpy array and store the loaded images into train train.append(np.asarray(img)) # store the label into the labels list labels.append(label)
Code: opening and displaying Images.
Python3
# create subplots using the plt.subplots function# the number of subplots depend on the n_rows and n_cols# all the subplots are stored in ax variables_, ax = plt.subplots(nrows = 4, ncols = 7, figsize =(12, 12)) # iterate through the ax variable by flattening itfor index, i in enumerate(ax.flatten()): # the imshow is used to show the image i.imshow(train[index]) # set the title i.set_title(index) # this below lines makes the code better visualize. i.set_xticks([]) i.set_yticks([])
Output:
Output of the above cell.
Now that we have the images stored in the train and output classes stored in labels we can move on to the next step.
Data CleaningIn this section, we will look at miss classified labels and improper image samples by removing these images my accuracy increased the val_score by 2%. It went from 94% to 96% and sometimes 97%.
Miss labelledImages: the code used to visualize the data is same as above
Miss-classified labels
Improper Data: Images of dashboards.
By removing these images the accuracy become more stable (less oscillations). One think to note here I was able to remove these dashboard images because I didn’t find any similar images in the test data.
Defining the DatasetClass: For the model to load the dataset from the disk pytorch provides a DatasetClass using this we don’t need to fit the entire model into memory.
Code:
Python3
# Creating a VehicleDataset class for loading the images and labels .# the following class needs to extend from the Dataset class# provided by pytorch framework and implement the __len__ and __getitem__ methods. class VehicleDataset(Dataset): def __init__(self, csv_name, folder, transform = None, label = False): self.label = label self.folder = folder print(csv_name) self.dataframe = pd.read_csv(self.folder+'/'+csv_name+'.csv') self.tms = transform def __len__(self): return len(self.dataframe) def __getitem__(self, index): row = self.dataframe.iloc[index] imgIndex = row['image_names'] imageFile = self.folder + '/' + img_index image = Image.open(image_file) if self.label: target = row['emergency_or_not'] if target == 0: encode = torch.FloatTensor([1, 0]) else: encode = torch.FloatTensor([0, 1]) return self.tms(image), encode return self.tms(image) # creating objects of VehicleDataset # the deep learning models accepts the image to be in tensor format# this is done using the transforms.ToTensor() methods transform = transforms.Compose([transforms.ToTensor(), ]) '''arguments:csv_name - name of the csv file in out case train.csvfolder - folder in which the images are storedtransform - transforms the image to tensor,label - used to differentiate between train and test set.'''' trainDataset = VehicleDataset('train', 'images', label = True, transform = transform)
Now that we have our data pipeline ready we need to create the deep learning model.
CNN Model:This post assumes that you have some knowledge of Neural Nets as explaining that is out of scope of this article. I am going to use a CNN (Convolution neural network). The model has 3 main layers naming the conv2d layer, batch Norm, and max pooling 2d the activation function used over here is relu:
Code:
Python
# the EmergencyCustomModel class defines our Neural Network# It inherites from the ImageClassificationBase class which has helper methods# for printing the loss and accuracy at each epochs. class EmergencyCustomModel(ImageClassificationBase): def __init__(self): super().__init__() self.network = nn.Sequential( nn.Conv2d(3, 32, kernel_size = 3, padding = 1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(64, 64, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(64, 128, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(128, 128, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(128, 256, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 2), # nn.Sigmoid(), ) def forward(self, xb): return self.network(xb)
One can find the entire model definition in this notebook in my github repoTraining function:
Code: the following function is used to train all the models in the post.
Python3
# defining the training method.# the evaluation method is used to calculate validation accuracy. @torch.no_grad()def evaluate(model, val_loader): model.eval() outputs = [model.validation_step(batch) for batch in val_loader] return model.validation_epoch_end(outputs) # The fit method is used to train the model# parameters'''epochs: no. of epochs the model trainsmax_lr: maximum learning rate.train_loader: here we pass the train datasetval_loader: here we pass the val_datasetopt_func : The learning algorithm that performs gradient descent.model : the neural network to train on.''' def fit(epochs, max_lr, model, train_loader, val_loader, weight_decay = 0, grad_clip = None, opt_func = torch.optim.SGD): torch.cuda.empty_cache() history = [] # Set up custom optimizer with weight decay optimizer = opt_func(model.parameters(), max_lr, weight_decay = weight_decay) # the loop iterates from 0 to number of epochs. # the model needs to be set in the train model by calling the model.train. for epoch in range(epochs): # Training Phase model.train() train_losses = [] for batch in train_loader: loss = model.training_step(batch) train_losses.append(loss) loss.backward() # Gradient clipping if grad_clip: nn.utils.clip_grad_value_(model.parameters(), grad_clip) optimizer.step() optimizer.zero_grad() # Validation phase result = evaluate(model, val_loader) result['train_loss'] = torch.stack(train_losses).mean().item() model.epoch_end(epoch, result) history.append(result) return history
Before starting training we need to split our data into train and validation set. This is done so that the model generalizes well on unseen data. We will do a 80 – 20 split 80% train and 20%test. After splitting the data we need to pass the datasets to a Data Loader this is provided by pytorch.
Code: Splitting and creating dataloaders.
Python3
# the batchSize is the number of images passes by the loader at a time.# reduce this number if theres an out of memory error.batchSize = 32valPct = 0.2 # code for splitting the data# valPct variable is used to split dataset valSize = int(valPct * len(trainDataset))trainSize = len(trainDataset) - valSizetrainDs, valDs = random_split(trainDataset, [trainSize, valSize]) # Creating dataloaders.train_loader = DataLoader(trainDs, batchSize)val_loader = DataLoader(valDs, batchSize)
Now we are ready to start training by calling the fit() method.
Python3
customModel = EmergencyCustomModel()epochs = 10lr = 0.01 # save the history to visualize later.history = fit(epochs, lr, customModel, trainDl, valDl)
Output of above code:
output of fit function
The entire code is available in github repo link is provide below.
Code: The plot function is used for producing the loss and accuracy graphs shown below
Python3
'''parameters:epochs = number of epochs the model was trained onhist = the history returned by the fit function. ''' def plot(hist, epochs = 10): trainLoss = [] valLoss = [] valScore = [] for i in range(epochs): trainLoss.append(hist[i]['train_loss']) valLoss.append(hist[i]['val_loss']) valScore.append(hist[i]['val_score']) plt.plot(trainLoss, label ='train_loss') plt.plot(valLoss, label ='val_loss') plt.legend() plt.title('loss') plt.figure() plt.plot(valScore, label ='val_score') plt.legend() plt.title('accuracy') # calling the function plot(history)
Output: Plotting the loss and accuracy plots.
loss and accuracy graphs
There is very less over-fitting and the val_accuracy reaches its peak value at 90%. here again, I would like to add when I had created a custom model in keras the height val_score I was able to achieve was 83% changing the framework got we an increase of 7%. One more thing the size of the mode, using pytorch I am able to use a model having more than 3 Conv2d layers without over-fitting. But in keras I could only use 2 layers not more than that anything higher or lower would just add to the training cost without improving the accuracy.
Transfer Learning: Using The Pre-trained Models: I made use of two model architectures resnet and densenet. One thing to not the densenet models produce almost similar results to resnet models with lower epochs and most important the saved model takes half the memory space.
Code:
Python3
# to use the pretrained model we make use of the torchvision.models library class ResNet50(ImageClassificationBase): def __init__(self): super().__init__() # this following line adds the downloads the resnet50 model is it doesn't exits # and stores it in pretrainedModle self.pretrainedModel = models.resnet50(pretrained = True) # since this model was trained on ImageNet data which has 1000 classes but for # problem we have only 2 so will need to modify the final layer of the model feature_in = self.pretrainedModel.fc.inFeatures self.pretrainedModel.fc = nn.Linear(feature_in, 2) def forward(self, x): return self.pretrainedModel(x) # Trainin the model.# final Learning withlr = 1e-4epochs = 5optFunc = torch.optim.Adam # Here I have made use of the wd this is used as a regularization parameter# It helps in preventing overfitting and helps our model to generalize. bestWd = 1e-4 custom_model = to_device(ResNet50(), device)hist = fit(epochs, lr, customModel, trainDl, valDl, bestWd, optFunc)
Output: Plotting the loss and accuracy plots.
here one can see a lot of over-fitting and now improvement in val_score. I decided to try using the cyclic scheduler training strategy here’s the result. I still need to do more experiment with this method but as one can see. I have reduced the overfitting to some extend but the val_accuracy is still low.
Using Densenet169: The dense net is similar to Resnet to instead to adding the skip connection it concatenates it hence the blocks are called as dense blocks.
Code:
Python3
class Densenet169(ImageClassificationBase): def __init__(self): super().__init__() # the below statement is used to download and store the pretrained model. self.pretrained_model = models.densenet169(pretrained = True) feature_in = self.pretrained_model.classifier.in_features self.pretrained_model.classifier = nn.Linear(feature_in, 2) def forward(self, x): return self.pretrained_model(x) Training the model# final Learning withlr = 1e-4epochs = 5optFunc = torch.optim.AdambestWd = 1e-4customModel2 = Densenet169() hist = fit(epochs, lr, customModel2, trainDl, valDl, bestWd, optFunc)
If you look at the loss and accuracy plots. The over-fitting has decreased. the val accuracy is better but this was done without the cyclic scheduler.
Code: Plotting the loss and accuracy plots.
Using early stopping the training can be stopped at 5 epochs.
Web APP:
https://emervehicledetector.herokuapp.com/
Note: the web app only accepts jpg images.Conclusion: I was able to get a 200 rank out of 10000 so I made it in the top 2% using the above model. all the code will be available in my github repo: https://github.com/evilc3/EmergencyVehicleDetectorEntire notebook: https://colab.research.google.com/drive/13En-V2A-w2o4uXuDZk0ypktxzX9joXIY?usp=sharingWeb app link: https://emervehicledetector.herokuapp.com/
rajeev0719singh
abhishek0719kadiyan
sagar0719kumar
rs1686740
gulshankumarar231
kapoorsagar226
akshaysingh98088
adnanirshad158
sweetyty
kk773572498
germanshephered48
as5853535
kk9826225
rkbhola5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 69,
"s": 28,
"text": "Detecting Emergency Vehicles Using CNNs "
},
{
"code": null,
"e": 387,
"s": 69,
"text": "Motivation: Recently I participated in JanataHack: Computer Vision Hackathon hosted by Analytics Vidhya. The aim of the competition was to create a binary image classifier that could differentiate the Non?-?Emergency Vehicles eg. private owned vehicles. from the emergency vehicles (police vehicles, ambulances, etc)."
},
{
"code": null,
"e": 718,
"s": 387,
"text": "Problem Statement: We need to create a classifier which is able to differentiate between Emergency and Non- Emergency vehicles. The Emergency vehicles are labelled 1 and Non- Emergency vehicles are labeled 0. In this article I am going to show the approach I followed to create a models that got be in the 147 place out of 10000. "
},
{
"code": null,
"e": 898,
"s": 718,
"text": "The models shows in this article are Convolution Neural Networks. I have tried to make the code as simple as I can. Readers are required to have some knowledge of neural networks."
},
{
"code": null,
"e": 923,
"s": 898,
"text": "Problem Solving Steps: "
},
{
"code": null,
"e": 1022,
"s": 923,
"text": "Loading and Visualizing the dataData CleaningModelingTransfer LearningParameter TuningFinal Model."
},
{
"code": null,
"e": 1055,
"s": 1022,
"text": "Loading and Visualizing the data"
},
{
"code": null,
"e": 1069,
"s": 1055,
"text": "Data Cleaning"
},
{
"code": null,
"e": 1078,
"s": 1069,
"text": "Modeling"
},
{
"code": null,
"e": 1096,
"s": 1078,
"text": "Transfer Learning"
},
{
"code": null,
"e": 1113,
"s": 1096,
"text": "Parameter Tuning"
},
{
"code": null,
"e": 1126,
"s": 1113,
"text": "Final Model."
},
{
"code": null,
"e": 1162,
"s": 1126,
"text": "Code: Loading And Visualizing Data "
},
{
"code": null,
"e": 1170,
"s": 1162,
"text": "Python3"
},
{
"code": "# importsimport numpy as npimport osimport matplotlib.pyplot as pltfrom PIL import Image, ImageOps, ImageFilter, ImageEnhanceimport pandas as pd # importing pytorch library.import torchvision.transforms as transformsimport torch.nn.functional as Fimport torch.nn as nnfrom torch.utils.data import Dataset, random_split, DataLoader",
"e": 1501,
"s": 1170,
"text": null
},
{
"code": null,
"e": 1519,
"s": 1501,
"text": "We will be using:"
},
{
"code": null,
"e": 1559,
"s": 1519,
"text": "numpy: to store the images into arrays,"
},
{
"code": null,
"e": 1596,
"s": 1559,
"text": "matplotlib: to visualize the images,"
},
{
"code": null,
"e": 1649,
"s": 1596,
"text": "PILLOW or(PIL): library to load and transform images"
},
{
"code": null,
"e": 1691,
"s": 1649,
"text": "Pytorch: For our deep learning framework."
},
{
"code": null,
"e": 1886,
"s": 1691,
"text": "Data Loading: The above image shows the datasets provided to us all the images the train and test set are present in the images folder, the train and test CVS files contains the name of images. "
},
{
"code": null,
"e": 1894,
"s": 1886,
"text": "Code: "
},
{
"code": null,
"e": 1902,
"s": 1894,
"text": "Python3"
},
{
"code": "# name of the image folderimagePaths = 'images' # reading the train.csv file using pandastrainImages = pd.read_csv('train.csv')# reading the test.csv file using pandastestImages = pd.read_csv('test.csv')# reading the submission file using pandassamples = pd.read_csv('sample_submission.csv')",
"e": 2194,
"s": 1902,
"text": null
},
{
"code": null,
"e": 2238,
"s": 2194,
"text": "Code: Loading the images into numpy arrays "
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Python3"
},
{
"code": "# defining train and labels list to store images and labels respectively.train = []labels = [] for image, label in zip(trainImages.iloc[:, 0], trainImages.iloc[:, 1]): # create a image path and store in img_path variable imgPath = os.path.join(imagePaths, image) # Use PIl Image class to load the image img = Image.open(imgPath) # apply median filter to the image this helps in reducing noise img = img.filter(ImageFilter.MedianFilter) # convert the image to numpy array and store the loaded images into train train.append(np.asarray(img)) # store the label into the labels list labels.append(label)",
"e": 2877,
"s": 2246,
"text": null
},
{
"code": null,
"e": 2915,
"s": 2877,
"text": "Code: opening and displaying Images. "
},
{
"code": null,
"e": 2923,
"s": 2915,
"text": "Python3"
},
{
"code": "# create subplots using the plt.subplots function# the number of subplots depend on the n_rows and n_cols# all the subplots are stored in ax variables_, ax = plt.subplots(nrows = 4, ncols = 7, figsize =(12, 12)) # iterate through the ax variable by flattening itfor index, i in enumerate(ax.flatten()): # the imshow is used to show the image i.imshow(train[index]) # set the title i.set_title(index) # this below lines makes the code better visualize. i.set_xticks([]) i.set_yticks([])",
"e": 3431,
"s": 2923,
"text": null
},
{
"code": null,
"e": 3440,
"s": 3431,
"text": "Output: "
},
{
"code": null,
"e": 3466,
"s": 3440,
"text": "Output of the above cell."
},
{
"code": null,
"e": 3583,
"s": 3466,
"text": "Now that we have the images stored in the train and output classes stored in labels we can move on to the next step."
},
{
"code": null,
"e": 3790,
"s": 3583,
"text": "Data CleaningIn this section, we will look at miss classified labels and improper image samples by removing these images my accuracy increased the val_score by 2%. It went from 94% to 96% and sometimes 97%."
},
{
"code": null,
"e": 3866,
"s": 3790,
"text": "Miss labelledImages: the code used to visualize the data is same as above "
},
{
"code": null,
"e": 3889,
"s": 3866,
"text": "Miss-classified labels"
},
{
"code": null,
"e": 3928,
"s": 3889,
"text": "Improper Data: Images of dashboards. "
},
{
"code": null,
"e": 4132,
"s": 3928,
"text": "By removing these images the accuracy become more stable (less oscillations). One think to note here I was able to remove these dashboard images because I didn’t find any similar images in the test data."
},
{
"code": null,
"e": 4301,
"s": 4132,
"text": "Defining the DatasetClass: For the model to load the dataset from the disk pytorch provides a DatasetClass using this we don’t need to fit the entire model into memory."
},
{
"code": null,
"e": 4309,
"s": 4301,
"text": "Code: "
},
{
"code": null,
"e": 4317,
"s": 4309,
"text": "Python3"
},
{
"code": "# Creating a VehicleDataset class for loading the images and labels .# the following class needs to extend from the Dataset class# provided by pytorch framework and implement the __len__ and __getitem__ methods. class VehicleDataset(Dataset): def __init__(self, csv_name, folder, transform = None, label = False): self.label = label self.folder = folder print(csv_name) self.dataframe = pd.read_csv(self.folder+'/'+csv_name+'.csv') self.tms = transform def __len__(self): return len(self.dataframe) def __getitem__(self, index): row = self.dataframe.iloc[index] imgIndex = row['image_names'] imageFile = self.folder + '/' + img_index image = Image.open(image_file) if self.label: target = row['emergency_or_not'] if target == 0: encode = torch.FloatTensor([1, 0]) else: encode = torch.FloatTensor([0, 1]) return self.tms(image), encode return self.tms(image) # creating objects of VehicleDataset # the deep learning models accepts the image to be in tensor format# this is done using the transforms.ToTensor() methods transform = transforms.Compose([transforms.ToTensor(), ]) '''arguments:csv_name - name of the csv file in out case train.csvfolder - folder in which the images are storedtransform - transforms the image to tensor,label - used to differentiate between train and test set.'''' trainDataset = VehicleDataset('train', 'images', label = True, transform = transform)",
"e": 5908,
"s": 4317,
"text": null
},
{
"code": null,
"e": 5992,
"s": 5908,
"text": "Now that we have our data pipeline ready we need to create the deep learning model."
},
{
"code": null,
"e": 6302,
"s": 5992,
"text": "CNN Model:This post assumes that you have some knowledge of Neural Nets as explaining that is out of scope of this article. I am going to use a CNN (Convolution neural network). The model has 3 main layers naming the conv2d layer, batch Norm, and max pooling 2d the activation function used over here is relu:"
},
{
"code": null,
"e": 6310,
"s": 6302,
"text": "Code: "
},
{
"code": null,
"e": 6317,
"s": 6310,
"text": "Python"
},
{
"code": "# the EmergencyCustomModel class defines our Neural Network# It inherites from the ImageClassificationBase class which has helper methods# for printing the loss and accuracy at each epochs. class EmergencyCustomModel(ImageClassificationBase): def __init__(self): super().__init__() self.network = nn.Sequential( nn.Conv2d(3, 32, kernel_size = 3, padding = 1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(32, 64, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(64, 64, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(64, 128, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(128, 128, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(128, 256, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 2), # nn.Sigmoid(), ) def forward(self, xb): return self.network(xb)",
"e": 7842,
"s": 6317,
"text": null
},
{
"code": null,
"e": 7937,
"s": 7842,
"text": "One can find the entire model definition in this notebook in my github repoTraining function: "
},
{
"code": null,
"e": 8012,
"s": 7937,
"text": "Code: the following function is used to train all the models in the post. "
},
{
"code": null,
"e": 8020,
"s": 8012,
"text": "Python3"
},
{
"code": "# defining the training method.# the evaluation method is used to calculate validation accuracy. @torch.no_grad()def evaluate(model, val_loader): model.eval() outputs = [model.validation_step(batch) for batch in val_loader] return model.validation_epoch_end(outputs) # The fit method is used to train the model# parameters'''epochs: no. of epochs the model trainsmax_lr: maximum learning rate.train_loader: here we pass the train datasetval_loader: here we pass the val_datasetopt_func : The learning algorithm that performs gradient descent.model : the neural network to train on.''' def fit(epochs, max_lr, model, train_loader, val_loader, weight_decay = 0, grad_clip = None, opt_func = torch.optim.SGD): torch.cuda.empty_cache() history = [] # Set up custom optimizer with weight decay optimizer = opt_func(model.parameters(), max_lr, weight_decay = weight_decay) # the loop iterates from 0 to number of epochs. # the model needs to be set in the train model by calling the model.train. for epoch in range(epochs): # Training Phase model.train() train_losses = [] for batch in train_loader: loss = model.training_step(batch) train_losses.append(loss) loss.backward() # Gradient clipping if grad_clip: nn.utils.clip_grad_value_(model.parameters(), grad_clip) optimizer.step() optimizer.zero_grad() # Validation phase result = evaluate(model, val_loader) result['train_loss'] = torch.stack(train_losses).mean().item() model.epoch_end(epoch, result) history.append(result) return history",
"e": 9713,
"s": 8020,
"text": null
},
{
"code": null,
"e": 10009,
"s": 9713,
"text": "Before starting training we need to split our data into train and validation set. This is done so that the model generalizes well on unseen data. We will do a 80 – 20 split 80% train and 20%test. After splitting the data we need to pass the datasets to a Data Loader this is provided by pytorch."
},
{
"code": null,
"e": 10052,
"s": 10009,
"text": "Code: Splitting and creating dataloaders. "
},
{
"code": null,
"e": 10060,
"s": 10052,
"text": "Python3"
},
{
"code": "# the batchSize is the number of images passes by the loader at a time.# reduce this number if theres an out of memory error.batchSize = 32valPct = 0.2 # code for splitting the data# valPct variable is used to split dataset valSize = int(valPct * len(trainDataset))trainSize = len(trainDataset) - valSizetrainDs, valDs = random_split(trainDataset, [trainSize, valSize]) # Creating dataloaders.train_loader = DataLoader(trainDs, batchSize)val_loader = DataLoader(valDs, batchSize)",
"e": 10541,
"s": 10060,
"text": null
},
{
"code": null,
"e": 10605,
"s": 10541,
"text": "Now we are ready to start training by calling the fit() method."
},
{
"code": null,
"e": 10613,
"s": 10605,
"text": "Python3"
},
{
"code": "customModel = EmergencyCustomModel()epochs = 10lr = 0.01 # save the history to visualize later.history = fit(epochs, lr, customModel, trainDl, valDl)",
"e": 10763,
"s": 10613,
"text": null
},
{
"code": null,
"e": 10786,
"s": 10763,
"text": "Output of above code: "
},
{
"code": null,
"e": 10809,
"s": 10786,
"text": "output of fit function"
},
{
"code": null,
"e": 10876,
"s": 10809,
"text": "The entire code is available in github repo link is provide below."
},
{
"code": null,
"e": 10965,
"s": 10876,
"text": "Code: The plot function is used for producing the loss and accuracy graphs shown below "
},
{
"code": null,
"e": 10973,
"s": 10965,
"text": "Python3"
},
{
"code": "'''parameters:epochs = number of epochs the model was trained onhist = the history returned by the fit function. ''' def plot(hist, epochs = 10): trainLoss = [] valLoss = [] valScore = [] for i in range(epochs): trainLoss.append(hist[i]['train_loss']) valLoss.append(hist[i]['val_loss']) valScore.append(hist[i]['val_score']) plt.plot(trainLoss, label ='train_loss') plt.plot(valLoss, label ='val_loss') plt.legend() plt.title('loss') plt.figure() plt.plot(valScore, label ='val_score') plt.legend() plt.title('accuracy') # calling the function plot(history)",
"e": 11599,
"s": 10973,
"text": null
},
{
"code": null,
"e": 11646,
"s": 11599,
"text": "Output: Plotting the loss and accuracy plots. "
},
{
"code": null,
"e": 11671,
"s": 11646,
"text": "loss and accuracy graphs"
},
{
"code": null,
"e": 12212,
"s": 11671,
"text": "There is very less over-fitting and the val_accuracy reaches its peak value at 90%. here again, I would like to add when I had created a custom model in keras the height val_score I was able to achieve was 83% changing the framework got we an increase of 7%. One more thing the size of the mode, using pytorch I am able to use a model having more than 3 Conv2d layers without over-fitting. But in keras I could only use 2 layers not more than that anything higher or lower would just add to the training cost without improving the accuracy."
},
{
"code": null,
"e": 12487,
"s": 12212,
"text": "Transfer Learning: Using The Pre-trained Models: I made use of two model architectures resnet and densenet. One thing to not the densenet models produce almost similar results to resnet models with lower epochs and most important the saved model takes half the memory space."
},
{
"code": null,
"e": 12495,
"s": 12487,
"text": "Code: "
},
{
"code": null,
"e": 12503,
"s": 12495,
"text": "Python3"
},
{
"code": "# to use the pretrained model we make use of the torchvision.models library class ResNet50(ImageClassificationBase): def __init__(self): super().__init__() # this following line adds the downloads the resnet50 model is it doesn't exits # and stores it in pretrainedModle self.pretrainedModel = models.resnet50(pretrained = True) # since this model was trained on ImageNet data which has 1000 classes but for # problem we have only 2 so will need to modify the final layer of the model feature_in = self.pretrainedModel.fc.inFeatures self.pretrainedModel.fc = nn.Linear(feature_in, 2) def forward(self, x): return self.pretrainedModel(x) # Trainin the model.# final Learning withlr = 1e-4epochs = 5optFunc = torch.optim.Adam # Here I have made use of the wd this is used as a regularization parameter# It helps in preventing overfitting and helps our model to generalize. bestWd = 1e-4 custom_model = to_device(ResNet50(), device)hist = fit(epochs, lr, customModel, trainDl, valDl, bestWd, optFunc)",
"e": 13575,
"s": 12503,
"text": null
},
{
"code": null,
"e": 13622,
"s": 13575,
"text": "Output: Plotting the loss and accuracy plots. "
},
{
"code": null,
"e": 13929,
"s": 13622,
"text": "here one can see a lot of over-fitting and now improvement in val_score. I decided to try using the cyclic scheduler training strategy here’s the result. I still need to do more experiment with this method but as one can see. I have reduced the overfitting to some extend but the val_accuracy is still low."
},
{
"code": null,
"e": 14088,
"s": 13929,
"text": "Using Densenet169: The dense net is similar to Resnet to instead to adding the skip connection it concatenates it hence the blocks are called as dense blocks."
},
{
"code": null,
"e": 14096,
"s": 14088,
"text": "Code: "
},
{
"code": null,
"e": 14104,
"s": 14096,
"text": "Python3"
},
{
"code": "class Densenet169(ImageClassificationBase): def __init__(self): super().__init__() # the below statement is used to download and store the pretrained model. self.pretrained_model = models.densenet169(pretrained = True) feature_in = self.pretrained_model.classifier.in_features self.pretrained_model.classifier = nn.Linear(feature_in, 2) def forward(self, x): return self.pretrained_model(x) Training the model# final Learning withlr = 1e-4epochs = 5optFunc = torch.optim.AdambestWd = 1e-4customModel2 = Densenet169() hist = fit(epochs, lr, customModel2, trainDl, valDl, bestWd, optFunc)",
"e": 14742,
"s": 14104,
"text": null
},
{
"code": null,
"e": 14893,
"s": 14742,
"text": "If you look at the loss and accuracy plots. The over-fitting has decreased. the val accuracy is better but this was done without the cyclic scheduler."
},
{
"code": null,
"e": 14938,
"s": 14893,
"text": "Code: Plotting the loss and accuracy plots. "
},
{
"code": null,
"e": 15000,
"s": 14938,
"text": "Using early stopping the training can be stopped at 5 epochs."
},
{
"code": null,
"e": 15010,
"s": 15000,
"text": "Web APP: "
},
{
"code": null,
"e": 15053,
"s": 15010,
"text": "https://emervehicledetector.herokuapp.com/"
},
{
"code": null,
"e": 15459,
"s": 15053,
"text": "Note: the web app only accepts jpg images.Conclusion: I was able to get a 200 rank out of 10000 so I made it in the top 2% using the above model. all the code will be available in my github repo: https://github.com/evilc3/EmergencyVehicleDetectorEntire notebook: https://colab.research.google.com/drive/13En-V2A-w2o4uXuDZk0ypktxzX9joXIY?usp=sharingWeb app link: https://emervehicledetector.herokuapp.com/ "
},
{
"code": null,
"e": 15475,
"s": 15459,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 15495,
"s": 15475,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 15510,
"s": 15495,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 15520,
"s": 15510,
"text": "rs1686740"
},
{
"code": null,
"e": 15538,
"s": 15520,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 15553,
"s": 15538,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 15570,
"s": 15553,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 15585,
"s": 15570,
"text": "adnanirshad158"
},
{
"code": null,
"e": 15594,
"s": 15585,
"text": "sweetyty"
},
{
"code": null,
"e": 15606,
"s": 15594,
"text": "kk773572498"
},
{
"code": null,
"e": 15624,
"s": 15606,
"text": "germanshephered48"
},
{
"code": null,
"e": 15634,
"s": 15624,
"text": "as5853535"
},
{
"code": null,
"e": 15644,
"s": 15634,
"text": "kk9826225"
},
{
"code": null,
"e": 15653,
"s": 15644,
"text": "rkbhola5"
},
{
"code": null,
"e": 15670,
"s": 15653,
"text": "Machine Learning"
},
{
"code": null,
"e": 15677,
"s": 15670,
"text": "Python"
},
{
"code": null,
"e": 15694,
"s": 15677,
"text": "Machine Learning"
},
{
"code": null,
"e": 15792,
"s": 15694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15825,
"s": 15792,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 15866,
"s": 15825,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 15902,
"s": 15866,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 15926,
"s": 15902,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 15977,
"s": 15926,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 16005,
"s": 15977,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 16027,
"s": 16005,
"text": "Python map() function"
},
{
"code": null,
"e": 16077,
"s": 16027,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 16095,
"s": 16077,
"text": "Python Dictionary"
}
] |
Vertical alignment in Bootstrap with Examples
|
15 Jul, 2021
Vertical Alignment in bootstrap changes the alignment of elements vertically with the help vertical-alignment utilities. The vertical-align utilities only affects inline(Present in one Line), inline-block(Present as blocks in one line), inline-table, and table cell(Elements in a cell of a table) elements.Various classes available in bootstrap library that are used for vertical alignment are:
.align-baseline
.align-top
.align-middle
.align-bottom
.align-text-bottom
.align-text-top
Below examples illustrate the vertical alignment classes in Bootstrap:Example 1: With Inline Elements
html
<!-- BootStrap Vertical alignment classes for inline elements --> <!DOCTYPE html><html><head> <title>GeeksForGeeks</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script></head> <body> <div class="container"> <h1>Vertical Align</h1> <p> Change the alignment of elements with the align classes (only works on inline, inline-block, inline-table and table cell elements): </p> <span class="align-baseline">Hello</span> <span class="align-top">This</span> <span class="align-middle">is</span> <span class="align-bottom">Geeks</span> <span class="align-text-top">for</span> <span class="align-text-bottom">Geeks</span> </div></body></html>
Output:
Example 2: With Table Cells.
html
<html><head> <title>GeeksForGeeks</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script></head> <body> <div class="container"> <table class='table table-striped table-bordered' style="height: 100px;"> <tbody> <tr> <td class="align-baseline"> Hello </td> <td class="align-top"> This </td> <td class="align-middle"> is </td> <td class="align-bottom"> Geeks </td> <td class="align-text-top"> for </td> <td class="align-text-bottom"> Geeks </td> </tr> </tbody> </table> </div></body></html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Reference: https://getbootstrap.com/docs/4.1/utilities/vertical-align/
ysachin2314
Picked
Technical Scripter 2018
Bootstrap
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 449,
"s": 52,
"text": "Vertical Alignment in bootstrap changes the alignment of elements vertically with the help vertical-alignment utilities. The vertical-align utilities only affects inline(Present in one Line), inline-block(Present as blocks in one line), inline-table, and table cell(Elements in a cell of a table) elements.Various classes available in bootstrap library that are used for vertical alignment are: "
},
{
"code": null,
"e": 465,
"s": 449,
"text": ".align-baseline"
},
{
"code": null,
"e": 476,
"s": 465,
"text": ".align-top"
},
{
"code": null,
"e": 490,
"s": 476,
"text": ".align-middle"
},
{
"code": null,
"e": 504,
"s": 490,
"text": ".align-bottom"
},
{
"code": null,
"e": 523,
"s": 504,
"text": ".align-text-bottom"
},
{
"code": null,
"e": 539,
"s": 523,
"text": ".align-text-top"
},
{
"code": null,
"e": 643,
"s": 539,
"text": "Below examples illustrate the vertical alignment classes in Bootstrap:Example 1: With Inline Elements "
},
{
"code": null,
"e": 648,
"s": 643,
"text": "html"
},
{
"code": "<!-- BootStrap Vertical alignment classes for inline elements --> <!DOCTYPE html><html><head> <title>GeeksForGeeks</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"></script></head> <body> <div class=\"container\"> <h1>Vertical Align</h1> <p> Change the alignment of elements with the align classes (only works on inline, inline-block, inline-table and table cell elements): </p> <span class=\"align-baseline\">Hello</span> <span class=\"align-top\">This</span> <span class=\"align-middle\">is</span> <span class=\"align-bottom\">Geeks</span> <span class=\"align-text-top\">for</span> <span class=\"align-text-bottom\">Geeks</span> </div></body></html>",
"e": 1768,
"s": 648,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1768,
"text": "Output: "
},
{
"code": null,
"e": 1809,
"s": 1778,
"text": "Example 2: With Table Cells. "
},
{
"code": null,
"e": 1814,
"s": 1809,
"text": "html"
},
{
"code": "<html><head> <title>GeeksForGeeks</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"></script></head> <body> <div class=\"container\"> <table class='table table-striped table-bordered' style=\"height: 100px;\"> <tbody> <tr> <td class=\"align-baseline\"> Hello </td> <td class=\"align-top\"> This </td> <td class=\"align-middle\"> is </td> <td class=\"align-bottom\"> Geeks </td> <td class=\"align-text-top\"> for </td> <td class=\"align-text-bottom\"> Geeks </td> </tr> </tbody> </table> </div></body></html>",
"e": 3102,
"s": 1814,
"text": null
},
{
"code": null,
"e": 3112,
"s": 3102,
"text": "Output: "
},
{
"code": null,
"e": 3131,
"s": 3112,
"text": "Supported Browser:"
},
{
"code": null,
"e": 3145,
"s": 3131,
"text": "Google Chrome"
},
{
"code": null,
"e": 3163,
"s": 3145,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3171,
"s": 3163,
"text": "Firefox"
},
{
"code": null,
"e": 3177,
"s": 3171,
"text": "Opera"
},
{
"code": null,
"e": 3184,
"s": 3177,
"text": "Safari"
},
{
"code": null,
"e": 3256,
"s": 3184,
"text": "Reference: https://getbootstrap.com/docs/4.1/utilities/vertical-align/ "
},
{
"code": null,
"e": 3268,
"s": 3256,
"text": "ysachin2314"
},
{
"code": null,
"e": 3275,
"s": 3268,
"text": "Picked"
},
{
"code": null,
"e": 3299,
"s": 3275,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3309,
"s": 3299,
"text": "Bootstrap"
},
{
"code": null,
"e": 3328,
"s": 3309,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3345,
"s": 3328,
"text": "Web Technologies"
},
{
"code": null,
"e": 3443,
"s": 3345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3493,
"s": 3443,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 3522,
"s": 3493,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3563,
"s": 3522,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 3619,
"s": 3563,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 3660,
"s": 3619,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 3722,
"s": 3660,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3755,
"s": 3722,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3816,
"s": 3755,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3866,
"s": 3816,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
B and B+ Trees - GeeksforGeeks
|
22 Aug, 2021
Insertion of 3 keys
10 20 30
Insertion of 4th key (1st split)
30
/ \
10*20 40
Insertion of 5th key no split
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 5
30
/ \
5*10*20 40
Insertion of 6th key (2nd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 6
8*30
/ | \
5 10*20 40
Insertion of 7th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 15
8*30
/ | \
5 10*15*20 40
Insertion of 8th key (3rd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 12
8*12*30
/ / \ \
5 10 15*20 40
Insertion of 9th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 17
8*12*30
/ / \ \
5 10 15*17*20 40
Insertion of 10th key (4th and 5th Splits)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 13
12
/ \
8 15*30
/ \ / | \
5 10 13 17*20 40
Disk Block size = 1024 bytes
Data Record Pointer size, r = 7 bytes
Value size, V = 9 bytes
Disk Block ptr, P = 6 bytes
A)
B)
C)
D) None of the above
Size of 1 record = 8 + 4 = 12
Let the order be N.
No. of index values per block = N - 1
(N - 1) 12 + 4 = 512
12N - 12 + 4 = 512
16N = 1009
N = 43.3333
We can get all values in range from 7 to 59 by accessing 5 nodes.
1) First search 7 in a leaf node.
2) Once 7 is found, linearly traverse till 15 is found.
See following diagram
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n22 Aug, 2021"
},
{
"code": null,
"e": 30739,
"s": 29577,
"text": "Insertion of 3 keys\n10 20 30\n\nInsertion of 4th key (1st split)\n 30\n / \\\n10*20 40\n\n\nInsertion of 5th key no split \nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 5\n 30\n / \\\n5*10*20 40\n\n\nInsertion of 6th key (2nd Split)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 6\n 8*30\n / | \\\n5 10*20 40 \n\n\nInsertion of 7th key\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 15\n 8*30\n / | \\\n5 10*15*20 40 \n\n\n\nInsertion of 8th key (3rd Split)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 12\n 8*12*30\n / / \\ \\\n 5 10 15*20 40 \n\n\nInsertion of 9th key \nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 17\n 8*12*30\n / / \\ \\\n5 10 15*17*20 40 \n\nInsertion of 10th key (4th and 5th Splits)\nTo maximize splits, let us insert a value in a node that has\nkey in access. Let us insert 13\n 12\n / \\\n 8 15*30\n / \\ / | \\ \n 5 10 13 17*20 40 \n"
},
{
"code": null,
"e": 30870,
"s": 30739,
"text": " Disk Block size = 1024 bytes\n \n Data Record Pointer size, r = 7 bytes\n Value size, V = 9 bytes\n Disk Block ptr, P = 6 bytes "
},
{
"code": null,
"e": 30907,
"s": 30870,
"text": "A) \n\nB) \n\nC) \n\nD) None of the above\n"
},
{
"code": null,
"e": 31064,
"s": 30907,
"text": "Size of 1 record = 8 + 4 = 12\n\nLet the order be N.\n\nNo. of index values per block = N - 1\n\n(N - 1) 12 + 4 = 512\n\n12N - 12 + 4 = 512\n\n16N = 1009\n\nN = 43.3333"
},
{
"code": null,
"e": 31246,
"s": 31064,
"text": "We can get all values in range from 7 to 59 by accessing 5 nodes. \n1) First search 7 in a leaf node.\n2) Once 7 is found, linearly traverse till 15 is found.\n\nSee following diagram "
}
] |
How to draw an SVG file on an HTML5 canvas?
|
To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas.
You can try the following code to draw an SVG file on an HTML canvas
<!DOCTYPE html>
<html>
<head>
<title>SVG file on HTML Canvas </title>
</head>
<body>
<canvas id="myCanvas" style="border:2px solid green;" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="300"
height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:50px">' +
'Simply Easy ' +
'<span style="color:blue;">' +
'Learning</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img1 = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);
img1.onload = function() {
ctx.drawImage(img1, 25, 70);
DOMURL.revokeObjectURL(url);
}
img1.src = url;
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1365,
"s": 1187,
"text": "To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas."
},
{
"code": null,
"e": 1434,
"s": 1365,
"text": "You can try the following code to draw an SVG file on an HTML canvas"
},
{
"code": null,
"e": 2586,
"s": 1434,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>SVG file on HTML Canvas </title>\n </head>\n <body>\n <canvas id=\"myCanvas\" style=\"border:2px solid green;\" width=\"300\" height=\"300\"></canvas>\n <script>\n var canvas = document.getElementById('myCanvas');\n var ctx = canvas.getContext('2d');\n var data = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"300\"\n height=\"200\">' +\n '<foreignObject width=\"100%\" height=\"100%\">' +\n '<div xmlns=\"http://www.w3.org/1999/xhtml\" style=\"font-size:50px\">' +\n 'Simply Easy ' +\n '<span style=\"color:blue;\">' +\n 'Learning</span>' +\n '</div>' +\n '</foreignObject>' +\n '</svg>';\n var DOMURL = window.URL || window.webkitURL || window;\n var img1 = new Image();\n var svg = new Blob([data], {type: 'image/svg+xml'});\n var url = DOMURL.createObjectURL(svg);\n img1.onload = function() {\n ctx.drawImage(img1, 25, 70);\n DOMURL.revokeObjectURL(url);\n }\n img1.src = url;\n </script>\n </body>\n</html>"
}
] |
PyQt5 – How to make Round Radio Button ?
|
22 Apr, 2020
In this article we will see how to create round radio button. By default the shape of radio button is rectangular although if we set width equal to the height it become square. Below is the representation of normal bordered radio button vs the radio button round in shape.
In order to do this we have to do the following :
1. Create a radio button.2. Set its width equal to height to make it square3. Add border to it with the help of setStyleSheet method.4. Set border radius to half of width.
Style sheet code to do this –
QRadioButton
{
border : 3px solid black;
border-radius : 60px;
}
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 120) # setting text to radio button self.radio_button.setText("Radio Button") # changing style sheet code of radio button setting border to # radio button and changing radius to half of width self.radio_button.setStyleSheet("QRadioButton" "{" "border : 3px solid black;" "border-radius : 60px;" "}") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "In this article we will see how to create round radio button. By default the shape of radio button is rectangular although if we set width equal to the height it become square. Below is the representation of normal bordered radio button vs the radio button round in shape. "
},
{
"code": null,
"e": 352,
"s": 302,
"text": "In order to do this we have to do the following :"
},
{
"code": null,
"e": 524,
"s": 352,
"text": "1. Create a radio button.2. Set its width equal to height to make it square3. Add border to it with the help of setStyleSheet method.4. Set border radius to half of width."
},
{
"code": null,
"e": 554,
"s": 524,
"text": "Style sheet code to do this –"
},
{
"code": null,
"e": 620,
"s": 554,
"text": "QRadioButton\n{\nborder : 3px solid black;\nborder-radius : 60px;\n}\n"
},
{
"code": null,
"e": 649,
"s": 620,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 120) # setting text to radio button self.radio_button.setText(\"Radio Button\") # changing style sheet code of radio button setting border to # radio button and changing radius to half of width self.radio_button.setStyleSheet(\"QRadioButton\" \"{\" \"border : 3px solid black;\" \"border-radius : 60px;\" \"}\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1984,
"s": 649,
"text": null
},
{
"code": null,
"e": 1993,
"s": 1984,
"text": "Output :"
},
{
"code": null,
"e": 2004,
"s": 1993,
"text": "Python-gui"
},
{
"code": null,
"e": 2016,
"s": 2004,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2023,
"s": 2016,
"text": "Python"
},
{
"code": null,
"e": 2121,
"s": 2023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2153,
"s": 2121,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2180,
"s": 2153,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2201,
"s": 2180,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2224,
"s": 2201,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2280,
"s": 2224,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2311,
"s": 2280,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2353,
"s": 2311,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2395,
"s": 2353,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2434,
"s": 2395,
"text": "Python | Get unique values from a list"
}
] |
Local variables in Java
|
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Here, age is a local variable. This is defined inside pupAge()method and its scope is limited to only this method.
Live Demo
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
Puppy age is: 7
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Local variables are declared in methods, constructors, or blocks."
},
{
"code": null,
"e": 1289,
"s": 1128,
"text": "Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block."
},
{
"code": null,
"e": 1342,
"s": 1289,
"text": "Access modifiers cannot be used for local variables."
},
{
"code": null,
"e": 1426,
"s": 1342,
"text": "Local variables are visible only within the declared method, constructor, or block."
},
{
"code": null,
"e": 1485,
"s": 1426,
"text": "Local variables are implemented at stack level internally."
},
{
"code": null,
"e": 1632,
"s": 1485,
"text": "There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use."
},
{
"code": null,
"e": 1747,
"s": 1632,
"text": "Here, age is a local variable. This is defined inside pupAge()method and its scope is limited to only this method."
},
{
"code": null,
"e": 1757,
"s": 1747,
"text": "Live Demo"
},
{
"code": null,
"e": 2002,
"s": 1757,
"text": "public class Test {\n public void pupAge() {\n int age = 0;\n age = age + 7;\n System.out.println(\"Puppy age is : \" + age);\n }\n\n public static void main(String args[]) {\n Test test = new Test();\n test.pupAge();\n }\n}"
},
{
"code": null,
"e": 2018,
"s": 2002,
"text": "Puppy age is: 7"
}
] |
How to set a particular font for a button text in Android using Kotlin?
|
This example demonstrates how to set a particular font for a button text in Android using Kotlin
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnChangeFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click to change font of the Button" />
<Button
android:id="@+id/btnChangeFont2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnChangeFont"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:text="Click to change font of the Button" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.Typeface
import android.graphics.Typeface.BOLD_ITALIC
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var btnChangeFont: Button
lateinit var btnChangeFont2: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
btnChangeFont = findViewById(R.id.btnChangeFont)
btnChangeFont.setOnClickListener { btnChangeFont.setTypeface(Typeface.MONOSPACE, Typeface.BOLD)}
btnChangeFont2 = findViewById(R.id.btnChangeFont2)
btnChangeFont2.setOnClickListener { btnChangeFont2.setTypeface(Typeface.SERIF, BOLD_ITALIC) }
}
}
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.q11">
<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 the 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": 1159,
"s": 1062,
"text": "This example demonstrates how to set a particular font for a button text in Android using Kotlin"
},
{
"code": null,
"e": 1287,
"s": 1159,
"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": 1352,
"s": 1287,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2509,
"s": 1352,
"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 tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n<Button\n android:id=\"@+id/btnChangeFont\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Click to change font of the Button\" />\n<Button\n android:id=\"@+id/btnChangeFont2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnChangeFont\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Click to change font of the Button\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2564,
"s": 2509,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3354,
"s": 2564,
"text": "import android.graphics.Typeface\nimport android.graphics.Typeface.BOLD_ITALIC\nimport android.os.Bundle\nimport android.widget.Button\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var btnChangeFont: Button\n lateinit var btnChangeFont2: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n btnChangeFont = findViewById(R.id.btnChangeFont)\n btnChangeFont.setOnClickListener { btnChangeFont.setTypeface(Typeface.MONOSPACE, Typeface.BOLD)}\n btnChangeFont2 = findViewById(R.id.btnChangeFont2)\n btnChangeFont2.setOnClickListener { btnChangeFont2.setTypeface(Typeface.SERIF, BOLD_ITALIC) }\n }\n}"
},
{
"code": null,
"e": 3409,
"s": 3354,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4080,
"s": 3409,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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": 4428,
"s": 4080,
"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 the 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": 4469,
"s": 4428,
"text": "Click here to download the project code."
}
] |
PyQt - QCheckBox Widget
|
A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. Its common use is in a scenario when the user is asked to choose one or more of the available options.
Unlike Radio buttons, check boxes are not mutually exclusive by default. In order to restrict the choice to one of the available items, the check boxes must be added to QButtonGroup.
The following table lists commonly used QCheckBox class methods −
setChecked()
Changes the state of checkbox button
setText()
Sets the label associated with the button
text()
Retrieves the caption of the button
isChecked()
Checks if the button is selected
setTriState()
Provides no change state to checkbox
Each time a checkbox is either checked or cleared, the object emits stateChanged() signal.
Here, two QCheckBox objects are added to a horizontal layout. Their stateChanged() signal is connected to btnstate() function. The source object of signal is passed to the function using lambda.
self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))
self.b2.toggled.connect(lambda:self.btnstate(self.b2))
The isChecked() function is used to check if the button is checked or not.
if b.text() == "Button1":
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class checkdemo(QWidget):
def __init__(self, parent = None):
super(checkdemo, self).__init__(parent)
layout = QHBoxLayout()
self.b1 = QCheckBox("Button1")
self.b1.setChecked(True)
self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))
layout.addWidget(self.b1)
self.b2 = QCheckBox("Button2")
self.b2.toggled.connect(lambda:self.btnstate(self.b2))
layout.addWidget(self.b2)
self.setLayout(layout)
self.setWindowTitle("checkbox demo")
def btnstate(self,b):
if b.text() == "Button1":
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
if b.text() == "Button2":
if b.isChecked() == True:
print b.text()+" is selected"
else:
print b.text()+" is deselected"
def main():
app = QApplication(sys.argv)
ex = checkdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
As mentioned earlier, checkBox buttons can be made mutually exclusive by adding them in the QButtonGroup object.
self.bg = QButtonGroup()
self.bg.addButton(self.b1,1)
self.bg.addButton(self.b2,2)
QButtonGroup object, provides abstract container for buttons and doesn’t have a visual representation. It emits buttonCliked() signal and sends Button object’s reference to the slot function btngroup().
self.bg.buttonClicked[QAbstractButton].connect(self.btngroup)
The btngroup() function displays the caption of the clicked checkbox.
def btngroup(self,btn):
print btn.text()+" is selected"
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2186,
"s": 1926,
"text": "A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. Its common use is in a scenario when the user is asked to choose one or more of the available options."
},
{
"code": null,
"e": 2369,
"s": 2186,
"text": "Unlike Radio buttons, check boxes are not mutually exclusive by default. In order to restrict the choice to one of the available items, the check boxes must be added to QButtonGroup."
},
{
"code": null,
"e": 2435,
"s": 2369,
"text": "The following table lists commonly used QCheckBox class methods −"
},
{
"code": null,
"e": 2448,
"s": 2435,
"text": "setChecked()"
},
{
"code": null,
"e": 2485,
"s": 2448,
"text": "Changes the state of checkbox button"
},
{
"code": null,
"e": 2495,
"s": 2485,
"text": "setText()"
},
{
"code": null,
"e": 2537,
"s": 2495,
"text": "Sets the label associated with the button"
},
{
"code": null,
"e": 2544,
"s": 2537,
"text": "text()"
},
{
"code": null,
"e": 2580,
"s": 2544,
"text": "Retrieves the caption of the button"
},
{
"code": null,
"e": 2592,
"s": 2580,
"text": "isChecked()"
},
{
"code": null,
"e": 2625,
"s": 2592,
"text": "Checks if the button is selected"
},
{
"code": null,
"e": 2639,
"s": 2625,
"text": "setTriState()"
},
{
"code": null,
"e": 2676,
"s": 2639,
"text": "Provides no change state to checkbox"
},
{
"code": null,
"e": 2767,
"s": 2676,
"text": "Each time a checkbox is either checked or cleared, the object emits stateChanged() signal."
},
{
"code": null,
"e": 2962,
"s": 2767,
"text": "Here, two QCheckBox objects are added to a horizontal layout. Their stateChanged() signal is connected to btnstate() function. The source object of signal is passed to the function using lambda."
},
{
"code": null,
"e": 3078,
"s": 2962,
"text": "self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))\nself.b2.toggled.connect(lambda:self.btnstate(self.b2))\n"
},
{
"code": null,
"e": 3153,
"s": 3078,
"text": "The isChecked() function is used to check if the button is checked or not."
},
{
"code": null,
"e": 3291,
"s": 3153,
"text": "if b.text() == \"Button1\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\""
},
{
"code": null,
"e": 3325,
"s": 3291,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 4422,
"s": 3325,
"text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass checkdemo(QWidget):\n def __init__(self, parent = None):\n super(checkdemo, self).__init__(parent)\n \n layout = QHBoxLayout()\n self.b1 = QCheckBox(\"Button1\")\n self.b1.setChecked(True)\n self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))\n layout.addWidget(self.b1)\n\t\t\n self.b2 = QCheckBox(\"Button2\")\n self.b2.toggled.connect(lambda:self.btnstate(self.b2))\n\n layout.addWidget(self.b2)\n self.setLayout(layout)\n self.setWindowTitle(\"checkbox demo\")\n\n def btnstate(self,b):\n if b.text() == \"Button1\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\n if b.text() == \"Button2\":\n if b.isChecked() == True:\n print b.text()+\" is selected\"\n else:\n print b.text()+\" is deselected\"\n\t\t\t\t\ndef main():\n\n app = QApplication(sys.argv)\n ex = checkdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 4535,
"s": 4422,
"text": "As mentioned earlier, checkBox buttons can be made mutually exclusive by adding them in the QButtonGroup object."
},
{
"code": null,
"e": 4618,
"s": 4535,
"text": "self.bg = QButtonGroup()\nself.bg.addButton(self.b1,1)\nself.bg.addButton(self.b2,2)"
},
{
"code": null,
"e": 4821,
"s": 4618,
"text": "QButtonGroup object, provides abstract container for buttons and doesn’t have a visual representation. It emits buttonCliked() signal and sends Button object’s reference to the slot function btngroup()."
},
{
"code": null,
"e": 4884,
"s": 4821,
"text": "self.bg.buttonClicked[QAbstractButton].connect(self.btngroup)\n"
},
{
"code": null,
"e": 4954,
"s": 4884,
"text": "The btngroup() function displays the caption of the clicked checkbox."
},
{
"code": null,
"e": 5013,
"s": 4954,
"text": "def btngroup(self,btn):\n print btn.text()+\" is selected\""
},
{
"code": null,
"e": 5050,
"s": 5013,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 5060,
"s": 5050,
"text": " ALAA EID"
},
{
"code": null,
"e": 5067,
"s": 5060,
"text": " Print"
},
{
"code": null,
"e": 5078,
"s": 5067,
"text": " Add Notes"
}
] |
Node.js indexOf() function - GeeksforGeeks
|
13 Oct, 2021
The indexOf() function is a string function from Node.js which is used to find a string with another string.
Syntax:
str1.indexOf( str2 )
Parameter: This function uses two parameters as mentioned above and described below:
str1: It holds the string content where another string to be search.
str2: It holds the search string.
Return Value: The function returns the index of the passed parameter.
Below programs demonstrate the working of indexOf() function:
Program 1:
function findIndex(str) { var index = str.indexOf("awesome"); console.log(index);} var str = "gfg is awesome"; findIndex(str);
Output:
7
Program 2:
function findIndex(str1, str2) { var index = str1.indexOf(str2); console.log(index);} var str1 = "Welcome to GeeksforGeeks";var str2 = "to" findIndex(str1, str2);
Output:
8
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Mongoose Populate() Method
Mongoose find() Function
Express.js req.params Property
Mongoose | findOneAndDelete() Function
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
|
[
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 24640,
"s": 24531,
"text": "The indexOf() function is a string function from Node.js which is used to find a string with another string."
},
{
"code": null,
"e": 24648,
"s": 24640,
"text": "Syntax:"
},
{
"code": null,
"e": 24669,
"s": 24648,
"text": "str1.indexOf( str2 )"
},
{
"code": null,
"e": 24754,
"s": 24669,
"text": "Parameter: This function uses two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 24823,
"s": 24754,
"text": "str1: It holds the string content where another string to be search."
},
{
"code": null,
"e": 24857,
"s": 24823,
"text": "str2: It holds the search string."
},
{
"code": null,
"e": 24927,
"s": 24857,
"text": "Return Value: The function returns the index of the passed parameter."
},
{
"code": null,
"e": 24989,
"s": 24927,
"text": "Below programs demonstrate the working of indexOf() function:"
},
{
"code": null,
"e": 25000,
"s": 24989,
"text": "Program 1:"
},
{
"code": "function findIndex(str) { var index = str.indexOf(\"awesome\"); console.log(index);} var str = \"gfg is awesome\"; findIndex(str);",
"e": 25135,
"s": 25000,
"text": null
},
{
"code": null,
"e": 25143,
"s": 25135,
"text": "Output:"
},
{
"code": null,
"e": 25145,
"s": 25143,
"text": "7"
},
{
"code": null,
"e": 25156,
"s": 25145,
"text": "Program 2:"
},
{
"code": "function findIndex(str1, str2) { var index = str1.indexOf(str2); console.log(index);} var str1 = \"Welcome to GeeksforGeeks\";var str2 = \"to\" findIndex(str1, str2);",
"e": 25339,
"s": 25156,
"text": null
},
{
"code": null,
"e": 25347,
"s": 25339,
"text": "Output:"
},
{
"code": null,
"e": 25349,
"s": 25347,
"text": "8"
},
{
"code": null,
"e": 25365,
"s": 25349,
"text": "NodeJS-function"
},
{
"code": null,
"e": 25373,
"s": 25365,
"text": "Node.js"
},
{
"code": null,
"e": 25390,
"s": 25373,
"text": "Web Technologies"
},
{
"code": null,
"e": 25488,
"s": 25390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25497,
"s": 25488,
"text": "Comments"
},
{
"code": null,
"e": 25510,
"s": 25497,
"text": "Old Comments"
},
{
"code": null,
"e": 25547,
"s": 25510,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 25574,
"s": 25547,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 25599,
"s": 25574,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 25630,
"s": 25599,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 25669,
"s": 25630,
"text": "Mongoose | findOneAndDelete() Function"
},
{
"code": null,
"e": 25706,
"s": 25669,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 25767,
"s": 25706,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 25839,
"s": 25767,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25897,
"s": 25839,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Lagrange multipliers with visualizations and code | by Rohit Pandey | Towards Data Science
|
In this story, we’re going to take an aerial tour of optimization with Lagrange multipliers. When do we need them? Whenever we have an optimization problem with constraints. Here are some examples:
A hedge fund wants to decide the proportions of stocks to include in their portfolio such that they get the maximum possible expected return, staying within some risk appetite (the risk might be measured in terms of the variance of the return for example).A school district wants to determine an allocation for various items on their lunch menu for their students. They want to minimize the cost per lunch while making sure the kids get a certain quantity of all required nutrients.A trucking company wants to transport goods from source warehouses to destination cities. Given the costs of transport for each warehouse-city pair, the total supply at each warehouse and total demand at each city, decide how much to ship from each warehouse to each city so that overall cost is minimized and demand met (constraint).
A hedge fund wants to decide the proportions of stocks to include in their portfolio such that they get the maximum possible expected return, staying within some risk appetite (the risk might be measured in terms of the variance of the return for example).
A school district wants to determine an allocation for various items on their lunch menu for their students. They want to minimize the cost per lunch while making sure the kids get a certain quantity of all required nutrients.
A trucking company wants to transport goods from source warehouses to destination cities. Given the costs of transport for each warehouse-city pair, the total supply at each warehouse and total demand at each city, decide how much to ship from each warehouse to each city so that overall cost is minimized and demand met (constraint).
We can see that constrained optimization can solve many practical, real world problems arising in domains from logistics to finance. In the rest of the blog, we will start with vanilla optimization without constraints. Then, we will add equality constraints. Then, we will describe the solution to completely general constrained optimization problem with both equality and inequality constraints (the conditions are called KKT — Karush, Kuhn, Tucker conditions). Finally, we demonstrate the power of these conditions on some toy problems. Many people consider the book by Nocedal and Wright the bible of numerical optimization and we will roughly follow chapter 13, side-stepping rigorous proofs (which can always be read from the text) and focusing more on visual intuition.
In this scenario, we have some variables in our control and an objective function that depends on them. There is no constraint on the variables and the objective function is to be minimized (if it were a maximization problem, we could simply negate the objective function and it would then become a minimization problem).
At any point, for a one dimensional function, the derivative of the function points in a direction that increases it (at least for small steps). Meaning that if we have a function f(x) and the derivative f’(x) is positive, then increasing x will increase f(x) and decreasing it will decrease f(x). If we were minimizing f(x), we would just take a small step opposite to the sign of f’(x) to decrease f(x). What if we’re at a point where f’(x)=0? Then, we might have reached an optima of f(x) since there’s no where else to go.
If there are multiple variables (say x and y), we can have a derivative with each of them. If we take these two numbers and construct a 2-d vector from them, we get the gradient of the function. Now, moving along the direction of the gradient will increase the function while moving opposite to it will decrease it (for small steps).
This means that as long as the gradient is non-zero, we can’t be at a minima since we can simply take a small step along the direction opposite to the gradient and decrease the function further. This means that a necessary (but not sufficient) condition for a point minimizing the function is that the gradient must be zero at that point.
Let’s take a concrete example so we can visualize what this looks like. Consider the function f(x,y) = x2+y2. This is a paraboloid and minimized when x=0 and y=0. The derivatives with respect to x and y become 2x and 2y respectively. So, the gradient becomes the vector ∇f = [2x,2y]. We can see that this is zero only when x=0 and y=0. Otherwise, the gradient points in a direction where f(x,y) will increase. So, the direction opposite the gradient will decrease f(x,y). This is shown in the figure below. The pink curve is the objective function f(x,y) which is minimized at the green point (0,0). The purple arrows are the gradients, which point in the direction where f(x,y) will increase. So to decrease it, we move in the opposite direction until we reach the green point.
To summarize, when optimizing a function, f in an unconstrained optimization problem, a necessary (but not sufficient) condition to be at a local optima is:
∇f = 0
It’s like when you’re at the top of a mountain (which would be a maxima). How do you know you’re at the top? No matter which direction you step along, you end up decreasing your altitude. So you’re definitely at an optima in your local neighborhood. Now, there might be another mountain right next to you which is even higher. So, you might not be at the global optima. In fact, if we consider the surface of the Earth as our domain (and height above sea level as our objective function), you’re at a local optima if you’re at the top of any old mountain (or building) but the global optima only if that mountain is Everest. In this article, we’re going to be content with finding a local optima.
Now what if we wanted to stay within the confines of a country? That would mean constraining the space in which we can search for our optima, making this an example of constrained optimization. In a way, un-constrained optimization is just a special case of constrained optimization.
For unconstrained minimization/maximization problems, we simply look for a point where the gradient is the zero vector. If the gradient is not zero, we just take a small step in the direction opposite to where it is pointing (if we’re minimizing; along it if we’re maximizing) and keep doing this until we do get to a point where it is zero and hence, there is no where else to go (this optimization method is called gradient descent). Note that we don’t have to move exactly along the gradient. As long as we move in a direction that has a positive projection (shadow) along the gradient, we end up increasing the objective function (and decreasing if we have a positive projection along the negative gradient). The figure below illustrates this. The green arrow is the gradient of the blue plane (and hence perpendicular to it) and the red arrow is the negative gradient. Since the light-blue arrows lie on the plane, the equation of the plane will yield 0 if we take a step along them. The yellow arrows have a positive shadow (projection) along the green one. So, moving along them will result in points that yield positive numbers when plugged into the equation of the plane (“increase” it). Similarly, the pink arrows have a positive shadow along the red one (reverse gradient). So, moving along them will result in points that yield negative numbers when plugged into the equation of the plane (“decrease” it).
For un-constrained minimization, we looked for a point where the gradient was zero. This was because if it wasn’t, we could decrease the objective function by going opposite to the gradient.
The same idea can be extended to the case when we have equality constraints. Like before, we need to find a point where we can’t find any possible direction to move where the objective function decreases. For unconstrained optimization, this simply meant that no such direction exists. When we have a constraint, there is another possibility. What if a direction that decreases the objective function exists, but the constraints forbid us from taking any step along it.
Let’s say you want to maximize the amount of money in your bank account. One way to immediately boost your earnings is to sell a kidney. But you probably have a constraint saying you’re not going to lose a vital organ. So, even though an easy path to increasing your earnings exists, your constraint prevents you from accessing it.
This means that the presence of the equality constraint actually reduces the strictness of the condition on the gradient. While it needed to be zero for a local optima without the equality constraint, it’s now okay for it to be non-zero as long as moving in any direction that has a positive shadow along it causes us to violate the constraint. This can only happen when the plane of the constraint is perpendicular to the gradient (like the plane and green arrow in figure 2).
Let’s go back to our objective function f(x,y)=x2+y2. Let’s add an equality constraint, y=1. This is a plane. In figure 3 below, the objective function is in pink and the plane is blue. Since we’re constrained to stay on the plane, we can’t move in any direction that has a positive or negative shadow along the gradient of the plane (blue arrows in the figure below) since that would increase or decrease the equation of the constraint, while we want to keep it constant. The plane intersects the equation of our objective function (pink paraboloid) in a curve which is a parabola. The pink arrows in the figure below are the gradients of the objective function at various points along this parabola. If the pink arrow has a projection along the blue plane, we can just move in the direction opposite to the vector corresponding to that projection. This will keep us on the plane, ensuring we don’t violate the constraint while still reducing the objective function. However, at the green point in figure 3 below, the pink arrow (gradient of objective function) has no projection whatsoever along the blue plane. In other words, the pink arrow is parallel to the blue arrow (which is the gradient of the constraint plane).
To decrease the objective function, we need to move in a direction that has a shadow along the negative gradient. But as soon as we do that, we’ll end up leaving the plane of the constraint. So, the constraint makes it impossible to decrease the objective function further at the green point. This means it must be a local minima. An easy way to check this condition is to require that the pink gradient of the objective function is parallel to the blue gradient of the constraint plane. And if two vectors are parallel, we can write one as a multiple of the other. Let’s call this multiple λ. If the gradient of the objective function is ∇f and that of the constraint is ∇c, the condition above is:
∇f = λ ∇c
The λ above is called the Lagrange multiplier. So, we now have a concrete condition to check for when looking for the local optima of a constrained optimization problem.
Inequality constraints mean you have to stay on one side of a boundary defining a constraint function as opposed to on it (which was the case for equality constraints). For example, staying inside the boundary of a fence. If we know how to deal with inequality constraints, we can solve any constrained optimization problem. This is because equality constraints can be converted to inequality constraints. Let’s say we require: c(x) = 0. Another way to express this is: c(x)≥0 and c(x)≤ 0. So, each equality constraint can always be replaced with two inequality constraints.
Just as constrained optimization with equality constraints can be handled with Lagrange multipliers as described in the previous section, so can constrained optimization with inequality constraints. What sets the inequality constraint conditions apart from equality constraints is that the Lagrange multipliers for inequality constraints must be positive. To see why, again consider taking a small step in a direction that has a positive component along the gradient. If we can take a step along this direction (if we are maximizing; opposite to it if we are minimizing); we can’t be at a maxima/minima. For inequality constraints, this translates to the Lagrange multiplier being positive. To see why, let’s go back to the constrained optimization problem we considered earlier (figure 3).
Minimize: f(x,y) = x2+y2
Subject to: c(x,y)=y-1=0
Now, let’s change the equality constraint to inequality. This can be done in two ways with completely different results. We can either require:
c(x,y) = y-1 ≥0. In this case, the constraint allows for anything in front of the blue plane in figure 3. It is easy to see that the green point in figure 3 continues to be a local optima. Also, since the blue arrow representing the constraints gradient and the pink arrow representing the objective function’s gradient point in the same direction, we have:
∇f = λ ∇c
with λ>0.
The other possibility is, c(x,y) = y-1≤0. Now, the feasible region becomes everything behind the blue plane. The constraint gradients will flip. So, figure 3 will end up looking like this:
Note that now,
The green point is no longer the local optima since we’re free to move to (0,0); which is the yellow point in figure 4 above.At the green point, we still have ∇f=λ ∇c. since the blue vector points opposite to the pink vector, we have λ<0.
The green point is no longer the local optima since we’re free to move to (0,0); which is the yellow point in figure 4 above.
At the green point, we still have ∇f=λ ∇c. since the blue vector points opposite to the pink vector, we have λ<0.
So, it is clear that for an inequality constraint, the condition ∇f=λ ∇c indicates we’re at a local optima only when λ>0.
Putting all of this together, for a general optimization problem:
Minimize f(x)
Subject to:
c_i(x) =0 for i ∈ Equality
c_i(x)≥0 for i ∈ Inequality
We get the full suite of conditions required to be at a local optima:
Lagrange multiplier condition:
∇f =∑_i λ_i ∇c_i(x) +∑_j λ_j ∇c_j(x); Eq(1)
Where i ∈ Equality and j ∈ Inequality constraints.
c_i(x)=0 for all i; Eq(2)
c_j(x)≥0 for all j; Eq(3)
λ_j ≥ 0; Eq(4)
Also note that for the two inequality constraint problems we considered, when we had y-1≥0, the green point in figure 3 was the solution. At this point, we were on the constraint plane (y-1=0). So, we actually had c(x)=0 and λ>0.
When we considered y-1≤0 on the other hand, the yellow point (x=0,y=0) in figure 4 became the local minima. This point was also the solution to the un-constrained problem. So, we simply had ∇f=0 here. Since the Lagrange condition requires ∇f = λ ∇c, we get λ ∇c = 0. Now, ∇c ≠0 at this point, which means we must have had: λ=0.
This means that if the constraint is active (c(x)=0), we should have λ≥0 while if it is not (c(x)≠ 0) we should have λ=0. So, one of them should be zero in all cases. This leads to the final condition (the complimentarity condition):
λ_j c_j(x) = 0 for all j ∈ Inequality; Eq(5)
Equations (1) through (5) are called the KKT conditions. Note that we haven’t really provided rigorous proofs for them, just constructing them based on the simple example. For a proof, the reader should refer to chapter 13 of the book by Nocedal and Wright.
A lot of people when they see these five equations feel like the problem has become even more complicated. How do these equations actually help us solve constrained optimization problems. The best way to get a feel for this is to go through some concrete examples. In the next section, we take a sample problem to which we know the answer in advance and see how the KKT conditions help us correctly identify all local optima.
Special cases of the generalized optimization problem involve a linear objective function and linear constraints. This is called a linearly constrained linear program (LCLP). The objective function and constraints can also be quadratic and an optimization problem like this is called a quadratically constrained quadratic program (QCQP). There are software packages that are capable of solving these kinds of optimization problems for an obscenely large number of constraints (in the millions). For simpler problems with a more manageable number of constraints however, we can leverage algorithms that can solve most (more general) polynomially constrained polynomial programs. Which means that the objective function and constraints can be arbitrary polynomial functions. This is because there is a general framework for solving systems of polynomial equations called “Buchberger’s algorithm” and the KKT conditions described above can be reduced to a system of polynomial equations. I wrote a detailed blog on Buchberger’s algorithm for solving systems of polynomial equations here. There is a python library called “sympy” that uses algorithms like this behind the scenes and solves general systems of polynomial equations. So without further ado, let’s frame our first constrained optimization problem.
Minimize: x3+y3Subject to: x2+y2=1
Notice that the constraint (x2+y2=1) implies we’re on the boundary of a circle with unit radius. So, we can say: x=cos(t), y=sin(t). The objective function then becomes: sin3(t)+cos3(t). If we plot this with t, we get the following graph:
We can see that t=0, π/2 and 5π/4 correspond to local maxima while t=π/4, π and 3π/2 correpond to local maxima. Now that we know the answer in advance, let’s see if the KKT conditions described above can find these as well.
Equation (1) gives (taking derivatives of objective function and constraint):
[3x2, 3y2] = λ[2x, 2y]
Equating the two components of the vectors on the two sides leads to the two equations:
3x2-2λx=0
3y2-2λy=0
Equation (2) simply requires that the equality constraint be satisfied:
x2+y2=1
And since there are no inequality constraints, we don’t need equations (3) to (6). Now, we can enter the three equations above into the symbolic equation solver the python library sympy provides.
This leads to the following result (all possible solutions to the system above with values of x, y and λ in that order):
[(-1, 0, -3/2), (0, -1, -3/2), (0, 1, 3/2), (1, 0, 3/2), (-sqrt(2)/2, -sqrt(2)/2, -3*sqrt(2)/4), (sqrt(2)/2, sqrt(2)/2, 3*sqrt(2)/4)]
(-1,0) corresponds to t=π; (0,-1) corresponds to t=3π/2; (-sqrt(2)/2,-sqrt(2)/2) corresponds to t=5π/4 and (sqrt(2)/2,sqrt(2)/2) corresponds to t=π/4. So, we can see that all the local maxima and local minima we identified above have been identified by the KKT conditions. Now, we can simply find the maximum and minimum values of the objective function at these candidate points.
Now, let’s change our equality constraint from the problem above to an inequality constraint and see how that changes our solution.
Minimize: x3+y3Subject to: x2+y2≤1
Where the constraint implied we could only be on the boundary of the unit circle in the previous case, we can now be anywhere inside it.
The full heat-map of the objective function within the constraint disk is plotted below (looks like a planet with a star somewhere around the top-right corner). The red arrows are the gradients of the boundary of the constraint while the black ones are the gradients of the objective function.
While the equality constrained problem was a one dimensional problem, this inequality constrained optimization problem is two dimensional. While there are only two ways to approach a point in one dimension (from left or right); there are an infinite number of ways to approach it in two dimensions. This means we need to beware of saddle points. These are points which qualify to be optima, but are not really optima since they are maxima when you approach them from one direction but minima when you approach them from another. The figure below shows what a saddle point looks like.
So, we need to re-evaluate all the points that were local minima or maxima in the case of the equality constraint and make sure none of them become saddle points.
Figure 5 tells us that t=0 (x=1,y=0) is a local maxima when approached along the boundary. And when we approach the point from inside the disk as well (say along the line joining x=0,y=0 to this point), the value of the objective function increases as we approach it. So, t=0 is a local maxima no matter where we approach it from. Using similar arguments (or noting the symmetry in x and y), so is t=π/2.
Similarly we can argue that t=π and t=3π/2 are local minima no matter where we approach them from inside the feasible region.
Looking at t=π/4 however, we note from figure 5 that approaching it along the boundary makes it a local minima. However, approaching it from inside the disk (along the line joining the origin to this point for example) makes it a local maxima. So, it is overall neither a local maxima nor a local minima. Such a point is called a saddle point. Using similar arguments, t=5π/4 is also a saddle point.
Now, let’s see what the KKT conditions say for our problem. Plugging the objective function and constraints into the KKT equations (1) through (5) we get:
To leverage polynomial equation solvers, we need to convert these to a system of polynomial equations. The first two conditions (6-(a) and (b))are already equations. The third one, x2+y2≤1 (6-(c)) is an inequality. But we can convert it into an equality by introducing a slack variable, k; x2+y2+k2=1. The last equation, λ≥0 is similarly an inequality, but we can do away with it if we simply replace λ with λ2. Now, we demonstrate how to enter these into the symbolic equation solving library python provides.
This produces the following result (the various solutions of the system above with variables x,y,λ,k in order):
[(-1, 0, -sqrt(6)/2, 0), (-1, 0, sqrt(6)/2, 0), (0, -1, -sqrt(6)/2, 0), (0, -1, sqrt(6)/2, 0), (0, 0, 0, -1), (0, 0, 0, 1), (0, 1, -sqrt(6)*I/2, 0), (0, 1, sqrt(6)*I/2, 0), (1, 0, -sqrt(6)*I/2, 0), (1, 0, sqrt(6)*I/2, 0), (-sqrt(2)/2, -sqrt(2)/2, -2**(1/4)*sqrt(3)/2, 0), (-sqrt(2)/2, -sqrt(2)/2, 2**(1/4)*sqrt(3)/2, 0), (sqrt(2)/2, sqrt(2)/2, -2**(1/4)*sqrt(3)*I/2, 0), (sqrt(2)/2, sqrt(2)/2, 2**(1/4)*sqrt(3)*I/2, 0)]
The capital ‘I’ in the solutions above refers to the square root of unity. We want to reject these solutions since we require λ2≥0. This means that the points that satisfy the KKT conditions are: (-1,0); (0,-1); (0,0); (-1/sqrt(2),-1/sqrt(2)). As mentioned earlier, the points (-1,0) (corresponding to t=π) and (0,-1) (corresponding to t=3π/2) are the minima. (0,0) and (-1/sqrt(2),-1/sqrt(2)) are saddle points that are also caught in the net. But note that none of the local maxima are caught. I’ll leave you with a small challenge. Change the code above so that it catches the maxima instead of the minima.
|
[
{
"code": null,
"e": 370,
"s": 172,
"text": "In this story, we’re going to take an aerial tour of optimization with Lagrange multipliers. When do we need them? Whenever we have an optimization problem with constraints. Here are some examples:"
},
{
"code": null,
"e": 1187,
"s": 370,
"text": "A hedge fund wants to decide the proportions of stocks to include in their portfolio such that they get the maximum possible expected return, staying within some risk appetite (the risk might be measured in terms of the variance of the return for example).A school district wants to determine an allocation for various items on their lunch menu for their students. They want to minimize the cost per lunch while making sure the kids get a certain quantity of all required nutrients.A trucking company wants to transport goods from source warehouses to destination cities. Given the costs of transport for each warehouse-city pair, the total supply at each warehouse and total demand at each city, decide how much to ship from each warehouse to each city so that overall cost is minimized and demand met (constraint)."
},
{
"code": null,
"e": 1444,
"s": 1187,
"text": "A hedge fund wants to decide the proportions of stocks to include in their portfolio such that they get the maximum possible expected return, staying within some risk appetite (the risk might be measured in terms of the variance of the return for example)."
},
{
"code": null,
"e": 1671,
"s": 1444,
"text": "A school district wants to determine an allocation for various items on their lunch menu for their students. They want to minimize the cost per lunch while making sure the kids get a certain quantity of all required nutrients."
},
{
"code": null,
"e": 2006,
"s": 1671,
"text": "A trucking company wants to transport goods from source warehouses to destination cities. Given the costs of transport for each warehouse-city pair, the total supply at each warehouse and total demand at each city, decide how much to ship from each warehouse to each city so that overall cost is minimized and demand met (constraint)."
},
{
"code": null,
"e": 2782,
"s": 2006,
"text": "We can see that constrained optimization can solve many practical, real world problems arising in domains from logistics to finance. In the rest of the blog, we will start with vanilla optimization without constraints. Then, we will add equality constraints. Then, we will describe the solution to completely general constrained optimization problem with both equality and inequality constraints (the conditions are called KKT — Karush, Kuhn, Tucker conditions). Finally, we demonstrate the power of these conditions on some toy problems. Many people consider the book by Nocedal and Wright the bible of numerical optimization and we will roughly follow chapter 13, side-stepping rigorous proofs (which can always be read from the text) and focusing more on visual intuition."
},
{
"code": null,
"e": 3104,
"s": 2782,
"text": "In this scenario, we have some variables in our control and an objective function that depends on them. There is no constraint on the variables and the objective function is to be minimized (if it were a maximization problem, we could simply negate the objective function and it would then become a minimization problem)."
},
{
"code": null,
"e": 3631,
"s": 3104,
"text": "At any point, for a one dimensional function, the derivative of the function points in a direction that increases it (at least for small steps). Meaning that if we have a function f(x) and the derivative f’(x) is positive, then increasing x will increase f(x) and decreasing it will decrease f(x). If we were minimizing f(x), we would just take a small step opposite to the sign of f’(x) to decrease f(x). What if we’re at a point where f’(x)=0? Then, we might have reached an optima of f(x) since there’s no where else to go."
},
{
"code": null,
"e": 3965,
"s": 3631,
"text": "If there are multiple variables (say x and y), we can have a derivative with each of them. If we take these two numbers and construct a 2-d vector from them, we get the gradient of the function. Now, moving along the direction of the gradient will increase the function while moving opposite to it will decrease it (for small steps)."
},
{
"code": null,
"e": 4304,
"s": 3965,
"text": "This means that as long as the gradient is non-zero, we can’t be at a minima since we can simply take a small step along the direction opposite to the gradient and decrease the function further. This means that a necessary (but not sufficient) condition for a point minimizing the function is that the gradient must be zero at that point."
},
{
"code": null,
"e": 5083,
"s": 4304,
"text": "Let’s take a concrete example so we can visualize what this looks like. Consider the function f(x,y) = x2+y2. This is a paraboloid and minimized when x=0 and y=0. The derivatives with respect to x and y become 2x and 2y respectively. So, the gradient becomes the vector ∇f = [2x,2y]. We can see that this is zero only when x=0 and y=0. Otherwise, the gradient points in a direction where f(x,y) will increase. So, the direction opposite the gradient will decrease f(x,y). This is shown in the figure below. The pink curve is the objective function f(x,y) which is minimized at the green point (0,0). The purple arrows are the gradients, which point in the direction where f(x,y) will increase. So to decrease it, we move in the opposite direction until we reach the green point."
},
{
"code": null,
"e": 5240,
"s": 5083,
"text": "To summarize, when optimizing a function, f in an unconstrained optimization problem, a necessary (but not sufficient) condition to be at a local optima is:"
},
{
"code": null,
"e": 5247,
"s": 5240,
"text": "∇f = 0"
},
{
"code": null,
"e": 5944,
"s": 5247,
"text": "It’s like when you’re at the top of a mountain (which would be a maxima). How do you know you’re at the top? No matter which direction you step along, you end up decreasing your altitude. So you’re definitely at an optima in your local neighborhood. Now, there might be another mountain right next to you which is even higher. So, you might not be at the global optima. In fact, if we consider the surface of the Earth as our domain (and height above sea level as our objective function), you’re at a local optima if you’re at the top of any old mountain (or building) but the global optima only if that mountain is Everest. In this article, we’re going to be content with finding a local optima."
},
{
"code": null,
"e": 6228,
"s": 5944,
"text": "Now what if we wanted to stay within the confines of a country? That would mean constraining the space in which we can search for our optima, making this an example of constrained optimization. In a way, un-constrained optimization is just a special case of constrained optimization."
},
{
"code": null,
"e": 7646,
"s": 6228,
"text": "For unconstrained minimization/maximization problems, we simply look for a point where the gradient is the zero vector. If the gradient is not zero, we just take a small step in the direction opposite to where it is pointing (if we’re minimizing; along it if we’re maximizing) and keep doing this until we do get to a point where it is zero and hence, there is no where else to go (this optimization method is called gradient descent). Note that we don’t have to move exactly along the gradient. As long as we move in a direction that has a positive projection (shadow) along the gradient, we end up increasing the objective function (and decreasing if we have a positive projection along the negative gradient). The figure below illustrates this. The green arrow is the gradient of the blue plane (and hence perpendicular to it) and the red arrow is the negative gradient. Since the light-blue arrows lie on the plane, the equation of the plane will yield 0 if we take a step along them. The yellow arrows have a positive shadow (projection) along the green one. So, moving along them will result in points that yield positive numbers when plugged into the equation of the plane (“increase” it). Similarly, the pink arrows have a positive shadow along the red one (reverse gradient). So, moving along them will result in points that yield negative numbers when plugged into the equation of the plane (“decrease” it)."
},
{
"code": null,
"e": 7837,
"s": 7646,
"text": "For un-constrained minimization, we looked for a point where the gradient was zero. This was because if it wasn’t, we could decrease the objective function by going opposite to the gradient."
},
{
"code": null,
"e": 8307,
"s": 7837,
"text": "The same idea can be extended to the case when we have equality constraints. Like before, we need to find a point where we can’t find any possible direction to move where the objective function decreases. For unconstrained optimization, this simply meant that no such direction exists. When we have a constraint, there is another possibility. What if a direction that decreases the objective function exists, but the constraints forbid us from taking any step along it."
},
{
"code": null,
"e": 8639,
"s": 8307,
"text": "Let’s say you want to maximize the amount of money in your bank account. One way to immediately boost your earnings is to sell a kidney. But you probably have a constraint saying you’re not going to lose a vital organ. So, even though an easy path to increasing your earnings exists, your constraint prevents you from accessing it."
},
{
"code": null,
"e": 9117,
"s": 8639,
"text": "This means that the presence of the equality constraint actually reduces the strictness of the condition on the gradient. While it needed to be zero for a local optima without the equality constraint, it’s now okay for it to be non-zero as long as moving in any direction that has a positive shadow along it causes us to violate the constraint. This can only happen when the plane of the constraint is perpendicular to the gradient (like the plane and green arrow in figure 2)."
},
{
"code": null,
"e": 10341,
"s": 9117,
"text": "Let’s go back to our objective function f(x,y)=x2+y2. Let’s add an equality constraint, y=1. This is a plane. In figure 3 below, the objective function is in pink and the plane is blue. Since we’re constrained to stay on the plane, we can’t move in any direction that has a positive or negative shadow along the gradient of the plane (blue arrows in the figure below) since that would increase or decrease the equation of the constraint, while we want to keep it constant. The plane intersects the equation of our objective function (pink paraboloid) in a curve which is a parabola. The pink arrows in the figure below are the gradients of the objective function at various points along this parabola. If the pink arrow has a projection along the blue plane, we can just move in the direction opposite to the vector corresponding to that projection. This will keep us on the plane, ensuring we don’t violate the constraint while still reducing the objective function. However, at the green point in figure 3 below, the pink arrow (gradient of objective function) has no projection whatsoever along the blue plane. In other words, the pink arrow is parallel to the blue arrow (which is the gradient of the constraint plane)."
},
{
"code": null,
"e": 11041,
"s": 10341,
"text": "To decrease the objective function, we need to move in a direction that has a shadow along the negative gradient. But as soon as we do that, we’ll end up leaving the plane of the constraint. So, the constraint makes it impossible to decrease the objective function further at the green point. This means it must be a local minima. An easy way to check this condition is to require that the pink gradient of the objective function is parallel to the blue gradient of the constraint plane. And if two vectors are parallel, we can write one as a multiple of the other. Let’s call this multiple λ. If the gradient of the objective function is ∇f and that of the constraint is ∇c, the condition above is:"
},
{
"code": null,
"e": 11051,
"s": 11041,
"text": "∇f = λ ∇c"
},
{
"code": null,
"e": 11221,
"s": 11051,
"text": "The λ above is called the Lagrange multiplier. So, we now have a concrete condition to check for when looking for the local optima of a constrained optimization problem."
},
{
"code": null,
"e": 11796,
"s": 11221,
"text": "Inequality constraints mean you have to stay on one side of a boundary defining a constraint function as opposed to on it (which was the case for equality constraints). For example, staying inside the boundary of a fence. If we know how to deal with inequality constraints, we can solve any constrained optimization problem. This is because equality constraints can be converted to inequality constraints. Let’s say we require: c(x) = 0. Another way to express this is: c(x)≥0 and c(x)≤ 0. So, each equality constraint can always be replaced with two inequality constraints."
},
{
"code": null,
"e": 12587,
"s": 11796,
"text": "Just as constrained optimization with equality constraints can be handled with Lagrange multipliers as described in the previous section, so can constrained optimization with inequality constraints. What sets the inequality constraint conditions apart from equality constraints is that the Lagrange multipliers for inequality constraints must be positive. To see why, again consider taking a small step in a direction that has a positive component along the gradient. If we can take a step along this direction (if we are maximizing; opposite to it if we are minimizing); we can’t be at a maxima/minima. For inequality constraints, this translates to the Lagrange multiplier being positive. To see why, let’s go back to the constrained optimization problem we considered earlier (figure 3)."
},
{
"code": null,
"e": 12612,
"s": 12587,
"text": "Minimize: f(x,y) = x2+y2"
},
{
"code": null,
"e": 12637,
"s": 12612,
"text": "Subject to: c(x,y)=y-1=0"
},
{
"code": null,
"e": 12781,
"s": 12637,
"text": "Now, let’s change the equality constraint to inequality. This can be done in two ways with completely different results. We can either require:"
},
{
"code": null,
"e": 13139,
"s": 12781,
"text": "c(x,y) = y-1 ≥0. In this case, the constraint allows for anything in front of the blue plane in figure 3. It is easy to see that the green point in figure 3 continues to be a local optima. Also, since the blue arrow representing the constraints gradient and the pink arrow representing the objective function’s gradient point in the same direction, we have:"
},
{
"code": null,
"e": 13149,
"s": 13139,
"text": "∇f = λ ∇c"
},
{
"code": null,
"e": 13159,
"s": 13149,
"text": "with λ>0."
},
{
"code": null,
"e": 13348,
"s": 13159,
"text": "The other possibility is, c(x,y) = y-1≤0. Now, the feasible region becomes everything behind the blue plane. The constraint gradients will flip. So, figure 3 will end up looking like this:"
},
{
"code": null,
"e": 13363,
"s": 13348,
"text": "Note that now,"
},
{
"code": null,
"e": 13602,
"s": 13363,
"text": "The green point is no longer the local optima since we’re free to move to (0,0); which is the yellow point in figure 4 above.At the green point, we still have ∇f=λ ∇c. since the blue vector points opposite to the pink vector, we have λ<0."
},
{
"code": null,
"e": 13728,
"s": 13602,
"text": "The green point is no longer the local optima since we’re free to move to (0,0); which is the yellow point in figure 4 above."
},
{
"code": null,
"e": 13842,
"s": 13728,
"text": "At the green point, we still have ∇f=λ ∇c. since the blue vector points opposite to the pink vector, we have λ<0."
},
{
"code": null,
"e": 13964,
"s": 13842,
"text": "So, it is clear that for an inequality constraint, the condition ∇f=λ ∇c indicates we’re at a local optima only when λ>0."
},
{
"code": null,
"e": 14030,
"s": 13964,
"text": "Putting all of this together, for a general optimization problem:"
},
{
"code": null,
"e": 14044,
"s": 14030,
"text": "Minimize f(x)"
},
{
"code": null,
"e": 14056,
"s": 14044,
"text": "Subject to:"
},
{
"code": null,
"e": 14083,
"s": 14056,
"text": "c_i(x) =0 for i ∈ Equality"
},
{
"code": null,
"e": 14111,
"s": 14083,
"text": "c_i(x)≥0 for i ∈ Inequality"
},
{
"code": null,
"e": 14181,
"s": 14111,
"text": "We get the full suite of conditions required to be at a local optima:"
},
{
"code": null,
"e": 14212,
"s": 14181,
"text": "Lagrange multiplier condition:"
},
{
"code": null,
"e": 14256,
"s": 14212,
"text": "∇f =∑_i λ_i ∇c_i(x) +∑_j λ_j ∇c_j(x); Eq(1)"
},
{
"code": null,
"e": 14307,
"s": 14256,
"text": "Where i ∈ Equality and j ∈ Inequality constraints."
},
{
"code": null,
"e": 14333,
"s": 14307,
"text": "c_i(x)=0 for all i; Eq(2)"
},
{
"code": null,
"e": 14359,
"s": 14333,
"text": "c_j(x)≥0 for all j; Eq(3)"
},
{
"code": null,
"e": 14374,
"s": 14359,
"text": "λ_j ≥ 0; Eq(4)"
},
{
"code": null,
"e": 14604,
"s": 14374,
"text": "Also note that for the two inequality constraint problems we considered, when we had y-1≥0, the green point in figure 3 was the solution. At this point, we were on the constraint plane (y-1=0). So, we actually had c(x)=0 and λ>0."
},
{
"code": null,
"e": 14933,
"s": 14604,
"text": "When we considered y-1≤0 on the other hand, the yellow point (x=0,y=0) in figure 4 became the local minima. This point was also the solution to the un-constrained problem. So, we simply had ∇f=0 here. Since the Lagrange condition requires ∇f = λ ∇c, we get λ ∇c = 0. Now, ∇c ≠0 at this point, which means we must have had: λ=0."
},
{
"code": null,
"e": 15168,
"s": 14933,
"text": "This means that if the constraint is active (c(x)=0), we should have λ≥0 while if it is not (c(x)≠ 0) we should have λ=0. So, one of them should be zero in all cases. This leads to the final condition (the complimentarity condition):"
},
{
"code": null,
"e": 15213,
"s": 15168,
"text": "λ_j c_j(x) = 0 for all j ∈ Inequality; Eq(5)"
},
{
"code": null,
"e": 15471,
"s": 15213,
"text": "Equations (1) through (5) are called the KKT conditions. Note that we haven’t really provided rigorous proofs for them, just constructing them based on the simple example. For a proof, the reader should refer to chapter 13 of the book by Nocedal and Wright."
},
{
"code": null,
"e": 15897,
"s": 15471,
"text": "A lot of people when they see these five equations feel like the problem has become even more complicated. How do these equations actually help us solve constrained optimization problems. The best way to get a feel for this is to go through some concrete examples. In the next section, we take a sample problem to which we know the answer in advance and see how the KKT conditions help us correctly identify all local optima."
},
{
"code": null,
"e": 17204,
"s": 15897,
"text": "Special cases of the generalized optimization problem involve a linear objective function and linear constraints. This is called a linearly constrained linear program (LCLP). The objective function and constraints can also be quadratic and an optimization problem like this is called a quadratically constrained quadratic program (QCQP). There are software packages that are capable of solving these kinds of optimization problems for an obscenely large number of constraints (in the millions). For simpler problems with a more manageable number of constraints however, we can leverage algorithms that can solve most (more general) polynomially constrained polynomial programs. Which means that the objective function and constraints can be arbitrary polynomial functions. This is because there is a general framework for solving systems of polynomial equations called “Buchberger’s algorithm” and the KKT conditions described above can be reduced to a system of polynomial equations. I wrote a detailed blog on Buchberger’s algorithm for solving systems of polynomial equations here. There is a python library called “sympy” that uses algorithms like this behind the scenes and solves general systems of polynomial equations. So without further ado, let’s frame our first constrained optimization problem."
},
{
"code": null,
"e": 17239,
"s": 17204,
"text": "Minimize: x3+y3Subject to: x2+y2=1"
},
{
"code": null,
"e": 17478,
"s": 17239,
"text": "Notice that the constraint (x2+y2=1) implies we’re on the boundary of a circle with unit radius. So, we can say: x=cos(t), y=sin(t). The objective function then becomes: sin3(t)+cos3(t). If we plot this with t, we get the following graph:"
},
{
"code": null,
"e": 17702,
"s": 17478,
"text": "We can see that t=0, π/2 and 5π/4 correspond to local maxima while t=π/4, π and 3π/2 correpond to local maxima. Now that we know the answer in advance, let’s see if the KKT conditions described above can find these as well."
},
{
"code": null,
"e": 17780,
"s": 17702,
"text": "Equation (1) gives (taking derivatives of objective function and constraint):"
},
{
"code": null,
"e": 17803,
"s": 17780,
"text": "[3x2, 3y2] = λ[2x, 2y]"
},
{
"code": null,
"e": 17891,
"s": 17803,
"text": "Equating the two components of the vectors on the two sides leads to the two equations:"
},
{
"code": null,
"e": 17901,
"s": 17891,
"text": "3x2-2λx=0"
},
{
"code": null,
"e": 17911,
"s": 17901,
"text": "3y2-2λy=0"
},
{
"code": null,
"e": 17983,
"s": 17911,
"text": "Equation (2) simply requires that the equality constraint be satisfied:"
},
{
"code": null,
"e": 17991,
"s": 17983,
"text": "x2+y2=1"
},
{
"code": null,
"e": 18187,
"s": 17991,
"text": "And since there are no inequality constraints, we don’t need equations (3) to (6). Now, we can enter the three equations above into the symbolic equation solver the python library sympy provides."
},
{
"code": null,
"e": 18308,
"s": 18187,
"text": "This leads to the following result (all possible solutions to the system above with values of x, y and λ in that order):"
},
{
"code": null,
"e": 18442,
"s": 18308,
"text": "[(-1, 0, -3/2), (0, -1, -3/2), (0, 1, 3/2), (1, 0, 3/2), (-sqrt(2)/2, -sqrt(2)/2, -3*sqrt(2)/4), (sqrt(2)/2, sqrt(2)/2, 3*sqrt(2)/4)]"
},
{
"code": null,
"e": 18823,
"s": 18442,
"text": "(-1,0) corresponds to t=π; (0,-1) corresponds to t=3π/2; (-sqrt(2)/2,-sqrt(2)/2) corresponds to t=5π/4 and (sqrt(2)/2,sqrt(2)/2) corresponds to t=π/4. So, we can see that all the local maxima and local minima we identified above have been identified by the KKT conditions. Now, we can simply find the maximum and minimum values of the objective function at these candidate points."
},
{
"code": null,
"e": 18955,
"s": 18823,
"text": "Now, let’s change our equality constraint from the problem above to an inequality constraint and see how that changes our solution."
},
{
"code": null,
"e": 18990,
"s": 18955,
"text": "Minimize: x3+y3Subject to: x2+y2≤1"
},
{
"code": null,
"e": 19127,
"s": 18990,
"text": "Where the constraint implied we could only be on the boundary of the unit circle in the previous case, we can now be anywhere inside it."
},
{
"code": null,
"e": 19421,
"s": 19127,
"text": "The full heat-map of the objective function within the constraint disk is plotted below (looks like a planet with a star somewhere around the top-right corner). The red arrows are the gradients of the boundary of the constraint while the black ones are the gradients of the objective function."
},
{
"code": null,
"e": 20005,
"s": 19421,
"text": "While the equality constrained problem was a one dimensional problem, this inequality constrained optimization problem is two dimensional. While there are only two ways to approach a point in one dimension (from left or right); there are an infinite number of ways to approach it in two dimensions. This means we need to beware of saddle points. These are points which qualify to be optima, but are not really optima since they are maxima when you approach them from one direction but minima when you approach them from another. The figure below shows what a saddle point looks like."
},
{
"code": null,
"e": 20168,
"s": 20005,
"text": "So, we need to re-evaluate all the points that were local minima or maxima in the case of the equality constraint and make sure none of them become saddle points."
},
{
"code": null,
"e": 20573,
"s": 20168,
"text": "Figure 5 tells us that t=0 (x=1,y=0) is a local maxima when approached along the boundary. And when we approach the point from inside the disk as well (say along the line joining x=0,y=0 to this point), the value of the objective function increases as we approach it. So, t=0 is a local maxima no matter where we approach it from. Using similar arguments (or noting the symmetry in x and y), so is t=π/2."
},
{
"code": null,
"e": 20699,
"s": 20573,
"text": "Similarly we can argue that t=π and t=3π/2 are local minima no matter where we approach them from inside the feasible region."
},
{
"code": null,
"e": 21099,
"s": 20699,
"text": "Looking at t=π/4 however, we note from figure 5 that approaching it along the boundary makes it a local minima. However, approaching it from inside the disk (along the line joining the origin to this point for example) makes it a local maxima. So, it is overall neither a local maxima nor a local minima. Such a point is called a saddle point. Using similar arguments, t=5π/4 is also a saddle point."
},
{
"code": null,
"e": 21254,
"s": 21099,
"text": "Now, let’s see what the KKT conditions say for our problem. Plugging the objective function and constraints into the KKT equations (1) through (5) we get:"
},
{
"code": null,
"e": 21765,
"s": 21254,
"text": "To leverage polynomial equation solvers, we need to convert these to a system of polynomial equations. The first two conditions (6-(a) and (b))are already equations. The third one, x2+y2≤1 (6-(c)) is an inequality. But we can convert it into an equality by introducing a slack variable, k; x2+y2+k2=1. The last equation, λ≥0 is similarly an inequality, but we can do away with it if we simply replace λ with λ2. Now, we demonstrate how to enter these into the symbolic equation solving library python provides."
},
{
"code": null,
"e": 21877,
"s": 21765,
"text": "This produces the following result (the various solutions of the system above with variables x,y,λ,k in order):"
},
{
"code": null,
"e": 22297,
"s": 21877,
"text": "[(-1, 0, -sqrt(6)/2, 0), (-1, 0, sqrt(6)/2, 0), (0, -1, -sqrt(6)/2, 0), (0, -1, sqrt(6)/2, 0), (0, 0, 0, -1), (0, 0, 0, 1), (0, 1, -sqrt(6)*I/2, 0), (0, 1, sqrt(6)*I/2, 0), (1, 0, -sqrt(6)*I/2, 0), (1, 0, sqrt(6)*I/2, 0), (-sqrt(2)/2, -sqrt(2)/2, -2**(1/4)*sqrt(3)/2, 0), (-sqrt(2)/2, -sqrt(2)/2, 2**(1/4)*sqrt(3)/2, 0), (sqrt(2)/2, sqrt(2)/2, -2**(1/4)*sqrt(3)*I/2, 0), (sqrt(2)/2, sqrt(2)/2, 2**(1/4)*sqrt(3)*I/2, 0)]"
}
] |
In MySQL, what is the difference between SERIAL and AUTO_INCREMENT?
|
In MySQL, both SERIAL and AUTO_INCREMENT are used to define a sequence as a default value for a field. But they are technically different from each other.
The AUTO_INCREMENT attribute is supported by all numeric data types except for BIT and DECIMAL. There can only be one AUTO_INCREMENT field per table and the sequence generated by an AUTO_INCREMENT field in one table cannot be used in any other table.
This attribute requires that a UNIQUE index exists on the field to ensure the sequence has no duplicates. The sequence would start by default from 1 and increment by 1 for every insert.
mysql> Create Table Student(Student_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.18 sec)
The query above declares Student_id AUTO_INCREMENT.
mysql> Insert Into Student(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> Select * from Student;
+------------+-------+
| Student_id | Name |
+------------+-------+
| 1 | RAM |
| 2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)
mysql> Show Create Table Student\G
*************************** 1. row ***************************
Table: Student
Create Table: CREATE TABLE `student` (
`Student_id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
On the other hand, SERIAL DEFAULT VALUE is shorthand for NOT NULL AUTO_INCREMENT UNIQUE KEY. The interger numeric type like TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT supports the SERIAL DEFAULT VALUE keyword.
mysql> Create Table Student_serial(Student_id SERIAL, Name VArchar(20));
Query OK, 0 rows affected (0.17 sec)
mysql> Insert into Student_serial(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> Select * from Student_serial;
+------------+-------+
| Student_id | Name |
+------------+-------+
| 1 | RAM |
| 2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)
mysql> Show Create Table Student_serial\G
*************************** 1. row ***************************
Table: Student_serial
Create Table: CREATE TABLE `student_serial` (
`Student_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(20) DEFAULT NULL,
UNIQUE KEY `Student_id` (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "In MySQL, both SERIAL and AUTO_INCREMENT are used to define a sequence as a default value for a field. But they are technically different from each other."
},
{
"code": null,
"e": 1469,
"s": 1217,
"text": "The AUTO_INCREMENT attribute is supported by all numeric data types except for BIT and DECIMAL. There can only be one AUTO_INCREMENT field per table and the sequence generated by an AUTO_INCREMENT field in one table cannot be used in any other table. "
},
{
"code": null,
"e": 1655,
"s": 1469,
"text": "This attribute requires that a UNIQUE index exists on the field to ensure the sequence has no duplicates. The sequence would start by default from 1 and increment by 1 for every insert."
},
{
"code": null,
"e": 1791,
"s": 1655,
"text": "mysql> Create Table Student(Student_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 1843,
"s": 1791,
"text": "The query above declares Student_id AUTO_INCREMENT."
},
{
"code": null,
"e": 2523,
"s": 1843,
"text": "mysql> Insert Into Student(Name) values('RAM'),('SHYAM');\nQuery OK, 2 rows affected (0.06 sec)\nRecords: 2 Duplicates: 0 Warnings: 0\n\nmysql> Select * from Student;\n+------------+-------+\n| Student_id | Name |\n+------------+-------+\n| 1 | RAM |\n| 2 | SHYAM |\n+------------+-------+\n2 rows in set (0.00 sec)\n\nmysql> Show Create Table Student\\G\n*************************** 1. row ***************************\n Table: Student\nCreate Table: CREATE TABLE `student` (\n `Student_id` int(11) NOT NULL AUTO_INCREMENT,\n `Name` varchar(20) DEFAULT NULL,\n PRIMARY KEY (`Student_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2736,
"s": 2523,
"text": "On the other hand, SERIAL DEFAULT VALUE is shorthand for NOT NULL AUTO_INCREMENT UNIQUE KEY. The interger numeric type like TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT supports the SERIAL DEFAULT VALUE keyword."
},
{
"code": null,
"e": 3585,
"s": 2736,
"text": "mysql> Create Table Student_serial(Student_id SERIAL, Name VArchar(20));\nQuery OK, 0 rows affected (0.17 sec)\n\nmysql> Insert into Student_serial(Name) values('RAM'),('SHYAM');\nQuery OK, 2 rows affected (0.12 sec)\nRecords: 2 Duplicates: 0 Warnings: 0\n\nmysql> Select * from Student_serial;\n+------------+-------+\n| Student_id | Name |\n+------------+-------+\n| 1 | RAM |\n| 2 | SHYAM |\n+------------+-------+\n2 rows in set (0.00 sec)\n\nmysql> Show Create Table Student_serial\\G\n*************************** 1. row ***************************\n Table: Student_serial\nCreate Table: CREATE TABLE `student_serial` (\n `Student_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n `Name` varchar(20) DEFAULT NULL,\n UNIQUE KEY `Student_id` (`Student_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1\n1 row in set (0.00 sec)"
}
] |
TIQ Part 1 — How to destroy your Power BI model with Auto Date/Time | by Nikola Ilic | Towards Data Science
|
TIQ stands for Time Intelligence Quotient. As “regular” intelligence is usually being measured as IQ, and Time Intelligence is one of the most important topics in data modeling, I decided to start a blog series which will introduce some basic concepts, pros and cons of specific solutions and potential pitfalls to avoid, everything in order to increase your overall TIQ and make your models more robust, scalable and flexible in terms of time analysis
If you ever performed any kind of data analysis, you should definitely know that analyzing numbers within different time periods, identifying trends over time, or evaluating various KPIs depending on the point in time when the specific events happened, is “bread and crumb” of every single BI project.
You can sneak without knowing details about customers, geography, products (sure it’s highly recommendable to use also these dimensions), but without knowing what is happening in general over time, your overall analysis will suffer.
Therefore, I sincerely consider Date dimension as “Majesty” — in my opinion, that is the most important dimension in the whole data model!
When I recently wrote about creating a custom Date dimension, I promised that I will dedicate a separate article and explain Time intelligence in more depth.
So, this is the first post in the series on Time Intelligence topic.
Because of its importance, I will try to offer a comprehensive overview of the Date dimension, obvious benefits it offers, and potential pitfalls when (not) being used properly in Power BI.
The answer is simple — sure, you can! But, you shouldn’t. If you are not using the Date dimension in your data model, Power BI will not let you down. On the contrary, it will “assist” you, by automatically creating date hierarchies on every single date column you have in your model!
Wow, that sounds awesome at first! Why should I waste my time building a separate Date dimension, when Power BI can do this for me? Stay tuned and you will soon find out why that’s not the outcome you are aiming for.
When you open a new Power BI file, under the File tab, choose Options and Settings and then Options. On the left, under Global, you will see the Time intelligence option.
If you check the option for Auto date/time for new files, every time you open a new Power BI file, Power BI will handle dates on its own.
Another place that you can set this up is under Current File on the left, then Data Load.
Let me briefly explain what is happening in the background when you check this option: Power BI will create a date hierarchy consisting of Year, Quarter, Month, and Date so that you can slice and dice data on these four levels of granularity.
I am using the Stack Overflow database for demo purposes since it is large enough to notice the behavior of our data model when auto date-time is enabled. The report itself is quite simple, containing two Cards which display a number of rows in two tables of our model:
Now, when you look in the Fields pane, you will notice that every column of date type is displayed as a hierarchy. Therefore, I can use one of these hierarchies to slice and dice data:
“What’s wrong with that ?”, you will ask a legitimate question. I’m getting solution out-of-the-box, without need to code something, import something, extending data model, etc.
Before I continue, let’s first see what is going on in the background when I try to use our “Date” dimension for calculating a simple measure of Total Year-to-Date number of Posts in Stack Overflow database:
If you take a look at the DAX code which was automatically created, you will notice unusual column reference for our CreationDate date column:
Count Posts YTD = IF( ISFILTERED('Posts'[CreationDate]), ERROR("Time intelligence quick measures can only be grouped or filtered by the Power BI-provided date hierarchy or primary date column."), TOTALYTD([Count Posts], 'Posts'[CreationDate].[Date]))
This means that Power BI points to a specific member of automatically created hierarchy (in our case .[Date], but it could also be .[Year], .[Quarter] or .[Month]).
Still, the calculation is here and everything looks fine. However, what if I want to enable my users to slice data per different dates? Or, if the users request to analyze data per week? Fiscal year? Day of the week?
Nothing from these would be possible using our auto date dimension! So, forget about flexibility, you get Year, Quarter, Month and Date and that’s it. Don’t get me wrong, this is quite fine for let’s say 80% of analysis, but what should we do with the rest?
For example, what if I wanted to compare data based on CreationDate and LastActivityDate over time and I wish to have a slicer to perform my analysis more conveniently.
As you notice, it’s not possible to satisfy this request with only one slicer. We would need two slicers, separate one for each date hierarchy. Now, imagine that we want to slice data based on four or five different dates. And not to say how ugly, counter-intuitive and complex becomes your report if you apply this strategy.
We can’t extend our date dimension with new attributes and that is the biggest limitation of this approach.
To get a feeling of what is going on under the hood, I will demonstrate what Power BI needs to do in order to handle this. For every single date column (in our case in Posts table, we have 5 of them: ClosedDate, CommunityOwnedDate, CreationDate, LastActivityDate, and LastEditDate), Power BI created a SEPARATE date table!
You don’t believe it? Just follow me...
When you go to Model view, no tables are there. So where are they (if they exist at all)?
The trick is that these tables are hidden by default and can’t be seen within the Power BI model, as described in this Microsoft article.
Therefore, let’s launch DAX Studio to support us in our search for these local date tables. For those of you who are not yet familiar with DAX Studio, I strongly recommend trying it — it has a whole bunch of handy features, and the most important thing, it’s free!
I’ve connected to my PBIX file and look:
On the left side, under Model, you will see a whole bunch of Date tables!!! Who created them? I didn’t, as you saw earlier. These are all automatically created date tables, which Power BI created behind the scenes to enable time intelligence calculations.
No need to say that those tables are part of your data model, even if you didn’t create them intentionally. The bigger the table with date columns, the bigger the whole model becomes.
I saw multiple examples when the data model simply bloated because of many auto date tables.
So, after reading all these negative stuff on Auto Date/Time feature, one could understandably ask a question:
Well, there is no official explanation from Microsoft, but I assume that the rationale behind this decision is that Power BI is being promoted as a self-service BI tool.
Let’s not forget that there are a lot of people out there who are not familiar with dimensional modeling concepts at all, let alone creating proper date dimensions by writing DAX or M code or using existing SQL date dimensions from Data Warehouse. And they need Power BI, they use Power BI.
For whatever reason Auto Date/Time is part of Power BI, just simply don’t use it.
In the next part of the TIQ series, I will write about possible solutions on how to handle the Date dimension in a proper way. So, stay tuned!
|
[
{
"code": null,
"e": 625,
"s": 172,
"text": "TIQ stands for Time Intelligence Quotient. As “regular” intelligence is usually being measured as IQ, and Time Intelligence is one of the most important topics in data modeling, I decided to start a blog series which will introduce some basic concepts, pros and cons of specific solutions and potential pitfalls to avoid, everything in order to increase your overall TIQ and make your models more robust, scalable and flexible in terms of time analysis"
},
{
"code": null,
"e": 927,
"s": 625,
"text": "If you ever performed any kind of data analysis, you should definitely know that analyzing numbers within different time periods, identifying trends over time, or evaluating various KPIs depending on the point in time when the specific events happened, is “bread and crumb” of every single BI project."
},
{
"code": null,
"e": 1160,
"s": 927,
"text": "You can sneak without knowing details about customers, geography, products (sure it’s highly recommendable to use also these dimensions), but without knowing what is happening in general over time, your overall analysis will suffer."
},
{
"code": null,
"e": 1299,
"s": 1160,
"text": "Therefore, I sincerely consider Date dimension as “Majesty” — in my opinion, that is the most important dimension in the whole data model!"
},
{
"code": null,
"e": 1457,
"s": 1299,
"text": "When I recently wrote about creating a custom Date dimension, I promised that I will dedicate a separate article and explain Time intelligence in more depth."
},
{
"code": null,
"e": 1526,
"s": 1457,
"text": "So, this is the first post in the series on Time Intelligence topic."
},
{
"code": null,
"e": 1716,
"s": 1526,
"text": "Because of its importance, I will try to offer a comprehensive overview of the Date dimension, obvious benefits it offers, and potential pitfalls when (not) being used properly in Power BI."
},
{
"code": null,
"e": 2000,
"s": 1716,
"text": "The answer is simple — sure, you can! But, you shouldn’t. If you are not using the Date dimension in your data model, Power BI will not let you down. On the contrary, it will “assist” you, by automatically creating date hierarchies on every single date column you have in your model!"
},
{
"code": null,
"e": 2217,
"s": 2000,
"text": "Wow, that sounds awesome at first! Why should I waste my time building a separate Date dimension, when Power BI can do this for me? Stay tuned and you will soon find out why that’s not the outcome you are aiming for."
},
{
"code": null,
"e": 2388,
"s": 2217,
"text": "When you open a new Power BI file, under the File tab, choose Options and Settings and then Options. On the left, under Global, you will see the Time intelligence option."
},
{
"code": null,
"e": 2526,
"s": 2388,
"text": "If you check the option for Auto date/time for new files, every time you open a new Power BI file, Power BI will handle dates on its own."
},
{
"code": null,
"e": 2616,
"s": 2526,
"text": "Another place that you can set this up is under Current File on the left, then Data Load."
},
{
"code": null,
"e": 2859,
"s": 2616,
"text": "Let me briefly explain what is happening in the background when you check this option: Power BI will create a date hierarchy consisting of Year, Quarter, Month, and Date so that you can slice and dice data on these four levels of granularity."
},
{
"code": null,
"e": 3129,
"s": 2859,
"text": "I am using the Stack Overflow database for demo purposes since it is large enough to notice the behavior of our data model when auto date-time is enabled. The report itself is quite simple, containing two Cards which display a number of rows in two tables of our model:"
},
{
"code": null,
"e": 3314,
"s": 3129,
"text": "Now, when you look in the Fields pane, you will notice that every column of date type is displayed as a hierarchy. Therefore, I can use one of these hierarchies to slice and dice data:"
},
{
"code": null,
"e": 3492,
"s": 3314,
"text": "“What’s wrong with that ?”, you will ask a legitimate question. I’m getting solution out-of-the-box, without need to code something, import something, extending data model, etc."
},
{
"code": null,
"e": 3700,
"s": 3492,
"text": "Before I continue, let’s first see what is going on in the background when I try to use our “Date” dimension for calculating a simple measure of Total Year-to-Date number of Posts in Stack Overflow database:"
},
{
"code": null,
"e": 3843,
"s": 3700,
"text": "If you take a look at the DAX code which was automatically created, you will notice unusual column reference for our CreationDate date column:"
},
{
"code": null,
"e": 4103,
"s": 3843,
"text": "Count Posts YTD = IF( ISFILTERED('Posts'[CreationDate]), ERROR(\"Time intelligence quick measures can only be grouped or filtered by the Power BI-provided date hierarchy or primary date column.\"), TOTALYTD([Count Posts], 'Posts'[CreationDate].[Date]))"
},
{
"code": null,
"e": 4268,
"s": 4103,
"text": "This means that Power BI points to a specific member of automatically created hierarchy (in our case .[Date], but it could also be .[Year], .[Quarter] or .[Month])."
},
{
"code": null,
"e": 4485,
"s": 4268,
"text": "Still, the calculation is here and everything looks fine. However, what if I want to enable my users to slice data per different dates? Or, if the users request to analyze data per week? Fiscal year? Day of the week?"
},
{
"code": null,
"e": 4743,
"s": 4485,
"text": "Nothing from these would be possible using our auto date dimension! So, forget about flexibility, you get Year, Quarter, Month and Date and that’s it. Don’t get me wrong, this is quite fine for let’s say 80% of analysis, but what should we do with the rest?"
},
{
"code": null,
"e": 4912,
"s": 4743,
"text": "For example, what if I wanted to compare data based on CreationDate and LastActivityDate over time and I wish to have a slicer to perform my analysis more conveniently."
},
{
"code": null,
"e": 5238,
"s": 4912,
"text": "As you notice, it’s not possible to satisfy this request with only one slicer. We would need two slicers, separate one for each date hierarchy. Now, imagine that we want to slice data based on four or five different dates. And not to say how ugly, counter-intuitive and complex becomes your report if you apply this strategy."
},
{
"code": null,
"e": 5346,
"s": 5238,
"text": "We can’t extend our date dimension with new attributes and that is the biggest limitation of this approach."
},
{
"code": null,
"e": 5669,
"s": 5346,
"text": "To get a feeling of what is going on under the hood, I will demonstrate what Power BI needs to do in order to handle this. For every single date column (in our case in Posts table, we have 5 of them: ClosedDate, CommunityOwnedDate, CreationDate, LastActivityDate, and LastEditDate), Power BI created a SEPARATE date table!"
},
{
"code": null,
"e": 5709,
"s": 5669,
"text": "You don’t believe it? Just follow me..."
},
{
"code": null,
"e": 5799,
"s": 5709,
"text": "When you go to Model view, no tables are there. So where are they (if they exist at all)?"
},
{
"code": null,
"e": 5937,
"s": 5799,
"text": "The trick is that these tables are hidden by default and can’t be seen within the Power BI model, as described in this Microsoft article."
},
{
"code": null,
"e": 6202,
"s": 5937,
"text": "Therefore, let’s launch DAX Studio to support us in our search for these local date tables. For those of you who are not yet familiar with DAX Studio, I strongly recommend trying it — it has a whole bunch of handy features, and the most important thing, it’s free!"
},
{
"code": null,
"e": 6243,
"s": 6202,
"text": "I’ve connected to my PBIX file and look:"
},
{
"code": null,
"e": 6499,
"s": 6243,
"text": "On the left side, under Model, you will see a whole bunch of Date tables!!! Who created them? I didn’t, as you saw earlier. These are all automatically created date tables, which Power BI created behind the scenes to enable time intelligence calculations."
},
{
"code": null,
"e": 6683,
"s": 6499,
"text": "No need to say that those tables are part of your data model, even if you didn’t create them intentionally. The bigger the table with date columns, the bigger the whole model becomes."
},
{
"code": null,
"e": 6776,
"s": 6683,
"text": "I saw multiple examples when the data model simply bloated because of many auto date tables."
},
{
"code": null,
"e": 6887,
"s": 6776,
"text": "So, after reading all these negative stuff on Auto Date/Time feature, one could understandably ask a question:"
},
{
"code": null,
"e": 7057,
"s": 6887,
"text": "Well, there is no official explanation from Microsoft, but I assume that the rationale behind this decision is that Power BI is being promoted as a self-service BI tool."
},
{
"code": null,
"e": 7348,
"s": 7057,
"text": "Let’s not forget that there are a lot of people out there who are not familiar with dimensional modeling concepts at all, let alone creating proper date dimensions by writing DAX or M code or using existing SQL date dimensions from Data Warehouse. And they need Power BI, they use Power BI."
},
{
"code": null,
"e": 7430,
"s": 7348,
"text": "For whatever reason Auto Date/Time is part of Power BI, just simply don’t use it."
}
] |
Angular 4 - Examples
|
In this chapter, we will discuss a few examples related to Angular 4.
To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components - header, footer, userlogin and mainpage.
The components are created using the following command −
C:\ngexamples\aexamples>ng g component header
installing component
create src\app\header\header.component.css
create src\app\header\header.component.html
create src\app\header\header.component.spec.ts
create src\app\header\header.component.ts
update src\app\app.module.ts
C:\ngexamples\aexamples>ng g component footer
installing component
create src\app\footer\footer.component.css
create src\app\footer\footer.component.html
create src\app\footer\footer.component.spec.ts
create src\app\footer\footer.component.ts
update src\app\app.module.ts
C:\ngexamples\aexamples>ng g component userlogin
installing component
create src\app\userlogin\userlogin.component.css
create src\app\userlogin\userlogin.component.html
create src\app\userlogin\userlogin.component.spec.ts
create src\app\userlogin\userlogin.component.ts
update src\app\app.module.ts
C:\ngexamples\aexamples>ng g component mainpage
installing component
create src\app\mainpage\mainpage.component.css
create src\app\mainpage\mainpage.component.html
create src\app\mainpage\mainpage.component.spec.ts
create src\app\mainpage\mainpage.component.ts
update src\app\app.module.ts
In the app.module.ts, the parent module has all the components added when created. The file looks as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes} froms '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MdTableModule} from '@angular/material';
import {HttpModule} from "@angular/http";
import {MdInputModule} from '@angular/material';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { UserloginComponent } from './userlogin/userlogin.component';
import { MainpageComponent } from './mainpage/mainpage.component';
const appRoutes: Routes = [
{
path: '',
component: UserloginComponent
},
{
path: 'app-mainpage',
component: MainpageComponent
}
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
UserloginComponent,
MainpageComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot(appRoutes),
BrowserAnimationsModule,
HttpModule,
MdTableModule,
MdInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The components created above are added −
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { UserloginComponent } from './userlogin/userlogin.component';
import { MainpageComponent } from './mainpage/mainpage.component';
The components are added in the declarations too −
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
UserloginComponent,
MainpageComponent
],
In the parent app.component.html, we have added the main structure of the file that will be seen by the user.
<div class="mainpage">
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
</div>
We have created a div and added <app-header></app-header>, <router-outlet></router-outlet> and <app-footer></app-footer>.
The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form.
To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes} from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MdTableModule} from '@angular/material';
import {HttpModule} from "@angular/http";
import {MdInputModule} from '@angular/material';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { UserloginComponent } from './userlogin/userlogin.component';
import { MainpageComponent } from './mainpage/mainpage.component';
const appRoutes: Routes = [
{
path: '',
component: UserloginComponent
},
{
path: 'app-mainpage',
component: MainpageComponent
}
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
UserloginComponent,
MainpageComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot(appRoutes),
BrowserAnimationsModule,
HttpModule,
MdTableModule,
MdInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as −
const appRoutes: Routes = [
{
path: '',
component: UserloginComponent
},
{
path: 'app-mainpage',
component: MainpageComponent
}
];
Routes take the array of components and by default the userloginComponent is called.
In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below −
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { Router} from '@angular/router';
@Component({
selector: 'app-userlogin',
templateUrl: './userlogin.component.html',
styleUrls: ['./userlogin.component.css']
})
export class UserloginComponent implements OnInit {
formdata;
constructor(private router: Router) { }
ngOnInit() {
this.formdata = new FormGroup({
uname: new FormControl("", Validators.compose([
Validators.required,
Validators.minLength(6)
])),
passwd: new FormControl("", this.passwordvalidation)
});
}
passwordvalidation(formcontrol) {
if (formcontrol.value.length < 5) {
return {"passwd" : true};
}
}
onClickSubmit(data) {
console.log(data.uname);
if (data.uname=="systemadmin" && data.passwd=="admin123") {
alert("Login Successful");
this.router.navigate(['app-mainpage'])
} else {
alert("Invalid Login");
return false;
}
}
}
Following is the .ts file for app.component.ts. Only the default details are present in it.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {title = 'app';}
Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
<div>
<hr />
</div>
We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here.
For the header, we will draw a horizontal line. A logo or any other detail can be added to make the header look more creative.
Let us now consider creating a footer component.
For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
<hr/>
As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here.
For the footer, we will just draw a horizontal line as shown in the .html file.
Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts.
The details of the files are as follows −
<div class="form_container">
<form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<header>Login</header>
<label>Username <span>*</span></label>
<input type="text" name="uname" formControlName="uname"/>
<div class="help">At least 6 character</div>
<label>Password <span>*</span></label>
<input type="password" class="fortextbox" name="passwd" formControlName="passwd"/>
<div class="help">Use upper and lowercase lettes as well</div>
<button [disabled]="!formdata.valid" value="Login">Login</button>
</form>
</div>
Here, we have created form with two input controls Username and Password. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms.
We consider the username and password mandatory, hence the validation for the same is added in the ts. Upon clicking the submit button, the control is passed to the onClickSubmit, which is defined in the ts file.
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { Router} from '@angular/router';
@Component({
selector: 'app-userlogin',
templateUrl: './userlogin.component.html',
styleUrls: ['./userlogin.component.css']
})
export class UserloginComponent implements OnInit {
formdata;
constructor(private router: Router) { }
ngOnInit() {
this.formdata = new FormGroup({
uname: new FormControl("", Validators.compose([
Validators.required,
Validators.minLength(6)
])),
passwd: new FormControl("", this.passwordvalidation)
});
}
passwordvalidation(formcontrol) {
if (formcontrol.value.length < 5) {
return {"passwd" : true};
}
}
onClickSubmit(data) {
console.log(data.uname);
if (data.uname == "systemadmin" && data.passwd == "admin123") {
alert("Login Successful");
this.router.navigate(['app-mainpage'])
}
}
}
For the formcontrol and validation, the modules are imported as shown below
import { FormGroup, FormControl, Validators} from '@angular/forms';
We need a router to navigate to a different component when the user and password are correct. For this, the router is imported as shown below −
import { Router} from '@angular/router';
In ngOnInit, the validation for the form is done. We need the username to be more than six characters and the field is mandatory. The same condition applies to password too.
Upon clicking submit, we can check if the username is systemadmin and the password is admin123. If yes, a dialog box appears that shows Login Successful and the router navigates to the app-mainpage, which is the selector of the mainpage component.
There is css added for the form in userlogin.component.css file −
.form_container{
margin : 0 auto;
width:600px;
}
form {
background: white;
width: 500px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7);
font-family: lato;
position: relative;
color: #333;
border-radius: 10px;
}
form header {
background: #FF3838;
padding: 30px 20px;
color: white;
font-size: 1.2em;
font-weight: 600;
border-radius: 10px 10px 0 0;
}
form label {
margin-left: 20px;
display: inline-block;
margin-top: 30px;
margin-bottom: 5px;
position: relative;
}
form label span {
color: #FF3838;
font-size: 2em;
position: absolute;
left: 2.3em;
top: -10px;
}
form input {
display: block;
width: 50%;
margin-left: 20px;
padding: 5px 20px;
font-size: 1em;
border-radius: 3px;
outline: none;
border: 1px solid #ccc;
}
form .help {
margin-left: 20px;
font-size: 0.8em;
color: #777;
}
form button {
position: relative;
margin-top: 30px;
margin-bottom: 30px;
left: 50%;
transform: translate(-50%, 0);
font-family: inherit;
color: white;
background: #FF3838;
outline: none;
border: none;
padding: 5px 15px;
font-size: 1.3em;
font-weight: 400;
border-radius: 3px;
box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4);
cursor: pointer;
transition: all 0.15s ease-in-out;
}
form button:hover {
background: #ff5252;
}
The userlogin.component.spec.ts file is empty as there no test cases right now.
Let us now discuss how the mainpage component works. The files created for mainpage component are mainpage.component.ts, mainpage.component.html, mainpage.component.css, and mainpage.component.spect.ts.
import { Component, OnInit, ViewChild} from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import {Http, Response, Headers, RequestOptions } from "@angular/http";
import 'rxjs/add/operator/map';
@Component({
selector: 'app-mainpage',
templateUrl: './mainpage.component.html',
styleUrls: ['./mainpage.component.css']
})
export class MainpageComponent implements OnInit {
formdata;
cutomerdata;
constructor(private http: Http) { }
stateCtrl: FormControl;
ngOnInit() {
this.formdata = new FormGroup({
fname: new FormControl("", Validators.compose([
Validators.required,
Validators.minLength(3)
])),
lname: new FormControl("", Validators.compose([
Validators.required,
Validators.minLength(3)
])),
address:new FormControl(""),
phoneno:new FormControl("")
});
}
onClickSubmit(data) {
document.getElementById("custtable").style.display="";
this.cutomerdata = [];
for (var prop in data) {
this.cutomerdata.push(data[prop]);
}
console.log(this.cutomerdata);
}
}
We have created a customer form with firstname, lastname , address and phone number. The validation of the same is done with the ngOnInit function. Upon clicking submit, the control comes to the function onClickSubmit. Here, the table which is used to display the entered details is made visible.
The customerdata is converted from json to array so that we can use the same in ngFor on the table, which is done in the .html file as shown below.
<div class="form_container">
<form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<header>Customer Details</header>
<label>FirstName <span>*</span></label>
<input type="text" name="fname" formControlName="fname"/>
<label>LastName <span>*</span></label>
<input type="text" name="lname" formControlName="lname"/>
<label>Address <span></span></label>
<input type="text" name="address" formControlName="address"/>
<label>Phone No <span></span></label>
<input type="text" name="phoneno" formControlName="phoneno"/>
<button [disabled]="!formdata.valid" value="Submit">Submit</button>
</form>
</div>
<br/>
<div id="custtable" style="display:none;margin:0 auto;">
<table>
<tr>
<td>FirstName</td>
<td>LastName</td>
<td>Address</td>
<td>Phone No</td>
</tr>
<tr>
<td *ngFor="let data of cutomerdata">
<h5>{{data}}</h5>
</td>
</tr>
</table>
</div>
Here, the first div has the customer details and the second div has the table, which will show the entered details. The display of the userlogin and the customer details is as shown below. This is the page with login form and header and footer.
Once you enter the details, the display is as shown below
Upon clicking submit, a dialog box appears which shows Login Successful.
If the details are invalid, a dialog box appears which shows Invalid Login as shown below −
If the login is successful, it will proceed to the next form of Customer Details as shown below −
Once the details are entered and submitted, a dialog box appears which shows the Customer Details are added as shown in the screenshot below −
When we click OK in the above screenshot, the details will appear as shown in the screenshot below −
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2062,
"s": 1992,
"text": "In this chapter, we will discuss a few examples related to Angular 4."
},
{
"code": null,
"e": 2375,
"s": 2062,
"text": "To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components - header, footer, userlogin and mainpage."
},
{
"code": null,
"e": 2432,
"s": 2375,
"text": "The components are created using the following command −"
},
{
"code": null,
"e": 2720,
"s": 2432,
"text": "C:\\ngexamples\\aexamples>ng g component header\ninstalling component\n create src\\app\\header\\header.component.css\n create src\\app\\header\\header.component.html\n create src\\app\\header\\header.component.spec.ts\n create src\\app\\header\\header.component.ts\n update src\\app\\app.module.ts\n"
},
{
"code": null,
"e": 3008,
"s": 2720,
"text": "C:\\ngexamples\\aexamples>ng g component footer\ninstalling component\n create src\\app\\footer\\footer.component.css\n create src\\app\\footer\\footer.component.html\n create src\\app\\footer\\footer.component.spec.ts\n create src\\app\\footer\\footer.component.ts\n update src\\app\\app.module.ts\n"
},
{
"code": null,
"e": 3323,
"s": 3008,
"text": "C:\\ngexamples\\aexamples>ng g component userlogin\ninstalling component\n create src\\app\\userlogin\\userlogin.component.css\n create src\\app\\userlogin\\userlogin.component.html\n create src\\app\\userlogin\\userlogin.component.spec.ts\n create src\\app\\userlogin\\userlogin.component.ts\n update src\\app\\app.module.ts\n"
},
{
"code": null,
"e": 3629,
"s": 3323,
"text": "C:\\ngexamples\\aexamples>ng g component mainpage\ninstalling component\n create src\\app\\mainpage\\mainpage.component.css\n create src\\app\\mainpage\\mainpage.component.html\n create src\\app\\mainpage\\mainpage.component.spec.ts\n create src\\app\\mainpage\\mainpage.component.ts\n update src\\app\\app.module.ts\n"
},
{
"code": null,
"e": 3740,
"s": 3629,
"text": "In the app.module.ts, the parent module has all the components added when created. The file looks as follows −"
},
{
"code": null,
"e": 5085,
"s": 3740,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { ReactiveFormsModule } from '@angular/forms';\n\nimport { RouterModule, Routes} froms '@angular/router';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport {MdTableModule} from '@angular/material';\n\nimport {HttpModule} from \"@angular/http\";\nimport {MdInputModule} from '@angular/material';\nimport { AppComponent } from './app.component';\n\nimport { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n\nconst appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n\n@NgModule({\n declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n ],\n \n imports: [\n BrowserModule,\n ReactiveFormsModule,\n RouterModule.forRoot(appRoutes),\n BrowserAnimationsModule,\n HttpModule,\n MdTableModule,\n MdInputModule\n ],\n \n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 5126,
"s": 5085,
"text": "The components created above are added −"
},
{
"code": null,
"e": 5386,
"s": 5126,
"text": "import { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n"
},
{
"code": null,
"e": 5437,
"s": 5386,
"text": "The components are added in the declarations too −"
},
{
"code": null,
"e": 5558,
"s": 5437,
"text": "declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n],\n"
},
{
"code": null,
"e": 5668,
"s": 5558,
"text": "In the parent app.component.html, we have added the main structure of the file that will be seen by the user."
},
{
"code": null,
"e": 5792,
"s": 5668,
"text": "<div class=\"mainpage\">\n <app-header></app-header>\n <router-outlet></router-outlet>\n <app-footer></app-footer>\n</div>\n"
},
{
"code": null,
"e": 5914,
"s": 5792,
"text": "We have created a div and added <app-header></app-header>, <router-outlet></router-outlet> and <app-footer></app-footer>."
},
{
"code": null,
"e": 6118,
"s": 5914,
"text": "The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form."
},
{
"code": null,
"e": 6244,
"s": 6118,
"text": "To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below −"
},
{
"code": null,
"e": 7584,
"s": 6244,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { ReactiveFormsModule } from '@angular/forms';\n\nimport { RouterModule, Routes} from '@angular/router';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport {MdTableModule} from '@angular/material';\n\nimport {HttpModule} from \"@angular/http\";\nimport {MdInputModule} from '@angular/material';\nimport { AppComponent } from './app.component';\n\nimport { HeaderComponent } from './header/header.component';\nimport { FooterComponent } from './footer/footer.component';\nimport { UserloginComponent } from './userlogin/userlogin.component';\nimport { MainpageComponent } from './mainpage/mainpage.component';\n\nconst appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n\n@NgModule({\n declarations: [\n AppComponent,\n HeaderComponent,\n FooterComponent,\n UserloginComponent,\n MainpageComponent\n ],\n \n imports: [\n BrowserModule,\n ReactiveFormsModule,\n RouterModule.forRoot(appRoutes),\n BrowserAnimationsModule,\n HttpModule,\n MdTableModule,\n MdInputModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 7734,
"s": 7584,
"text": "We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as −"
},
{
"code": null,
"e": 7902,
"s": 7734,
"text": "const appRoutes: Routes = [\n {\n path: '',\n component: UserloginComponent\n },\n {\n path: 'app-mainpage',\n component: MainpageComponent\n }\n];\n"
},
{
"code": null,
"e": 7987,
"s": 7902,
"text": "Routes take the array of components and by default the userloginComponent is called."
},
{
"code": null,
"e": 8123,
"s": 7987,
"text": "In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below −"
},
{
"code": null,
"e": 9227,
"s": 8123,
"text": "import { Component, OnInit } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\nimport { Router} from '@angular/router';\n\n@Component({\n selector: 'app-userlogin',\n templateUrl: './userlogin.component.html',\n styleUrls: ['./userlogin.component.css']\n})\n\nexport class UserloginComponent implements OnInit {\n formdata;\n constructor(private router: Router) { }\n ngOnInit() {\n this.formdata = new FormGroup({\n uname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(6)\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n \n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n \n onClickSubmit(data) {\n console.log(data.uname);\n if (data.uname==\"systemadmin\" && data.passwd==\"admin123\") {\n alert(\"Login Successful\");\n this.router.navigate(['app-mainpage'])\n } else {\n alert(\"Invalid Login\");\n return false;\n }\n }\n}"
},
{
"code": null,
"e": 9319,
"s": 9227,
"text": "Following is the .ts file for app.component.ts. Only the default details are present in it."
},
{
"code": null,
"e": 9526,
"s": 9319,
"text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {title = 'app';}\n"
},
{
"code": null,
"e": 9788,
"s": 9526,
"text": "Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts."
},
{
"code": null,
"e": 10058,
"s": 9788,
"text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-header',\n templateUrl: './header.component.html',\n styleUrls: ['./header.component.css']\n})\n\nexport class HeaderComponent implements OnInit {\n constructor() { }\n ngOnInit() {}\n}\n"
},
{
"code": null,
"e": 10082,
"s": 10058,
"text": "<div>\n <hr />\n</div>\n"
},
{
"code": null,
"e": 10248,
"s": 10082,
"text": "We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here."
},
{
"code": null,
"e": 10375,
"s": 10248,
"text": "For the header, we will draw a horizontal line. A logo or any other detail can be added to make the header look more creative."
},
{
"code": null,
"e": 10424,
"s": 10375,
"text": "Let us now consider creating a footer component."
},
{
"code": null,
"e": 10563,
"s": 10424,
"text": "For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created."
},
{
"code": null,
"e": 10833,
"s": 10563,
"text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-footer',\n templateUrl: './footer.component.html',\n styleUrls: ['./footer.component.css']\n})\n\nexport class FooterComponent implements OnInit {\n constructor() { }\n ngOnInit() { }\n}"
},
{
"code": null,
"e": 10840,
"s": 10833,
"text": "<hr/>\n"
},
{
"code": null,
"e": 11001,
"s": 10840,
"text": "As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here."
},
{
"code": null,
"e": 11081,
"s": 11001,
"text": "For the footer, we will just draw a horizontal line as shown in the .html file."
},
{
"code": null,
"e": 11295,
"s": 11081,
"text": "Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts."
},
{
"code": null,
"e": 11337,
"s": 11295,
"text": "The details of the files are as follows −"
},
{
"code": null,
"e": 11941,
"s": 11337,
"text": "<div class=\"form_container\">\n <form [formGroup]=\"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <header>Login</header>\n <label>Username <span>*</span></label>\n <input type=\"text\" name=\"uname\" formControlName=\"uname\"/>\n \n <div class=\"help\">At least 6 character</div>\n <label>Password <span>*</span></label>\n <input type=\"password\" class=\"fortextbox\" name=\"passwd\" formControlName=\"passwd\"/>\n \n <div class=\"help\">Use upper and lowercase lettes as well</div>\n <button [disabled]=\"!formdata.valid\" value=\"Login\">Login</button>\n </form>\n</div>"
},
{
"code": null,
"e": 12117,
"s": 11941,
"text": "Here, we have created form with two input controls Username and Password. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms."
},
{
"code": null,
"e": 12330,
"s": 12117,
"text": "We consider the username and password mandatory, hence the validation for the same is added in the ts. Upon clicking the submit button, the control is passed to the onClickSubmit, which is defined in the ts file."
},
{
"code": null,
"e": 13359,
"s": 12330,
"text": "import { Component, OnInit } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\nimport { Router} from '@angular/router';\n\n@Component({\n selector: 'app-userlogin',\n templateUrl: './userlogin.component.html',\n styleUrls: ['./userlogin.component.css']\n})\n\nexport class UserloginComponent implements OnInit {\n formdata;\n constructor(private router: Router) { }\n ngOnInit() {\n this.formdata = new FormGroup({\n uname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(6)\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n onClickSubmit(data) {\n console.log(data.uname);\n if (data.uname == \"systemadmin\" && data.passwd == \"admin123\") {\n alert(\"Login Successful\");\n this.router.navigate(['app-mainpage'])\n }\n }\n}"
},
{
"code": null,
"e": 13435,
"s": 13359,
"text": "For the formcontrol and validation, the modules are imported as shown below"
},
{
"code": null,
"e": 13504,
"s": 13435,
"text": "import { FormGroup, FormControl, Validators} from '@angular/forms';\n"
},
{
"code": null,
"e": 13648,
"s": 13504,
"text": "We need a router to navigate to a different component when the user and password are correct. For this, the router is imported as shown below −"
},
{
"code": null,
"e": 13690,
"s": 13648,
"text": "import { Router} from '@angular/router';\n"
},
{
"code": null,
"e": 13864,
"s": 13690,
"text": "In ngOnInit, the validation for the form is done. We need the username to be more than six characters and the field is mandatory. The same condition applies to password too."
},
{
"code": null,
"e": 14112,
"s": 13864,
"text": "Upon clicking submit, we can check if the username is systemadmin and the password is admin123. If yes, a dialog box appears that shows Login Successful and the router navigates to the app-mainpage, which is the selector of the mainpage component."
},
{
"code": null,
"e": 14178,
"s": 14112,
"text": "There is css added for the form in userlogin.component.css file −"
},
{
"code": null,
"e": 15546,
"s": 14178,
"text": ".form_container{\n margin : 0 auto;\n width:600px;\n}\n\nform {\n background: white;\n width: 500px;\n box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7);\n font-family: lato;\n position: relative;\n color: #333;\n border-radius: 10px;\n}\n\nform header {\n background: #FF3838;\n padding: 30px 20px;\n color: white;\n font-size: 1.2em;\n font-weight: 600;\n border-radius: 10px 10px 0 0;\n}\n\nform label {\n margin-left: 20px;\n display: inline-block;\n margin-top: 30px;\n margin-bottom: 5px;\n position: relative;\n}\n\nform label span {\n color: #FF3838;\n font-size: 2em;\n position: absolute;\n left: 2.3em;\n top: -10px;\n}\nform input {\n display: block;\n width: 50%;\n margin-left: 20px;\n padding: 5px 20px;\n font-size: 1em;\n border-radius: 3px;\n outline: none;\n border: 1px solid #ccc;\n}\n\nform .help {\n margin-left: 20px;\n font-size: 0.8em;\n color: #777;\n}\n\nform button {\n position: relative;\n margin-top: 30px;\n margin-bottom: 30px;\n left: 50%;\n transform: translate(-50%, 0);\n font-family: inherit;\n color: white;\n background: #FF3838;\n outline: none;\n border: none;\n padding: 5px 15px;\n font-size: 1.3em;\n font-weight: 400;\n border-radius: 3px;\n box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4);\n cursor: pointer;\n transition: all 0.15s ease-in-out;\n}\nform button:hover {\n background: #ff5252;\n}"
},
{
"code": null,
"e": 15626,
"s": 15546,
"text": "The userlogin.component.spec.ts file is empty as there no test cases right now."
},
{
"code": null,
"e": 15829,
"s": 15626,
"text": "Let us now discuss how the mainpage component works. The files created for mainpage component are mainpage.component.ts, mainpage.component.html, mainpage.component.css, and mainpage.component.spect.ts."
},
{
"code": null,
"e": 17010,
"s": 15829,
"text": "import { Component, OnInit, ViewChild} from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n\nimport {Http, Response, Headers, RequestOptions } from \"@angular/http\";\nimport 'rxjs/add/operator/map';\n\n@Component({\n selector: 'app-mainpage',\n templateUrl: './mainpage.component.html',\n styleUrls: ['./mainpage.component.css']\n})\n\nexport class MainpageComponent implements OnInit {\n formdata;\n cutomerdata;\n constructor(private http: Http) { }\n stateCtrl: FormControl;\n ngOnInit() {\n this.formdata = new FormGroup({\n fname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(3)\n ])),\n lname: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.minLength(3)\n ])),\n address:new FormControl(\"\"),\n phoneno:new FormControl(\"\")\n });\n }\n onClickSubmit(data) {\n document.getElementById(\"custtable\").style.display=\"\";\n this.cutomerdata = [];\n for (var prop in data) {\n this.cutomerdata.push(data[prop]);\n }\n console.log(this.cutomerdata);\n }\n}"
},
{
"code": null,
"e": 17307,
"s": 17010,
"text": "We have created a customer form with firstname, lastname , address and phone number. The validation of the same is done with the ngOnInit function. Upon clicking submit, the control comes to the function onClickSubmit. Here, the table which is used to display the entered details is made visible."
},
{
"code": null,
"e": 17455,
"s": 17307,
"text": "The customerdata is converted from json to array so that we can use the same in ngFor on the table, which is done in the .html file as shown below."
},
{
"code": null,
"e": 18484,
"s": 17455,
"text": "<div class=\"form_container\">\n <form [formGroup]=\"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <header>Customer Details</header>\n <label>FirstName <span>*</span></label>\n <input type=\"text\" name=\"fname\" formControlName=\"fname\"/>\n <label>LastName <span>*</span></label>\n \n <input type=\"text\" name=\"lname\" formControlName=\"lname\"/>\n <label>Address <span></span></label>\n <input type=\"text\" name=\"address\" formControlName=\"address\"/>\n <label>Phone No <span></span></label>\n <input type=\"text\" name=\"phoneno\" formControlName=\"phoneno\"/>\n <button [disabled]=\"!formdata.valid\" value=\"Submit\">Submit</button>\n </form>\n</div>\n<br/>\n\n<div id=\"custtable\" style=\"display:none;margin:0 auto;\">\n <table>\n <tr>\n <td>FirstName</td>\n <td>LastName</td>\n <td>Address</td>\n <td>Phone No</td>\n </tr>\n <tr>\n <td *ngFor=\"let data of cutomerdata\">\n <h5>{{data}}</h5>\n </td>\n </tr>\n </table>\n</div>"
},
{
"code": null,
"e": 18729,
"s": 18484,
"text": "Here, the first div has the customer details and the second div has the table, which will show the entered details. The display of the userlogin and the customer details is as shown below. This is the page with login form and header and footer."
},
{
"code": null,
"e": 18787,
"s": 18729,
"text": "Once you enter the details, the display is as shown below"
},
{
"code": null,
"e": 18860,
"s": 18787,
"text": "Upon clicking submit, a dialog box appears which shows Login Successful."
},
{
"code": null,
"e": 18952,
"s": 18860,
"text": "If the details are invalid, a dialog box appears which shows Invalid Login as shown below −"
},
{
"code": null,
"e": 19050,
"s": 18952,
"text": "If the login is successful, it will proceed to the next form of Customer Details as shown below −"
},
{
"code": null,
"e": 19193,
"s": 19050,
"text": "Once the details are entered and submitted, a dialog box appears which shows the Customer Details are added as shown in the screenshot below −"
},
{
"code": null,
"e": 19294,
"s": 19193,
"text": "When we click OK in the above screenshot, the details will appear as shown in the screenshot below −"
},
{
"code": null,
"e": 19329,
"s": 19294,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 19343,
"s": 19329,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 19378,
"s": 19343,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 19392,
"s": 19378,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 19427,
"s": 19392,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 19447,
"s": 19427,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 19482,
"s": 19447,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 19499,
"s": 19482,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 19532,
"s": 19499,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 19544,
"s": 19532,
"text": " Senol Atac"
},
{
"code": null,
"e": 19579,
"s": 19544,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 19591,
"s": 19579,
"text": " Senol Atac"
},
{
"code": null,
"e": 19598,
"s": 19591,
"text": " Print"
},
{
"code": null,
"e": 19609,
"s": 19598,
"text": " Add Notes"
}
] |
SENTIMENTAL ANALYSIS USING VADER. interpretation and classification of... | by Aditya Beri | Towards Data Science
|
Sentiment analysis is a text analysis method that detects polarity (e.g. a positive or negative opinion) within the text, whether a whole document, paragraph, sentence, or clause.
Sentiment analysis aims to measure the attitude, sentiments, evaluations, attitudes, and emotions of a speaker/writer based on the computational treatment of subjectivity in a text.
Though it may seem easy on paper, Sentiment Analysis is a tricky subject. A text may contain multiple sentiments all at once. For instance,
“The acting was good , but the movie could have been better”
The above sentence consists of two polarities!!!
VADER ( Valence Aware Dictionary for Sentiment Reasoning) is a model used for text sentiment analysis that is sensitive to both polarity (positive/negative) and intensity (strength) of emotion. It is available in the NLTK package and can be applied directly to unlabeled text data.
VADER sentimental analysis relies on a dictionary that maps lexical features to emotion intensities known as sentiment scores. The sentiment score of a text can be obtained by summing up the intensity of each word in the text.
For example- Words like ‘love’, ‘enjoy’, ‘happy’, ‘like’ all convey a positive sentiment. Also VADER is intelligent enough to understand the basic context of these words, such as “did not love” as a negative statement. It also understands the emphasis of capitalization and punctuation, such as “ENJOY”
We won’t try to determine if a sentence is objective or subjective, fact or opinion. Rather, we care only if the text expresses a positive, negative or neutral opinion.
We’ll also try to aggregate all of the sentences in a document or paragraph, to arrive at an overall opinion.
We won’t try to perform a fine-grained analysis that would determine the degree of positivity/negativity. That is, we’re not trying to guess how many stars a reviewer awarded, just whether the review was positive or negative.
First, consider the text being analyzed. A model trained on paragraph-long reviews might not be effective. Make sure to use an appropriate model for the task at hand.
Next, decide the type of analysis to perform. Some rudimentary sentiment analysis models go one step further, and consider two-word combinations, or bigrams. We will be going to work on complete sentences, and for this we’re going to import a trained NLTK lexicon called VADER.
For this model you can use a variety of datasets like amazon reviews, movie reviews, or any other reviews for any product.
import nltknltk.download('vader_lexicon')from nltk.sentiment.vader import SentimentIntensityAnalyzersid = SentimentIntensityAnalyzer()
VADER’s SentimentIntensityAnalyzer() takes in a string and returns a dictionary of scores in each of four categories:
negative
neutral
positive
compound (computed by normalizing the scores above
Let us analyze some random statements through our sentimental analyzer
a = 'This was a good movie.'sid.polarity_scores(a)OUTPUT-{'neg': 0.0, 'neu': 0.508, 'pos': 0.492, 'compound': 0.4404}a = 'This was the best, most awesome movie EVER MADE!!!'sid.polarity_scores(a)OUTPUT-{'neg': 0.0, 'neu': 0.425, 'pos': 0.575, 'compound': 0.8877}
import numpy as npimport pandas as pddf = pd.read_csv('../TextFiles/reviews.tsv', sep='\t')df.head()
df['label'].value_counts()OUTPUT-neg 5097pos 4903Name: label, dtype: int64
This step to clean any blank spaces within the reviews.
# REMOVE NaN VALUES AND EMPTY STRINGS:df.dropna(inplace=True)blanks = [] # start with an empty listfor i,lb,rv in df.itertuples(): if type(rv)==str: if rv.isspace(): blanks.append(i) df.drop(blanks, inplace=True)
Now we’ll add columns to the original DataFrame to store polarity_score dictionaries, extracted compound scores, and new “pos/neg” labels derived from the compound score. We’ll use this last column to perform an accuracy test. The reviews in this method will be classified into negative, positive and, neutral ratio.
df['sc ores'] = df['review'].apply(lambda review: sid.polarity_scores(review))df.head()
Now will call out compound as a separate column and all values greater than zeroes will be considered a positive review and all values less than zero would be considered as a negative review.
df['compound'] = df['scores'].apply(lambda score_dict: score_dict['compound'])df.head()
df['comp_score'] = df['compound'].apply(lambda c: 'pos' if c >=0 else 'neg')df.head()
So now we have got a complete analysis of every review as either positive or negative.
Now let us pass some new reviews to test how our model performs!
# Write a review as one continuous string (multiple sentences are ok)review = 'The shoes I brought were amazing.'# Obtain the sid scores for your reviewsid.polarity_scores(review)OUTPUT-{'neg': 0.0, 'neu': 0.513, 'pos': 0.487, 'compound': 0.5859}review='The mobile phone I bought was the WORST and very BAD'# Obtain the sid scores for your reviewsid.polarity_scores(review)OUTPUT-{'neg': 0.539, 'neu': 0.461, 'pos': 0.0, 'compound': -0.8849}
The results of VADER analysis don’t seem to be only remarkable but also very encouraging. The results show the advantages which will be attained by the utilization of VADER in cases of web sites wherein the text data could be a complex mixture of a range of text.
There are two of my other articles published in Towards Data Science publication on the related topics for this blog. Do have a read on those for better understanding in Natural Language Processing
Stemming vs Lemmatization — https://link.medium.com/JWpURpQjt6
Word vectors and Semantics — https://link.medium.com/tuVCswhYu6
|
[
{
"code": null,
"e": 352,
"s": 172,
"text": "Sentiment analysis is a text analysis method that detects polarity (e.g. a positive or negative opinion) within the text, whether a whole document, paragraph, sentence, or clause."
},
{
"code": null,
"e": 534,
"s": 352,
"text": "Sentiment analysis aims to measure the attitude, sentiments, evaluations, attitudes, and emotions of a speaker/writer based on the computational treatment of subjectivity in a text."
},
{
"code": null,
"e": 674,
"s": 534,
"text": "Though it may seem easy on paper, Sentiment Analysis is a tricky subject. A text may contain multiple sentiments all at once. For instance,"
},
{
"code": null,
"e": 735,
"s": 674,
"text": "“The acting was good , but the movie could have been better”"
},
{
"code": null,
"e": 784,
"s": 735,
"text": "The above sentence consists of two polarities!!!"
},
{
"code": null,
"e": 1066,
"s": 784,
"text": "VADER ( Valence Aware Dictionary for Sentiment Reasoning) is a model used for text sentiment analysis that is sensitive to both polarity (positive/negative) and intensity (strength) of emotion. It is available in the NLTK package and can be applied directly to unlabeled text data."
},
{
"code": null,
"e": 1293,
"s": 1066,
"text": "VADER sentimental analysis relies on a dictionary that maps lexical features to emotion intensities known as sentiment scores. The sentiment score of a text can be obtained by summing up the intensity of each word in the text."
},
{
"code": null,
"e": 1596,
"s": 1293,
"text": "For example- Words like ‘love’, ‘enjoy’, ‘happy’, ‘like’ all convey a positive sentiment. Also VADER is intelligent enough to understand the basic context of these words, such as “did not love” as a negative statement. It also understands the emphasis of capitalization and punctuation, such as “ENJOY”"
},
{
"code": null,
"e": 1765,
"s": 1596,
"text": "We won’t try to determine if a sentence is objective or subjective, fact or opinion. Rather, we care only if the text expresses a positive, negative or neutral opinion."
},
{
"code": null,
"e": 1875,
"s": 1765,
"text": "We’ll also try to aggregate all of the sentences in a document or paragraph, to arrive at an overall opinion."
},
{
"code": null,
"e": 2101,
"s": 1875,
"text": "We won’t try to perform a fine-grained analysis that would determine the degree of positivity/negativity. That is, we’re not trying to guess how many stars a reviewer awarded, just whether the review was positive or negative."
},
{
"code": null,
"e": 2268,
"s": 2101,
"text": "First, consider the text being analyzed. A model trained on paragraph-long reviews might not be effective. Make sure to use an appropriate model for the task at hand."
},
{
"code": null,
"e": 2546,
"s": 2268,
"text": "Next, decide the type of analysis to perform. Some rudimentary sentiment analysis models go one step further, and consider two-word combinations, or bigrams. We will be going to work on complete sentences, and for this we’re going to import a trained NLTK lexicon called VADER."
},
{
"code": null,
"e": 2669,
"s": 2546,
"text": "For this model you can use a variety of datasets like amazon reviews, movie reviews, or any other reviews for any product."
},
{
"code": null,
"e": 2804,
"s": 2669,
"text": "import nltknltk.download('vader_lexicon')from nltk.sentiment.vader import SentimentIntensityAnalyzersid = SentimentIntensityAnalyzer()"
},
{
"code": null,
"e": 2922,
"s": 2804,
"text": "VADER’s SentimentIntensityAnalyzer() takes in a string and returns a dictionary of scores in each of four categories:"
},
{
"code": null,
"e": 2931,
"s": 2922,
"text": "negative"
},
{
"code": null,
"e": 2939,
"s": 2931,
"text": "neutral"
},
{
"code": null,
"e": 2948,
"s": 2939,
"text": "positive"
},
{
"code": null,
"e": 2999,
"s": 2948,
"text": "compound (computed by normalizing the scores above"
},
{
"code": null,
"e": 3070,
"s": 2999,
"text": "Let us analyze some random statements through our sentimental analyzer"
},
{
"code": null,
"e": 3333,
"s": 3070,
"text": "a = 'This was a good movie.'sid.polarity_scores(a)OUTPUT-{'neg': 0.0, 'neu': 0.508, 'pos': 0.492, 'compound': 0.4404}a = 'This was the best, most awesome movie EVER MADE!!!'sid.polarity_scores(a)OUTPUT-{'neg': 0.0, 'neu': 0.425, 'pos': 0.575, 'compound': 0.8877}"
},
{
"code": null,
"e": 3434,
"s": 3333,
"text": "import numpy as npimport pandas as pddf = pd.read_csv('../TextFiles/reviews.tsv', sep='\\t')df.head()"
},
{
"code": null,
"e": 3515,
"s": 3434,
"text": "df['label'].value_counts()OUTPUT-neg 5097pos 4903Name: label, dtype: int64"
},
{
"code": null,
"e": 3571,
"s": 3515,
"text": "This step to clean any blank spaces within the reviews."
},
{
"code": null,
"e": 3832,
"s": 3571,
"text": "# REMOVE NaN VALUES AND EMPTY STRINGS:df.dropna(inplace=True)blanks = [] # start with an empty listfor i,lb,rv in df.itertuples(): if type(rv)==str: if rv.isspace(): blanks.append(i) df.drop(blanks, inplace=True)"
},
{
"code": null,
"e": 4149,
"s": 3832,
"text": "Now we’ll add columns to the original DataFrame to store polarity_score dictionaries, extracted compound scores, and new “pos/neg” labels derived from the compound score. We’ll use this last column to perform an accuracy test. The reviews in this method will be classified into negative, positive and, neutral ratio."
},
{
"code": null,
"e": 4237,
"s": 4149,
"text": "df['sc ores'] = df['review'].apply(lambda review: sid.polarity_scores(review))df.head()"
},
{
"code": null,
"e": 4429,
"s": 4237,
"text": "Now will call out compound as a separate column and all values greater than zeroes will be considered a positive review and all values less than zero would be considered as a negative review."
},
{
"code": null,
"e": 4518,
"s": 4429,
"text": "df['compound'] = df['scores'].apply(lambda score_dict: score_dict['compound'])df.head()"
},
{
"code": null,
"e": 4604,
"s": 4518,
"text": "df['comp_score'] = df['compound'].apply(lambda c: 'pos' if c >=0 else 'neg')df.head()"
},
{
"code": null,
"e": 4691,
"s": 4604,
"text": "So now we have got a complete analysis of every review as either positive or negative."
},
{
"code": null,
"e": 4756,
"s": 4691,
"text": "Now let us pass some new reviews to test how our model performs!"
},
{
"code": null,
"e": 5198,
"s": 4756,
"text": "# Write a review as one continuous string (multiple sentences are ok)review = 'The shoes I brought were amazing.'# Obtain the sid scores for your reviewsid.polarity_scores(review)OUTPUT-{'neg': 0.0, 'neu': 0.513, 'pos': 0.487, 'compound': 0.5859}review='The mobile phone I bought was the WORST and very BAD'# Obtain the sid scores for your reviewsid.polarity_scores(review)OUTPUT-{'neg': 0.539, 'neu': 0.461, 'pos': 0.0, 'compound': -0.8849}"
},
{
"code": null,
"e": 5462,
"s": 5198,
"text": "The results of VADER analysis don’t seem to be only remarkable but also very encouraging. The results show the advantages which will be attained by the utilization of VADER in cases of web sites wherein the text data could be a complex mixture of a range of text."
},
{
"code": null,
"e": 5660,
"s": 5462,
"text": "There are two of my other articles published in Towards Data Science publication on the related topics for this blog. Do have a read on those for better understanding in Natural Language Processing"
},
{
"code": null,
"e": 5723,
"s": 5660,
"text": "Stemming vs Lemmatization — https://link.medium.com/JWpURpQjt6"
}
] |
Draw circles using the polar coordinates and mid-point circle drawing algorithm on the same console using openGL in C++ - GeeksforGeeks
|
16 Jul, 2021
In this article, the task is to draw circles in two different subwindows using two different algorithms, and the circles are created using a single mouse click.
Approach:
There are two subwindows and both of them use different algorithms to create circles.
The left subwindow creates a circle using Midpoint Circle drawing algorithm and the right subwindow implements the concept of polar coordinates.
A circle can be created anywhere on the console using a single left mouse click and the coordinates of the center of the circle created depends on the position of the click.
To change the color of the circle, right-click on the mouse.
After performing all operations, jump out of the program by simply pressing the Esc key on the keyboard.
Below is the implementation of the above approach:
C++
// C++ program to implement onClick// functionality in OpenGL to draw// a circle using polar coordinates// and midpoint algorithm#include <GL/glut.h>#include <iostream>#include <math.h>#include <stdlib.h>#define xpix 500#include <cstring>using namespace std; float r, g, b, x, y;bool flag = true;int counter = 0; // Function to plot the coordinatesvoid plot(int x1, int y1){ // Initialize the points glBegin(GL_POINTS); // Draw the vertex glVertex2i(x1 + x, y1 + y); // End glEnd();} // Function works on mouse clickvoid mouse(int button, int state, int mousex, int mousey){ // Check if the current click // is left-click or not if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { flag = true; x = mousex; y = 600 - mousey; } // Check if the current click // is right-click or not else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { if (counter > 4) { counter = 0; } counter++; // Redisplay glutPostRedisplay(); }} // Function that exits from programvoid keyboard(unsigned char key, int x, int y){ switch (key) { case 27: glutHideWindow(); }} // Function to draw the circles using// the midpoint circle algorithmsvoid midPointCircleDraw(void){ // Change the color of circles on // the right click if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 400.0, 0.0, 600.0); int r = 50; if (flag) { // Begin the pointer glBegin(GL_POLYGON); int x1 = 0; int y1 = r; // Initialising the value // of the decision float decision = 5 / 4 - r; // Print the initial point on // the axes after translation plot(x1, y1); while (y1 > x1) { // Mid-point is inside or // on the perimeter if (decision < 0) { x1++; decision += 2 * x1 + 1; } // Mid-point is outside // the perimeter else { y1--; x1++; decision += 2 * (x1 - y1) + 1; } // Plot the points in the // different octants plot(x1, y1); plot(x1, -y1); plot(-x1, y1); plot(-x1, -y1); plot(y1, x1); plot(-y1, x1); plot(y1, -x1); plot(-y1, -x1); } } glFlush();} // Function to draw the circle using// the polar coordinatesvoid polarCoordinateCircleDraw(void){ float angle_theta; // Change the color of the circles // on right click if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 800.0, 0.0, 600.0); if (flag) { // Begin the pointer glBegin(GL_POLYGON); // Iterate through all the // 360 degrees for (int i = 0; i < 360; i++) { angle_theta = i * 3.142 / 180; glVertex2f(x + 50 * cos(angle_theta), y + 50 * sin(angle_theta)); } // Set the vertex glEnd(); } // Flushes the frame buffer to // the screen glFlush();} // Driver Codeint main(int argc, char** argv){ // Initialize the drivers glutInit(&argc, argv); // Initialize the display mode glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Update the window size glutInitWindowSize(800, 600); // Update the window position glutInitWindowPosition(100, 100); int mainWindow = glutCreateWindow( "Circle Generation using " "Midpoint Algorithm on " "left and using Polar " "Coordinates on right"); // Set the background color of // the right sub-window glClearColor(0, 0, 0, 0); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display the event handler // (polarCoordinateCircleDraw) glutDisplayFunc( polarCoordinateCircleDraw); // Mouse event handler glutMouseFunc(mouse); // Create the sub-window to implement // midpoint algorithm on left int subWindow1 = glutCreateSubWindow( mainWindow, 0, 0, 400, 600); glutInitWindowPosition(100, 100); // Sets the background color of // the left sub-window glClearColor(1, 0.5, 0.5, 1); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display the event handler // (midPointCircleDraw) glutDisplayFunc(midPointCircleDraw); // Mouse event handler glutMouseFunc(mouse); // Keyboard event handler glutKeyboardFunc(keyboard); // Loops the current event glutMainLoop();}
Output:
akshaysingh98088
c-graphics
computer-graphics
OpenGL
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
CSV file management using C++
|
[
{
"code": null,
"e": 24018,
"s": 23990,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 24179,
"s": 24018,
"text": "In this article, the task is to draw circles in two different subwindows using two different algorithms, and the circles are created using a single mouse click."
},
{
"code": null,
"e": 24189,
"s": 24179,
"text": "Approach:"
},
{
"code": null,
"e": 24275,
"s": 24189,
"text": "There are two subwindows and both of them use different algorithms to create circles."
},
{
"code": null,
"e": 24420,
"s": 24275,
"text": "The left subwindow creates a circle using Midpoint Circle drawing algorithm and the right subwindow implements the concept of polar coordinates."
},
{
"code": null,
"e": 24594,
"s": 24420,
"text": "A circle can be created anywhere on the console using a single left mouse click and the coordinates of the center of the circle created depends on the position of the click."
},
{
"code": null,
"e": 24655,
"s": 24594,
"text": "To change the color of the circle, right-click on the mouse."
},
{
"code": null,
"e": 24760,
"s": 24655,
"text": "After performing all operations, jump out of the program by simply pressing the Esc key on the keyboard."
},
{
"code": null,
"e": 24811,
"s": 24760,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24815,
"s": 24811,
"text": "C++"
},
{
"code": "// C++ program to implement onClick// functionality in OpenGL to draw// a circle using polar coordinates// and midpoint algorithm#include <GL/glut.h>#include <iostream>#include <math.h>#include <stdlib.h>#define xpix 500#include <cstring>using namespace std; float r, g, b, x, y;bool flag = true;int counter = 0; // Function to plot the coordinatesvoid plot(int x1, int y1){ // Initialize the points glBegin(GL_POINTS); // Draw the vertex glVertex2i(x1 + x, y1 + y); // End glEnd();} // Function works on mouse clickvoid mouse(int button, int state, int mousex, int mousey){ // Check if the current click // is left-click or not if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { flag = true; x = mousex; y = 600 - mousey; } // Check if the current click // is right-click or not else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { if (counter > 4) { counter = 0; } counter++; // Redisplay glutPostRedisplay(); }} // Function that exits from programvoid keyboard(unsigned char key, int x, int y){ switch (key) { case 27: glutHideWindow(); }} // Function to draw the circles using// the midpoint circle algorithmsvoid midPointCircleDraw(void){ // Change the color of circles on // the right click if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 400.0, 0.0, 600.0); int r = 50; if (flag) { // Begin the pointer glBegin(GL_POLYGON); int x1 = 0; int y1 = r; // Initialising the value // of the decision float decision = 5 / 4 - r; // Print the initial point on // the axes after translation plot(x1, y1); while (y1 > x1) { // Mid-point is inside or // on the perimeter if (decision < 0) { x1++; decision += 2 * x1 + 1; } // Mid-point is outside // the perimeter else { y1--; x1++; decision += 2 * (x1 - y1) + 1; } // Plot the points in the // different octants plot(x1, y1); plot(x1, -y1); plot(-x1, y1); plot(-x1, -y1); plot(y1, x1); plot(-y1, x1); plot(y1, -x1); plot(-y1, -x1); } } glFlush();} // Function to draw the circle using// the polar coordinatesvoid polarCoordinateCircleDraw(void){ float angle_theta; // Change the color of the circles // on right click if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 800.0, 0.0, 600.0); if (flag) { // Begin the pointer glBegin(GL_POLYGON); // Iterate through all the // 360 degrees for (int i = 0; i < 360; i++) { angle_theta = i * 3.142 / 180; glVertex2f(x + 50 * cos(angle_theta), y + 50 * sin(angle_theta)); } // Set the vertex glEnd(); } // Flushes the frame buffer to // the screen glFlush();} // Driver Codeint main(int argc, char** argv){ // Initialize the drivers glutInit(&argc, argv); // Initialize the display mode glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Update the window size glutInitWindowSize(800, 600); // Update the window position glutInitWindowPosition(100, 100); int mainWindow = glutCreateWindow( \"Circle Generation using \" \"Midpoint Algorithm on \" \"left and using Polar \" \"Coordinates on right\"); // Set the background color of // the right sub-window glClearColor(0, 0, 0, 0); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display the event handler // (polarCoordinateCircleDraw) glutDisplayFunc( polarCoordinateCircleDraw); // Mouse event handler glutMouseFunc(mouse); // Create the sub-window to implement // midpoint algorithm on left int subWindow1 = glutCreateSubWindow( mainWindow, 0, 0, 400, 600); glutInitWindowPosition(100, 100); // Sets the background color of // the left sub-window glClearColor(1, 0.5, 0.5, 1); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display the event handler // (midPointCircleDraw) glutDisplayFunc(midPointCircleDraw); // Mouse event handler glutMouseFunc(mouse); // Keyboard event handler glutKeyboardFunc(keyboard); // Loops the current event glutMainLoop();}",
"e": 30222,
"s": 24815,
"text": null
},
{
"code": null,
"e": 30230,
"s": 30222,
"text": "Output:"
},
{
"code": null,
"e": 30247,
"s": 30230,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 30258,
"s": 30247,
"text": "c-graphics"
},
{
"code": null,
"e": 30276,
"s": 30258,
"text": "computer-graphics"
},
{
"code": null,
"e": 30283,
"s": 30276,
"text": "OpenGL"
},
{
"code": null,
"e": 30287,
"s": 30283,
"text": "C++"
},
{
"code": null,
"e": 30300,
"s": 30287,
"text": "C++ Programs"
},
{
"code": null,
"e": 30304,
"s": 30300,
"text": "CPP"
},
{
"code": null,
"e": 30402,
"s": 30304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30411,
"s": 30402,
"text": "Comments"
},
{
"code": null,
"e": 30424,
"s": 30411,
"text": "Old Comments"
},
{
"code": null,
"e": 30445,
"s": 30424,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 30473,
"s": 30445,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30506,
"s": 30473,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30526,
"s": 30506,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30550,
"s": 30526,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 30585,
"s": 30550,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30611,
"s": 30585,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 30655,
"s": 30611,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 30714,
"s": 30655,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to select all columns except one in a Pandas DataFrame?
|
To select all columns except one column in Pandas DataFrame, we can use df.loc[:, df.columns != <column name>].
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Print the input DataFrame, df.
Initialize a variable col with column name that you want to exclude.
Initialize a variable col with column name that you want to exclude.
Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column.
Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column.
Print the DataFrame without col column.
Print the DataFrame without col column.
Live Demo
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print("Input DataFrame is:\n", df)
col = "y"
df1 = df.loc[:, df.columns != col]
print "DataFrame without Column-y: \n", df1
Input DataFrame is:
x y z
0 5 4 4
1 2 1 1
2 1 5 5
3 9 10 0
DataFrame without Column-y:
x z
0 5 4
1 2 1
2 1 5
3 9 0
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To select all columns except one column in Pandas DataFrame, we can use df.loc[:, df.columns != <column name>]."
},
{
"code": null,
"e": 1258,
"s": 1174,
"text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df."
},
{
"code": null,
"e": 1342,
"s": 1258,
"text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df."
},
{
"code": null,
"e": 1373,
"s": 1342,
"text": "Print the input DataFrame, df."
},
{
"code": null,
"e": 1404,
"s": 1373,
"text": "Print the input DataFrame, df."
},
{
"code": null,
"e": 1473,
"s": 1404,
"text": "Initialize a variable col with column name that you want to exclude."
},
{
"code": null,
"e": 1542,
"s": 1473,
"text": "Initialize a variable col with column name that you want to exclude."
},
{
"code": null,
"e": 1634,
"s": 1542,
"text": "Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column."
},
{
"code": null,
"e": 1726,
"s": 1634,
"text": "Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column."
},
{
"code": null,
"e": 1766,
"s": 1726,
"text": "Print the DataFrame without col column."
},
{
"code": null,
"e": 1806,
"s": 1766,
"text": "Print the DataFrame without col column."
},
{
"code": null,
"e": 1817,
"s": 1806,
"text": " Live Demo"
},
{
"code": null,
"e": 2070,
"s": 1817,
"text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 1, 9],\n \"y\": [4, 1, 5, 10],\n \"z\": [4, 1, 5, 0]\n }\n)\nprint(\"Input DataFrame is:\\n\", df)\n\ncol = \"y\"\ndf1 = df.loc[:, df.columns != col]\n\nprint \"DataFrame without Column-y: \\n\", df1"
},
{
"code": null,
"e": 2214,
"s": 2070,
"text": "Input DataFrame is:\n x y z\n0 5 4 4\n1 2 1 1\n2 1 5 5\n3 9 10 0\n\nDataFrame without Column-y:\n x z\n0 5 4\n1 2 1\n2 1 5\n3 9 0"
}
] |
Find records on or after a specific date in MongoDB?
|
To find records on or after a date, use $gte i.e., greater than equal. Let us create a collection with documents −
> db.demo91.insertOne({"ArrivalDate":new ISODate("2020-01-10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d49fd79799acab037af66")
}
> db.demo91.insertOne({"ArrivalDate":new ISODate("2019-12-14")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d4a0679799acab037af67")
}
Display all documents from a collection with the help of find() method −
> db.demo91.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d49fd79799acab037af66"), "ArrivalDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e2d4a0679799acab037af67"), "ArrivalDate" : ISODate("2019-12-14T00:00:00Z") }
Following is the query to find records on or after a specific date in MongoDB −
> db.demo91.find({ArrivalDate: { $gte: ISODate('2020-01-10') } });
This will produce the following output −
{ "_id" : ObjectId("5e2d49fd79799acab037af66"), "ArrivalDate" : ISODate("2020-01-10T00:00:00Z") }
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "To find records on or after a date, use $gte i.e., greater than equal. Let us create a collection with documents −"
},
{
"code": null,
"e": 1479,
"s": 1177,
"text": "> db.demo91.insertOne({\"ArrivalDate\":new ISODate(\"2020-01-10\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d49fd79799acab037af66\")\n}\n> db.demo91.insertOne({\"ArrivalDate\":new ISODate(\"2019-12-14\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d4a0679799acab037af67\")\n}"
},
{
"code": null,
"e": 1552,
"s": 1479,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1572,
"s": 1552,
"text": "> db.demo91.find();"
},
{
"code": null,
"e": 1613,
"s": 1572,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1809,
"s": 1613,
"text": "{ \"_id\" : ObjectId(\"5e2d49fd79799acab037af66\"), \"ArrivalDate\" : ISODate(\"2020-01-10T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e2d4a0679799acab037af67\"), \"ArrivalDate\" : ISODate(\"2019-12-14T00:00:00Z\") }"
},
{
"code": null,
"e": 1889,
"s": 1809,
"text": "Following is the query to find records on or after a specific date in MongoDB −"
},
{
"code": null,
"e": 1956,
"s": 1889,
"text": "> db.demo91.find({ArrivalDate: { $gte: ISODate('2020-01-10') } });"
},
{
"code": null,
"e": 1997,
"s": 1956,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2095,
"s": 1997,
"text": "{ \"_id\" : ObjectId(\"5e2d49fd79799acab037af66\"), \"ArrivalDate\" : ISODate(\"2020-01-10T00:00:00Z\") }"
}
] |
DAX Date & Time - EOMONTH function
|
Returns the date in datetime format of the last day of the month, before or after a specified number of months.
EOMONTH (<start_date>, <months>)
start_date
A date that represents the start date.
It can be in datetime or text format.
months
A whole number that represents the number of months before or after start_date.
If months is not an integer, rounded up or down to the nearest integer.
A date in datetime format.
You can use EOMONTH to calculate the maturity dates or due dates that fall on the last day of the month.
DAX works with dates in datetime format. Dates stored in other formats are converted implicitly.
If start_date is not a valid date, EOMONTH returns an error.
If start_date is not a valid date, EOMONTH returns an error.
If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid.
If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid.
DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.
DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.
If the text representation of the date cannot be correctly converted to a datetime value, the function returns an error.
= EOMONTH (DATE (2016,4,5),5) returns 9/30/2016 12:00:00 AM
= EOMONTH (DATE (2016,4,5),4.5) also returns 9/30/2016 12:00:00 AM, as 4.5 will be rounded up to 5.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2113,
"s": 2001,
"text": "Returns the date in datetime format of the last day of the month, before or after a specified number of months."
},
{
"code": null,
"e": 2148,
"s": 2113,
"text": "EOMONTH (<start_date>, <months>) \n"
},
{
"code": null,
"e": 2159,
"s": 2148,
"text": "start_date"
},
{
"code": null,
"e": 2198,
"s": 2159,
"text": "A date that represents the start date."
},
{
"code": null,
"e": 2236,
"s": 2198,
"text": "It can be in datetime or text format."
},
{
"code": null,
"e": 2243,
"s": 2236,
"text": "months"
},
{
"code": null,
"e": 2323,
"s": 2243,
"text": "A whole number that represents the number of months before or after start_date."
},
{
"code": null,
"e": 2395,
"s": 2323,
"text": "If months is not an integer, rounded up or down to the nearest integer."
},
{
"code": null,
"e": 2422,
"s": 2395,
"text": "A date in datetime format."
},
{
"code": null,
"e": 2527,
"s": 2422,
"text": "You can use EOMONTH to calculate the maturity dates or due dates that fall on the last day of the month."
},
{
"code": null,
"e": 2624,
"s": 2527,
"text": "DAX works with dates in datetime format. Dates stored in other formats are converted implicitly."
},
{
"code": null,
"e": 2685,
"s": 2624,
"text": "If start_date is not a valid date, EOMONTH returns an error."
},
{
"code": null,
"e": 2746,
"s": 2685,
"text": "If start_date is not a valid date, EOMONTH returns an error."
},
{
"code": null,
"e": 2898,
"s": 2746,
"text": "If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid."
},
{
"code": null,
"e": 3050,
"s": 2898,
"text": "If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid."
},
{
"code": null,
"e": 3563,
"s": 3050,
"text": "DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,\n\nIf the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016.\nIf the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.\n\n"
},
{
"code": null,
"e": 3724,
"s": 3563,
"text": "DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,"
},
{
"code": null,
"e": 3902,
"s": 3724,
"text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016."
},
{
"code": null,
"e": 4080,
"s": 3902,
"text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string, \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016."
},
{
"code": null,
"e": 4251,
"s": 4080,
"text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016."
},
{
"code": null,
"e": 4422,
"s": 4251,
"text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016."
},
{
"code": null,
"e": 4543,
"s": 4422,
"text": "If the text representation of the date cannot be correctly converted to a datetime value, the function returns an error."
},
{
"code": null,
"e": 4705,
"s": 4543,
"text": "= EOMONTH (DATE (2016,4,5),5) returns 9/30/2016 12:00:00 AM \n= EOMONTH (DATE (2016,4,5),4.5) also returns 9/30/2016 12:00:00 AM, as 4.5 will be rounded up to 5. "
},
{
"code": null,
"e": 4740,
"s": 4705,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4754,
"s": 4740,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 4787,
"s": 4754,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4801,
"s": 4787,
"text": " Randy Minder"
},
{
"code": null,
"e": 4836,
"s": 4801,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4850,
"s": 4836,
"text": " Randy Minder"
},
{
"code": null,
"e": 4857,
"s": 4850,
"text": " Print"
},
{
"code": null,
"e": 4868,
"s": 4857,
"text": " Add Notes"
}
] |
JSON - Objects
|
JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript −
Creation of an empty Object −
var JSONObj = {};
Creation of a new Object −
var JSONObj = new Object();
Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator −
Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator −
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the below code as json_object.htm −
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the following result −
The following example shows creation of an array object in javascript using JSON, save the below code as json_array_object.htm −
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");
for(i = 0;i<books.Pascal.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i = 0;i<books.Scala.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It produces the following result −
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1897,
"s": 1780,
"text": "JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript −"
},
{
"code": null,
"e": 1927,
"s": 1897,
"text": "Creation of an empty Object −"
},
{
"code": null,
"e": 1946,
"s": 1927,
"text": "var JSONObj = {};\n"
},
{
"code": null,
"e": 1973,
"s": 1946,
"text": "Creation of a new Object −"
},
{
"code": null,
"e": 2002,
"s": 1973,
"text": "var JSONObj = new Object();\n"
},
{
"code": null,
"e": 2152,
"s": 2002,
"text": "Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator −"
},
{
"code": null,
"e": 2302,
"s": 2152,
"text": "Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator −"
},
{
"code": null,
"e": 2363,
"s": 2302,
"text": "var JSONObj = { \"bookname \":\"VB BLACK BOOK\", \"price\":500 };\n"
},
{
"code": null,
"e": 2482,
"s": 2363,
"text": "This is an example that shows creation of an object in javascript using JSON, save the below code as json_object.htm −"
},
{
"code": null,
"e": 2968,
"s": 2482,
"text": "<html>\n <head>\n <title>Creating Object JSON with JavaScript</title>\n <script language = \"javascript\" >\n var JSONObj = { \"name\" : \"tutorialspoint.com\", \"year\" : 2005 };\n\t\t\n document.write(\"<h1>JSON with JavaScript example</h1>\");\n document.write(\"<br>\");\n document.write(\"<h3>Website Name = \"+JSONObj.name+\"</h3>\"); \n document.write(\"<h3>Year = \"+JSONObj.year+\"</h3>\"); \n </script>\n </head>\n \n <body>\n </body>\t\n</html>"
},
{
"code": null,
"e": 3087,
"s": 2968,
"text": "Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the following result −"
},
{
"code": null,
"e": 3216,
"s": 3087,
"text": "The following example shows creation of an array object in javascript using JSON, save the below code as json_array_object.htm −"
},
{
"code": null,
"e": 4865,
"s": 3216,
"text": "<html>\n <head>\n <title>Creation of array object in javascript using JSON</title>\n <script language = \"javascript\" >\n document.writeln(\"<h2>JSON array object</h2>\");\n var books = { \"Pascal\" : [ \n { \"Name\" : \"Pascal Made Simple\", \"price\" : 700 },\n { \"Name\" : \"Guide to Pascal\", \"price\" : 400 }], \n\t\t\t\t\n \"Scala\" : [\n { \"Name\" : \"Scala for the Impatient\", \"price\" : 1000 }, \n { \"Name\" : \"Scala in Depth\", \"price\" : 1300 }] \n } \n var i = 0\n document.writeln(\"<table border = '2'><tr>\");\n\t\t\t\n for(i = 0;i<books.Pascal.length;i++) {\t\n document.writeln(\"<td>\");\n document.writeln(\"<table border = '1' width = 100 >\");\n document.writeln(\"<tr><td><b>Name</b></td><td width = 50>\" + books.Pascal[i].Name+\"</td></tr>\");\n document.writeln(\"<tr><td><b>Price</b></td><td width = 50>\" + books.Pascal[i].price +\"</td></tr>\");\n document.writeln(\"</table>\");\n document.writeln(\"</td>\");\n }\n\n for(i = 0;i<books.Scala.length;i++) {\n document.writeln(\"<td>\");\n document.writeln(\"<table border = '1' width = 100 >\");\n document.writeln(\"<tr><td><b>Name</b></td><td width = 50>\" + books.Scala[i].Name+\"</td></tr>\");\n document.writeln(\"<tr><td><b>Price</b></td><td width = 50>\" + books.Scala[i].price+\"</td></tr>\");\n document.writeln(\"</table>\");\n document.writeln(\"</td>\");\n }\n\t\t\t\n document.writeln(\"</tr></table>\");\n </script>\n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 4990,
"s": 4865,
"text": "Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It produces the following result −"
},
{
"code": null,
"e": 5023,
"s": 4990,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5040,
"s": 5023,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5073,
"s": 5040,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5090,
"s": 5073,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5123,
"s": 5090,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5140,
"s": 5123,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5175,
"s": 5140,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5192,
"s": 5175,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5223,
"s": 5192,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 5236,
"s": 5223,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5271,
"s": 5236,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5294,
"s": 5271,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5301,
"s": 5294,
"text": " Print"
},
{
"code": null,
"e": 5312,
"s": 5301,
"text": " Add Notes"
}
] |
Facebook API | Set-3 - GeeksforGeeks
|
25 Jun, 2019
Prerequisite: Facebook API | Set-1, Set-2
In this article we will be discussing three methods:
searchget_connectionsget_allconnections
search
get_connections
get_allconnections
The valid value types are place and placetopic.
Parameters:id: It is a string containing a valid value.args: This is optional and they need to passed a query params.
Example: Get details of all places that are near Connaught Place Delhi. The Latitude and Longitude of Connaught Place are – 28.6304, 77.2177
import jsonimport facebook def main(): token = "Please replace with your access token" graph = facebook.GraphAPI(token) places = graph.search(type ='place', center ='28.6304, 77.2177', fields ='name, location') for place in places['data']: print('%s %s' %(place['name'].encode(), place['location'].get('zip'))) if __name__ == '__main__': main()
Please refer to the link Search Reference for complete list of fields that can used.
This methods aims at returning all connections or we can say Edges for the mentioned object as dict.
Parameters:id:A string specifying the unique id for the resource under question.connection name: A string specifying the connection or edges between the objects.
If connection name parameter is left empty then get_connections method will simply return the basic information of the authenticated user.
Example #1: We want to find out the total count of the number of Friends of the active user.
import jsonimport facebook def main(): token = "Please replace this with your access token" graph = facebook.GraphAPI(token) friends = graph.get_connections(id ='me', connection_name ='friends') print(json.dumps(friends, indent = 4)) if __name__ == '__main__': main()
Example #2: We want to get list of all posts from a page. For this, we will be using get_connections and later on, we will demonstrate how to use get_all_connections method.
import jsonimport facebook def main(): token = "Please replace this with your PAGE Access Token" graph = facebook.GraphAPI(token) posts_25 = graph.get_connections(id ='PAGE_ID', connection_name ='posts', fields ='id, created_time') print(json.dumps(posts_25, indent = 4)) if __name__ == '__main__': main()
Note: This example by default print latest 25 posts. You can add a filter for the post using limit(...) to set the limit for the number of the posts.
Example #3: In this example we will use get_connections method to print all the comments for the posts in reverse_chronological order, show sub comments including hidden comments and also show the total count of the comments.
import jsonimport facebook def main(): token = "Please replace this with your PAGE Access Token" graph = facebook.GraphAPI(token) posts_25 = graph.get_connections(id ='POST_ID', connection_name ='comments', include_hidden = True, order ='reverse_chronological', filter ='stream', summary ='total_count') print(json.dumps(posts_25, indent = 4)) if __name__ == '__main__': main()
Iterates over all pages returned by a get_connections call and yields the individual items.
Parameters:id:A string specifying the unique id for the resource under question.connection name: A string specifying the connection or edges between the objects.
Example #1: In this example I have used get_all_connections to list all the posts from a Page listed using the since datetime parameter.
import jsonimport facebookfrom datetime import datetime def main(): token = "Please replace this with your PAGE Access Token" graph = facebook.GraphAPI(token) posts_all = graph.get_all_connections(id ='PAGE_ID', connection_name ='posts', fields ='created_time, id', since = datetime(2017, 1, 1, 0, 0, 0)) for ind, post in enumerate(posts_all): print(json.dumps(ind, indent = 4)) print(json.dumps(post, indent = 4)) if __name__ == '__main__': main()
References:
https://developers.facebook.com/docs/marketing-api/insights/parametershttps://developers.facebook.com/docs/graph-api/
https://developers.facebook.com/docs/marketing-api/insights/parameters
https://developers.facebook.com/docs/graph-api/
Information-Security
GBlog
Python
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
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Python Dictionary
Read a file line by line in Python
|
[
{
"code": null,
"e": 25473,
"s": 25445,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 25515,
"s": 25473,
"text": "Prerequisite: Facebook API | Set-1, Set-2"
},
{
"code": null,
"e": 25568,
"s": 25515,
"text": "In this article we will be discussing three methods:"
},
{
"code": null,
"e": 25608,
"s": 25568,
"text": "searchget_connectionsget_allconnections"
},
{
"code": null,
"e": 25615,
"s": 25608,
"text": "search"
},
{
"code": null,
"e": 25631,
"s": 25615,
"text": "get_connections"
},
{
"code": null,
"e": 25650,
"s": 25631,
"text": "get_allconnections"
},
{
"code": null,
"e": 25698,
"s": 25650,
"text": "The valid value types are place and placetopic."
},
{
"code": null,
"e": 25816,
"s": 25698,
"text": "Parameters:id: It is a string containing a valid value.args: This is optional and they need to passed a query params."
},
{
"code": null,
"e": 25957,
"s": 25816,
"text": "Example: Get details of all places that are near Connaught Place Delhi. The Latitude and Longitude of Connaught Place are – 28.6304, 77.2177"
},
{
"code": "import jsonimport facebook def main(): token = \"Please replace with your access token\" graph = facebook.GraphAPI(token) places = graph.search(type ='place', center ='28.6304, 77.2177', fields ='name, location') for place in places['data']: print('%s %s' %(place['name'].encode(), place['location'].get('zip'))) if __name__ == '__main__': main()",
"e": 26378,
"s": 25957,
"text": null
},
{
"code": null,
"e": 26463,
"s": 26378,
"text": "Please refer to the link Search Reference for complete list of fields that can used."
},
{
"code": null,
"e": 26564,
"s": 26463,
"text": "This methods aims at returning all connections or we can say Edges for the mentioned object as dict."
},
{
"code": null,
"e": 26726,
"s": 26564,
"text": "Parameters:id:A string specifying the unique id for the resource under question.connection name: A string specifying the connection or edges between the objects."
},
{
"code": null,
"e": 26865,
"s": 26726,
"text": "If connection name parameter is left empty then get_connections method will simply return the basic information of the authenticated user."
},
{
"code": null,
"e": 26958,
"s": 26865,
"text": "Example #1: We want to find out the total count of the number of Friends of the active user."
},
{
"code": "import jsonimport facebook def main(): token = \"Please replace this with your access token\" graph = facebook.GraphAPI(token) friends = graph.get_connections(id ='me', connection_name ='friends') print(json.dumps(friends, indent = 4)) if __name__ == '__main__': main()",
"e": 27243,
"s": 26958,
"text": null
},
{
"code": null,
"e": 27417,
"s": 27243,
"text": "Example #2: We want to get list of all posts from a page. For this, we will be using get_connections and later on, we will demonstrate how to use get_all_connections method."
},
{
"code": "import jsonimport facebook def main(): token = \"Please replace this with your PAGE Access Token\" graph = facebook.GraphAPI(token) posts_25 = graph.get_connections(id ='PAGE_ID', connection_name ='posts', fields ='id, created_time') print(json.dumps(posts_25, indent = 4)) if __name__ == '__main__': main() ",
"e": 27792,
"s": 27417,
"text": null
},
{
"code": null,
"e": 27942,
"s": 27792,
"text": "Note: This example by default print latest 25 posts. You can add a filter for the post using limit(...) to set the limit for the number of the posts."
},
{
"code": null,
"e": 28168,
"s": 27942,
"text": "Example #3: In this example we will use get_connections method to print all the comments for the posts in reverse_chronological order, show sub comments including hidden comments and also show the total count of the comments."
},
{
"code": "import jsonimport facebook def main(): token = \"Please replace this with your PAGE Access Token\" graph = facebook.GraphAPI(token) posts_25 = graph.get_connections(id ='POST_ID', connection_name ='comments', include_hidden = True, order ='reverse_chronological', filter ='stream', summary ='total_count') print(json.dumps(posts_25, indent = 4)) if __name__ == '__main__': main() ",
"e": 28639,
"s": 28168,
"text": null
},
{
"code": null,
"e": 28731,
"s": 28639,
"text": "Iterates over all pages returned by a get_connections call and yields the individual items."
},
{
"code": null,
"e": 28893,
"s": 28731,
"text": "Parameters:id:A string specifying the unique id for the resource under question.connection name: A string specifying the connection or edges between the objects."
},
{
"code": null,
"e": 29030,
"s": 28893,
"text": "Example #1: In this example I have used get_all_connections to list all the posts from a Page listed using the since datetime parameter."
},
{
"code": "import jsonimport facebookfrom datetime import datetime def main(): token = \"Please replace this with your PAGE Access Token\" graph = facebook.GraphAPI(token) posts_all = graph.get_all_connections(id ='PAGE_ID', connection_name ='posts', fields ='created_time, id', since = datetime(2017, 1, 1, 0, 0, 0)) for ind, post in enumerate(posts_all): print(json.dumps(ind, indent = 4)) print(json.dumps(post, indent = 4)) if __name__ == '__main__': main()",
"e": 29598,
"s": 29030,
"text": null
},
{
"code": null,
"e": 29610,
"s": 29598,
"text": "References:"
},
{
"code": null,
"e": 29728,
"s": 29610,
"text": "https://developers.facebook.com/docs/marketing-api/insights/parametershttps://developers.facebook.com/docs/graph-api/"
},
{
"code": null,
"e": 29799,
"s": 29728,
"text": "https://developers.facebook.com/docs/marketing-api/insights/parameters"
},
{
"code": null,
"e": 29847,
"s": 29799,
"text": "https://developers.facebook.com/docs/graph-api/"
},
{
"code": null,
"e": 29868,
"s": 29847,
"text": "Information-Security"
},
{
"code": null,
"e": 29874,
"s": 29868,
"text": "GBlog"
},
{
"code": null,
"e": 29881,
"s": 29874,
"text": "Python"
},
{
"code": null,
"e": 29979,
"s": 29881,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30004,
"s": 29979,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30039,
"s": 30004,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 30101,
"s": 30039,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30127,
"s": 30101,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 30160,
"s": 30127,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 30188,
"s": 30160,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30238,
"s": 30188,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30282,
"s": 30238,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 30300,
"s": 30282,
"text": "Python Dictionary"
}
] |
Collections enumeration() method in Java with Examples - GeeksforGeeks
|
08 Jun, 2021
The enumeration() method of java.util.Collections class is used to return an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.Syntax:
public static Enumeration enumeration(Collection c)
Parameters: This method takes the collection c as a parameter for which an enumeration is to be returned.Return Value: This method returns an enumeration over the specified collection.Below are the examples to illustrate the enumeration() methodExample 1:
Java
// Java program to demonstrate// enumeration() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> arrlist = new ArrayList<String>(); // Adding element to srclst arrlist.add("Ram"); arrlist.add("Gopal"); arrlist.add("Verma"); // Print the list System.out.println("List: " + arrlist); // creating object of type Enumeration<String> Enumeration<String> e = Collections.enumeration(arrlist); // Print the Enumeration System.out.println("\nEnumeration over list: "); // print the enumeration while (e.hasMoreElements()) System.out.println("Value is: " + e.nextElement()); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: [Ram, Gopal, Verma]
Enumeration over list:
Value is: Ram
Value is: Gopal
Value is: Verma
Example 2:
Java
// Java program to demonstrate// enumeration() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<Integer> List<Integer> arrlist = new ArrayList<Integer>(); // Adding element to srclst arrlist.add(20); arrlist.add(30); arrlist.add(40); // Print the list System.out.println("List: " + arrlist); // creating object of type Enumeration<Integer> Enumeration<Integer> e = Collections.enumeration(arrlist); // Print the Enumeration System.out.println("\nEnumeration over list: "); // print the enumeration while (e.hasMoreElements()) System.out.println("Value is: " + e.nextElement()); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: [20, 30, 40]
Enumeration over list:
Value is: 20
Value is: 30
Value is: 40
anikakapoor
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 24090,
"s": 24062,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 24305,
"s": 24090,
"text": "The enumeration() method of java.util.Collections class is used to return an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.Syntax: "
},
{
"code": null,
"e": 24358,
"s": 24305,
"text": "public static Enumeration enumeration(Collection c)"
},
{
"code": null,
"e": 24616,
"s": 24358,
"text": "Parameters: This method takes the collection c as a parameter for which an enumeration is to be returned.Return Value: This method returns an enumeration over the specified collection.Below are the examples to illustrate the enumeration() methodExample 1: "
},
{
"code": null,
"e": 24621,
"s": 24616,
"text": "Java"
},
{
"code": "// Java program to demonstrate// enumeration() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> arrlist = new ArrayList<String>(); // Adding element to srclst arrlist.add(\"Ram\"); arrlist.add(\"Gopal\"); arrlist.add(\"Verma\"); // Print the list System.out.println(\"List: \" + arrlist); // creating object of type Enumeration<String> Enumeration<String> e = Collections.enumeration(arrlist); // Print the Enumeration System.out.println(\"\\nEnumeration over list: \"); // print the enumeration while (e.hasMoreElements()) System.out.println(\"Value is: \" + e.nextElement()); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 25740,
"s": 24621,
"text": null
},
{
"code": null,
"e": 25837,
"s": 25740,
"text": "List: [Ram, Gopal, Verma]\n\nEnumeration over list: \nValue is: Ram\nValue is: Gopal\nValue is: Verma"
},
{
"code": null,
"e": 25852,
"s": 25839,
"text": "Example 2: "
},
{
"code": null,
"e": 25857,
"s": 25852,
"text": "Java"
},
{
"code": "// Java program to demonstrate// enumeration() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<Integer> List<Integer> arrlist = new ArrayList<Integer>(); // Adding element to srclst arrlist.add(20); arrlist.add(30); arrlist.add(40); // Print the list System.out.println(\"List: \" + arrlist); // creating object of type Enumeration<Integer> Enumeration<Integer> e = Collections.enumeration(arrlist); // Print the Enumeration System.out.println(\"\\nEnumeration over list: \"); // print the enumeration while (e.hasMoreElements()) System.out.println(\"Value is: \" + e.nextElement()); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 26969,
"s": 25857,
"text": null
},
{
"code": null,
"e": 27052,
"s": 26969,
"text": "List: [20, 30, 40]\n\nEnumeration over list: \nValue is: 20\nValue is: 30\nValue is: 40"
},
{
"code": null,
"e": 27066,
"s": 27054,
"text": "anikakapoor"
},
{
"code": null,
"e": 27086,
"s": 27066,
"text": "Java - util package"
},
{
"code": null,
"e": 27103,
"s": 27086,
"text": "Java-Collections"
},
{
"code": null,
"e": 27118,
"s": 27103,
"text": "Java-Functions"
},
{
"code": null,
"e": 27123,
"s": 27118,
"text": "Java"
},
{
"code": null,
"e": 27128,
"s": 27123,
"text": "Java"
},
{
"code": null,
"e": 27145,
"s": 27128,
"text": "Java-Collections"
},
{
"code": null,
"e": 27243,
"s": 27145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27258,
"s": 27243,
"text": "Stream In Java"
},
{
"code": null,
"e": 27277,
"s": 27258,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27298,
"s": 27277,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27328,
"s": 27298,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27374,
"s": 27328,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27391,
"s": 27374,
"text": "Generics in Java"
},
{
"code": null,
"e": 27434,
"s": 27391,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27455,
"s": 27434,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27477,
"s": 27455,
"text": "PriorityQueue in Java"
}
] |
Python program to convert a list of characters into a string
|
Python requires this kind of conversion a lot. For example, such conversions are useful for serialization purposes. An example of such a conversion would be −
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] to "hello world"
Python has a join method that can be used for such conversions. It can be applied on a delimiter string that'll be used to concatenate the objects together. In this case, we need an empty delimiter string. We can implement it as follows −
Live Demo
letters = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
sentence = ''.join(letters)
print(sentence)
This will give the output −
hello world
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "Python requires this kind of conversion a lot. For example, such conversions are useful for serialization purposes. An example of such a conversion would be −"
},
{
"code": null,
"e": 1294,
"s": 1221,
"text": "['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] to \"hello world\""
},
{
"code": null,
"e": 1533,
"s": 1294,
"text": "Python has a join method that can be used for such conversions. It can be applied on a delimiter string that'll be used to concatenate the objects together. In this case, we need an empty delimiter string. We can implement it as follows −"
},
{
"code": null,
"e": 1544,
"s": 1533,
"text": " Live Demo"
},
{
"code": null,
"e": 1654,
"s": 1544,
"text": "letters = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']\nsentence = ''.join(letters)\nprint(sentence)"
},
{
"code": null,
"e": 1682,
"s": 1654,
"text": "This will give the output −"
},
{
"code": null,
"e": 1694,
"s": 1682,
"text": "hello world"
}
] |
Practical Explainable AI: Loan Approval Use Case | by Raheel Ahmad | Towards Data Science
|
Explainability is extremely crucial in systems that are responsible for carrying out mission-critical tasks. For example, in healthcare, if scientists are relying on AI models to help them figure out whether the patient will have cancer or not, they need to be 100% sure of their diagnoses otherwise this can result in death, a lot of lawsuits and a lot of damage done in trust. Nature is this problem is so intense that explainability sits at the core of this problem: the data scientists and the human operators, in this case, the doctors need to understand how the machine learning system is behaving and how did it come to a decision.
Explainable AI is also important in finance or fintech in particular due to the growing adoption of machine learning solutions for credit scoring, loan approval, insurance, investment decisions and so on. Here again, there is a cost associated with the wrong decisions by the machine learning system: so there is a huge need to understand how the model actually works.
Using black-box AI increases business risk and exposes the businesses to a deep downside — from credit card applications to determining disease to criminal justice.
The reason why black-box models are not desirable becomes more clear when we look at how the business functions as a whole:
For the business decision-maker, data scientists need to answer the question of why they can trust our models, for IT & Operation, data scientists need to tell them how can they monitor and debug if an error occurs, for the data scientist, they need to know how they can further improve the accuracy of their models and finally, for regulators and auditors, they need to be able to get an answer to whether our AI system is fair or not?
Explainable AI aims at providing clear and transparent predictions. An end-to-end system that provides decisions and explanations to the user and ultimately provides automated feedback to constantly improve the AI system. Remember, xAI is highly driven by the feedback so is a two-way interaction between the human and the AI system.
In the end, we should understand why behind the model, the impact of the model, where the model fails and what recommendations to provide.
explainx is an open-source explainable AI platform created by explainX.ai. Explainx, written in python, aims to help data scientists explain, monitor and debug black-box AI model — the purpose is to help build robust, unbiased and transparent AI applications.
Within the explainx architecture, explainx provides access to state of the art interpretability techniques in just a single line of code within our Jupyter notebook.
For this example, we will use the HELOC dataset provided by FICO. The customers in this dataset have requested a credit line in the range of USD 5,000–150,000. Our job is to predict RiskPerformance: whether they will make timely payments over a two year period. The prediction can then be used to decide whether the homeowner qualifies for a line of credit.
For this example, we will train CatBoost classifier model. After the training is done, we will use the explainx xAI module to explain our model and build a narrative for a business user to understand!
Let’s start with opening up our Jupyter notebooks and installing the explainx library. You can also clone the repository from the link below:
https://github.com/explainX/explainx
pip install explainx
Let’s import relevant packages:
from explainx import *import catboostfrom sklearn.model_selection import train_test_split
Let’s load and pre-process our dataset for model building. The dataset is already available in the explainx library.
X, y = explainx.dataset_heloc()#split data into train and testX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=0
Begin training. For the sake of this tutorial, we are going to keep it simple!
# Run catboost modelmodel = CatBoostClassifier(iterations=500, learning_rate=.3, depth=2)# Fit modelmodel.fit(X_train.to_numpy(), y_train)
After the training is done, we can simply pass the test data into the explainx function and get our explanations!
explainx.ai(X_test, y_test, model, model_name="catboost")
Once explainx and running, all you need to do is point your browser to http://127.0.0.1:8050 and you’ll see a very nice user interface called explainX.Dashboard.
App running on https://127.0.0.1:8050/
Note: If you want to view it inline, simple pass mode="inline” argument into the explainx function.
For this tutorial, we will not go in the nitty-gritty of model building, model metrics and evaluation. Instead, we will dive right into the explanation part which is the main aim of this tutorial. So let’s start opening up the black-box!
We will tackle the model at four levels:
Global Level Explanation
Local Prediction Explanation
Scenario Analysis
Feature Interaction & Distributions
We will be using the overall feature importance and overall feature impact graphs to give us a basic underlying logic of the model.
Interpretation: This tells that according to the CatBoost model, ExternalRiskEstimate, MSinceMostRecentInq and PercentTradesNeverDelqare the top three variables with the largest impact on RiskPerformance. These three represents Risk Estimate, Credit Inquiries and Debt Level information: extremely important categories when assessing risk.
This information gives us a general idea of feature contribution but to understand whether each of these features has a positive or a negative impact on RiskPerformancewe need to consult the feature impact graph.
This graph gives us even more insight into the model logic. We can clearly observe that ExternalRiskEstimate impacts the predicting variable positively — pushes it towards “Good Credit Risk Performance” and that matches our intuition as well. We have to use a little bit of our domain knowledge in finance for this: ExternalRiskEstimateis a consolidated version of some risk markers (higher is better) so automatically we learn that this variable will always positively affect the prediction. Then we have NumSatisfactoryTrades:the number of “satisfactory” accounts (“trades”) has a significant positive effect on the predicted probability of good credit.
However, in the lower end, delinquency variables push the overall prediction towards 0 (in this case, application denied). This is interesting and we can even dig deeper and see when does this negative effect of delinquency wears off? (Something to try on your own!)
Now as we have an idea of how each feature affects the prediction, we can move on to explaining a single prediction for a specific customer. For that, we will be using an impact graph or a decision plot that will help us get attribution scores for that particular prediction. To further support our analysis, we will calculate similar profiles that most closely resemble the one we are trying to predict.
So let’s explain for customer on Row # 9 in our data. For this specific customer, the application was approved because the RiskPerformance was “Good” and our model also classified it correctly!
Let’s explore the model logic:
So this graph clearly shows the top three positive and top three negatively impacting variables. According to the model, MSinceMostRecentInq had the most positive impact on the variable. So this tells us that the higher value of this variable means that there is no penalty for having more than one month since the most recent inquiry. Then we have ExternalRiskEstimate that again plays a positive role in pushing the prediction towards “good credit behaviour”. However, PercentTradesNeverDelq affected the prediction negatively: this might be the case if the value of this variable is extremely small because the smaller value for this variable lowers the probability of good credit score.
To keep it short, these findings match our mental-models as the attribution score of each variable is correctly assigned. To further support our analysis, we will find similar customers!
Explainx comes with an in-built prototypical analysis function which provides a much more well rounded and comprehensive view of why the decision for the applicant may be justifiable.
The above table depicts the five closest user profiles to the chosen applicant. Based on importance weight assigned to each profile by the method, we see that the prototype under column zero is the most representative user profile by far. This is (intuitively) confirmed from the feature similarity where more than 50% of the features (12 out of 23) of this prototype are identical to that of the chosen user whose prediction we want to explain. Also, the bank employee looking at the prototypical users and their features surmise that the approved applicant belongs to a group with high values of ExternalRiskEstimate. This justification gives the bank employees more confidence in approving the user’s application.
Now, let’s explore different scenarios and see how the model performs. We can apply the data filters within the data table (no need to write SQL queries to filter your data) and explain multiple instances and scenarios very easily.
This is extremely useful when you are trying to understand behaviour on a specific cluster or group of data. For example, we want to see if the model attributes the same weights to the users when the ExternalRiskEstimate is > 60 and MSinceOldestTradeOpen is greater than 200.
We can clearly see the dominance of ExternalRiskEstimate from the chart below.
When the ExternalRiskEstimate is greater than 60, it is seen as a positive sign which matches our internal mental model as well: ExternalRiskEstimate is actually monotonically decreasing which means that as the value of ExternalRiskEstimate increases, the probability of Bad Credit Score decreases! So in this cluster where the RiskEstimate is greater than 60, we will have more Good customers who were extended the credit line. We can confirm this by using a feature interaction plot, specifically a partial dependence plot:
The partial dependence plot validates our assumption. In the plot below, Red = Good RiskPerformance (credit line extended) and Silver = Bad RiskPerformance (credit line denied).
We can clearly see that pattern that as ExternalRiskEstimate value increases, its impacts on the output also increases and we have more instances of good risk performance. We see more concentration of red dots as the ExternalRiskEstimate value goes up and that makes a lot of sense!
Data Scientists can use explainx to further explore patterns by looking at interactions between different variables and how they impact the overall prediction. So let’s end by summarizing our findings for a business user to understand:
According to the CatBoost model, ExternalRiskEstimate, MSinceMostRecentInq and PercentTradesNeverDelqare the top three variables with the largest impact on RiskPerformance.
ExternalRiskEstimate impacts the predicting variable positively — pushes it towards “Good Credit Risk” but delinquency variables push the overall prediction towards “Bad Credit Risk” (in this case, application denied).
For our customer # 9, RiskPerformance = Good, ExternalRiskEstimate played a positive role in pushing the prediction towards “good credit behaviour”. However, PercentTradesNeverDelq affected the prediction negatively: this might be the case if the value of this variable is extremely small because the smaller value for this variable lowers the probability of good credit score.
We found customers that had very similar behaviour and variable values to our customer # 9: strengthening our hypothesis even more.
We were able to validate the model’s logic by further exploring the PDP that clearly showed us how increasing the value of ExternalRiskEstimate increases the probability of loan approval.
Data Scientist can further explore a similar process and build an even more comprehensive data narrative that anyone can easily understand.
I hope you all enjoyed this case study. Explainability is extremely crucial and more than relevant today — so the ability to present a narrative that shows your understanding of how AI works is a vital skill for a data scientist. This is the real essence of human-AI understanding and democratization of AI.
Download explainx: https://github.com/explainX/explainxDocumentation: https://explainx-documentation.netlify.app/
|
[
{
"code": null,
"e": 686,
"s": 47,
"text": "Explainability is extremely crucial in systems that are responsible for carrying out mission-critical tasks. For example, in healthcare, if scientists are relying on AI models to help them figure out whether the patient will have cancer or not, they need to be 100% sure of their diagnoses otherwise this can result in death, a lot of lawsuits and a lot of damage done in trust. Nature is this problem is so intense that explainability sits at the core of this problem: the data scientists and the human operators, in this case, the doctors need to understand how the machine learning system is behaving and how did it come to a decision."
},
{
"code": null,
"e": 1055,
"s": 686,
"text": "Explainable AI is also important in finance or fintech in particular due to the growing adoption of machine learning solutions for credit scoring, loan approval, insurance, investment decisions and so on. Here again, there is a cost associated with the wrong decisions by the machine learning system: so there is a huge need to understand how the model actually works."
},
{
"code": null,
"e": 1220,
"s": 1055,
"text": "Using black-box AI increases business risk and exposes the businesses to a deep downside — from credit card applications to determining disease to criminal justice."
},
{
"code": null,
"e": 1344,
"s": 1220,
"text": "The reason why black-box models are not desirable becomes more clear when we look at how the business functions as a whole:"
},
{
"code": null,
"e": 1781,
"s": 1344,
"text": "For the business decision-maker, data scientists need to answer the question of why they can trust our models, for IT & Operation, data scientists need to tell them how can they monitor and debug if an error occurs, for the data scientist, they need to know how they can further improve the accuracy of their models and finally, for regulators and auditors, they need to be able to get an answer to whether our AI system is fair or not?"
},
{
"code": null,
"e": 2115,
"s": 1781,
"text": "Explainable AI aims at providing clear and transparent predictions. An end-to-end system that provides decisions and explanations to the user and ultimately provides automated feedback to constantly improve the AI system. Remember, xAI is highly driven by the feedback so is a two-way interaction between the human and the AI system."
},
{
"code": null,
"e": 2254,
"s": 2115,
"text": "In the end, we should understand why behind the model, the impact of the model, where the model fails and what recommendations to provide."
},
{
"code": null,
"e": 2514,
"s": 2254,
"text": "explainx is an open-source explainable AI platform created by explainX.ai. Explainx, written in python, aims to help data scientists explain, monitor and debug black-box AI model — the purpose is to help build robust, unbiased and transparent AI applications."
},
{
"code": null,
"e": 2680,
"s": 2514,
"text": "Within the explainx architecture, explainx provides access to state of the art interpretability techniques in just a single line of code within our Jupyter notebook."
},
{
"code": null,
"e": 3038,
"s": 2680,
"text": "For this example, we will use the HELOC dataset provided by FICO. The customers in this dataset have requested a credit line in the range of USD 5,000–150,000. Our job is to predict RiskPerformance: whether they will make timely payments over a two year period. The prediction can then be used to decide whether the homeowner qualifies for a line of credit."
},
{
"code": null,
"e": 3239,
"s": 3038,
"text": "For this example, we will train CatBoost classifier model. After the training is done, we will use the explainx xAI module to explain our model and build a narrative for a business user to understand!"
},
{
"code": null,
"e": 3381,
"s": 3239,
"text": "Let’s start with opening up our Jupyter notebooks and installing the explainx library. You can also clone the repository from the link below:"
},
{
"code": null,
"e": 3418,
"s": 3381,
"text": "https://github.com/explainX/explainx"
},
{
"code": null,
"e": 3439,
"s": 3418,
"text": "pip install explainx"
},
{
"code": null,
"e": 3471,
"s": 3439,
"text": "Let’s import relevant packages:"
},
{
"code": null,
"e": 3561,
"s": 3471,
"text": "from explainx import *import catboostfrom sklearn.model_selection import train_test_split"
},
{
"code": null,
"e": 3678,
"s": 3561,
"text": "Let’s load and pre-process our dataset for model building. The dataset is already available in the explainx library."
},
{
"code": null,
"e": 3827,
"s": 3678,
"text": "X, y = explainx.dataset_heloc()#split data into train and testX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=0"
},
{
"code": null,
"e": 3906,
"s": 3827,
"text": "Begin training. For the sake of this tutorial, we are going to keep it simple!"
},
{
"code": null,
"e": 4095,
"s": 3906,
"text": "# Run catboost modelmodel = CatBoostClassifier(iterations=500, learning_rate=.3, depth=2)# Fit modelmodel.fit(X_train.to_numpy(), y_train)"
},
{
"code": null,
"e": 4209,
"s": 4095,
"text": "After the training is done, we can simply pass the test data into the explainx function and get our explanations!"
},
{
"code": null,
"e": 4267,
"s": 4209,
"text": "explainx.ai(X_test, y_test, model, model_name=\"catboost\")"
},
{
"code": null,
"e": 4429,
"s": 4267,
"text": "Once explainx and running, all you need to do is point your browser to http://127.0.0.1:8050 and you’ll see a very nice user interface called explainX.Dashboard."
},
{
"code": null,
"e": 4468,
"s": 4429,
"text": "App running on https://127.0.0.1:8050/"
},
{
"code": null,
"e": 4568,
"s": 4468,
"text": "Note: If you want to view it inline, simple pass mode=\"inline” argument into the explainx function."
},
{
"code": null,
"e": 4806,
"s": 4568,
"text": "For this tutorial, we will not go in the nitty-gritty of model building, model metrics and evaluation. Instead, we will dive right into the explanation part which is the main aim of this tutorial. So let’s start opening up the black-box!"
},
{
"code": null,
"e": 4847,
"s": 4806,
"text": "We will tackle the model at four levels:"
},
{
"code": null,
"e": 4872,
"s": 4847,
"text": "Global Level Explanation"
},
{
"code": null,
"e": 4901,
"s": 4872,
"text": "Local Prediction Explanation"
},
{
"code": null,
"e": 4919,
"s": 4901,
"text": "Scenario Analysis"
},
{
"code": null,
"e": 4955,
"s": 4919,
"text": "Feature Interaction & Distributions"
},
{
"code": null,
"e": 5087,
"s": 4955,
"text": "We will be using the overall feature importance and overall feature impact graphs to give us a basic underlying logic of the model."
},
{
"code": null,
"e": 5427,
"s": 5087,
"text": "Interpretation: This tells that according to the CatBoost model, ExternalRiskEstimate, MSinceMostRecentInq and PercentTradesNeverDelqare the top three variables with the largest impact on RiskPerformance. These three represents Risk Estimate, Credit Inquiries and Debt Level information: extremely important categories when assessing risk."
},
{
"code": null,
"e": 5640,
"s": 5427,
"text": "This information gives us a general idea of feature contribution but to understand whether each of these features has a positive or a negative impact on RiskPerformancewe need to consult the feature impact graph."
},
{
"code": null,
"e": 6296,
"s": 5640,
"text": "This graph gives us even more insight into the model logic. We can clearly observe that ExternalRiskEstimate impacts the predicting variable positively — pushes it towards “Good Credit Risk Performance” and that matches our intuition as well. We have to use a little bit of our domain knowledge in finance for this: ExternalRiskEstimateis a consolidated version of some risk markers (higher is better) so automatically we learn that this variable will always positively affect the prediction. Then we have NumSatisfactoryTrades:the number of “satisfactory” accounts (“trades”) has a significant positive effect on the predicted probability of good credit."
},
{
"code": null,
"e": 6563,
"s": 6296,
"text": "However, in the lower end, delinquency variables push the overall prediction towards 0 (in this case, application denied). This is interesting and we can even dig deeper and see when does this negative effect of delinquency wears off? (Something to try on your own!)"
},
{
"code": null,
"e": 6968,
"s": 6563,
"text": "Now as we have an idea of how each feature affects the prediction, we can move on to explaining a single prediction for a specific customer. For that, we will be using an impact graph or a decision plot that will help us get attribution scores for that particular prediction. To further support our analysis, we will calculate similar profiles that most closely resemble the one we are trying to predict."
},
{
"code": null,
"e": 7162,
"s": 6968,
"text": "So let’s explain for customer on Row # 9 in our data. For this specific customer, the application was approved because the RiskPerformance was “Good” and our model also classified it correctly!"
},
{
"code": null,
"e": 7193,
"s": 7162,
"text": "Let’s explore the model logic:"
},
{
"code": null,
"e": 7884,
"s": 7193,
"text": "So this graph clearly shows the top three positive and top three negatively impacting variables. According to the model, MSinceMostRecentInq had the most positive impact on the variable. So this tells us that the higher value of this variable means that there is no penalty for having more than one month since the most recent inquiry. Then we have ExternalRiskEstimate that again plays a positive role in pushing the prediction towards “good credit behaviour”. However, PercentTradesNeverDelq affected the prediction negatively: this might be the case if the value of this variable is extremely small because the smaller value for this variable lowers the probability of good credit score."
},
{
"code": null,
"e": 8071,
"s": 7884,
"text": "To keep it short, these findings match our mental-models as the attribution score of each variable is correctly assigned. To further support our analysis, we will find similar customers!"
},
{
"code": null,
"e": 8255,
"s": 8071,
"text": "Explainx comes with an in-built prototypical analysis function which provides a much more well rounded and comprehensive view of why the decision for the applicant may be justifiable."
},
{
"code": null,
"e": 8972,
"s": 8255,
"text": "The above table depicts the five closest user profiles to the chosen applicant. Based on importance weight assigned to each profile by the method, we see that the prototype under column zero is the most representative user profile by far. This is (intuitively) confirmed from the feature similarity where more than 50% of the features (12 out of 23) of this prototype are identical to that of the chosen user whose prediction we want to explain. Also, the bank employee looking at the prototypical users and their features surmise that the approved applicant belongs to a group with high values of ExternalRiskEstimate. This justification gives the bank employees more confidence in approving the user’s application."
},
{
"code": null,
"e": 9204,
"s": 8972,
"text": "Now, let’s explore different scenarios and see how the model performs. We can apply the data filters within the data table (no need to write SQL queries to filter your data) and explain multiple instances and scenarios very easily."
},
{
"code": null,
"e": 9480,
"s": 9204,
"text": "This is extremely useful when you are trying to understand behaviour on a specific cluster or group of data. For example, we want to see if the model attributes the same weights to the users when the ExternalRiskEstimate is > 60 and MSinceOldestTradeOpen is greater than 200."
},
{
"code": null,
"e": 9559,
"s": 9480,
"text": "We can clearly see the dominance of ExternalRiskEstimate from the chart below."
},
{
"code": null,
"e": 10085,
"s": 9559,
"text": "When the ExternalRiskEstimate is greater than 60, it is seen as a positive sign which matches our internal mental model as well: ExternalRiskEstimate is actually monotonically decreasing which means that as the value of ExternalRiskEstimate increases, the probability of Bad Credit Score decreases! So in this cluster where the RiskEstimate is greater than 60, we will have more Good customers who were extended the credit line. We can confirm this by using a feature interaction plot, specifically a partial dependence plot:"
},
{
"code": null,
"e": 10263,
"s": 10085,
"text": "The partial dependence plot validates our assumption. In the plot below, Red = Good RiskPerformance (credit line extended) and Silver = Bad RiskPerformance (credit line denied)."
},
{
"code": null,
"e": 10546,
"s": 10263,
"text": "We can clearly see that pattern that as ExternalRiskEstimate value increases, its impacts on the output also increases and we have more instances of good risk performance. We see more concentration of red dots as the ExternalRiskEstimate value goes up and that makes a lot of sense!"
},
{
"code": null,
"e": 10782,
"s": 10546,
"text": "Data Scientists can use explainx to further explore patterns by looking at interactions between different variables and how they impact the overall prediction. So let’s end by summarizing our findings for a business user to understand:"
},
{
"code": null,
"e": 10955,
"s": 10782,
"text": "According to the CatBoost model, ExternalRiskEstimate, MSinceMostRecentInq and PercentTradesNeverDelqare the top three variables with the largest impact on RiskPerformance."
},
{
"code": null,
"e": 11174,
"s": 10955,
"text": "ExternalRiskEstimate impacts the predicting variable positively — pushes it towards “Good Credit Risk” but delinquency variables push the overall prediction towards “Bad Credit Risk” (in this case, application denied)."
},
{
"code": null,
"e": 11552,
"s": 11174,
"text": "For our customer # 9, RiskPerformance = Good, ExternalRiskEstimate played a positive role in pushing the prediction towards “good credit behaviour”. However, PercentTradesNeverDelq affected the prediction negatively: this might be the case if the value of this variable is extremely small because the smaller value for this variable lowers the probability of good credit score."
},
{
"code": null,
"e": 11684,
"s": 11552,
"text": "We found customers that had very similar behaviour and variable values to our customer # 9: strengthening our hypothesis even more."
},
{
"code": null,
"e": 11872,
"s": 11684,
"text": "We were able to validate the model’s logic by further exploring the PDP that clearly showed us how increasing the value of ExternalRiskEstimate increases the probability of loan approval."
},
{
"code": null,
"e": 12012,
"s": 11872,
"text": "Data Scientist can further explore a similar process and build an even more comprehensive data narrative that anyone can easily understand."
},
{
"code": null,
"e": 12320,
"s": 12012,
"text": "I hope you all enjoyed this case study. Explainability is extremely crucial and more than relevant today — so the ability to present a narrative that shows your understanding of how AI works is a vital skill for a data scientist. This is the real essence of human-AI understanding and democratization of AI."
}
] |
C library function - getenv()
|
The C library function char *getenv(const char *name) searches for the environment string pointed to by name and returns the associated value to the string.
Following is the declaration for getenv() function.
char *getenv(const char *name)
name − This is the C string containing the name of the requested variable.
name − This is the C string containing the name of the requested variable.
This function returns a null-terminated string with the value of the requested environment variable, or NULL if that environment variable does not exist.
The following example shows the usage of getenv() function.
#include <stdio.h>
#include <stdlib.h>
int main () {
printf("PATH : %s\n", getenv("PATH"));
printf("HOME : %s\n", getenv("HOME"));
printf("ROOT : %s\n", getenv("ROOT"));
return(0);
}
Let us compile and run the above program that will produce the following result −
PATH : /sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
HOME : /
ROOT : (null)
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 2007,
"text": "The C library function char *getenv(const char *name) searches for the environment string pointed to by name and returns the associated value to the string."
},
{
"code": null,
"e": 2216,
"s": 2164,
"text": "Following is the declaration for getenv() function."
},
{
"code": null,
"e": 2247,
"s": 2216,
"text": "char *getenv(const char *name)"
},
{
"code": null,
"e": 2322,
"s": 2247,
"text": "name − This is the C string containing the name of the requested variable."
},
{
"code": null,
"e": 2397,
"s": 2322,
"text": "name − This is the C string containing the name of the requested variable."
},
{
"code": null,
"e": 2551,
"s": 2397,
"text": "This function returns a null-terminated string with the value of the requested environment variable, or NULL if that environment variable does not exist."
},
{
"code": null,
"e": 2611,
"s": 2551,
"text": "The following example shows the usage of getenv() function."
},
{
"code": null,
"e": 2808,
"s": 2611,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n printf(\"PATH : %s\\n\", getenv(\"PATH\"));\n printf(\"HOME : %s\\n\", getenv(\"HOME\"));\n printf(\"ROOT : %s\\n\", getenv(\"ROOT\"));\n\n return(0);\n}"
},
{
"code": null,
"e": 2890,
"s": 2808,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 2966,
"s": 2890,
"text": "PATH : /sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin\nHOME : /\nROOT : (null)\n"
},
{
"code": null,
"e": 2999,
"s": 2966,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3014,
"s": 2999,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3049,
"s": 3014,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3064,
"s": 3049,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3099,
"s": 3064,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3113,
"s": 3099,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3146,
"s": 3113,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3164,
"s": 3146,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3199,
"s": 3164,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3218,
"s": 3199,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3251,
"s": 3218,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3263,
"s": 3251,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3270,
"s": 3263,
"text": " Print"
},
{
"code": null,
"e": 3281,
"s": 3270,
"text": " Add Notes"
}
] |
LSB based Image steganography using MATLAB - GeeksforGeeks
|
12 Dec, 2021
Prerequisite: Image Steganography Introduction, Implementation using Python.Steganography is the method of hiding secret data inside any form of digital media. The main idea behind steganography is to hide the existence of data in any medium like audio, video, image, etc. When we talk about image steganography, the idea is quite simple. Images are made up of pixels which usually refer to the color of that particular pixel. In a grayscale (black and white) image, these pixel values range from 0-255, 0 being black and 255 being white. Concept of LSB based data embedding: LSB stands for Least Significant Bit. The idea behind LSB embedding is that if we change the last bit value of a pixel, there won’t be much visible change in the color. For example, 0 is black. Changing the value to 1 won’t make much of a difference since it is still black, just a lighter shade. The encoding is done using the following steps:
Convert the image to grayscaleResize the image if neededConvert the message to its binary formatInitialize output image same as input imageTraverse through each pixel of the image and do the following: Convert the pixel value to binaryGet the next bit of the message to be embeddedCreate a variable tempIf the message bit and the LSB of the pixel are same, set temp = 0If the message bit and the LSB of the pixel are different, set temp = 1This setting of temp can be done by taking XOR of message bit and the LSB of the pixelUpdate the pixel of output image to input image pixel value + tempKeep updating the output image till all the bits in the message are embeddedFinally, write the input as well as the output image to local system.
Convert the image to grayscale
Resize the image if needed
Convert the message to its binary format
Initialize output image same as input image
Traverse through each pixel of the image and do the following: Convert the pixel value to binaryGet the next bit of the message to be embeddedCreate a variable tempIf the message bit and the LSB of the pixel are same, set temp = 0If the message bit and the LSB of the pixel are different, set temp = 1This setting of temp can be done by taking XOR of message bit and the LSB of the pixelUpdate the pixel of output image to input image pixel value + temp
Convert the pixel value to binary
Get the next bit of the message to be embedded
Create a variable temp
If the message bit and the LSB of the pixel are same, set temp = 0
If the message bit and the LSB of the pixel are different, set temp = 1
This setting of temp can be done by taking XOR of message bit and the LSB of the pixel
Update the pixel of output image to input image pixel value + temp
Keep updating the output image till all the bits in the message are embedded
Finally, write the input as well as the output image to local system.
Example:Input : message=’geeksforgeeks’
Output : Image with the given message embedded:
Below is the implementation in MATLAB:
matlab
% Clear the existing workspaceclear all; % Clear the command windowclc; % Read the input imageinput = imread('peppers.png'); % Convert image to grayscaleinput=rgb2gray(input); % Resize the image to required sizeinput=imresize(input, [512 512]); % Message to be embeddedmessage='geeksforgeeks'; % Length of the message where each character is 8 bitslen = length(message) * 8; % Get all the ASCII values of the characters of the messageascii_value = uint8(message); % Convert the decimal values to binarybin_message = transpose(dec2bin(ascii_value, 8)); % Get all the binary digits in separate rowbin_message = bin_message(:); % Length of the binary messageN = length(bin_message); % Converting the char array to numeric arraybin_num_message=str2num(bin_message); % Initialize output as inputoutput = input; % Get height and width for traversing through the imageheight = size(input, 1);width = size(input, 2); % Counter for number of embedded bitsembed_counter = 1; % Traverse through the imagefor i = 1 : height for j = 1 : width % If more bits are remaining to embed if(embed_counter <= len) % Finding the Least Significant Bit of the current pixel LSB = mod(double(input(i, j)), 2); % Find whether the bit is same or needs to change temp = double(xor(LSB, bin_num_message(embed_counter))); % Updating the output to input + temp output(i, j) = input(i, j)+temp; % Increment the embed counter embed_counter = embed_counter+1; end endend % Write both the input and output images to local storage% Mention the path to a folder here.imwrite(input, 'path_to_folder\originalImage.png');imwrite(output, 'path_to_folder\stegoImage.png');
Comparison of images:
As we can see in the above screenshot, the input and the output image look exactly the same to the human eye. The output image has the message embedded in it.Advantages of this method:
This method is very fast and easy to implement in comparison to other methods of image Steganography.
The output image has very slight difference to the input image.
Instead of embedding the message in only the LSB, we can embed the message in last two LSBs, thus embedding even large messages.
This method forms the basics of many other complex algorithms
Instead of embedding the message in only the LSB, we can embed the message in last two LSBs, thus embedding even large messages.
Disadvantages of this method:
This type of encoding the data is weak since it can be easily decoded by taking the LSBs of the image and getting the message in binary format.
This is method is too old because it was used long ago when other encoding methods were not yet developed.
When embedding the message in more than one LSB, the image quality may reduce depending on how many pixels are changed.
aravind3y
adnanirshad158
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Decision Tree Introduction with example
Reinforcement learning
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction
|
[
{
"code": null,
"e": 26475,
"s": 26447,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 27397,
"s": 26475,
"text": "Prerequisite: Image Steganography Introduction, Implementation using Python.Steganography is the method of hiding secret data inside any form of digital media. The main idea behind steganography is to hide the existence of data in any medium like audio, video, image, etc. When we talk about image steganography, the idea is quite simple. Images are made up of pixels which usually refer to the color of that particular pixel. In a grayscale (black and white) image, these pixel values range from 0-255, 0 being black and 255 being white. Concept of LSB based data embedding: LSB stands for Least Significant Bit. The idea behind LSB embedding is that if we change the last bit value of a pixel, there won’t be much visible change in the color. For example, 0 is black. Changing the value to 1 won’t make much of a difference since it is still black, just a lighter shade. The encoding is done using the following steps: "
},
{
"code": null,
"e": 28135,
"s": 27397,
"text": "Convert the image to grayscaleResize the image if neededConvert the message to its binary formatInitialize output image same as input imageTraverse through each pixel of the image and do the following: Convert the pixel value to binaryGet the next bit of the message to be embeddedCreate a variable tempIf the message bit and the LSB of the pixel are same, set temp = 0If the message bit and the LSB of the pixel are different, set temp = 1This setting of temp can be done by taking XOR of message bit and the LSB of the pixelUpdate the pixel of output image to input image pixel value + tempKeep updating the output image till all the bits in the message are embeddedFinally, write the input as well as the output image to local system."
},
{
"code": null,
"e": 28166,
"s": 28135,
"text": "Convert the image to grayscale"
},
{
"code": null,
"e": 28193,
"s": 28166,
"text": "Resize the image if needed"
},
{
"code": null,
"e": 28234,
"s": 28193,
"text": "Convert the message to its binary format"
},
{
"code": null,
"e": 28278,
"s": 28234,
"text": "Initialize output image same as input image"
},
{
"code": null,
"e": 28732,
"s": 28278,
"text": "Traverse through each pixel of the image and do the following: Convert the pixel value to binaryGet the next bit of the message to be embeddedCreate a variable tempIf the message bit and the LSB of the pixel are same, set temp = 0If the message bit and the LSB of the pixel are different, set temp = 1This setting of temp can be done by taking XOR of message bit and the LSB of the pixelUpdate the pixel of output image to input image pixel value + temp"
},
{
"code": null,
"e": 28766,
"s": 28732,
"text": "Convert the pixel value to binary"
},
{
"code": null,
"e": 28813,
"s": 28766,
"text": "Get the next bit of the message to be embedded"
},
{
"code": null,
"e": 28836,
"s": 28813,
"text": "Create a variable temp"
},
{
"code": null,
"e": 28903,
"s": 28836,
"text": "If the message bit and the LSB of the pixel are same, set temp = 0"
},
{
"code": null,
"e": 28975,
"s": 28903,
"text": "If the message bit and the LSB of the pixel are different, set temp = 1"
},
{
"code": null,
"e": 29062,
"s": 28975,
"text": "This setting of temp can be done by taking XOR of message bit and the LSB of the pixel"
},
{
"code": null,
"e": 29129,
"s": 29062,
"text": "Update the pixel of output image to input image pixel value + temp"
},
{
"code": null,
"e": 29206,
"s": 29129,
"text": "Keep updating the output image till all the bits in the message are embedded"
},
{
"code": null,
"e": 29276,
"s": 29206,
"text": "Finally, write the input as well as the output image to local system."
},
{
"code": null,
"e": 29318,
"s": 29276,
"text": "Example:Input : message=’geeksforgeeks’ "
},
{
"code": null,
"e": 29368,
"s": 29318,
"text": "Output : Image with the given message embedded: "
},
{
"code": null,
"e": 29408,
"s": 29368,
"text": "Below is the implementation in MATLAB: "
},
{
"code": null,
"e": 29415,
"s": 29408,
"text": "matlab"
},
{
"code": "% Clear the existing workspaceclear all; % Clear the command windowclc; % Read the input imageinput = imread('peppers.png'); % Convert image to grayscaleinput=rgb2gray(input); % Resize the image to required sizeinput=imresize(input, [512 512]); % Message to be embeddedmessage='geeksforgeeks'; % Length of the message where each character is 8 bitslen = length(message) * 8; % Get all the ASCII values of the characters of the messageascii_value = uint8(message); % Convert the decimal values to binarybin_message = transpose(dec2bin(ascii_value, 8)); % Get all the binary digits in separate rowbin_message = bin_message(:); % Length of the binary messageN = length(bin_message); % Converting the char array to numeric arraybin_num_message=str2num(bin_message); % Initialize output as inputoutput = input; % Get height and width for traversing through the imageheight = size(input, 1);width = size(input, 2); % Counter for number of embedded bitsembed_counter = 1; % Traverse through the imagefor i = 1 : height for j = 1 : width % If more bits are remaining to embed if(embed_counter <= len) % Finding the Least Significant Bit of the current pixel LSB = mod(double(input(i, j)), 2); % Find whether the bit is same or needs to change temp = double(xor(LSB, bin_num_message(embed_counter))); % Updating the output to input + temp output(i, j) = input(i, j)+temp; % Increment the embed counter embed_counter = embed_counter+1; end endend % Write both the input and output images to local storage% Mention the path to a folder here.imwrite(input, 'path_to_folder\\originalImage.png');imwrite(output, 'path_to_folder\\stegoImage.png');",
"e": 31231,
"s": 29415,
"text": null
},
{
"code": null,
"e": 31255,
"s": 31231,
"text": "Comparison of images: "
},
{
"code": null,
"e": 31442,
"s": 31255,
"text": "As we can see in the above screenshot, the input and the output image look exactly the same to the human eye. The output image has the message embedded in it.Advantages of this method: "
},
{
"code": null,
"e": 31544,
"s": 31442,
"text": "This method is very fast and easy to implement in comparison to other methods of image Steganography."
},
{
"code": null,
"e": 31608,
"s": 31544,
"text": "The output image has very slight difference to the input image."
},
{
"code": null,
"e": 31737,
"s": 31608,
"text": "Instead of embedding the message in only the LSB, we can embed the message in last two LSBs, thus embedding even large messages."
},
{
"code": null,
"e": 31799,
"s": 31737,
"text": "This method forms the basics of many other complex algorithms"
},
{
"code": null,
"e": 31928,
"s": 31799,
"text": "Instead of embedding the message in only the LSB, we can embed the message in last two LSBs, thus embedding even large messages."
},
{
"code": null,
"e": 31960,
"s": 31928,
"text": "Disadvantages of this method: "
},
{
"code": null,
"e": 32104,
"s": 31960,
"text": "This type of encoding the data is weak since it can be easily decoded by taking the LSBs of the image and getting the message in binary format."
},
{
"code": null,
"e": 32211,
"s": 32104,
"text": "This is method is too old because it was used long ago when other encoding methods were not yet developed."
},
{
"code": null,
"e": 32333,
"s": 32211,
"text": "When embedding the message in more than one LSB, the image quality may reduce depending on how many pixels are changed. "
},
{
"code": null,
"e": 32345,
"s": 32335,
"text": "aravind3y"
},
{
"code": null,
"e": 32360,
"s": 32345,
"text": "adnanirshad158"
},
{
"code": null,
"e": 32377,
"s": 32360,
"text": "Image-Processing"
},
{
"code": null,
"e": 32384,
"s": 32377,
"text": "MATLAB"
},
{
"code": null,
"e": 32410,
"s": 32384,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 32508,
"s": 32410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32531,
"s": 32508,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 32545,
"s": 32531,
"text": "Decision Tree"
},
{
"code": null,
"e": 32585,
"s": 32545,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 32608,
"s": 32585,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 32652,
"s": 32608,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 32675,
"s": 32652,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 32713,
"s": 32675,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 32747,
"s": 32713,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 32778,
"s": 32747,
"text": "Clustering in Machine Learning"
}
] |
Find distance from root to given node in a binary tree - GeeksforGeeks
|
24 Jun, 2021
Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Distance means the number of edges between two nodes.
Examples:
Input : x = 45,
Root of below tree
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output : Distance = 3
There are three edges on path
from root to 45.
For more understanding of question,
in above tree distance of 35 is two
and distance of 10 is 1.
Approach: The idea is to traverse the tree from the root. Check if x is present at the root or in the left subtree or in the right subtree. We initialize distance as -1 and add 1 to distance for all three cases.
C++
Java
Python3
C#
Javascript
// C++ program to find distance of a given// node from root.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new Binary// Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootint findDistance(Node *root, int x){ // Base case if (root == NULL) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root->data == x) || (dist = findDistance(root->left, x)) >= 0 || (dist = findDistance(root->right, x)) >= 0) return dist + 1; return dist;} // Driver Program to test above functionsint main(){ Node *root = newNode(5); root->left = newNode(10); root->right = newNode(15); root->left->left = newNode(20); root->left->right = newNode(25); root->left->right->right = newNode(45); root->right->left = newNode(30); root->right->right = newNode(35); cout << findDistance(root, 45); return 0;}
// Java program to find distance of a given// node from root.import java.util.*;class GfG { // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // A utility function to create a new Binary// Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootstatic int findDistance(Node root, int x){ // Base case if (root == null) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist;} // Driver Program to test above functionspublic static void main(String[] args){ Node root = newNode(5); root.left = newNode(10); root.right = newNode(15); root.left.left = newNode(20); root.left.right = newNode(25); root.left.right.right = newNode(45); root.right.left = newNode(30); root.right.right = newNode(35); System.out.println(findDistance(root, 45));}}
# Python3 program to find distance of# a given node from root. # A class to create a new Binary# Tree Nodeclass newNode: def __init__(self, item): self.data = item self.left = self.right = None # Returns -1 if x doesn't exist in tree.# Else returns distance of x from rootdef findDistance(root, x): # Base case if (root == None): return -1 # Initialize distance dist = -1 # Check if x is present at root or # in left subtree or right subtree. if (root.data == x): return dist + 1 else: dist = findDistance(root.left, x) if dist >= 0: return dist + 1 else: dist = findDistance(root.right, x) if dist >= 0: return dist + 1 return dist # Driver Codeif __name__ == '__main__': root = newNode(5) root.left = newNode(10) root.right = newNode(15) root.left.left = newNode(20) root.left.right = newNode(25) root.left.right.right = newNode(45) root.right.left = newNode(30) root.right.right = newNode(35) print(findDistance(root, 45)) # This code is contributed by PranchalK
// C# program to find distance of a given// node from root.using System; class GfG{ // A Binary Tree Node class Node { public int data; public Node left, right; } // A utility function to create // a new Binary Tree Node static Node newNode(int item) { Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp; } // Returns -1 if x doesn't exist in tree. Else // returns distance of x from root static int findDistance(Node root, int x) { // Base case if (root == null) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist; } // Driver code public static void Main(String[] args) { Node root = newNode(5); root.left = newNode(10); root.right = newNode(15); root.left.left = newNode(20); root.left.right = newNode(25); root.left.right.right = newNode(45); root.right.left = newNode(30); root.right.right = newNode(35); Console.WriteLine(findDistance(root, 45)); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to find distance// of a given node from root. // A Binary Tree Nodeclass Node{ // A utility function to create a // new Binary Tree Node constructor(data) { this.data = data; this.left = this.right = null; }} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootfunction findDistance(root, x){ // Base case if (root == null) return -1; // Initialize distance let dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist;} // Driver codelet root = new Node(5);root.left = new Node(10);root.right = new Node(15);root.left.left = new Node(20);root.left.right = new Node(25);root.left.right.right = new Node(45);root.right.left = new Node(30);root.right.right = new Node(35); document.write(findDistance(root, 45)); // This code is contributed by rag2127 </script>
Output:
3
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTubeGeeksforGeeks500K subscribersFind distance from root to given node 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 / 4:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pavbfn1FHrs" 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 Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
prerna saini
29AjayKumar
PranchalKatiyar
rohitsingh07052
rag2127
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 35768,
"s": 35740,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 35925,
"s": 35768,
"text": "Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Distance means the number of edges between two nodes."
},
{
"code": null,
"e": 35936,
"s": 35925,
"text": "Examples: "
},
{
"code": null,
"e": 36250,
"s": 35936,
"text": "Input : x = 45,\n Root of below tree\n 5\n / \\\n 10 15\n / \\ / \\\n 20 25 30 35\n \\\n 45\nOutput : Distance = 3 \nThere are three edges on path\nfrom root to 45.\n\nFor more understanding of question,\nin above tree distance of 35 is two\nand distance of 10 is 1."
},
{
"code": null,
"e": 36463,
"s": 36250,
"text": "Approach: The idea is to traverse the tree from the root. Check if x is present at the root or in the left subtree or in the right subtree. We initialize distance as -1 and add 1 to distance for all three cases. "
},
{
"code": null,
"e": 36467,
"s": 36463,
"text": "C++"
},
{
"code": null,
"e": 36472,
"s": 36467,
"text": "Java"
},
{
"code": null,
"e": 36480,
"s": 36472,
"text": "Python3"
},
{
"code": null,
"e": 36483,
"s": 36480,
"text": "C#"
},
{
"code": null,
"e": 36494,
"s": 36483,
"text": "Javascript"
},
{
"code": "// C++ program to find distance of a given// node from root.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; Node *left, *right;}; // A utility function to create a new Binary// Tree NodeNode *newNode(int item){ Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootint findDistance(Node *root, int x){ // Base case if (root == NULL) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root->data == x) || (dist = findDistance(root->left, x)) >= 0 || (dist = findDistance(root->right, x)) >= 0) return dist + 1; return dist;} // Driver Program to test above functionsint main(){ Node *root = newNode(5); root->left = newNode(10); root->right = newNode(15); root->left->left = newNode(20); root->left->right = newNode(25); root->left->right->right = newNode(45); root->right->left = newNode(30); root->right->right = newNode(35); cout << findDistance(root, 45); return 0;}",
"e": 37698,
"s": 36494,
"text": null
},
{
"code": "// Java program to find distance of a given// node from root.import java.util.*;class GfG { // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // A utility function to create a new Binary// Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootstatic int findDistance(Node root, int x){ // Base case if (root == null) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist;} // Driver Program to test above functionspublic static void main(String[] args){ Node root = newNode(5); root.left = newNode(10); root.right = newNode(15); root.left.left = newNode(20); root.left.right = newNode(25); root.left.right.right = newNode(45); root.right.left = newNode(30); root.right.right = newNode(35); System.out.println(findDistance(root, 45));}}",
"e": 38920,
"s": 37698,
"text": null
},
{
"code": "# Python3 program to find distance of# a given node from root. # A class to create a new Binary# Tree Nodeclass newNode: def __init__(self, item): self.data = item self.left = self.right = None # Returns -1 if x doesn't exist in tree.# Else returns distance of x from rootdef findDistance(root, x): # Base case if (root == None): return -1 # Initialize distance dist = -1 # Check if x is present at root or # in left subtree or right subtree. if (root.data == x): return dist + 1 else: dist = findDistance(root.left, x) if dist >= 0: return dist + 1 else: dist = findDistance(root.right, x) if dist >= 0: return dist + 1 return dist # Driver Codeif __name__ == '__main__': root = newNode(5) root.left = newNode(10) root.right = newNode(15) root.left.left = newNode(20) root.left.right = newNode(25) root.left.right.right = newNode(45) root.right.left = newNode(30) root.right.right = newNode(35) print(findDistance(root, 45)) # This code is contributed by PranchalK",
"e": 40050,
"s": 38920,
"text": null
},
{
"code": "// C# program to find distance of a given// node from root.using System; class GfG{ // A Binary Tree Node class Node { public int data; public Node left, right; } // A utility function to create // a new Binary Tree Node static Node newNode(int item) { Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp; } // Returns -1 if x doesn't exist in tree. Else // returns distance of x from root static int findDistance(Node root, int x) { // Base case if (root == null) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist; } // Driver code public static void Main(String[] args) { Node root = newNode(5); root.left = newNode(10); root.right = newNode(15); root.left.left = newNode(20); root.left.right = newNode(25); root.left.right.right = newNode(45); root.right.left = newNode(30); root.right.right = newNode(35); Console.WriteLine(findDistance(root, 45)); }} // This code is contributed by 29AjayKumar",
"e": 41471,
"s": 40050,
"text": null
},
{
"code": "<script> // Javascript program to find distance// of a given node from root. // A Binary Tree Nodeclass Node{ // A utility function to create a // new Binary Tree Node constructor(data) { this.data = data; this.left = this.right = null; }} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootfunction findDistance(root, x){ // Base case if (root == null) return -1; // Initialize distance let dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root.data == x) || (dist = findDistance(root.left, x)) >= 0 || (dist = findDistance(root.right, x)) >= 0) return dist + 1; return dist;} // Driver codelet root = new Node(5);root.left = new Node(10);root.right = new Node(15);root.left.left = new Node(20);root.left.right = new Node(25);root.left.right.right = new Node(45);root.right.left = new Node(30);root.right.right = new Node(35); document.write(findDistance(root, 45)); // This code is contributed by rag2127 </script>",
"e": 42554,
"s": 41471,
"text": null
},
{
"code": null,
"e": 42563,
"s": 42554,
"text": "Output: "
},
{
"code": null,
"e": 42565,
"s": 42563,
"text": "3"
},
{
"code": null,
"e": 42587,
"s": 42565,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 42609,
"s": 42587,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 43462,
"s": 42609,
"text": "YouTubeGeeksforGeeks500K subscribersFind distance from root to given node 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 / 4:03•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=pavbfn1FHrs\" 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": 43885,
"s": 43462,
"text": "This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 43898,
"s": 43885,
"text": "prerna saini"
},
{
"code": null,
"e": 43910,
"s": 43898,
"text": "29AjayKumar"
},
{
"code": null,
"e": 43926,
"s": 43910,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 43942,
"s": 43926,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 43950,
"s": 43942,
"text": "rag2127"
},
{
"code": null,
"e": 43955,
"s": 43950,
"text": "Tree"
},
{
"code": null,
"e": 43960,
"s": 43955,
"text": "Tree"
},
{
"code": null,
"e": 44058,
"s": 43960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44067,
"s": 44058,
"text": "Comments"
},
{
"code": null,
"e": 44080,
"s": 44067,
"text": "Old Comments"
},
{
"code": null,
"e": 44130,
"s": 44080,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 44165,
"s": 44130,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 44199,
"s": 44165,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 44228,
"s": 44199,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 44269,
"s": 44228,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 44312,
"s": 44269,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 44374,
"s": 44312,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 44407,
"s": 44374,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 44421,
"s": 44407,
"text": "Decision Tree"
}
] |
How to get the first day of next month in MySQL?
|
With the help of following MySQL query, we can get the first day of next month −
mysql> SELECT DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01') AS
'FIRST DAY OF NEXT MONTH';
+-------------------------+
| FIRST DAY OF NEXT MONTH |
+-------------------------+
| 2017-11-01 |
+-------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "With the help of following MySQL query, we can get the first day of next month −"
},
{
"code": null,
"e": 1404,
"s": 1143,
"text": "mysql> SELECT DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01') AS\n'FIRST DAY OF NEXT MONTH';\n+-------------------------+\n| FIRST DAY OF NEXT MONTH |\n+-------------------------+\n| 2017-11-01 |\n+-------------------------+\n1 row in set (0.00 sec)"
}
] |
How to set checkbox checked on button click in AngularJS ? - GeeksforGeeks
|
14 Oct, 2020
In this article, we will see how to set checkbox checked on the click of a button in AngularJS.
Approach: The approach is to use the ng-checked to check the checkbox in the DOM. In the first example, a single checkbox is checked by the button and In the second example, multiple checkbox are checked by button. ng-model is used to bind the checkboxes.
Example 1:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.checkIt = function () { if (!$scope.check) { $scope.check = true; } else { $scope.check = false; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set checkbox checked on button click in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Checkbox: <input type="checkbox" ng-checked="check"> <br> <br> <button ng-click="checkIt()" ng-model='check'> Click to Check </button> <br> <br> </div> </div></body> </html>
Output:
Example 2:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.checkIt = function () { if (!$scope.check) { $scope.check = true; } else { $scope.check = false; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set checkbox checked on button click in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Checkbox1: <input type="checkbox" ng-checked="check"> <br> Checkbox2: <input type="checkbox" ng-checked="check"> <br> Checkbox3: <input type="checkbox" ng-checked="check"> <br> <br> <button ng-click="checkIt()" ng-model='check'> Click to Check </button> <br> <br> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 25205,
"s": 25109,
"text": "In this article, we will see how to set checkbox checked on the click of a button in AngularJS."
},
{
"code": null,
"e": 25461,
"s": 25205,
"text": "Approach: The approach is to use the ng-checked to check the checkbox in the DOM. In the first example, a single checkbox is checked by the button and In the second example, multiple checkbox are checked by button. ng-model is used to bind the checkboxes."
},
{
"code": null,
"e": 25472,
"s": 25461,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.checkIt = function () { if (!$scope.check) { $scope.check = true; } else { $scope.check = false; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set checkbox checked on button click in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Checkbox: <input type=\"checkbox\" ng-checked=\"check\"> <br> <br> <button ng-click=\"checkIt()\" ng-model='check'> Click to Check </button> <br> <br> </div> </div></body> </html>",
"e": 26511,
"s": 25472,
"text": null
},
{
"code": null,
"e": 26519,
"s": 26511,
"text": "Output:"
},
{
"code": null,
"e": 26530,
"s": 26519,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.checkIt = function () { if (!$scope.check) { $scope.check = true; } else { $scope.check = false; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set checkbox checked on button click in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Checkbox1: <input type=\"checkbox\" ng-checked=\"check\"> <br> Checkbox2: <input type=\"checkbox\" ng-checked=\"check\"> <br> Checkbox3: <input type=\"checkbox\" ng-checked=\"check\"> <br> <br> <button ng-click=\"checkIt()\" ng-model='check'> Click to Check </button> <br> <br> </div> </div></body> </html>",
"e": 27780,
"s": 26530,
"text": null
},
{
"code": null,
"e": 27788,
"s": 27780,
"text": "Output:"
},
{
"code": null,
"e": 27925,
"s": 27788,
"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": 27940,
"s": 27925,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 27950,
"s": 27940,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27960,
"s": 27950,
"text": "AngularJS"
},
{
"code": null,
"e": 27965,
"s": 27960,
"text": "HTML"
},
{
"code": null,
"e": 27982,
"s": 27965,
"text": "Web Technologies"
},
{
"code": null,
"e": 27987,
"s": 27982,
"text": "HTML"
},
{
"code": null,
"e": 28085,
"s": 27987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28094,
"s": 28085,
"text": "Comments"
},
{
"code": null,
"e": 28107,
"s": 28094,
"text": "Old Comments"
},
{
"code": null,
"e": 28151,
"s": 28107,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28215,
"s": 28151,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 28268,
"s": 28215,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28292,
"s": 28268,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28327,
"s": 28292,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28377,
"s": 28327,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28439,
"s": 28377,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28487,
"s": 28439,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28547,
"s": 28487,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
C program to perform reflection of the given 2D image using computer graphics - GeeksforGeeks
|
04 May, 2021
In this article, we will discuss how to perform reflection in C using computer graphics using logic rather than the direct matrix formula of translation followed by rotation and translation.
This technique has currently been applied for the object taken as a triangle, the code can be applied to any object, provided the (Xn, Yn) coordinates are adapted into it.
The base logic of this technique is that in any given reflection, the lateral inversion of the reflected object is at the same distance from any given side as the source object. i.e., if a source object is at a distance of 10 pixels from the left, then the reflected object will be at a distance of 10 pixels from the right and the same is applicable for top and bottom sides.
Example on a real-life basis:
If a person is standing in front of a mirror, the distance between the right hand of the person and the mirror’s right boundary will be the same as the distance between the left hand of the person’s reflection and the left boundary.
For the convenience of displaying the above technique via a program let’s draw the source object at the 2nd graph quadrant, but it can be done from any quadrant with minor changes to the code.
Steps of the aforementioned technique:
Create an object in the 2nd graph quadrant by providing the coordinates.
For reflection along X-axis:Y-axis coordinates will remain the same.Obtain laterally inverted X-axis coordinates distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis.Draw another object using the laterally inverted X coordinates obtained from the above step while keeping the Y coordinate the same.The above steps will generate a mirror image or reflection of the source object.In this scenario, the reflected object will be formed at the 1st quadrant.
Y-axis coordinates will remain the same.
Obtain laterally inverted X-axis coordinates distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis.
Draw another object using the laterally inverted X coordinates obtained from the above step while keeping the Y coordinate the same.
The above steps will generate a mirror image or reflection of the source object.
In this scenario, the reflected object will be formed at the 1st quadrant.
For reflection along Y-axis:X-axis coordinates will remain the same.Obtain laterally inverted Y-axis coordinates’ distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis. Draw another object using the laterally inverted Y coordinates obtained from the above step while keeping the X coordinate the same.The above steps will generate a mirror image or reflection of the source object.In this scenario, the reflected object will be formed at the 3rd quadrant.
X-axis coordinates will remain the same.
Obtain laterally inverted Y-axis coordinates’ distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis.
Draw another object using the laterally inverted Y coordinates obtained from the above step while keeping the X coordinate the same.
The above steps will generate a mirror image or reflection of the source object.
In this scenario, the reflected object will be formed at the 3rd quadrant.
2c. For reflection along the origin:X-axis and Y-axis coordinates will change.Obtain laterally inverted Y-axis coordinate distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis.Obtain laterally inverted X-axis coordinate distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis. Draw another object using the laterally inverted X and Y coordinates obtained from the above steps.The above steps will generate a mirror image or reflection of the source object.This time, the reflection is about origin as both X & Y coordinates have changed, pushing the object inside out.In this scenario, the reflected object will be formed at the 4th quadrant.
X-axis and Y-axis coordinates will change.
Obtain laterally inverted Y-axis coordinate distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis.
Obtain laterally inverted X-axis coordinate distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis.
Draw another object using the laterally inverted X and Y coordinates obtained from the above steps.
The above steps will generate a mirror image or reflection of the source object.
This time, the reflection is about origin as both X & Y coordinates have changed, pushing the object inside out.
In this scenario, the reflected object will be formed at the 4th quadrant.
Approach:
Draw a line in graphics to act as a Y-axis, by passing along 4 values as parameters of the line() function as line(getmaxx()/2, 0, getmaxx()/2, getmaxy()).Draw a line in graphics to act as X-axis by passing along 4 values as parameters of the line() function as line(0, getmaxy()/2, getmaxx(), getmaxy()/2).Draw an object using the line() function with parameters from set variables.Perform reflection and draw the object along origin using Step 3 of the technique and color it red to distinguish it from other objects.Perform reflection and draw the object along the X-axis using Step 1 of the technique and color it cyan to distinguish it from other objects.Perform reflection and draw the object along the Y-axis using Step 2 of the technique and color it green to distinguish it from other objects.
Draw a line in graphics to act as a Y-axis, by passing along 4 values as parameters of the line() function as line(getmaxx()/2, 0, getmaxx()/2, getmaxy()).
Draw a line in graphics to act as X-axis by passing along 4 values as parameters of the line() function as line(0, getmaxy()/2, getmaxx(), getmaxy()/2).
Draw an object using the line() function with parameters from set variables.
Perform reflection and draw the object along origin using Step 3 of the technique and color it red to distinguish it from other objects.
Perform reflection and draw the object along the X-axis using Step 1 of the technique and color it cyan to distinguish it from other objects.
Perform reflection and draw the object along the Y-axis using Step 2 of the technique and color it green to distinguish it from other objects.
Below is the implementation of the above approach:
C
// C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize the drivers int gm, gd = DETECT, ax, x1 = 100; int x2 = 100, x3 = 200, y1 = 100; int y2 = 200, y3 = 100; // Add in your BGI folder path // like below initgraph(&gd, &gm, // "C:\\TURBOC3\\BGI"); initgraph(&gd, &gm, ""); cleardevice(); // Draw the graph line(getmaxx() / 2, 0, getmaxx() / 2, getmaxy()); line(0, getmaxy() / 2, getmaxx(), getmaxy() / 2); // Object initially at 2nd quadrant printf("Before Reflection Object" " in 2nd Quadrant"); // Set the color setcolor(14); line(x1, y1, x2, y2); line(x2, y2, x3, y3); line(x3, y3, x1, y1); getch(); // After reflection printf("\nAfter Reflection"); // Reflection along origin i.e., // in 4th quadrant setcolor(4); line(getmaxx() - x1, getmaxy() - y1, getmaxx() - x2, getmaxy() - y2); line(getmaxx() - x2, getmaxy() - y2, getmaxx() - x3, getmaxy() - y3); line(getmaxx() - x3, getmaxy() - y3, getmaxx() - x1, getmaxy() - y1); // Reflection along x-axis i.e., // in 1st quadrant setcolor(3); line(getmaxx() - x1, y1, getmaxx() - x2, y2); line(getmaxx() - x2, y2, getmaxx() - x3, y3); line(getmaxx() - x3, y3, getmaxx() - x1, y1); // Reflection along y-axis i.e., // in 3rd quadrant setcolor(2); line(x1, getmaxy() - y1, x2, getmaxy() - y2); line(x2, getmaxy() - y2, x3, getmaxy() - y3); line(x3, getmaxy() - y3, x1, getmaxy() - y1); getch(); // Close the graphics closegraph();}
Output:
c-graphics
computer-graphics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
Header files in C/C++ and its uses
C Program to read contents of Whole File
Basics of File Handling in C
|
[
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n04 May, 2021"
},
{
"code": null,
"e": 25780,
"s": 25589,
"text": "In this article, we will discuss how to perform reflection in C using computer graphics using logic rather than the direct matrix formula of translation followed by rotation and translation."
},
{
"code": null,
"e": 25952,
"s": 25780,
"text": "This technique has currently been applied for the object taken as a triangle, the code can be applied to any object, provided the (Xn, Yn) coordinates are adapted into it."
},
{
"code": null,
"e": 26329,
"s": 25952,
"text": "The base logic of this technique is that in any given reflection, the lateral inversion of the reflected object is at the same distance from any given side as the source object. i.e., if a source object is at a distance of 10 pixels from the left, then the reflected object will be at a distance of 10 pixels from the right and the same is applicable for top and bottom sides."
},
{
"code": null,
"e": 26359,
"s": 26329,
"text": "Example on a real-life basis:"
},
{
"code": null,
"e": 26592,
"s": 26359,
"text": "If a person is standing in front of a mirror, the distance between the right hand of the person and the mirror’s right boundary will be the same as the distance between the left hand of the person’s reflection and the left boundary."
},
{
"code": null,
"e": 26785,
"s": 26592,
"text": "For the convenience of displaying the above technique via a program let’s draw the source object at the 2nd graph quadrant, but it can be done from any quadrant with minor changes to the code."
},
{
"code": null,
"e": 26824,
"s": 26785,
"text": "Steps of the aforementioned technique:"
},
{
"code": null,
"e": 26897,
"s": 26824,
"text": "Create an object in the 2nd graph quadrant by providing the coordinates."
},
{
"code": null,
"e": 27421,
"s": 26897,
"text": "For reflection along X-axis:Y-axis coordinates will remain the same.Obtain laterally inverted X-axis coordinates distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis.Draw another object using the laterally inverted X coordinates obtained from the above step while keeping the Y coordinate the same.The above steps will generate a mirror image or reflection of the source object.In this scenario, the reflected object will be formed at the 1st quadrant."
},
{
"code": null,
"e": 27462,
"s": 27421,
"text": "Y-axis coordinates will remain the same."
},
{
"code": null,
"e": 27632,
"s": 27462,
"text": "Obtain laterally inverted X-axis coordinates distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis."
},
{
"code": null,
"e": 27765,
"s": 27632,
"text": "Draw another object using the laterally inverted X coordinates obtained from the above step while keeping the Y coordinate the same."
},
{
"code": null,
"e": 27846,
"s": 27765,
"text": "The above steps will generate a mirror image or reflection of the source object."
},
{
"code": null,
"e": 27921,
"s": 27846,
"text": "In this scenario, the reflected object will be formed at the 1st quadrant."
},
{
"code": null,
"e": 28451,
"s": 27921,
"text": " For reflection along Y-axis:X-axis coordinates will remain the same.Obtain laterally inverted Y-axis coordinates’ distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis. Draw another object using the laterally inverted Y coordinates obtained from the above step while keeping the X coordinate the same.The above steps will generate a mirror image or reflection of the source object.In this scenario, the reflected object will be formed at the 3rd quadrant."
},
{
"code": null,
"e": 28492,
"s": 28451,
"text": "X-axis coordinates will remain the same."
},
{
"code": null,
"e": 28667,
"s": 28492,
"text": "Obtain laterally inverted Y-axis coordinates’ distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis. "
},
{
"code": null,
"e": 28800,
"s": 28667,
"text": "Draw another object using the laterally inverted Y coordinates obtained from the above step while keeping the X coordinate the same."
},
{
"code": null,
"e": 28881,
"s": 28800,
"text": "The above steps will generate a mirror image or reflection of the source object."
},
{
"code": null,
"e": 28956,
"s": 28881,
"text": "In this scenario, the reflected object will be formed at the 3rd quadrant."
},
{
"code": null,
"e": 29737,
"s": 28956,
"text": "2c. For reflection along the origin:X-axis and Y-axis coordinates will change.Obtain laterally inverted Y-axis coordinate distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis.Obtain laterally inverted X-axis coordinate distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis. Draw another object using the laterally inverted X and Y coordinates obtained from the above steps.The above steps will generate a mirror image or reflection of the source object.This time, the reflection is about origin as both X & Y coordinates have changed, pushing the object inside out.In this scenario, the reflected object will be formed at the 4th quadrant."
},
{
"code": null,
"e": 29780,
"s": 29737,
"text": "X-axis and Y-axis coordinates will change."
},
{
"code": null,
"e": 29949,
"s": 29780,
"text": "Obtain laterally inverted Y-axis coordinate distance by calculating the distance between the Y coordinate of the source object and its nearest surface along the Y-axis."
},
{
"code": null,
"e": 30119,
"s": 29949,
"text": "Obtain laterally inverted X-axis coordinate distance by calculating the distance between the X coordinate of the source object and its nearest surface along the X-axis. "
},
{
"code": null,
"e": 30219,
"s": 30119,
"text": "Draw another object using the laterally inverted X and Y coordinates obtained from the above steps."
},
{
"code": null,
"e": 30300,
"s": 30219,
"text": "The above steps will generate a mirror image or reflection of the source object."
},
{
"code": null,
"e": 30413,
"s": 30300,
"text": "This time, the reflection is about origin as both X & Y coordinates have changed, pushing the object inside out."
},
{
"code": null,
"e": 30488,
"s": 30413,
"text": "In this scenario, the reflected object will be formed at the 4th quadrant."
},
{
"code": null,
"e": 30498,
"s": 30488,
"text": "Approach:"
},
{
"code": null,
"e": 31301,
"s": 30498,
"text": "Draw a line in graphics to act as a Y-axis, by passing along 4 values as parameters of the line() function as line(getmaxx()/2, 0, getmaxx()/2, getmaxy()).Draw a line in graphics to act as X-axis by passing along 4 values as parameters of the line() function as line(0, getmaxy()/2, getmaxx(), getmaxy()/2).Draw an object using the line() function with parameters from set variables.Perform reflection and draw the object along origin using Step 3 of the technique and color it red to distinguish it from other objects.Perform reflection and draw the object along the X-axis using Step 1 of the technique and color it cyan to distinguish it from other objects.Perform reflection and draw the object along the Y-axis using Step 2 of the technique and color it green to distinguish it from other objects."
},
{
"code": null,
"e": 31457,
"s": 31301,
"text": "Draw a line in graphics to act as a Y-axis, by passing along 4 values as parameters of the line() function as line(getmaxx()/2, 0, getmaxx()/2, getmaxy())."
},
{
"code": null,
"e": 31610,
"s": 31457,
"text": "Draw a line in graphics to act as X-axis by passing along 4 values as parameters of the line() function as line(0, getmaxy()/2, getmaxx(), getmaxy()/2)."
},
{
"code": null,
"e": 31687,
"s": 31610,
"text": "Draw an object using the line() function with parameters from set variables."
},
{
"code": null,
"e": 31824,
"s": 31687,
"text": "Perform reflection and draw the object along origin using Step 3 of the technique and color it red to distinguish it from other objects."
},
{
"code": null,
"e": 31966,
"s": 31824,
"text": "Perform reflection and draw the object along the X-axis using Step 1 of the technique and color it cyan to distinguish it from other objects."
},
{
"code": null,
"e": 32109,
"s": 31966,
"text": "Perform reflection and draw the object along the Y-axis using Step 2 of the technique and color it green to distinguish it from other objects."
},
{
"code": null,
"e": 32160,
"s": 32109,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 32162,
"s": 32160,
"text": "C"
},
{
"code": "// C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ // Initialize the drivers int gm, gd = DETECT, ax, x1 = 100; int x2 = 100, x3 = 200, y1 = 100; int y2 = 200, y3 = 100; // Add in your BGI folder path // like below initgraph(&gd, &gm, // \"C:\\\\TURBOC3\\\\BGI\"); initgraph(&gd, &gm, \"\"); cleardevice(); // Draw the graph line(getmaxx() / 2, 0, getmaxx() / 2, getmaxy()); line(0, getmaxy() / 2, getmaxx(), getmaxy() / 2); // Object initially at 2nd quadrant printf(\"Before Reflection Object\" \" in 2nd Quadrant\"); // Set the color setcolor(14); line(x1, y1, x2, y2); line(x2, y2, x3, y3); line(x3, y3, x1, y1); getch(); // After reflection printf(\"\\nAfter Reflection\"); // Reflection along origin i.e., // in 4th quadrant setcolor(4); line(getmaxx() - x1, getmaxy() - y1, getmaxx() - x2, getmaxy() - y2); line(getmaxx() - x2, getmaxy() - y2, getmaxx() - x3, getmaxy() - y3); line(getmaxx() - x3, getmaxy() - y3, getmaxx() - x1, getmaxy() - y1); // Reflection along x-axis i.e., // in 1st quadrant setcolor(3); line(getmaxx() - x1, y1, getmaxx() - x2, y2); line(getmaxx() - x2, y2, getmaxx() - x3, y3); line(getmaxx() - x3, y3, getmaxx() - x1, y1); // Reflection along y-axis i.e., // in 3rd quadrant setcolor(2); line(x1, getmaxy() - y1, x2, getmaxy() - y2); line(x2, getmaxy() - y2, x3, getmaxy() - y3); line(x3, getmaxy() - y3, x1, getmaxy() - y1); getch(); // Close the graphics closegraph();}",
"e": 33874,
"s": 32162,
"text": null
},
{
"code": null,
"e": 33882,
"s": 33874,
"text": "Output:"
},
{
"code": null,
"e": 33893,
"s": 33882,
"text": "c-graphics"
},
{
"code": null,
"e": 33911,
"s": 33893,
"text": "computer-graphics"
},
{
"code": null,
"e": 33922,
"s": 33911,
"text": "C Language"
},
{
"code": null,
"e": 33933,
"s": 33922,
"text": "C Programs"
},
{
"code": null,
"e": 34031,
"s": 33933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34069,
"s": 34031,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 34095,
"s": 34069,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 34117,
"s": 34095,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 34137,
"s": 34117,
"text": "Multithreading in C"
},
{
"code": null,
"e": 34178,
"s": 34137,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34191,
"s": 34178,
"text": "Strings in C"
},
{
"code": null,
"e": 34232,
"s": 34191,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34267,
"s": 34232,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 34308,
"s": 34267,
"text": "C Program to read contents of Whole File"
}
] |
MomentJS - Time from now
|
This method will tell the length of time from now. Suppose for example if you pass a date to this method it will display the difference if it is in years, months, hours, minutes, or seconds.
moment().fromNow();
moment().fromNow(Boolean);
var changeddate = moment([2018, 0, 1]).fromNow();
Observe that the date given to the moment is 01/01/2018, the difference till date is 4 months, so the output is given as 4 months ago.
Observe the following example to check the output when no inputs are given to the moment −
var changeddate = moment().fromNow();
Note that in the above shown output, it has the ago keyword appended at the end. In case you do not need it, pass true to fromNow(true) method as shown below −
var changeddate = moment([2015, 10, 01]).fromNow();
var changeddate1 = moment([2015, 10, 01]).fromNow(true);
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2151,
"s": 1960,
"text": "This method will tell the length of time from now. Suppose for example if you pass a date to this method it will display the difference if it is in years, months, hours, minutes, or seconds."
},
{
"code": null,
"e": 2199,
"s": 2151,
"text": "moment().fromNow();\nmoment().fromNow(Boolean);\n"
},
{
"code": null,
"e": 2249,
"s": 2199,
"text": "var changeddate = moment([2018, 0, 1]).fromNow();"
},
{
"code": null,
"e": 2384,
"s": 2249,
"text": "Observe that the date given to the moment is 01/01/2018, the difference till date is 4 months, so the output is given as 4 months ago."
},
{
"code": null,
"e": 2475,
"s": 2384,
"text": "Observe the following example to check the output when no inputs are given to the moment −"
},
{
"code": null,
"e": 2513,
"s": 2475,
"text": "var changeddate = moment().fromNow();"
},
{
"code": null,
"e": 2673,
"s": 2513,
"text": "Note that in the above shown output, it has the ago keyword appended at the end. In case you do not need it, pass true to fromNow(true) method as shown below −"
},
{
"code": null,
"e": 2782,
"s": 2673,
"text": "var changeddate = moment([2015, 10, 01]).fromNow();\nvar changeddate1 = moment([2015, 10, 01]).fromNow(true);"
},
{
"code": null,
"e": 2789,
"s": 2782,
"text": " Print"
},
{
"code": null,
"e": 2800,
"s": 2789,
"text": " Add Notes"
}
] |
Detect the RGB color from a webcam using Python - OpenCV - GeeksforGeeks
|
02 Sep, 2020
Prerequisites: Python NumPy, Python OpenCV
Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python.
Approach:
Import the cv2 and NumPy modulesCapture the webcam video using the cv2.VideoCapture(0) method.Display the current frame using the cv2.imshow() method.Run a while loop and take the current frame using the read() method.Take the red, blue and green elements and store them in a list.Compute the average of each list.Whichever average has the greatest value, display that color.
Import the cv2 and NumPy modules
Capture the webcam video using the cv2.VideoCapture(0) method.
Display the current frame using the cv2.imshow() method.
Run a while loop and take the current frame using the read() method.
Take the red, blue and green elements and store them in a list.
Compute the average of each list.
Whichever average has the greatest value, display that color.
Python3
# importing required librariesimport cv2import numpy as np # taking the input from webcamvid = cv2.VideoCapture(0) # running while loop just to make sure that# our program keep running untill we stop itwhile True: # capturing the current frame _, frame = vid.read() # displaying the current frame cv2.imshow("frame", frame) # setting values for base colors b = frame[:, :, :1] g = frame[:, :, 1:2] r = frame[:, :, 2:] # computing the mean b_mean = np.mean(b) g_mean = np.mean(g) r_mean = np.mean(r) # displaying the most prominent color if (b_mean > g_mean and b_mean > r_mean): print("Blue") if (g_mean > r_mean and g_mean > b_mean): print("Green") else: print("Red")
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25871,
"s": 25843,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 25914,
"s": 25871,
"text": "Prerequisites: Python NumPy, Python OpenCV"
},
{
"code": null,
"e": 26067,
"s": 25914,
"text": "Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python."
},
{
"code": null,
"e": 26077,
"s": 26067,
"text": "Approach:"
},
{
"code": null,
"e": 26453,
"s": 26077,
"text": "Import the cv2 and NumPy modulesCapture the webcam video using the cv2.VideoCapture(0) method.Display the current frame using the cv2.imshow() method.Run a while loop and take the current frame using the read() method.Take the red, blue and green elements and store them in a list.Compute the average of each list.Whichever average has the greatest value, display that color."
},
{
"code": null,
"e": 26486,
"s": 26453,
"text": "Import the cv2 and NumPy modules"
},
{
"code": null,
"e": 26549,
"s": 26486,
"text": "Capture the webcam video using the cv2.VideoCapture(0) method."
},
{
"code": null,
"e": 26606,
"s": 26549,
"text": "Display the current frame using the cv2.imshow() method."
},
{
"code": null,
"e": 26675,
"s": 26606,
"text": "Run a while loop and take the current frame using the read() method."
},
{
"code": null,
"e": 26739,
"s": 26675,
"text": "Take the red, blue and green elements and store them in a list."
},
{
"code": null,
"e": 26773,
"s": 26739,
"text": "Compute the average of each list."
},
{
"code": null,
"e": 26835,
"s": 26773,
"text": "Whichever average has the greatest value, display that color."
},
{
"code": null,
"e": 26843,
"s": 26835,
"text": "Python3"
},
{
"code": "# importing required librariesimport cv2import numpy as np # taking the input from webcamvid = cv2.VideoCapture(0) # running while loop just to make sure that# our program keep running untill we stop itwhile True: # capturing the current frame _, frame = vid.read() # displaying the current frame cv2.imshow(\"frame\", frame) # setting values for base colors b = frame[:, :, :1] g = frame[:, :, 1:2] r = frame[:, :, 2:] # computing the mean b_mean = np.mean(b) g_mean = np.mean(g) r_mean = np.mean(r) # displaying the most prominent color if (b_mean > g_mean and b_mean > r_mean): print(\"Blue\") if (g_mean > r_mean and g_mean > b_mean): print(\"Green\") else: print(\"Red\")",
"e": 27594,
"s": 26843,
"text": null
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Output:"
},
{
"code": null,
"e": 27616,
"s": 27602,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27623,
"s": 27616,
"text": "Python"
},
{
"code": null,
"e": 27721,
"s": 27623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27739,
"s": 27721,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27774,
"s": 27739,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27806,
"s": 27774,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27828,
"s": 27806,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27870,
"s": 27828,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27900,
"s": 27870,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27926,
"s": 27900,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27955,
"s": 27926,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27999,
"s": 27955,
"text": "Reading and Writing to text files in Python"
}
] |
C++ Loop Types
|
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −
C++ programming language provides the following type of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2548,
"s": 2318,
"text": "There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 2654,
"s": 2548,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 2835,
"s": 2654,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 2929,
"s": 2835,
"text": "C++ programming language provides the following type of loops to handle looping requirements."
},
{
"code": null,
"e": 3060,
"s": 2929,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 3165,
"s": 3060,
"text": "Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 3255,
"s": 3165,
"text": "Like a ‘while’ statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 3339,
"s": 3255,
"text": "You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop."
},
{
"code": null,
"e": 3506,
"s": 3339,
"text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 3553,
"s": 3506,
"text": "C++ supports the following control statements."
},
{
"code": null,
"e": 3676,
"s": 3553,
"text": "Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch."
},
{
"code": null,
"e": 3785,
"s": 3676,
"text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 3893,
"s": 3785,
"text": "Transfers control to the labeled statement. Though it is not advised to use goto statement in your program."
},
{
"code": null,
"e": 4160,
"s": 3893,
"text": "A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty."
},
{
"code": null,
"e": 4301,
"s": 4160,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n for( ; ; ) {\n printf(\"This loop will run forever.\\n\");\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 4519,
"s": 4301,
"text": "When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop."
},
{
"code": null,
"e": 4588,
"s": 4519,
"text": "NOTE − You can terminate an infinite loop by pressing Ctrl + C keys."
},
{
"code": null,
"e": 4625,
"s": 4588,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4644,
"s": 4625,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4676,
"s": 4644,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 4699,
"s": 4676,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4735,
"s": 4699,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4752,
"s": 4735,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4787,
"s": 4752,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4804,
"s": 4787,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4839,
"s": 4804,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4856,
"s": 4839,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4891,
"s": 4856,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4908,
"s": 4891,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4915,
"s": 4908,
"text": " Print"
},
{
"code": null,
"e": 4926,
"s": 4915,
"text": " Add Notes"
}
] |
Python Faker Library - GeeksforGeeks
|
24 Nov, 2020
Faker is a Python package that generates fake data for you.
Installation: Help LinkOpen Anaconda prompt command to install:
conda install -c conda-forge faker
Import package
from faker import Faker
Faker has the ability to print/get a lot of different fake data, for instance, it can print fake name, address, email, text, etc.
Important most commonly used faker commands
fake.name()
fake.address()
fake.email()
fake.text()
fake.country()
from faker import Fakerfake = Faker()print (fake.email())print(fake.country())print(fake.name())print(fake.text())print(fake.latitude(), fake.longitude())print(fake.url())
OUTPUT:(Different every time)
vwilson@hotmail.com
Belgium
Shane Hunter
Commodi vel libero placeat quibusdam odio odio consequatur. Ducimus libero quae optio non quidem. Facilis quas impedit quo.
26.5687745 -124.802165
http://www.turner.com/
Application 1 : Create a json of 100 students with name students.json that contains student name, address, location coordinates and student roll number.
from faker import Faker # To create a json fileimport json # For student id from random import randint fake = Faker() def input_data(x): # dictionary student_data ={} for i in range(0, x): student_data[i]={} student_data[i]['id']= randint(1, 100) student_data[i]['name']= fake.name() student_data[i]['address']= fake.address() student_data[i]['latitude']= str(fake.latitude()) student_data[i]['longitude']= str(fake.longitude()) print(student_data) # dictionary dumped as json in a json file with open('students.json', 'w') as fp: json.dump(student_data, fp) def main(): # Enter number of students # For the above task make this 100 number_of_students = 10 input_data(number_of_students) main() # The folder or location where this python code # is save there a students.json will be created # having 10 students data.
OUTPUT
{0: {'id': 20, 'name': 'Benjamin Washington', 'address': 'USCGC Garrison\nFPO AP 48025-9793', 'latitude': '-68.975800', 'longitude': '153.009590'}, 1: {'id': 2, 'name': 'Christopher Howell', 'address': '7778 Sarah Center Apt. 663\nLawrenceport, WY 78084', 'latitude': '-21.8141675', 'longitude': '-122.830387'}, 2: {'id': 67, 'name': 'Fernando Fuentes', 'address': '7756 Bradford Plain Suite 997\nEast Chelseaburgh, KY 75776', 'latitude': '-82.791227', 'longitude': '-42.964122'}, 3: {'id': 86, 'name': 'Patrick Torres', 'address': 'Unit 5217 Box 7477\nDPO AE 82354-0160', 'latitude': '34.949096', 'longitude': '121.715387'}, 4: {'id': 11, 'name': 'James Hines', 'address': '4567 Donald Grove\nWilliamhaven, MO 85891', 'latitude': '86.7208035', 'longitude': '-48.103935'}, 5: {'id': 33, 'name': 'James Miller', 'address': 'PSC 2613, Box 7165\nAPO AP 29256-6576', 'latitude': '-35.4630595', 'longitude': '-50.415667'}, 6: {'id': 76, 'name': 'Randall Fuller', 'address': '7731 Garcia Pike\nNew Eric, KS 20545', 'latitude': '12.198124', 'longitude': '126.720134'}, 7: {'id': 49, 'name': 'Ivan Franco', 'address': '801 Chambers Light\nWest Daniel, IA 17114-4374', 'latitude': '-58.2576055', 'longitude': '171.773233'}, 8: {'id': 75, 'name': 'Amy Smith', 'address': '995 Luna Stream Apt. 297\nThompsonchester, NY 82115', 'latitude': '80.4262245', 'longitude': '115.142004'}, 9: {'id': 38, 'name': 'Danielle Thomas', 'address': '7309 Chris Ferry Suite 674\nColebury, MA 39673-2967', 'latitude': '-73.340443', 'longitude': '-176.964241'}}
Application 2: Print 10 fake names and countries in Hindi language.
from faker import Faker #'hi_IN' changed the languagefake = Faker('hi_IN') for i in range(0, 10): print('Name->', fake.name(), 'Country->', fake.country())
Application 3: Create fake profile
import faker from Fakerfake = Faker()print(fake.profile())
OUTPUT
{'job': 'Town planner', 'company': 'Martinez-Clark', 'ssn': '559-93-0521', 'residence': '46820 Johnny Circles\nStokesside, IL 87065-2470', 'current_location': (Decimal('83.5271055'), Decimal('43.705455')), 'blood_group': 'A+', 'website': ['https://www.taylor.com/'], 'username': 'hsmith', 'name': 'Christopher Davis', 'sex': 'M', 'address': '335 Mcdaniel Fork Suite 589\nTeresabury, AZ 85283', 'mail': 'kenneth48@yahoo.com', 'birthdate': '1981-03-29'}
Application 4: Seeding the Generator getting particular fake data again.Seeding gives use the same fake data result that was generated at first instance at that seed number.Example
from faker import Fakerfake = Faker() fake.seed(1)print(fake.name())print(fake.address())print(fake.email())
OUTPUT
Ryan Gallagher
7631 Johnson Village Suite 690
Adamsbury, NC 50008
bparks@johnson.info
NOTE: Even if I run the program, again and again, I would get the same result. As soon as I remove that fake.seed(1) line, we see randomness in data generation.
Application 5: Print data from the list you want.
import faker from Faker fake = Faker() # Print random sentences print(fake.sentence()) # List has words that we want in our sentence word_list = ["GFG", "Geeksforgeeks", "shaurya", "says", "Gfg", "GEEKS"] # Let's print 5 sentences that# have words from our word_list for i in range(0, 5): # You need to use ext_word_list = listnameyoucreated print(fake.sentence(ext_word_list = word_list))
OUTPUT
# This is the random sentence that is generated using
# fake.sentence()
Error architecto inventore aut.
# These are the 5 sentence that contains words from
# word_list we provided
Shaurya shaurya GEEKS Geeksforgeeks.
Gfg shaurya Geeksforgeeks GFG Gfg GFG.
Geeksforgeeks Gfg says Geeksforgeeks GEEKS Gfg Gfg GFG.
Geeksforgeeks shaurya GFG Geeksforgeeks Gfg GEEKS.
Gfg Geeksforgeeks says GFG GEEKS says.
Summary of what we learned from Faker1. Fake data generation like name, address, email, text, sentence, etc2. Creating a JSON file of fake data.3. Different language fake data printed.4. Creating Profile5. Seeding i.e printing particular fake data6. Generating a sentence that contains the words we provided.
Python-Library
Python
Technical Scripter
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
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
|
[
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 24776,
"s": 24716,
"text": "Faker is a Python package that generates fake data for you."
},
{
"code": null,
"e": 24840,
"s": 24776,
"text": "Installation: Help LinkOpen Anaconda prompt command to install:"
},
{
"code": null,
"e": 24877,
"s": 24840,
"text": "conda install -c conda-forge faker \n"
},
{
"code": null,
"e": 24892,
"s": 24877,
"text": "Import package"
},
{
"code": null,
"e": 24917,
"s": 24892,
"text": " from faker import Faker"
},
{
"code": null,
"e": 25047,
"s": 24917,
"text": "Faker has the ability to print/get a lot of different fake data, for instance, it can print fake name, address, email, text, etc."
},
{
"code": null,
"e": 25091,
"s": 25047,
"text": "Important most commonly used faker commands"
},
{
"code": null,
"e": 25159,
"s": 25091,
"text": "fake.name()\nfake.address()\nfake.email()\nfake.text()\nfake.country()\n"
},
{
"code": "from faker import Fakerfake = Faker()print (fake.email())print(fake.country())print(fake.name())print(fake.text())print(fake.latitude(), fake.longitude())print(fake.url())",
"e": 25331,
"s": 25159,
"text": null
},
{
"code": null,
"e": 25573,
"s": 25331,
"text": "OUTPUT:(Different every time)\nvwilson@hotmail.com\nBelgium\nShane Hunter\nCommodi vel libero placeat quibusdam odio odio consequatur. Ducimus libero quae optio non quidem. Facilis quas impedit quo.\n26.5687745 -124.802165\nhttp://www.turner.com/\n"
},
{
"code": null,
"e": 25726,
"s": 25573,
"text": "Application 1 : Create a json of 100 students with name students.json that contains student name, address, location coordinates and student roll number."
},
{
"code": "from faker import Faker # To create a json fileimport json # For student id from random import randint fake = Faker() def input_data(x): # dictionary student_data ={} for i in range(0, x): student_data[i]={} student_data[i]['id']= randint(1, 100) student_data[i]['name']= fake.name() student_data[i]['address']= fake.address() student_data[i]['latitude']= str(fake.latitude()) student_data[i]['longitude']= str(fake.longitude()) print(student_data) # dictionary dumped as json in a json file with open('students.json', 'w') as fp: json.dump(student_data, fp) def main(): # Enter number of students # For the above task make this 100 number_of_students = 10 input_data(number_of_students) main() # The folder or location where this python code # is save there a students.json will be created # having 10 students data. ",
"e": 26674,
"s": 25726,
"text": null
},
{
"code": null,
"e": 28215,
"s": 26674,
"text": "OUTPUT \n{0: {'id': 20, 'name': 'Benjamin Washington', 'address': 'USCGC Garrison\\nFPO AP 48025-9793', 'latitude': '-68.975800', 'longitude': '153.009590'}, 1: {'id': 2, 'name': 'Christopher Howell', 'address': '7778 Sarah Center Apt. 663\\nLawrenceport, WY 78084', 'latitude': '-21.8141675', 'longitude': '-122.830387'}, 2: {'id': 67, 'name': 'Fernando Fuentes', 'address': '7756 Bradford Plain Suite 997\\nEast Chelseaburgh, KY 75776', 'latitude': '-82.791227', 'longitude': '-42.964122'}, 3: {'id': 86, 'name': 'Patrick Torres', 'address': 'Unit 5217 Box 7477\\nDPO AE 82354-0160', 'latitude': '34.949096', 'longitude': '121.715387'}, 4: {'id': 11, 'name': 'James Hines', 'address': '4567 Donald Grove\\nWilliamhaven, MO 85891', 'latitude': '86.7208035', 'longitude': '-48.103935'}, 5: {'id': 33, 'name': 'James Miller', 'address': 'PSC 2613, Box 7165\\nAPO AP 29256-6576', 'latitude': '-35.4630595', 'longitude': '-50.415667'}, 6: {'id': 76, 'name': 'Randall Fuller', 'address': '7731 Garcia Pike\\nNew Eric, KS 20545', 'latitude': '12.198124', 'longitude': '126.720134'}, 7: {'id': 49, 'name': 'Ivan Franco', 'address': '801 Chambers Light\\nWest Daniel, IA 17114-4374', 'latitude': '-58.2576055', 'longitude': '171.773233'}, 8: {'id': 75, 'name': 'Amy Smith', 'address': '995 Luna Stream Apt. 297\\nThompsonchester, NY 82115', 'latitude': '80.4262245', 'longitude': '115.142004'}, 9: {'id': 38, 'name': 'Danielle Thomas', 'address': '7309 Chris Ferry Suite 674\\nColebury, MA 39673-2967', 'latitude': '-73.340443', 'longitude': '-176.964241'}}\n"
},
{
"code": null,
"e": 28283,
"s": 28215,
"text": "Application 2: Print 10 fake names and countries in Hindi language."
},
{
"code": "from faker import Faker #'hi_IN' changed the languagefake = Faker('hi_IN') for i in range(0, 10): print('Name->', fake.name(), 'Country->', fake.country()) ",
"e": 28462,
"s": 28283,
"text": null
},
{
"code": null,
"e": 28497,
"s": 28462,
"text": "Application 3: Create fake profile"
},
{
"code": "import faker from Fakerfake = Faker()print(fake.profile())",
"e": 28556,
"s": 28497,
"text": null
},
{
"code": null,
"e": 29016,
"s": 28556,
"text": "OUTPUT\n{'job': 'Town planner', 'company': 'Martinez-Clark', 'ssn': '559-93-0521', 'residence': '46820 Johnny Circles\\nStokesside, IL 87065-2470', 'current_location': (Decimal('83.5271055'), Decimal('43.705455')), 'blood_group': 'A+', 'website': ['https://www.taylor.com/'], 'username': 'hsmith', 'name': 'Christopher Davis', 'sex': 'M', 'address': '335 Mcdaniel Fork Suite 589\\nTeresabury, AZ 85283', 'mail': 'kenneth48@yahoo.com', 'birthdate': '1981-03-29'}\n"
},
{
"code": null,
"e": 29197,
"s": 29016,
"text": "Application 4: Seeding the Generator getting particular fake data again.Seeding gives use the same fake data result that was generated at first instance at that seed number.Example"
},
{
"code": "from faker import Fakerfake = Faker() fake.seed(1)print(fake.name())print(fake.address())print(fake.email())",
"e": 29307,
"s": 29197,
"text": null
},
{
"code": null,
"e": 29401,
"s": 29307,
"text": "OUTPUT\nRyan Gallagher\n7631 Johnson Village Suite 690\nAdamsbury, NC 50008\nbparks@johnson.info\n"
},
{
"code": null,
"e": 29562,
"s": 29401,
"text": "NOTE: Even if I run the program, again and again, I would get the same result. As soon as I remove that fake.seed(1) line, we see randomness in data generation."
},
{
"code": null,
"e": 29612,
"s": 29562,
"text": "Application 5: Print data from the list you want."
},
{
"code": "import faker from Faker fake = Faker() # Print random sentences print(fake.sentence()) # List has words that we want in our sentence word_list = [\"GFG\", \"Geeksforgeeks\", \"shaurya\", \"says\", \"Gfg\", \"GEEKS\"] # Let's print 5 sentences that# have words from our word_list for i in range(0, 5): # You need to use ext_word_list = listnameyoucreated print(fake.sentence(ext_word_list = word_list)) ",
"e": 30041,
"s": 29612,
"text": null
},
{
"code": null,
"e": 30453,
"s": 30041,
"text": "OUTPUT\n# This is the random sentence that is generated using\n# fake.sentence()\nError architecto inventore aut.\n\n# These are the 5 sentence that contains words from \n# word_list we provided\nShaurya shaurya GEEKS Geeksforgeeks.\nGfg shaurya Geeksforgeeks GFG Gfg GFG.\nGeeksforgeeks Gfg says Geeksforgeeks GEEKS Gfg Gfg GFG.\nGeeksforgeeks shaurya GFG Geeksforgeeks Gfg GEEKS.\nGfg Geeksforgeeks says GFG GEEKS says.\n"
},
{
"code": null,
"e": 30762,
"s": 30453,
"text": "Summary of what we learned from Faker1. Fake data generation like name, address, email, text, sentence, etc2. Creating a JSON file of fake data.3. Different language fake data printed.4. Creating Profile5. Seeding i.e printing particular fake data6. Generating a sentence that contains the words we provided."
},
{
"code": null,
"e": 30777,
"s": 30762,
"text": "Python-Library"
},
{
"code": null,
"e": 30784,
"s": 30777,
"text": "Python"
},
{
"code": null,
"e": 30803,
"s": 30784,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30901,
"s": 30803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30910,
"s": 30901,
"text": "Comments"
},
{
"code": null,
"e": 30923,
"s": 30910,
"text": "Old Comments"
},
{
"code": null,
"e": 30941,
"s": 30923,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30976,
"s": 30941,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30998,
"s": 30976,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31030,
"s": 30998,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31060,
"s": 31030,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31102,
"s": 31060,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31139,
"s": 31102,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31183,
"s": 31139,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 31212,
"s": 31183,
"text": "*args and **kwargs in Python"
}
] |
Apache Derby - Update Data
|
The UPDATE statement is used to update data in a table. Apache Derby provides two types of updates (syntax) namely searched update and positioned update.
The searched UPDATE statement updates all the specified columns of a table.
Following is the syntax of the UPDATE query −
ij> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=, and >=, as well as the BETWEEN and LIKE operators.
Suppose you have a table Employee in the database with the 4 records as shown below −
ID |NAME |SALARY |LOCATION
----------------------------------------------------------
1 |Amit |30000 |Hyderabad
2 |Kalyan |40000 |Vishakhapatnam
3 |Renuka |50000 |Delhi
4 |Archana|15000 |Mumbai
The following SQL UPDATE statement updates the location and salary of an employee whose name is Kaylan.
ij> UPDATE Employees SET Location = 'Chennai', Salary = 43000 WHERE Name='Kalyan';
1 rows inserted/updated/deleted
If you get the contents of the Employees table, you can observe the changes done by the UPDATE query.
ij> select * from Employees;
ID |NAME |SALARY |LOCATION
----------------------------------------------------------
1 |Amit |30000 |Hyderabad
2 |Kalyan |43000 |Chennai
3 |Renuka |50000 |Delhi
4 |Archana |15000 |Mumbai
4 rows selected
This section explains how to update the existing records of a table in the Apache Derby database using JDBC application.
If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_NAME ;password=PASSWORD"
Follow the steps given below to update the existing records of a table in Apache Derby.
To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method.
In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method.
You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method.
After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method returns data. Use either of these methods and execute the statement created previously.
Following JDBC example demonstrates how to update the existing records of a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class UpdateData {
public static void main(String args[]) throws Exception {
//Registering the driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
Connection conn = DriverManager.getConnection(URL);
//Creating the Statement object
Statement stmt = conn.createStatement();
//Creating a table and populating it
String query = "CREATE TABLE Employees("
+ "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Name VARCHAR(255), Salary INT NOT NULL, "
+ "Location VARCHAR(255), "
+ "PRIMARY KEY (Id))";
String query = "INSERT INTO Employees("
+ "Name, Salary, Location) VALUES "
+ "('Amit', 30000, 'Hyderabad'), "
+ "('Kalyan', 40000, 'Vishakhapatnam'), "
+ "('Renuka', 50000, 'Delhi'), "
+ "('Archana', 15000, 'Mumbai'), "
+ "('Trupthi', 45000, 'Kochin'), "
+ "('Suchatra', 33000, 'Pune'), "
+ "('Rahul', 39000, 'Lucknow'), "
+ "('Trupti', 45000, 'Kochin')";
//Executing the query
String query = "UPDATE Employees SET Location = 'Chennai', Salary = 43000 WHERE
Name = 'Kalyan'";
int num = stmt.executeUpdate(query);
System.out.println("Number of records updated are: "+num);
}
}
On executing the above program, you will get the following output −
Number of records updated are: 1
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2334,
"s": 2180,
"text": "The UPDATE statement is used to update data in a table. Apache Derby provides two types of updates (syntax) namely searched update and positioned update."
},
{
"code": null,
"e": 2410,
"s": 2334,
"text": "The searched UPDATE statement updates all the specified columns of a table."
},
{
"code": null,
"e": 2456,
"s": 2410,
"text": "Following is the syntax of the UPDATE query −"
},
{
"code": null,
"e": 2553,
"s": 2456,
"text": "ij> UPDATE table_name\n SET column_name = value, column_name = value, ...\n WHERE conditions;\n"
},
{
"code": null,
"e": 2679,
"s": 2553,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=, and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 2765,
"s": 2679,
"text": "Suppose you have a table Employee in the database with the 4 records as shown below −"
},
{
"code": null,
"e": 2973,
"s": 2765,
"text": "ID |NAME |SALARY |LOCATION\n----------------------------------------------------------\n1 |Amit |30000 |Hyderabad\n2 |Kalyan |40000 |Vishakhapatnam\n3 |Renuka |50000 |Delhi\n4 |Archana|15000 |Mumbai \n"
},
{
"code": null,
"e": 3077,
"s": 2973,
"text": "The following SQL UPDATE statement updates the location and salary of an employee whose name is Kaylan."
},
{
"code": null,
"e": 3193,
"s": 3077,
"text": "ij> UPDATE Employees SET Location = 'Chennai', Salary = 43000 WHERE Name='Kalyan';\n1 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 3295,
"s": 3193,
"text": "If you get the contents of the Employees table, you can observe the changes done by the UPDATE query."
},
{
"code": null,
"e": 3546,
"s": 3295,
"text": "ij> select * from Employees;\nID |NAME |SALARY |LOCATION\n----------------------------------------------------------\n1 |Amit |30000 |Hyderabad \n2 |Kalyan |43000 |Chennai\n3 |Renuka |50000 |Delhi\n4 |Archana |15000 |Mumbai\n4 rows selected\n"
},
{
"code": null,
"e": 3667,
"s": 3546,
"text": "This section explains how to update the existing records of a table in the Apache Derby database using JDBC application."
},
{
"code": null,
"e": 3969,
"s": 3667,
"text": "If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_NAME ;password=PASSWORD\""
},
{
"code": null,
"e": 4057,
"s": 3969,
"text": "Follow the steps given below to update the existing records of a table in Apache Derby."
},
{
"code": null,
"e": 4327,
"s": 4057,
"text": "To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method."
},
{
"code": null,
"e": 4635,
"s": 4327,
"text": "In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method."
},
{
"code": null,
"e": 4928,
"s": 4635,
"text": "You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method."
},
{
"code": null,
"e": 5319,
"s": 4928,
"text": "After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method returns data. Use either of these methods and execute the statement created previously."
},
{
"code": null,
"e": 5552,
"s": 5319,
"text": "Following JDBC example demonstrates how to update the existing records of a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver."
},
{
"code": null,
"e": 7057,
"s": 5552,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class UpdateData {\n public static void main(String args[]) throws Exception {\n //Registering the driver\n Class.forName(\"org.apache.derby.jdbc.EmbeddedDriver\");\n //Getting the Connection object\n String URL = \"jdbc:derby:sampleDB;create=true\";\n Connection conn = DriverManager.getConnection(URL);\n\n //Creating the Statement object\n Statement stmt = conn.createStatement();\n\n //Creating a table and populating it\n String query = \"CREATE TABLE Employees(\"\n + \"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, \"\n + \"Name VARCHAR(255), Salary INT NOT NULL, \"\n + \"Location VARCHAR(255), \"\n + \"PRIMARY KEY (Id))\";\n String query = \"INSERT INTO Employees(\"\n + \"Name, Salary, Location) VALUES \"\n + \"('Amit', 30000, 'Hyderabad'), \"\n + \"('Kalyan', 40000, 'Vishakhapatnam'), \"\n + \"('Renuka', 50000, 'Delhi'), \"\n + \"('Archana', 15000, 'Mumbai'), \"\n + \"('Trupthi', 45000, 'Kochin'), \"\n + \"('Suchatra', 33000, 'Pune'), \"\n + \"('Rahul', 39000, 'Lucknow'), \"\n + \"('Trupti', 45000, 'Kochin')\";\n //Executing the query\n String query = \"UPDATE Employees SET Location = 'Chennai', Salary = 43000 WHERE\n Name = 'Kalyan'\";\n int num = stmt.executeUpdate(query);\n System.out.println(\"Number of records updated are: \"+num);\n }\n}"
},
{
"code": null,
"e": 7125,
"s": 7057,
"text": "On executing the above program, you will get the following output −"
},
{
"code": null,
"e": 7160,
"s": 7125,
"text": "Number of records updated are: 1 \n"
},
{
"code": null,
"e": 7195,
"s": 7160,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7214,
"s": 7195,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7249,
"s": 7214,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7270,
"s": 7249,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 7303,
"s": 7270,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7316,
"s": 7303,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7351,
"s": 7316,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7369,
"s": 7351,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7402,
"s": 7369,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7420,
"s": 7402,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7453,
"s": 7420,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7471,
"s": 7453,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7478,
"s": 7471,
"text": " Print"
},
{
"code": null,
"e": 7489,
"s": 7478,
"text": " Add Notes"
}
] |
Average of Cubes of first N natural numbers - GeeksforGeeks
|
08 Oct, 2021
Given a positive integer N, the task is to find the average of cubes of first N natural numbers. Examples:
Input: N = 2 Output: 4.5 Explanation: For integer N = 2, We have ( 13 + 23 ) = 1 + 8 = 9 average = 9 / 2 that is 4.5Input: N = 3 Output: 12 Explanation: For N = 3, We have ( 13 + 23 + 23 + 23 + 33 + 23 ) = 27 + 8 + 1 = 36 average = 36 / 3 that is 12
Naive Approach: The naive approach is to find the sum of cubes of first N natural numbers and divide it by N.Below is the implementation of above approach:
C
C++
Java
Python3
C#
Javascript
// C program for the above approach#include <stdio.h> // Function to find average of cubesdouble findAverageOfCube(int n){ // Store sum of cubes of // numbers in the sum double sum = 0; // Calculate sum of cubes int i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given number int n = 3; // Function Call printf("%lf", findAverageOfCube(n)); return 0;}
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find average of cubesdouble findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given Number int n = 3; // Function Call cout << findAverageOfCube(n);}
// Java program for the above approachimport java.util.*;import java.io.*;class GFG{ // Function to find average of cubesstatic double findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codepublic static void main(String[] args){ // Given Number int n = 3; // Function Call System.out.print(findAverageOfCube(n));}} // This code is contributed by shivanisinghss2110
# Python3 program for the above approach # Function to find average of cubesdef findAverageOfCube(n): # Storing sum of cubes # of numbers in sum sum = 0 # Calculate sum of cubes for i in range(1, n + 1): sum += i * i * i # Return average return round(sum / n, 6) # Driver Codeif __name__ == '__main__': # Given Number n = 3 # Function Call print(findAverageOfCube(n)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to find average of cubesstatic double findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codepublic static void Main(){ // Given Number int n = 3; // Function Call Console.Write(findAverageOfCube(n));}} // This code is contributed by Nidhi_biet
<script>// javascript program for the above approach // Function to find average of cubesfunction findAverageOfCube( n){ // Store sum of cubes of // numbers in the sum let sum = 0; // Calculate sum of cubes let i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Code // Given number let n = 3; // Function Call document.write(findAverageOfCube(n).toFixed(6)); // This code is contributed by todaysgaurav </script>
12.000000
Time complexity: O(N) Efficient Approach:
We know that, Sum of cubes of first N Natural Numbers =
Average is given by: => => => =>
Therefore, the average of the cube sum of first N natural numbers is given by Below is the implementation of above approach:
C
C++
Java
Python3
C#
Javascript
// C program for the above approach#include <stdio.h> // Function to find average of cubesdouble findAverageOfCube(int n){ // Store sum of cubes of // numbers in the sum double sum = 0; // Calculate sum of cubes int i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given number int n = 3; // Function Call printf("%lf", findAverageOfCube(n)); return 0;}
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // function to find an average of cubesdouble findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (n * (n + 1) * (n + 1)) / 4; return ans;} // Driver Codeint main(){ // Given Number int n = 3; // Function Call cout << findAverageofCube(n); return 0;}
// Java program for the above approachclass GFG{ // function to find an average of cubesstatic double findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (int)((n * (n + 1) * (n + 1)) / 4); return ans;} // Driver Codepublic static void main(String[] args){ // Given Number int n = 3; // Function Call System.out.print(findAverageofCube(n));}} // This code is contributed by shivanisinghss2110
# Python3 program for the above approach # Function to find average of cubesdef findAverageOfCube (n): # Apply the formula n*(n+1)^2/4 ans = (n * (n + 1) * (n + 1)) / 4 return ans # Driver codeif __name__ == '__main__': # Given number n = 3 # Function call print(findAverageOfCube(n)) # This code is contributed by himanshu77
// C# program for the above approachusing System;class GFG{ // function to find an average of cubesstatic double findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (int)((n * (n + 1) * (n + 1)) / 4); return ans;} // Driver Codepublic static void Main(){ // Given Number int n = 3; // Function Call Console.Write(findAverageofCube(n));}} // This code is contributed by Code_Mech
<script>// javascript program for the above approach// function to find an average of cubesfunction findAverageofCube(n){ // Apply the formula n(n+1)^2/4 var ans = parseInt(((n * (n + 1) * (n + 1)) / 4)); return ans;} // Driver Code // Given Numbervar n = 3; // Function Calldocument.write(findAverageofCube(n)); // This code is contributed by Amit Katiyar</script>
12.000000
Time Complexity: O(1)
mohit kumar 29
shivanisinghss2110
nidhi_biet
Code_Mech
himanshu77
todaysgaurav
amit143katiyar
gulshankumarar231
maths-cube
Natural Numbers
Aptitude
Articles
C Language
C Programs
C++
C++ Programs
Competitive Programming
Java
Mathematical
Puzzles
Python
Mathematical
Java
Puzzles
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Puzzle | How much money did the man have before entering the bank?
Program to find the last two digits of x^y
Puzzle | Splitting a Cake with a Missing Piece in two equal portion
Order and Ranking Questions & Answers
10 Tips and Tricks to Crack Internships and Placements
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Mutex vs Semaphore
|
[
{
"code": null,
"e": 24721,
"s": 24693,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 24829,
"s": 24721,
"text": "Given a positive integer N, the task is to find the average of cubes of first N natural numbers. Examples: "
},
{
"code": null,
"e": 25080,
"s": 24829,
"text": "Input: N = 2 Output: 4.5 Explanation: For integer N = 2, We have ( 13 + 23 ) = 1 + 8 = 9 average = 9 / 2 that is 4.5Input: N = 3 Output: 12 Explanation: For N = 3, We have ( 13 + 23 + 23 + 23 + 33 + 23 ) = 27 + 8 + 1 = 36 average = 36 / 3 that is 12 "
},
{
"code": null,
"e": 25238,
"s": 25082,
"text": "Naive Approach: The naive approach is to find the sum of cubes of first N natural numbers and divide it by N.Below is the implementation of above approach:"
},
{
"code": null,
"e": 25240,
"s": 25238,
"text": "C"
},
{
"code": null,
"e": 25244,
"s": 25240,
"text": "C++"
},
{
"code": null,
"e": 25249,
"s": 25244,
"text": "Java"
},
{
"code": null,
"e": 25257,
"s": 25249,
"text": "Python3"
},
{
"code": null,
"e": 25260,
"s": 25257,
"text": "C#"
},
{
"code": null,
"e": 25271,
"s": 25260,
"text": "Javascript"
},
{
"code": "// C program for the above approach#include <stdio.h> // Function to find average of cubesdouble findAverageOfCube(int n){ // Store sum of cubes of // numbers in the sum double sum = 0; // Calculate sum of cubes int i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given number int n = 3; // Function Call printf(\"%lf\", findAverageOfCube(n)); return 0;}",
"e": 25742,
"s": 25271,
"text": null
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find average of cubesdouble findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given Number int n = 3; // Function Call cout << findAverageOfCube(n);}",
"e": 26213,
"s": 25742,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;import java.io.*;class GFG{ // Function to find average of cubesstatic double findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codepublic static void main(String[] args){ // Given Number int n = 3; // Function Call System.out.print(findAverageOfCube(n));}} // This code is contributed by shivanisinghss2110",
"e": 26786,
"s": 26213,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find average of cubesdef findAverageOfCube(n): # Storing sum of cubes # of numbers in sum sum = 0 # Calculate sum of cubes for i in range(1, n + 1): sum += i * i * i # Return average return round(sum / n, 6) # Driver Codeif __name__ == '__main__': # Given Number n = 3 # Function Call print(findAverageOfCube(n)) # This code is contributed by mohit kumar 29",
"e": 27244,
"s": 26786,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find average of cubesstatic double findAverageOfCube(int n){ // Storing sum of cubes // of numbers in sum double sum = 0; // Calculate sum of cubes for (int i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codepublic static void Main(){ // Given Number int n = 3; // Function Call Console.Write(findAverageOfCube(n));}} // This code is contributed by Nidhi_biet",
"e": 27768,
"s": 27244,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to find average of cubesfunction findAverageOfCube( n){ // Store sum of cubes of // numbers in the sum let sum = 0; // Calculate sum of cubes let i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Code // Given number let n = 3; // Function Call document.write(findAverageOfCube(n).toFixed(6)); // This code is contributed by todaysgaurav </script>",
"e": 28277,
"s": 27768,
"text": null
},
{
"code": null,
"e": 28287,
"s": 28277,
"text": "12.000000"
},
{
"code": null,
"e": 28333,
"s": 28289,
"text": "Time complexity: O(N) Efficient Approach: "
},
{
"code": null,
"e": 28390,
"s": 28333,
"text": "We know that, Sum of cubes of first N Natural Numbers = "
},
{
"code": null,
"e": 28429,
"s": 28390,
"text": " Average is given by: => => => => "
},
{
"code": null,
"e": 28555,
"s": 28429,
"text": "Therefore, the average of the cube sum of first N natural numbers is given by Below is the implementation of above approach:"
},
{
"code": null,
"e": 28557,
"s": 28555,
"text": "C"
},
{
"code": null,
"e": 28561,
"s": 28557,
"text": "C++"
},
{
"code": null,
"e": 28566,
"s": 28561,
"text": "Java"
},
{
"code": null,
"e": 28574,
"s": 28566,
"text": "Python3"
},
{
"code": null,
"e": 28577,
"s": 28574,
"text": "C#"
},
{
"code": null,
"e": 28588,
"s": 28577,
"text": "Javascript"
},
{
"code": "// C program for the above approach#include <stdio.h> // Function to find average of cubesdouble findAverageOfCube(int n){ // Store sum of cubes of // numbers in the sum double sum = 0; // Calculate sum of cubes int i; for (i = 1; i <= n; i++) { sum += i * i * i; } // Return average return sum / n;} // Driver Codeint main(){ // Given number int n = 3; // Function Call printf(\"%lf\", findAverageOfCube(n)); return 0;}",
"e": 29060,
"s": 28588,
"text": null
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // function to find an average of cubesdouble findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (n * (n + 1) * (n + 1)) / 4; return ans;} // Driver Codeint main(){ // Given Number int n = 3; // Function Call cout << findAverageofCube(n); return 0;}",
"e": 29438,
"s": 29060,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // function to find an average of cubesstatic double findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (int)((n * (n + 1) * (n + 1)) / 4); return ans;} // Driver Codepublic static void main(String[] args){ // Given Number int n = 3; // Function Call System.out.print(findAverageofCube(n));}} // This code is contributed by shivanisinghss2110",
"e": 29872,
"s": 29438,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find average of cubesdef findAverageOfCube (n): # Apply the formula n*(n+1)^2/4 ans = (n * (n + 1) * (n + 1)) / 4 return ans # Driver codeif __name__ == '__main__': # Given number n = 3 # Function call print(findAverageOfCube(n)) # This code is contributed by himanshu77",
"e": 30222,
"s": 29872,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // function to find an average of cubesstatic double findAverageofCube(double n){ // Apply the formula n(n+1)^2/4 int ans = (int)((n * (n + 1) * (n + 1)) / 4); return ans;} // Driver Codepublic static void Main(){ // Given Number int n = 3; // Function Call Console.Write(findAverageofCube(n));}} // This code is contributed by Code_Mech",
"e": 30642,
"s": 30222,
"text": null
},
{
"code": "<script>// javascript program for the above approach// function to find an average of cubesfunction findAverageofCube(n){ // Apply the formula n(n+1)^2/4 var ans = parseInt(((n * (n + 1) * (n + 1)) / 4)); return ans;} // Driver Code // Given Numbervar n = 3; // Function Calldocument.write(findAverageofCube(n)); // This code is contributed by Amit Katiyar</script>",
"e": 31017,
"s": 30642,
"text": null
},
{
"code": null,
"e": 31027,
"s": 31017,
"text": "12.000000"
},
{
"code": null,
"e": 31051,
"s": 31029,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 31066,
"s": 31051,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31085,
"s": 31066,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31096,
"s": 31085,
"text": "nidhi_biet"
},
{
"code": null,
"e": 31106,
"s": 31096,
"text": "Code_Mech"
},
{
"code": null,
"e": 31117,
"s": 31106,
"text": "himanshu77"
},
{
"code": null,
"e": 31130,
"s": 31117,
"text": "todaysgaurav"
},
{
"code": null,
"e": 31145,
"s": 31130,
"text": "amit143katiyar"
},
{
"code": null,
"e": 31163,
"s": 31145,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 31174,
"s": 31163,
"text": "maths-cube"
},
{
"code": null,
"e": 31190,
"s": 31174,
"text": "Natural Numbers"
},
{
"code": null,
"e": 31199,
"s": 31190,
"text": "Aptitude"
},
{
"code": null,
"e": 31208,
"s": 31199,
"text": "Articles"
},
{
"code": null,
"e": 31219,
"s": 31208,
"text": "C Language"
},
{
"code": null,
"e": 31230,
"s": 31219,
"text": "C Programs"
},
{
"code": null,
"e": 31234,
"s": 31230,
"text": "C++"
},
{
"code": null,
"e": 31247,
"s": 31234,
"text": "C++ Programs"
},
{
"code": null,
"e": 31271,
"s": 31247,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31276,
"s": 31271,
"text": "Java"
},
{
"code": null,
"e": 31289,
"s": 31276,
"text": "Mathematical"
},
{
"code": null,
"e": 31297,
"s": 31289,
"text": "Puzzles"
},
{
"code": null,
"e": 31304,
"s": 31297,
"text": "Python"
},
{
"code": null,
"e": 31317,
"s": 31304,
"text": "Mathematical"
},
{
"code": null,
"e": 31322,
"s": 31317,
"text": "Java"
},
{
"code": null,
"e": 31330,
"s": 31322,
"text": "Puzzles"
},
{
"code": null,
"e": 31334,
"s": 31330,
"text": "CPP"
},
{
"code": null,
"e": 31432,
"s": 31334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31441,
"s": 31432,
"text": "Comments"
},
{
"code": null,
"e": 31454,
"s": 31441,
"text": "Old Comments"
},
{
"code": null,
"e": 31521,
"s": 31454,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 31564,
"s": 31521,
"text": "Program to find the last two digits of x^y"
},
{
"code": null,
"e": 31632,
"s": 31564,
"text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion"
},
{
"code": null,
"e": 31670,
"s": 31632,
"text": "Order and Ranking Questions & Answers"
},
{
"code": null,
"e": 31725,
"s": 31670,
"text": "10 Tips and Tricks to Crack Internships and Placements"
},
{
"code": null,
"e": 31775,
"s": 31725,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 31822,
"s": 31775,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 31858,
"s": 31822,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 31911,
"s": 31858,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
}
] |
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ? - GeeksforGeeks
|
22 Jul, 2021
Cookies are simply small text files that a web server sends to the user’s browser. They contain the following data.
Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the server it should be sent to.
Name-value pair with actual data.
The expiry date for when the cookie becomes invalid.
Domain and path of the server it should be sent to.
Approach: To retrieve all the stored cookies in JavaScript, we can use the document.cookie property but this property returns a single string in which the key-value pair is separated by a “;”. It would be great if we can store the key-value pair into an object as it would make the retrieval process much easier. JavaScript does not provide any methods for such a scenario. So let’s work around this problem.
We need to create a function that will parse the cookie string and would return an object containing all the cookies. This would be a simple process with the following steps.
Get each individual key-value pair from the cookie string using string.split(“;”).Separate keys from values in each pair using string.split(“=”).Create an object with all key-value pairs and return the object.
Get each individual key-value pair from the cookie string using string.split(“;”).
Separate keys from values in each pair using string.split(“=”).
Create an object with all key-value pairs and return the object.
Example: Refer to the comments in the following code for better understanding.
Javascript
<script> function cookieParser(cookieString) { // Return an empty object if cookieString // is empty if (cookieString === "") return {}; // Get each individual key-value pairs // from the cookie string // This returns a new array let pairs = cookieString.split(";"); // Separate keys from values in each pair string // Returns a new array which looks like // [[key1,value1], [key2,value2], ...] let splittedPairs = pairs.map(cookie => cookie.split("=")); // Create an object with all key-value pairs const cookieObj = splittedPairs.reduce(function (obj, cookie) { // cookie[0] is the key of cookie // cookie[1] is the value of the cookie // decodeURIComponent() decodes the cookie // string, to handle cookies with special // characters, e.g. '$'. // string.trim() trims the blank spaces // auround the key and value. obj[decodeURIComponent(cookie[0].trim())] = decodeURIComponent(cookie[1].trim()); return obj; }, {}) return cookieObj; } let dummyCookieString = "username=John; gfg=GeeksForGeeks; foo=education"; // Pass document.cookie to retrieve actual cookies let cookieObj = cookieParser(dummyCookieString); console.log(`cookie gfg has value ${cookieObj['gfg']}.`); console.log(`cookie foo has value ${cookieObj['foo']}.`);</script>
Output:
cookie gfg has value GeeksForGeeks.
cookie foo has value education.
gabaa406
http
javascript-functions
JavaScript-Questions
Picked
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": 25398,
"s": 25370,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 25514,
"s": 25398,
"text": "Cookies are simply small text files that a web server sends to the user’s browser. They contain the following data."
},
{
"code": null,
"e": 25651,
"s": 25514,
"text": "Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the server it should be sent to."
},
{
"code": null,
"e": 25685,
"s": 25651,
"text": "Name-value pair with actual data."
},
{
"code": null,
"e": 25738,
"s": 25685,
"text": "The expiry date for when the cookie becomes invalid."
},
{
"code": null,
"e": 25790,
"s": 25738,
"text": "Domain and path of the server it should be sent to."
},
{
"code": null,
"e": 26199,
"s": 25790,
"text": "Approach: To retrieve all the stored cookies in JavaScript, we can use the document.cookie property but this property returns a single string in which the key-value pair is separated by a “;”. It would be great if we can store the key-value pair into an object as it would make the retrieval process much easier. JavaScript does not provide any methods for such a scenario. So let’s work around this problem."
},
{
"code": null,
"e": 26374,
"s": 26199,
"text": "We need to create a function that will parse the cookie string and would return an object containing all the cookies. This would be a simple process with the following steps."
},
{
"code": null,
"e": 26584,
"s": 26374,
"text": "Get each individual key-value pair from the cookie string using string.split(“;”).Separate keys from values in each pair using string.split(“=”).Create an object with all key-value pairs and return the object."
},
{
"code": null,
"e": 26667,
"s": 26584,
"text": "Get each individual key-value pair from the cookie string using string.split(“;”)."
},
{
"code": null,
"e": 26731,
"s": 26667,
"text": "Separate keys from values in each pair using string.split(“=”)."
},
{
"code": null,
"e": 26796,
"s": 26731,
"text": "Create an object with all key-value pairs and return the object."
},
{
"code": null,
"e": 26875,
"s": 26796,
"text": "Example: Refer to the comments in the following code for better understanding."
},
{
"code": null,
"e": 26886,
"s": 26875,
"text": "Javascript"
},
{
"code": "<script> function cookieParser(cookieString) { // Return an empty object if cookieString // is empty if (cookieString === \"\") return {}; // Get each individual key-value pairs // from the cookie string // This returns a new array let pairs = cookieString.split(\";\"); // Separate keys from values in each pair string // Returns a new array which looks like // [[key1,value1], [key2,value2], ...] let splittedPairs = pairs.map(cookie => cookie.split(\"=\")); // Create an object with all key-value pairs const cookieObj = splittedPairs.reduce(function (obj, cookie) { // cookie[0] is the key of cookie // cookie[1] is the value of the cookie // decodeURIComponent() decodes the cookie // string, to handle cookies with special // characters, e.g. '$'. // string.trim() trims the blank spaces // auround the key and value. obj[decodeURIComponent(cookie[0].trim())] = decodeURIComponent(cookie[1].trim()); return obj; }, {}) return cookieObj; } let dummyCookieString = \"username=John; gfg=GeeksForGeeks; foo=education\"; // Pass document.cookie to retrieve actual cookies let cookieObj = cookieParser(dummyCookieString); console.log(`cookie gfg has value ${cookieObj['gfg']}.`); console.log(`cookie foo has value ${cookieObj['foo']}.`);</script>",
"e": 28394,
"s": 26886,
"text": null
},
{
"code": null,
"e": 28402,
"s": 28394,
"text": "Output:"
},
{
"code": null,
"e": 28470,
"s": 28402,
"text": "cookie gfg has value GeeksForGeeks.\ncookie foo has value education."
},
{
"code": null,
"e": 28479,
"s": 28470,
"text": "gabaa406"
},
{
"code": null,
"e": 28484,
"s": 28479,
"text": "http"
},
{
"code": null,
"e": 28505,
"s": 28484,
"text": "javascript-functions"
},
{
"code": null,
"e": 28526,
"s": 28505,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28533,
"s": 28526,
"text": "Picked"
},
{
"code": null,
"e": 28544,
"s": 28533,
"text": "JavaScript"
},
{
"code": null,
"e": 28561,
"s": 28544,
"text": "Web Technologies"
},
{
"code": null,
"e": 28659,
"s": 28561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28699,
"s": 28659,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28760,
"s": 28699,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28801,
"s": 28760,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28823,
"s": 28801,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28877,
"s": 28823,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28917,
"s": 28877,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28950,
"s": 28917,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28993,
"s": 28950,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29043,
"s": 28993,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Equivalence Class Testing- Next date problem - GeeksforGeeks
|
28 Jan, 2020
Equivalence class testing (Equivalence class Partitioning) is a black-box testing technique used in software testing as a major step in the Software development life cycle (SDLC). This testing technique is better than many of the testing techniques like boundary value analysis, worst case testing, robust case testing and many more in terms of time consumption and terms of precision of the test cases. Since testing is done to identify possible risks, equivalence class testing performs better than the other techniques as the test cases generated using it are logically identified with partitions in between to create different input and output classes. This can be shown from the next-date problem which is stated below:
Given a day in the format of day-month-year, you need to find the next date for the given date. Perform boundary value analysis and equivalence-class testing for this.
Conditions :
D: 1<Day<31
M: 1<Month<12
Y: 1800 <Year <2048
Boundary Value Analysis:
No. of test Cases (n = no. of variables) = 4n+1 = 4*3 +1 =13
Test Cases:
Equivalence Class Testing:
Input classes:
Day:
D1: day between 1 to 28
D2: 29
D3: 30
D4: 31
Month:
M1: Month has 30 days
M2: Month has 31 days
M3: Month is February
Year:
Y1: Year is a leap year
Y2: Year is a normal year
Output Classes:
Increment Day
Reset Day and Increment Month
Increment Year
Invalid Date
Strong Normal Equivalence Class Test Cases:
Test Cases:
So from this problem it is clearly seen that equivalence class testing clearly checks for many cases that boundary value did not considered like that of February which has 28-29 days, leap year which lead to variation in number of days in February and many more.
Hence the above example proves that equivalence partitioning generates more efficient test cases that should be considered during risk assessment.
Software Testing
Technical Scripter 2019
Software Engineering
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Software Engineering | SDLC V-Model
Difference between Spring and Spring Boot
Difference between Unit Testing and Integration Testing
Software Engineering | Requirements Engineering Process
Software Engineering | Software Quality Assurance
|
[
{
"code": null,
"e": 25975,
"s": 25947,
"text": "\n28 Jan, 2020"
},
{
"code": null,
"e": 26700,
"s": 25975,
"text": "Equivalence class testing (Equivalence class Partitioning) is a black-box testing technique used in software testing as a major step in the Software development life cycle (SDLC). This testing technique is better than many of the testing techniques like boundary value analysis, worst case testing, robust case testing and many more in terms of time consumption and terms of precision of the test cases. Since testing is done to identify possible risks, equivalence class testing performs better than the other techniques as the test cases generated using it are logically identified with partitions in between to create different input and output classes. This can be shown from the next-date problem which is stated below:"
},
{
"code": null,
"e": 26868,
"s": 26700,
"text": "Given a day in the format of day-month-year, you need to find the next date for the given date. Perform boundary value analysis and equivalence-class testing for this."
},
{
"code": null,
"e": 26881,
"s": 26868,
"text": "Conditions :"
},
{
"code": null,
"e": 26931,
"s": 26881,
"text": "D: 1<Day<31\nM: 1<Month<12\nY: 1800 <Year <2048 "
},
{
"code": null,
"e": 26956,
"s": 26931,
"text": "Boundary Value Analysis:"
},
{
"code": null,
"e": 27018,
"s": 26956,
"text": "No. of test Cases (n = no. of variables) = 4n+1 = 4*3 +1 =13 "
},
{
"code": null,
"e": 27030,
"s": 27018,
"text": "Test Cases:"
},
{
"code": null,
"e": 27057,
"s": 27030,
"text": "Equivalence Class Testing:"
},
{
"code": null,
"e": 27072,
"s": 27057,
"text": "Input classes:"
},
{
"code": null,
"e": 27253,
"s": 27072,
"text": "Day:\nD1: day between 1 to 28\nD2: 29\nD3: 30 \nD4: 31\nMonth:\nM1: Month has 30 days\nM2: Month has 31 days\nM3: Month is February\nYear:\nY1: Year is a leap year\nY2: Year is a normal year "
},
{
"code": null,
"e": 27269,
"s": 27253,
"text": "Output Classes:"
},
{
"code": null,
"e": 27342,
"s": 27269,
"text": "Increment Day\nReset Day and Increment Month\nIncrement Year\nInvalid Date\n"
},
{
"code": null,
"e": 27386,
"s": 27342,
"text": "Strong Normal Equivalence Class Test Cases:"
},
{
"code": null,
"e": 27398,
"s": 27386,
"text": "Test Cases:"
},
{
"code": null,
"e": 27661,
"s": 27398,
"text": "So from this problem it is clearly seen that equivalence class testing clearly checks for many cases that boundary value did not considered like that of February which has 28-29 days, leap year which lead to variation in number of days in February and many more."
},
{
"code": null,
"e": 27808,
"s": 27661,
"text": "Hence the above example proves that equivalence partitioning generates more efficient test cases that should be considered during risk assessment."
},
{
"code": null,
"e": 27825,
"s": 27808,
"text": "Software Testing"
},
{
"code": null,
"e": 27849,
"s": 27825,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 27870,
"s": 27849,
"text": "Software Engineering"
},
{
"code": null,
"e": 27889,
"s": 27870,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27987,
"s": 27889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28029,
"s": 27987,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 28077,
"s": 28029,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 28126,
"s": 28077,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 28174,
"s": 28126,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 28209,
"s": 28174,
"text": "Levels in Data Flow Diagrams (DFD)"
},
{
"code": null,
"e": 28245,
"s": 28209,
"text": "Software Engineering | SDLC V-Model"
},
{
"code": null,
"e": 28287,
"s": 28245,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 28343,
"s": 28287,
"text": "Difference between Unit Testing and Integration Testing"
},
{
"code": null,
"e": 28399,
"s": 28343,
"text": "Software Engineering | Requirements Engineering Process"
}
] |
fputcsv() function in PHP
|
The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.
fputcsv(file_pointer, fields, delimiter, enclosure, escape)
file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
fields − Array of string.
fields − Array of string.
delimiter − Character that specifies the field separator. Default is comma ( , )
delimiter − Character that specifies the field separator. Default is comma ( , )
enclosure − Set the field enclosure character. Defaults as a double quotation mark.
enclosure − Set the field enclosure character. Defaults as a double quotation mark.
escape − Set the escape character. Defaults as a backslash (\).
escape − Set the escape character. Defaults as a backslash (\).
The fputcsv() function returns the length of the written string.
The following is an example that writes content to the “employees.csv” file.
<?php
$mylist = array (
"Jack,Tim",
"Henry,Tom",
);
$file_pointer = fopen("employees.csv","w");
foreach ($mylist as $line) {
fputcsv($file_pointer,explode(',',$line));
}
fclose($file_pointer);
?>
The CSV file “employees.csv” will have the following content now.
Jack,Tim,
Henry,Tom
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string."
},
{
"code": null,
"e": 1253,
"s": 1193,
"text": "fputcsv(file_pointer, fields, delimiter, enclosure, escape)"
},
{
"code": null,
"e": 1356,
"s": 1253,
"text": "file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()."
},
{
"code": null,
"e": 1459,
"s": 1356,
"text": "file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()."
},
{
"code": null,
"e": 1485,
"s": 1459,
"text": "fields − Array of string."
},
{
"code": null,
"e": 1511,
"s": 1485,
"text": "fields − Array of string."
},
{
"code": null,
"e": 1592,
"s": 1511,
"text": "delimiter − Character that specifies the field separator. Default is comma ( , )"
},
{
"code": null,
"e": 1673,
"s": 1592,
"text": "delimiter − Character that specifies the field separator. Default is comma ( , )"
},
{
"code": null,
"e": 1757,
"s": 1673,
"text": "enclosure − Set the field enclosure character. Defaults as a double quotation mark."
},
{
"code": null,
"e": 1841,
"s": 1757,
"text": "enclosure − Set the field enclosure character. Defaults as a double quotation mark."
},
{
"code": null,
"e": 1905,
"s": 1841,
"text": "escape − Set the escape character. Defaults as a backslash (\\)."
},
{
"code": null,
"e": 1969,
"s": 1905,
"text": "escape − Set the escape character. Defaults as a backslash (\\)."
},
{
"code": null,
"e": 2034,
"s": 1969,
"text": "The fputcsv() function returns the length of the written string."
},
{
"code": null,
"e": 2111,
"s": 2034,
"text": "The following is an example that writes content to the “employees.csv” file."
},
{
"code": null,
"e": 2316,
"s": 2111,
"text": "<?php\n$mylist = array (\n \"Jack,Tim\",\n \"Henry,Tom\",\n);\n$file_pointer = fopen(\"employees.csv\",\"w\");\nforeach ($mylist as $line) {\n fputcsv($file_pointer,explode(',',$line));\n}\nfclose($file_pointer);\n?>"
},
{
"code": null,
"e": 2382,
"s": 2316,
"text": "The CSV file “employees.csv” will have the following content now."
},
{
"code": null,
"e": 2402,
"s": 2382,
"text": "Jack,Tim,\nHenry,Tom"
}
] |
How to return an object from a JavaScript function?
|
To return an object from a JavaScript function, use the return statement, with this keyword.
You can try to run the following code to return an object from a JavaScipt function −
Live Demo
<html>
<head>
<script>
var employee = {
empname: "David",
department : "Finance",
id : 002,
details : function() {
return this.empname + " with Department " + this.department;
}
};
document.write(employee.details());
</script>
</head>
</html>
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To return an object from a JavaScript function, use the return statement, with this keyword."
},
{
"code": null,
"e": 1241,
"s": 1155,
"text": "You can try to run the following code to return an object from a JavaScipt function −"
},
{
"code": null,
"e": 1252,
"s": 1241,
"text": " Live Demo"
},
{
"code": null,
"e": 1616,
"s": 1252,
"text": "<html>\n <head>\n <script>\n var employee = {\n empname: \"David\",\n department : \"Finance\",\n id : 002,\n details : function() {\n return this.empname + \" with Department \" + this.department;\n }\n };\n\n document.write(employee.details());\n </script>\n </head>\n</html>"
}
] |
How to compute f1 score for named-entity recognition in Keras | by Hironsan | Towards Data Science
|
In named-entity recognition, f1 score is used to evaluate the performance of trained models, especially, the evaluation is per entity, not token.
The function to evaluate f1 score is implemented in many machine learning frameworks. However, its target is classification tasks, not sequence labeling like named-entity recognition.
Fortunately, Keras allows us to access the validation data during training via a Callback class. By extending Callback, we can evaluate f1 score for named-entity recognition.
Here is a sample code to compute and print out the f1 score, recall, and precision at the end of each epoch. You don’t have to implement this code on your own, it is included in seqeval package:
import numpy as npfrom keras.callbacks import Callbackfrom seqeval.metrics import f1_score, classification_reportclass F1Metrics(Callback): def __init__(self, id2label, pad_value=0, validation_data=None): """ Args: id2label (dict): id to label mapping. (e.g. {1: 'B-LOC', 2: 'I-LOC'}) pad_value (int): padding value. """ super(F1Metrics, self).__init__() self.id2label = id2label self.pad_value = pad_value self.validation_data = validation_data self.is_fit = validation_data is None def find_pad_index(self, array): """Find padding index. Args: array (list): integer list. Returns: idx: padding index. Examples: >>> array = [1, 2, 0] >>> self.find_pad_index(array) 2 """ try: return list(array).index(self.pad_value) except ValueError: return len(array) def get_length(self, y): """Get true length of y. Args: y (list): padded list. Returns: lens: true length of y. Examples: >>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]] >>> self.get_length(y) [1, 2, 3] """ lens = [self.find_pad_index(row) for row in y] return lens def convert_idx_to_name(self, y, lens): """Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'} >>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]] >>> lens = [1, 2, 3] >>> self.convert_idx_to_name(y, lens) [['B-LOC'], ['B-LOC', 'I-LOC'], ['B-LOC', 'B-LOC', 'B-LOC']] """ y = [[self.id2label[idx] for idx in row[:l]] for row, l in zip(y, lens)] return y def predict(self, X, y): """Predict sequences. Args: X (list): input data. y (list): tags. Returns: y_true: true sequences. y_pred: predicted sequences. """ y_pred = self.model.predict_on_batch(X) # reduce dimension. y_true = np.argmax(y, -1) y_pred = np.argmax(y_pred, -1) lens = self.get_length(y_true) y_true = self.convert_idx_to_name(y_true, lens) y_pred = self.convert_idx_to_name(y_pred, lens) return y_true, y_pred def score(self, y_true, y_pred): """Calculate f1 score. Args: y_true (list): true sequences. y_pred (list): predicted sequences. Returns: score: f1 score. """ score = f1_score(y_true, y_pred) print(' - f1: {:04.2f}'.format(score * 100)) print(classification_report(y_true, y_pred, digits=4)) return score def on_epoch_end(self, epoch, logs={}): if self.is_fit: self.on_epoch_end_fit(epoch, logs) else: self.on_epoch_end_fit_generator(epoch, logs) def on_epoch_end_fit(self, epoch, logs={}): X = self.validation_data[0] y = self.validation_data[1] y_true, y_pred = self.predict(X, y) score = self.score(y_true, y_pred) logs['f1'] = score def on_epoch_end_fit_generator(self, epoch, logs={}): y_true = [] y_pred = [] for X, y in self.validation_data: y_true_batch, y_pred_batch = self.predict(X, y) y_true.extend(y_true_batch) y_pred.extend(y_pred_batch) score = self.score(y_true, y_pred) logs['f1'] = scoreid2label = {1: 'B-LOC', 2: 'I-LOC'}f1score = F1Metrics(id2label)
Define the model, and add the callback in the fit function:
model.fit(x_train, y_train, validation_data=(x_valid, y_valid), epochs=1, batch_size=32, callbacks=[f1score])
The printout during training would look like this:
Epoch 1/1541/541 [==============================] - 46s 85ms/step - loss: 9.5729 - f1: 53.24 precision recall f1-score support PER 0.5754 0.4484 0.5040 1617 ORG 0.3798 0.4395 0.4075 1661 MISC 0.4202 0.4387 0.4293 702 LOC 0.6886 0.7650 0.7248 1668avg / total 0.5320 0.5381 0.5315 5648
The format is similar to scikit-learn’s classification_report function.
That’s it. Have a nice day!
|
[
{
"code": null,
"e": 318,
"s": 172,
"text": "In named-entity recognition, f1 score is used to evaluate the performance of trained models, especially, the evaluation is per entity, not token."
},
{
"code": null,
"e": 502,
"s": 318,
"text": "The function to evaluate f1 score is implemented in many machine learning frameworks. However, its target is classification tasks, not sequence labeling like named-entity recognition."
},
{
"code": null,
"e": 677,
"s": 502,
"text": "Fortunately, Keras allows us to access the validation data during training via a Callback class. By extending Callback, we can evaluate f1 score for named-entity recognition."
},
{
"code": null,
"e": 872,
"s": 677,
"text": "Here is a sample code to compute and print out the f1 score, recall, and precision at the end of each epoch. You don’t have to implement this code on your own, it is included in seqeval package:"
},
{
"code": null,
"e": 4614,
"s": 872,
"text": "import numpy as npfrom keras.callbacks import Callbackfrom seqeval.metrics import f1_score, classification_reportclass F1Metrics(Callback): def __init__(self, id2label, pad_value=0, validation_data=None): \"\"\" Args: id2label (dict): id to label mapping. (e.g. {1: 'B-LOC', 2: 'I-LOC'}) pad_value (int): padding value. \"\"\" super(F1Metrics, self).__init__() self.id2label = id2label self.pad_value = pad_value self.validation_data = validation_data self.is_fit = validation_data is None def find_pad_index(self, array): \"\"\"Find padding index. Args: array (list): integer list. Returns: idx: padding index. Examples: >>> array = [1, 2, 0] >>> self.find_pad_index(array) 2 \"\"\" try: return list(array).index(self.pad_value) except ValueError: return len(array) def get_length(self, y): \"\"\"Get true length of y. Args: y (list): padded list. Returns: lens: true length of y. Examples: >>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]] >>> self.get_length(y) [1, 2, 3] \"\"\" lens = [self.find_pad_index(row) for row in y] return lens def convert_idx_to_name(self, y, lens): \"\"\"Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'} >>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]] >>> lens = [1, 2, 3] >>> self.convert_idx_to_name(y, lens) [['B-LOC'], ['B-LOC', 'I-LOC'], ['B-LOC', 'B-LOC', 'B-LOC']] \"\"\" y = [[self.id2label[idx] for idx in row[:l]] for row, l in zip(y, lens)] return y def predict(self, X, y): \"\"\"Predict sequences. Args: X (list): input data. y (list): tags. Returns: y_true: true sequences. y_pred: predicted sequences. \"\"\" y_pred = self.model.predict_on_batch(X) # reduce dimension. y_true = np.argmax(y, -1) y_pred = np.argmax(y_pred, -1) lens = self.get_length(y_true) y_true = self.convert_idx_to_name(y_true, lens) y_pred = self.convert_idx_to_name(y_pred, lens) return y_true, y_pred def score(self, y_true, y_pred): \"\"\"Calculate f1 score. Args: y_true (list): true sequences. y_pred (list): predicted sequences. Returns: score: f1 score. \"\"\" score = f1_score(y_true, y_pred) print(' - f1: {:04.2f}'.format(score * 100)) print(classification_report(y_true, y_pred, digits=4)) return score def on_epoch_end(self, epoch, logs={}): if self.is_fit: self.on_epoch_end_fit(epoch, logs) else: self.on_epoch_end_fit_generator(epoch, logs) def on_epoch_end_fit(self, epoch, logs={}): X = self.validation_data[0] y = self.validation_data[1] y_true, y_pred = self.predict(X, y) score = self.score(y_true, y_pred) logs['f1'] = score def on_epoch_end_fit_generator(self, epoch, logs={}): y_true = [] y_pred = [] for X, y in self.validation_data: y_true_batch, y_pred_batch = self.predict(X, y) y_true.extend(y_true_batch) y_pred.extend(y_pred_batch) score = self.score(y_true, y_pred) logs['f1'] = scoreid2label = {1: 'B-LOC', 2: 'I-LOC'}f1score = F1Metrics(id2label)"
},
{
"code": null,
"e": 4674,
"s": 4614,
"text": "Define the model, and add the callback in the fit function:"
},
{
"code": null,
"e": 4821,
"s": 4674,
"text": "model.fit(x_train, y_train, validation_data=(x_valid, y_valid), epochs=1, batch_size=32, callbacks=[f1score])"
},
{
"code": null,
"e": 4872,
"s": 4821,
"text": "The printout during training would look like this:"
},
{
"code": null,
"e": 5277,
"s": 4872,
"text": "Epoch 1/1541/541 [==============================] - 46s 85ms/step - loss: 9.5729 - f1: 53.24 precision recall f1-score support PER 0.5754 0.4484 0.5040 1617 ORG 0.3798 0.4395 0.4075 1661 MISC 0.4202 0.4387 0.4293 702 LOC 0.6886 0.7650 0.7248 1668avg / total 0.5320 0.5381 0.5315 5648"
},
{
"code": null,
"e": 5349,
"s": 5277,
"text": "The format is similar to scikit-learn’s classification_report function."
}
] |
How to catch ZeroDivisionError Exception in Python?
|
When zero shows up in the denominator of a division operation, a ZeroDivisionError is raised.
We re-write the given code as follows to handle the exception and find its type.
import sys
try:
x = 11/0
print x
except Exception as e:
print sys.exc_type
print e
<type 'exceptions.ZeroDivisionError'>
integer division or modulo by zero
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "When zero shows up in the denominator of a division operation, a ZeroDivisionError is raised."
},
{
"code": null,
"e": 1237,
"s": 1156,
"text": "We re-write the given code as follows to handle the exception and find its type."
},
{
"code": null,
"e": 1320,
"s": 1237,
"text": "import sys\ntry:\nx = 11/0\nprint x\nexcept Exception as e:\nprint sys.exc_type\nprint e"
},
{
"code": null,
"e": 1395,
"s": 1320,
"text": "<type 'exceptions.ZeroDivisionError'>\ninteger division or modulo by zero\n\n"
}
] |
How to stop asynctask thread in Kotlin?
|
This example demonstrates how to stop an asynctask thread in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnDo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/btnCancel"
android:layout_centerInParent="true"
android:layout_marginBottom="25sp"
android:text="Do AsyncTask" />
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/textView"
android:layout_centerInParent="true"
android:layout_marginBottom="20dp"
android:text="Cancel" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:textSize="20sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.Color
import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var btnDo: Button
private lateinit var btnCancel: Button
private lateinit var textView: TextView
private var myTask: AsyncTask<*, *, *>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
btnDo = findViewById(R.id.btnDo)
btnCancel = findViewById(R.id.btnCancel)
textView = findViewById(R.id.textView)
btnDo.setOnClickListener(View.OnClickListener {
textView.text = ""
myTask = DownloadTask().execute("Task1", "Task2", "Task3", "Task4", "Task5")
})
btnCancel.setOnClickListener(View.OnClickListener { myTask!!.cancel(true) })
}
private open inner class DownloadTask :
AsyncTask<String?, Int?, List<String>>() {
override fun onPreExecute() {
super.onPreExecute()
textView.setTextColor(Color.BLUE)
textView.text = textView.text.toString() + "\n Starting Task...."
}
override fun doInBackground(vararg params: String?): List<String>? {
val count = params.size
val taskList: MutableList<String> = ArrayList(count)
for (i in 0 until count) {
val currentTask = params[i]
taskList.add(currentTask.toString())
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
publishProgress(((i + 1) / count.toFloat() * 100).toInt())
if (isCancelled) {
break
}
}
return taskList
}
override fun onCancelled() {
super.onCancelled()
textView.setTextColor(Color.RED)
textView.text = textView.text.toString() + "\n Operation is cancelled.."
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
textView.text = textView.text.toString() + "\n Completed:)" + values[0] + "%"
}
override fun onPostExecute(result: List<String>) {
super.onPostExecute(result)
textView.text = textView.text.toString() + "\n\n Done...."
for (i in result.indices) {
textView.text = textView.text.toString() + "\n" +
result[i]
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q10">
<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 the
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": 1131,
"s": 1062,
"text": "This example demonstrates how to stop an asynctask thread in Kotlin."
},
{
"code": null,
"e": 1260,
"s": 1131,
"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": 1325,
"s": 1260,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2443,
"s": 1325,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnDo\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/btnCancel\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"25sp\"\n android:text=\"Do AsyncTask\" />\n <Button\n android:id=\"@+id/btnCancel\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/textView\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"20dp\"\n android:text=\"Cancel\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:gravity=\"center_horizontal\"\n android:textSize=\"20sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2498,
"s": 2443,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 5173,
"s": 2498,
"text": "import android.graphics.Color\nimport android.os.AsyncTask\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n private lateinit var btnDo: Button\n private lateinit var btnCancel: Button\n private lateinit var textView: TextView\n private var myTask: AsyncTask<*, *, *>? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n btnDo = findViewById(R.id.btnDo)\n btnCancel = findViewById(R.id.btnCancel)\n textView = findViewById(R.id.textView)\n btnDo.setOnClickListener(View.OnClickListener {\n textView.text = \"\"\n myTask = DownloadTask().execute(\"Task1\", \"Task2\", \"Task3\", \"Task4\", \"Task5\")\n })\n btnCancel.setOnClickListener(View.OnClickListener { myTask!!.cancel(true) })\n }\n private open inner class DownloadTask :\n AsyncTask<String?, Int?, List<String>>() {\n override fun onPreExecute() {\n super.onPreExecute()\n textView.setTextColor(Color.BLUE)\n textView.text = textView.text.toString() + \"\\n Starting Task....\"\n }\n override fun doInBackground(vararg params: String?): List<String>? {\n val count = params.size\n val taskList: MutableList<String> = ArrayList(count)\n for (i in 0 until count) {\n val currentTask = params[i]\n taskList.add(currentTask.toString())\n try {\n Thread.sleep(1000)\n } catch (e: InterruptedException) {\n e.printStackTrace()\n }\n publishProgress(((i + 1) / count.toFloat() * 100).toInt())\n if (isCancelled) {\n break\n }\n }\n return taskList\n }\n override fun onCancelled() {\n super.onCancelled()\n textView.setTextColor(Color.RED)\n textView.text = textView.text.toString() + \"\\n Operation is cancelled..\"\n }\n override fun onProgressUpdate(vararg values: Int?) {\n super.onProgressUpdate(*values)\n textView.text = textView.text.toString() + \"\\n Completed:)\" + values[0] + \"%\"\n }\n override fun onPostExecute(result: List<String>) {\n super.onPostExecute(result)\n textView.text = textView.text.toString() + \"\\n\\n Done....\"\n for (i in result.indices) {\n textView.text = textView.text.toString() + \"\\n\" +\n result[i]\n }\n }\n }\n}"
},
{
"code": null,
"e": 5228,
"s": 5173,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5895,
"s": 5228,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q10\">\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": 6243,
"s": 5895,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with\nyour computer. To run the app from android studio, open one of your project's activity files and click the\nRun icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
What are the rules of margin collapse in CSS ? - GeeksforGeeks
|
23 Apr, 2021
Margin collapsing is a behavior of CSS where the vertical margins of block-level elements are combined into one i.e. to the margin of the element with the largest value. Sometimes when we assigned margins to elements it does not work in the way we think it to be and that creates confusion. The following rules will help you understand margin collapsing:
Rule 1: Only vertical margins of block-level elements are collapsed
The first rule is that only the vertical margins of elements will collapse and not the horizontal margins. The CSS rules that govern margin collapsing say that horizontal margins can never satisfy the required conditions.
Example 1:
HTML
<html><head> <style> p { font-size: 24px; margin-top: 34px; margin-bottom: 34px; background-color: rgb(79, 236, 119); } </style></head><body> <div class="container"> <p> This paragraph's bottom margin is collapsed. </p> <p> This paragraph is 34px below the above text. </p> </div></body></html>
Output: In this example, instead of sitting 68px apart the 34px margins of the first and second <p> tag merge, occupying the same space. As the bottom margin of the first paragraph merges with the top margin of the second paragraph. Hence, the space between the two-paragraph is 34px only.
Example 2: This example demonstrates what will happen if when horizontal margins are used.
HTML
<html><head> <style> p { font-size: 24px; display: inline-block; margin-left: 34px; margin-right: 34px; background-color: rgb(79, 236, 119); } </style></head><body> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p></body></html>
Output: It is clear that horizontal margins do not collapse. Margin collapsing only happens to block-level elements. Other than block-level elements no other elements margin can collapse. Here, we have two <p> tags that were inline-block, hence their margin does not collapse.
Rule 2: The elements should be adjacent
Margin collapsing occurs only when the block elements come in direct contact with each other. They should not be separated by any line break or other elements. We generally provide <br> tag between two elements, but due to this, the margins will not collapse.
Example: In this example, we provide a line break between two elements.
HTML
<html><head> <style> p { margin-top: 32px; margin-bottom: 32px; background-color: rgb(79, 236, 119); } </style></head><body> <p>This is paragraph 1</p> <br> <p>This is paragraph 2.</p> </body></html>
Output: You can see in the output that the top margin of the second <p> tag does not collapse with the bottom margin of the first <p>tag and this happens due to the line break between the two elements. Elements must be adjacent for margin collapsing.
Rule 3. The element with the bigger margins will be used
This rule decides what will happen when the margins are asymmetrical. That means if the top element wants 62px of space below, while the bottom element only needs 24px above. In this condition, the space between the two elements will be 62px only. As it is already explained above if you have two adjacent elements with no padding, or border, or line break between them (i.e., their margins touch vertically), then their margin will collapse and the larger margin of the two wins.
Rule 4: The overflow property should be set to visible
Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse. Hence, overflow: hidden and overflow: auto will not let margin collapse.
Rule 5: Negative Margins will add up
A negative margin is used to reduce space between two elements. It put elements closer to each other. Consider that margin-bottom of first element is -65px and margin-top of second element is -25px . In that case, the space between the two elements will be -65px as it is more significant than -25px. But when one margin is positive and another is negative then these margins are added to get the space between the elements.
Example:
HTML
<html><head> <style> div { font-size: 24px; height: 75px; background-color: rgb(79, 236, 119); } #b1 { margin-bottom: 50px; } #b2 { margin-top: -25px; } </style></head><body> <div id="b1">This is block 1.</div> <div id="b2">This is block 2.</div></body></html>
Output: In this example, margin-bottom of first div is 50px and margin-top of second div is -25px . So the size of space between them will be 25px (-25px+50px).
Rule 6: No collapsing of margins between Parent and Child elements
A margin is used to increase the space between the sibling elements. It cannot be used for increasing the space between parent and child elements as for that we have padding. Margin only gets transferred from child element to parent element as margin always tries to increase the space between siblings elements and due to which we feel that the margin is applied to the parent element. So there is no margin collapsing between parent and child elements there is only transferring of a margin between them.
For transferring the margin to the parent element the below conditions have to be satisfied:
Parent and Child should be adjacent.
The height of the parent element should be auto.
Parent elements should not have any padding or border.
Rule 7: Collapsing only works on a flow layout
The margin never collapses when the elements are aligned in flexbox or grid box, or they are not in-flow e.g. absolutely positioned or floated.
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 25340,
"s": 24985,
"text": "Margin collapsing is a behavior of CSS where the vertical margins of block-level elements are combined into one i.e. to the margin of the element with the largest value. Sometimes when we assigned margins to elements it does not work in the way we think it to be and that creates confusion. The following rules will help you understand margin collapsing:"
},
{
"code": null,
"e": 25408,
"s": 25340,
"text": "Rule 1: Only vertical margins of block-level elements are collapsed"
},
{
"code": null,
"e": 25630,
"s": 25408,
"text": "The first rule is that only the vertical margins of elements will collapse and not the horizontal margins. The CSS rules that govern margin collapsing say that horizontal margins can never satisfy the required conditions."
},
{
"code": null,
"e": 25641,
"s": 25630,
"text": "Example 1:"
},
{
"code": null,
"e": 25646,
"s": 25641,
"text": "HTML"
},
{
"code": "<html><head> <style> p { font-size: 24px; margin-top: 34px; margin-bottom: 34px; background-color: rgb(79, 236, 119); } </style></head><body> <div class=\"container\"> <p> This paragraph's bottom margin is collapsed. </p> <p> This paragraph is 34px below the above text. </p> </div></body></html>",
"e": 26009,
"s": 25646,
"text": null
},
{
"code": null,
"e": 26299,
"s": 26009,
"text": "Output: In this example, instead of sitting 68px apart the 34px margins of the first and second <p> tag merge, occupying the same space. As the bottom margin of the first paragraph merges with the top margin of the second paragraph. Hence, the space between the two-paragraph is 34px only."
},
{
"code": null,
"e": 26390,
"s": 26299,
"text": "Example 2: This example demonstrates what will happen if when horizontal margins are used."
},
{
"code": null,
"e": 26395,
"s": 26390,
"text": "HTML"
},
{
"code": "<html><head> <style> p { font-size: 24px; display: inline-block; margin-left: 34px; margin-right: 34px; background-color: rgb(79, 236, 119); } </style></head><body> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p></body></html>",
"e": 26665,
"s": 26395,
"text": null
},
{
"code": null,
"e": 26942,
"s": 26665,
"text": "Output: It is clear that horizontal margins do not collapse. Margin collapsing only happens to block-level elements. Other than block-level elements no other elements margin can collapse. Here, we have two <p> tags that were inline-block, hence their margin does not collapse."
},
{
"code": null,
"e": 26982,
"s": 26942,
"text": "Rule 2: The elements should be adjacent"
},
{
"code": null,
"e": 27242,
"s": 26982,
"text": "Margin collapsing occurs only when the block elements come in direct contact with each other. They should not be separated by any line break or other elements. We generally provide <br> tag between two elements, but due to this, the margins will not collapse."
},
{
"code": null,
"e": 27314,
"s": 27242,
"text": "Example: In this example, we provide a line break between two elements."
},
{
"code": null,
"e": 27319,
"s": 27314,
"text": "HTML"
},
{
"code": "<html><head> <style> p { margin-top: 32px; margin-bottom: 32px; background-color: rgb(79, 236, 119); } </style></head><body> <p>This is paragraph 1</p> <br> <p>This is paragraph 2.</p> </body></html>",
"e": 27546,
"s": 27319,
"text": null
},
{
"code": null,
"e": 27797,
"s": 27546,
"text": "Output: You can see in the output that the top margin of the second <p> tag does not collapse with the bottom margin of the first <p>tag and this happens due to the line break between the two elements. Elements must be adjacent for margin collapsing."
},
{
"code": null,
"e": 27854,
"s": 27797,
"text": "Rule 3. The element with the bigger margins will be used"
},
{
"code": null,
"e": 28335,
"s": 27854,
"text": "This rule decides what will happen when the margins are asymmetrical. That means if the top element wants 62px of space below, while the bottom element only needs 24px above. In this condition, the space between the two elements will be 62px only. As it is already explained above if you have two adjacent elements with no padding, or border, or line break between them (i.e., their margins touch vertically), then their margin will collapse and the larger margin of the two wins."
},
{
"code": null,
"e": 28391,
"s": 28335,
"text": "Rule 4: The overflow property should be set to visible "
},
{
"code": null,
"e": 28650,
"s": 28391,
"text": "Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse. Hence, overflow: hidden and overflow: auto will not let margin collapse."
},
{
"code": null,
"e": 28687,
"s": 28650,
"text": "Rule 5: Negative Margins will add up"
},
{
"code": null,
"e": 29112,
"s": 28687,
"text": "A negative margin is used to reduce space between two elements. It put elements closer to each other. Consider that margin-bottom of first element is -65px and margin-top of second element is -25px . In that case, the space between the two elements will be -65px as it is more significant than -25px. But when one margin is positive and another is negative then these margins are added to get the space between the elements."
},
{
"code": null,
"e": 29121,
"s": 29112,
"text": "Example:"
},
{
"code": null,
"e": 29126,
"s": 29121,
"text": "HTML"
},
{
"code": "<html><head> <style> div { font-size: 24px; height: 75px; background-color: rgb(79, 236, 119); } #b1 { margin-bottom: 50px; } #b2 { margin-top: -25px; } </style></head><body> <div id=\"b1\">This is block 1.</div> <div id=\"b2\">This is block 2.</div></body></html>",
"e": 29438,
"s": 29126,
"text": null
},
{
"code": null,
"e": 29599,
"s": 29438,
"text": "Output: In this example, margin-bottom of first div is 50px and margin-top of second div is -25px . So the size of space between them will be 25px (-25px+50px)."
},
{
"code": null,
"e": 29666,
"s": 29599,
"text": "Rule 6: No collapsing of margins between Parent and Child elements"
},
{
"code": null,
"e": 30173,
"s": 29666,
"text": "A margin is used to increase the space between the sibling elements. It cannot be used for increasing the space between parent and child elements as for that we have padding. Margin only gets transferred from child element to parent element as margin always tries to increase the space between siblings elements and due to which we feel that the margin is applied to the parent element. So there is no margin collapsing between parent and child elements there is only transferring of a margin between them."
},
{
"code": null,
"e": 30266,
"s": 30173,
"text": "For transferring the margin to the parent element the below conditions have to be satisfied:"
},
{
"code": null,
"e": 30303,
"s": 30266,
"text": "Parent and Child should be adjacent."
},
{
"code": null,
"e": 30352,
"s": 30303,
"text": "The height of the parent element should be auto."
},
{
"code": null,
"e": 30407,
"s": 30352,
"text": "Parent elements should not have any padding or border."
},
{
"code": null,
"e": 30455,
"s": 30407,
"text": " Rule 7: Collapsing only works on a flow layout"
},
{
"code": null,
"e": 30599,
"s": 30455,
"text": "The margin never collapses when the elements are aligned in flexbox or grid box, or they are not in-flow e.g. absolutely positioned or floated."
},
{
"code": null,
"e": 30614,
"s": 30599,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30628,
"s": 30614,
"text": "CSS-Questions"
},
{
"code": null,
"e": 30635,
"s": 30628,
"text": "Picked"
},
{
"code": null,
"e": 30639,
"s": 30635,
"text": "CSS"
},
{
"code": null,
"e": 30656,
"s": 30639,
"text": "Web Technologies"
},
{
"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": 30763,
"s": 30754,
"text": "Comments"
},
{
"code": null,
"e": 30776,
"s": 30763,
"text": "Old Comments"
},
{
"code": null,
"e": 30813,
"s": 30776,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30842,
"s": 30813,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30881,
"s": 30842,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30923,
"s": 30881,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30958,
"s": 30923,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 31014,
"s": 30958,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 31047,
"s": 31014,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31090,
"s": 31047,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31151,
"s": 31090,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
MFC - Command Button
|
A command button is an enhanced version of the regular button. It displays a green arrow icon on the left, followed by a caption in regular size. Under the main caption, it can display another smaller caption that serves as a hint to provide more information.
Create
Creates the Windows button control and attaches it to the CButton object.
DrawItem
Override to draw an owner-drawn CButton object.
GetBitmap
Retrieves the handle of the bitmap previously set with SetBitmap.
GetButtonStyle
Retrieves information about the button control style.
GetCheck
Retrieves the check state of a button control.
GetCursor
Retrieves the handle of the cursor image previously set with SetCursor.
GetIcon
Retrieves the handle of the icon previously set with SetIcon.
GetIdealSize
Retrieves the ideal size of the button control.
GetImageList
Retrieves the image list of the button control.
GetNote
Retrieves the note component of the current command link control.
GetNoteLength
Retrieves the length of the note text for the current command link control.
GetSplitGlyph
Retrieves the glyph associated with the current split button control.
GetSplitImageList
Retrieves the image list for the current split button control.
GetSplitInfo
Retrieves information that defines the current split button control.
GetSplitSize
Retrieves the bounding rectangle of the drop-down component of the current split button control.
GetSplitStyle
Retrieves the split button styles that define the current split button control.
GetState
Retrieves the check state, highlight state, and focus state of a button control.
GetTextMargin
Retrieves the text margin of the button control.
SetBitmap
Specifies a bitmap to be displayed on the button.
SetButtonStyle
Changes the style of a button.
SetCheck
Sets the check state of a button control.
SetCursor
Specifies a cursor image to be displayed on the button.
SetDropDownState
Sets the drop-down state of the current split button control.
SetIcon
Specifies an icon to be displayed on the button.
SetImageList
Sets the image list of the button control.
SetNote
Sets the note on the current command link control.
SetSplitGlyph
Associates a specified glyph with the current split button control.
SetSplitImageList
Associates an image list with the current split button control.
SetSplitInfo
Specifies information that defines the current split button control.
SetSplitSize
Sets the bounding rectangle of the drop-down component of the current split button control.
SetSplitStyle
Sets the style of the current split button control.
SetState
Sets the highlighting state of a button control.
SetTextMargin
Sets the text margin of the button control.
Here is the list of messages mapping for Command Button control −
Let us look into a simple example of command button by creating a new MFC dialog based project MFCCommandButton
Step 1 − From the Toolbox, add Command Button Control.
Step 2 − Change the Caption to My Command button.
Step 3 − Add the event handler for this button and add the following message in the event handler.
void CMFCCommandButtonDlg::OnBnClickedCommand1() {
// TODO: Add your control notification handler code here
MessageBox(L"My Command Button Clicked");
}
Step 4 − When the above code is compiled and executed, you will see the following output.
Step 5 − When the My Command Button is clicked; the following message will be displayed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2327,
"s": 2067,
"text": "A command button is an enhanced version of the regular button. It displays a green arrow icon on the left, followed by a caption in regular size. Under the main caption, it can display another smaller caption that serves as a hint to provide more information."
},
{
"code": null,
"e": 2334,
"s": 2327,
"text": "Create"
},
{
"code": null,
"e": 2408,
"s": 2334,
"text": "Creates the Windows button control and attaches it to the CButton object."
},
{
"code": null,
"e": 2417,
"s": 2408,
"text": "DrawItem"
},
{
"code": null,
"e": 2465,
"s": 2417,
"text": "Override to draw an owner-drawn CButton object."
},
{
"code": null,
"e": 2475,
"s": 2465,
"text": "GetBitmap"
},
{
"code": null,
"e": 2541,
"s": 2475,
"text": "Retrieves the handle of the bitmap previously set with SetBitmap."
},
{
"code": null,
"e": 2556,
"s": 2541,
"text": "GetButtonStyle"
},
{
"code": null,
"e": 2610,
"s": 2556,
"text": "Retrieves information about the button control style."
},
{
"code": null,
"e": 2619,
"s": 2610,
"text": "GetCheck"
},
{
"code": null,
"e": 2666,
"s": 2619,
"text": "Retrieves the check state of a button control."
},
{
"code": null,
"e": 2676,
"s": 2666,
"text": "GetCursor"
},
{
"code": null,
"e": 2748,
"s": 2676,
"text": "Retrieves the handle of the cursor image previously set with SetCursor."
},
{
"code": null,
"e": 2756,
"s": 2748,
"text": "GetIcon"
},
{
"code": null,
"e": 2818,
"s": 2756,
"text": "Retrieves the handle of the icon previously set with SetIcon."
},
{
"code": null,
"e": 2831,
"s": 2818,
"text": "GetIdealSize"
},
{
"code": null,
"e": 2879,
"s": 2831,
"text": "Retrieves the ideal size of the button control."
},
{
"code": null,
"e": 2892,
"s": 2879,
"text": "GetImageList"
},
{
"code": null,
"e": 2940,
"s": 2892,
"text": "Retrieves the image list of the button control."
},
{
"code": null,
"e": 2948,
"s": 2940,
"text": "GetNote"
},
{
"code": null,
"e": 3014,
"s": 2948,
"text": "Retrieves the note component of the current command link control."
},
{
"code": null,
"e": 3028,
"s": 3014,
"text": "GetNoteLength"
},
{
"code": null,
"e": 3104,
"s": 3028,
"text": "Retrieves the length of the note text for the current command link control."
},
{
"code": null,
"e": 3118,
"s": 3104,
"text": "GetSplitGlyph"
},
{
"code": null,
"e": 3188,
"s": 3118,
"text": "Retrieves the glyph associated with the current split button control."
},
{
"code": null,
"e": 3206,
"s": 3188,
"text": "GetSplitImageList"
},
{
"code": null,
"e": 3269,
"s": 3206,
"text": "Retrieves the image list for the current split button control."
},
{
"code": null,
"e": 3282,
"s": 3269,
"text": "GetSplitInfo"
},
{
"code": null,
"e": 3351,
"s": 3282,
"text": "Retrieves information that defines the current split button control."
},
{
"code": null,
"e": 3364,
"s": 3351,
"text": "GetSplitSize"
},
{
"code": null,
"e": 3461,
"s": 3364,
"text": "Retrieves the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 3475,
"s": 3461,
"text": "GetSplitStyle"
},
{
"code": null,
"e": 3555,
"s": 3475,
"text": "Retrieves the split button styles that define the current split button control."
},
{
"code": null,
"e": 3564,
"s": 3555,
"text": "GetState"
},
{
"code": null,
"e": 3645,
"s": 3564,
"text": "Retrieves the check state, highlight state, and focus state of a button control."
},
{
"code": null,
"e": 3659,
"s": 3645,
"text": "GetTextMargin"
},
{
"code": null,
"e": 3708,
"s": 3659,
"text": "Retrieves the text margin of the button control."
},
{
"code": null,
"e": 3718,
"s": 3708,
"text": "SetBitmap"
},
{
"code": null,
"e": 3768,
"s": 3718,
"text": "Specifies a bitmap to be displayed on the button."
},
{
"code": null,
"e": 3783,
"s": 3768,
"text": "SetButtonStyle"
},
{
"code": null,
"e": 3814,
"s": 3783,
"text": "Changes the style of a button."
},
{
"code": null,
"e": 3823,
"s": 3814,
"text": "SetCheck"
},
{
"code": null,
"e": 3865,
"s": 3823,
"text": "Sets the check state of a button control."
},
{
"code": null,
"e": 3875,
"s": 3865,
"text": "SetCursor"
},
{
"code": null,
"e": 3931,
"s": 3875,
"text": "Specifies a cursor image to be displayed on the button."
},
{
"code": null,
"e": 3948,
"s": 3931,
"text": "SetDropDownState"
},
{
"code": null,
"e": 4010,
"s": 3948,
"text": "Sets the drop-down state of the current split button control."
},
{
"code": null,
"e": 4018,
"s": 4010,
"text": "SetIcon"
},
{
"code": null,
"e": 4067,
"s": 4018,
"text": "Specifies an icon to be displayed on the button."
},
{
"code": null,
"e": 4080,
"s": 4067,
"text": "SetImageList"
},
{
"code": null,
"e": 4123,
"s": 4080,
"text": "Sets the image list of the button control."
},
{
"code": null,
"e": 4131,
"s": 4123,
"text": "SetNote"
},
{
"code": null,
"e": 4182,
"s": 4131,
"text": "Sets the note on the current command link control."
},
{
"code": null,
"e": 4196,
"s": 4182,
"text": "SetSplitGlyph"
},
{
"code": null,
"e": 4264,
"s": 4196,
"text": "Associates a specified glyph with the current split button control."
},
{
"code": null,
"e": 4282,
"s": 4264,
"text": "SetSplitImageList"
},
{
"code": null,
"e": 4346,
"s": 4282,
"text": "Associates an image list with the current split button control."
},
{
"code": null,
"e": 4359,
"s": 4346,
"text": "SetSplitInfo"
},
{
"code": null,
"e": 4428,
"s": 4359,
"text": "Specifies information that defines the current split button control."
},
{
"code": null,
"e": 4441,
"s": 4428,
"text": "SetSplitSize"
},
{
"code": null,
"e": 4533,
"s": 4441,
"text": "Sets the bounding rectangle of the drop-down component of the current split button control."
},
{
"code": null,
"e": 4547,
"s": 4533,
"text": "SetSplitStyle"
},
{
"code": null,
"e": 4599,
"s": 4547,
"text": "Sets the style of the current split button control."
},
{
"code": null,
"e": 4608,
"s": 4599,
"text": "SetState"
},
{
"code": null,
"e": 4657,
"s": 4608,
"text": "Sets the highlighting state of a button control."
},
{
"code": null,
"e": 4671,
"s": 4657,
"text": "SetTextMargin"
},
{
"code": null,
"e": 4715,
"s": 4671,
"text": "Sets the text margin of the button control."
},
{
"code": null,
"e": 4781,
"s": 4715,
"text": "Here is the list of messages mapping for Command Button control −"
},
{
"code": null,
"e": 4893,
"s": 4781,
"text": "Let us look into a simple example of command button by creating a new MFC dialog based project MFCCommandButton"
},
{
"code": null,
"e": 4948,
"s": 4893,
"text": "Step 1 − From the Toolbox, add Command Button Control."
},
{
"code": null,
"e": 4998,
"s": 4948,
"text": "Step 2 − Change the Caption to My Command button."
},
{
"code": null,
"e": 5097,
"s": 4998,
"text": "Step 3 − Add the event handler for this button and add the following message in the event handler."
},
{
"code": null,
"e": 5259,
"s": 5097,
"text": "void CMFCCommandButtonDlg::OnBnClickedCommand1() {\n \n // TODO: Add your control notification handler code here\n MessageBox(L\"My Command Button Clicked\");\n}"
},
{
"code": null,
"e": 5349,
"s": 5259,
"text": "Step 4 − When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 5438,
"s": 5349,
"text": "Step 5 − When the My Command Button is clicked; the following message will be displayed."
},
{
"code": null,
"e": 5445,
"s": 5438,
"text": " Print"
},
{
"code": null,
"e": 5456,
"s": 5445,
"text": " Add Notes"
}
] |
How to Master Python for Data Science | by Chanin Nantasenamat | Towards Data Science
|
So you’re embarking on your journey into data science and everyone recommends that you start with learning how to code. You decided on Python and are now paralyzed by the large piles of learning resources that are at your disposal. Perhaps you are overwhelmed and owing to analysis paralysis, you are procrastinating your first steps in learning how to code in Python.
In this article, I’ll be your guide and take you on a journey of exploring the essential bare minimal knowledge that you need in order to master Python for getting started in data science. I will assume that you have no prior coding experience or that you may come from a non-technical background. However, if you are coming from a technical or computer science background and have knowledge of a prior programming language and would like to transition to Python, you can use this article as a high-level overview to get acquainted with the gist of the Python language. Either way, it is the aim of this article to navigate you through the landscape of the Python language at their intersection with data science, which will help you get started in no time.
The first (and famous) question that you may have is:
What programming language should you learn?
After doing some research on the internet you may have decided on Python owing to the following reasons:
Python is an interpreted, high-level programming language that is readable and easy to understand syntax
Python has ample learning resources available for Python
Python has high versatility and multiple use cases according to Python Developers Survey 2020 conducted by Python Software Foundation and JetBrains
Python has a vast collection of libraries for performing various operations and tasks
Python is a popular language according to the TIOBE index and Stack Overflow Developer Survey
Python is a highly sought after skills by employers
Another question that you may have is:
How exactly will Python help your data science projects?
To answer this question, let’s consider the data life cycle as shown below. In essence there are 5 major steps consisting of data collection, data cleaning, exploratory data analysis, model building and model deployment. All of these steps can be implemented in Python and once coded, the resulting code is reusable and can therefore be repurposed for other related projects.
Aside from data analytics, data science and data engineering, the great versatility of Python allows it to be applied for endless possibilities including automation, robotics, web development, web scraping, game development and software development. Moreover, Python is being used in practically every domain that we can think of, including but not limited to Aerospace, Banking, Business, Consulting, Healthcare, Insurance, Retail and Information Technology (see the Data Sheet made by ActiveState on Top 10 Python Use Cases).
Figuring out why you’re learning Python may help you stay motivated when life’s getting in the way. Sure, having consistency and good habits may only get you so far. Having a clear reason for learning may help to boost your motivation and steer you back on track.
A part of learning any new technical skills is to take a dive in approach to learning. Don’t be afraid of failing or getting stuck as these are inevitable. Remember that if you’re not stuck, you’re not learning! I have always liked to approach learning new things by making as much mistakes as possible and the plus side is the valuable lessons learned that can be used for tackling it the second time around.
In fact, I have learned about the OODA loop from one of Daniel Bourke’s blog that the faster we can iterate through this loop, the better we will be in attaining intended goals.
The OODA loops stands for Observe, Orient, Decide and Act, which was originally a military strategy designed by US Air Force Colonel John Boyd for use in combat. The key is speed and to achieve that speed, the iteration through the loop must proceed faster. Thus, when applied in implementing coding projects, the faster we can iterate through the OODA loop the more we will learn.
There are ample learning resources available for learning Python. Depending on the approach that resonates with you, select those that maximizes your learning potential.
3.3.1. Reading
If reading is your thing, there are several great books and written tutorials that you can learn Python from. → Python Basics: A Practical Introduction to Python 3 → Automate the Boring Stuff with Python: Practical Programming for Total Beginners → Python Crash Course: A Hands-On, Project-Based Introduction to Programming
Some good books using Python in the context of data science and machine learning are as follows: → Python Data Science Handbook: Essential Tools for Working with Data → Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython → Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
3.3.2. Visual
Perhaps you are more of a visual person then there’s a lot of great YouTube channels out there that teaches the concepts as well as practical tutorials. These includes: freeCodeCamp, Data Professor, Coding Professor, CD Dojo, Corey Schafer, Tech with Tim, Python Programmer, Data School, Keith Galli, Kylie Ying and Programming with Mosh.
3.3.3. Projects
Nothing beats learning by doing. It is also the greatest way to push your learning to the limits. The large collection of datasets available on Kaggle is a great starting point to get inspiration for starting your own projects. Guided Projects by Coursera is also another way to implement projects under the guidance of a course mentor. If you’re into live training, Data Science Dojo has an introductory Python for Data Science program that can be completed in a week’s time.
Being able to successfully follow tutorials and being able to implement your own projects from scratch are two different things. Sure, for the former you can successfully follow each steps of the tutorial but when it comes the time that you have to figure out for your own which approach to use or which libraries/functions to use, you may succumb to the challenge and get stuck.
So how exactly can you make the transition from being a follower of coding tutorials to actually being able to implement your own projects? Find out in the next section.
The answer is quite simple. You have to start doing projects. The more, the merrier. As you accumulate experience from many projects, you’re going to acquire skills pertaining to problem solving and problem framing.
To get started, follow these process:
Select an interesting problem to work on.Understand the problem.Break down the problem to the smallest parts.Implement the small parts. Next, piece together the results of these parts and holistically see if they addressed the problem.Rinse and repeat.
Select an interesting problem to work on.
Understand the problem.
Break down the problem to the smallest parts.
Implement the small parts. Next, piece together the results of these parts and holistically see if they addressed the problem.
Rinse and repeat.
You may also find the project to be more engaging if you’re passionate about the topic or if it piques your interest. Look around you, what topics are you interested in and think about what you would like to know more about. For example, if you are a YouTube content creator, you may find it interesting to analyze your content in relation to its performance (e.g. views, hours watched, watch time, video clickthrough rate, etc.).
You should become familiar with using Python functions to perform various tasks. In a nutshell, the thousands of Python libraries that are available on PyPI, conda or GitHub comes pre-equipped with a wide-range of functions that you can use right out of the box.
The essence of these functions is that it normally takes in input arguments for which it uses to perform a pre-defined task or sets of tasks before returning the output. Input arguments can be explicitly specified when running the function but if none are specified then Python assumes that you’re using a set of default parameters.
Before embarking on writing your own custom function, do some Googling to see if there are already some existing functions from libraries that performs similar functionalities as to what you plan on implementing. Chances are there may already be an existing function for which you just need to simply import and use.
It should be noted that if you’re familiar with one library you’re also likely to be able to pick up other related libraries. For example, if you’re already familiar with using matplotlib, using seaborn or plotly should be fairly easy to learn and implement because the foundations are already in place. Similar with the deep learning libraries (e.g. tensorflow, torch, fastai and mxnet).
As you code your projects and you’re code throws out errors, it is therefore essential that you learn how to debug the code and problem solve. However, if the error goes beyond your comprehension, it is very important that you know how to ask for help.
The first person that you should ask is yourself. Yes, I know you may be wondering how would that work since you’re clueless right now. By asking yourself, I mean that you first try to solve the problem yourself before you ask others for help. This is important because it goes to show your character and your persistence.
So how exactly can you debug the code and problem solve.
Read the output carefully as the reason for the error is explicitly written in the output. Sometimes even the simplest error may have slipped our mind such as forgetting to install some libraries or forgetting to first defining the variables before using it.If you are still clueless, now it’s time to start Googling. Thus, you will now have to learn how to master the Art of Asking the Right Questions. If you’re asking Google using irrelevant keywords, you may not find any useful answers in the search results. The easiest way is to include keywords related to the problem.
Read the output carefully as the reason for the error is explicitly written in the output. Sometimes even the simplest error may have slipped our mind such as forgetting to install some libraries or forgetting to first defining the variables before using it.
If you are still clueless, now it’s time to start Googling. Thus, you will now have to learn how to master the Art of Asking the Right Questions. If you’re asking Google using irrelevant keywords, you may not find any useful answers in the search results. The easiest way is to include keywords related to the problem.
In the search query, I would use the following as keywords
<name of Python or R library> <copy and paste the error message>
Yes, that’s basically it. But let’s say I would like to limit my search from only Stack Overflow I would add site:stackoverflow.com as an additional statement in the search query. Or alternatively, you can head over to Stack Overflow and perform the search there.
A recurring theme in any learning journey is to develop a habit of learning, which will help you to become consistent in your learning journey. Coding consistently will put your momentum in action and the more you use it the more skillful you’ll become. As the saying goes:
Use it or lose it.
The 66 Days of Data initiative started by Ken Jee is a great way to build good habits of learning, maintain consistency and gain accountability for your learning. Taking part in this initiative is quite easy:
Spend at least 5 minutes a day coding or doing data scienceShare what you’ve done and learned using the #66daysofdata hashtag on Twitter or Linkedin.
Spend at least 5 minutes a day coding or doing data science
Share what you’ve done and learned using the #66daysofdata hashtag on Twitter or Linkedin.
Integrated Development Environment (IDE) can be thought of as the work space that will house your code and not only that, it also provides additional amenities and convenience that can augment your coding process.
Basic features of an IDE include syntax highlighting, code folding and bracket matching, path awareness of files in the project as well as the ability to run selected code blocks or the entire file. More advanced features might include code suggestions/completion, debugging tool as well as support for version control.
Popular IDEs for Python includes:
VS Code — A powerful and highly customizable IDE.
PyCharm — Another powerful IDE but may require a paid subscription to unlock all features available in the Pro version, other than that the community version offers a good standard IDE.
Spyder — R and MATLAB users will find this to have a RStudio/MATLAB vibe.
Atom — Sports a beginner friendly interface that is highly customizable.
Jupyter notebook can be installed locally to any operating system of your choice (i.e. be it Windows, Linux or Mac OSX) via pip or conda. Other flavors of Jupyter is the Jupyterlab that also provides a workspace and IDE-like environment for larger and more complex projects.
Cloud deviants of the Jupyter notebook have been a blessing to all aspiring and practicing data scientists as it enables everyone access to powerful computational resources (i.e. both CPU and GPU computing).
I conducted a survey in the community section of my YouTube channel (Data Professor) to see which of the cloud-based Jupyter notebooks were most popular amongst the community.
As can be seen above, the five popular Jupyter notebooks include:
Google Colab
Kaggle Notebooks
Deepnote
Datalore
Paperspace Gradient Notebooks
It should be noted that all of these notebooks provide a free tier (with access to limited computational resources) as well as pro tier (with access to more powerful computational resources) that may require some upfront cost. There may be more but the above are those that I have frequently heard of.
Code suggestion and completion plug-ins such as the one offered by Kite provides immense support for speeding up the coding process as it helps to suggest the completion of lines of codes. This comes in handy especially when you have to sit long hours to code. A couple of seconds saved here and there may accumulate drastically over time. Such code suggestion may also double as an educational or reinforcement tool (i.e. sometimes our mind gets bogged down over long periods of coding) as it may suggest certain code blocks based on the context of the code that we have written.
In this section, we will cover the bare minimum that you need to know to get started in Python.
Variables, Data types and Operators — This is the most important as you’ll be doing this a lot for virtually all your projects. You can think of this as sort of like the alphabets which are the building blocks that you use for spelling words. Defining and using variables allows you to store values for later usage, the various data types allows you the flexibility to make use of data (i.e. whether it be numerical or categorical data that is quantitative or qualitative). Operators will allow you to use process and filter data.
Lists comprehensions and operations — This will be useful for pre-processing data arrays as datasets are essentially collections of numerical or categorical values.
Loops — Loops such as for and while allows us to iterate through each element in an array, list or data frames to perform the same task. At a high-level this allows us to automate the processing of data.
Conditional statements — if, elif and else allows the code to make decisions as to the appropriate paths to proceed with handling or processing the input data. We can use it to perform a certain task if a certain condition is met. For example, we can use it to figure out what is the data type of the input data, if it is numerical we perform processing tasks A otherwise (else) we perform processing tasks B.
Creating and using functions — Function creation helps to group similar processing tasks together in a modular manner that essentially saves your future self’s time as it allows makes your code reusable.
File handling —Reading and writing files; creating, moving and renaming folders; setting environmental paths; navigating through the paths, etc.
Error and exception handling — Errors is inevitable and devising the proper handling of such errors is a great way to prevent the code from stalling and not proceeding further.
Data handling — pandas is the go-to library for handling the common data formats as either 1-dimensional Series (i.e. can be thought of as a single column of a DataFrame) or 2-dimensional DataFrames (i.e. common for tabular datasets).
Statistical analysis — statsmodels is a library that provides functions for statistical test, statistical models as well as building linear regression models.
Machine learning — scikit-learn is the go-to library for building machine learning models. Aside from model building, the library also contains example datasets, utility functions for pre-processing datasets as well as for evaluating the model performance.
Deep learning — Popular libraries for deep learning includes TensorFlow (tensorflow) and PyTorch (torch). Other libraries include fastai and mxnet.
Scientific computation — scipy is the go-to library for scientific and technical computation that encompasses integration, interpolation, optimization, linear algebra, image and signal processing, etc.
Data visualization — There are several libraries for data visualization and the most popular is matplotlib which allows the generation of a wide range of plots. seaborn is an alternative library that draws its functionality from matplotlib but the resulting plots are more refined and attractive. plotly allows the generation of interactive plots
Web applications — django and flask are standard web frameworks for web development as well as for deploying machine learning models. In recent years, minimal and more lightweight alternatives have gained popularity as they are simple and quick to implement. Some of these include streamlit, dash and pywebio.
In 2001, Guido van Rossum, Barry Warsaw and Nick Coghlan released a document that establishes a set of guidelines and best practices for writing Python code called the PEP8. Particularly, PEP is an acynoym for Python Enhancement Proposal and PEP8 is just one of many documents released. The major aim of PEP 8 is to improve the readability and consistency of Python code.
As Guido van Rossum puts it:
“Code is read much more often than it is written”
Thus, writing readable code is like paying it forward because it will either be read by your future self or by others. A common situation that I often encounter is poorly documented code either by myself or by my colleagues, but luckily we have improved over the years.
It is always a great idea to document your code as soon as you have written it because chances are, as time passes you may have forgot some of the reasons for why you’re using a certain approach over another. I also find it helps to also include my train of thoughts that goes into certain blocks of code, which your future self may appreciate as it may very well serve as a good starting point for improving the code at a future point in time (i.e. when you’re brain is at a fresh mental state and ideas may flow better).
Doing crossword puzzles or sudoku are good mental exercises and why not do the same for putting your Python skills to the test. Platforms such as Leetcode and HackerRank helps you learn and practice data structures and algorithms as well as prepare for technical interviews. Other similar platforms in the data science realm are Interview Query and StrataScratch.
Kaggle is a great place for aspiring data scientists to learn data science by means of participating in data competitions. Aside from this, there are ample datasets from which to practice with as well as a large collection of community published notebooks from which to draw inspirations from. If you’re keen on making it to the top as a Kaggler, there’s a Coursera course on How to Win a Data Science Competition: Learn from Top Kagglers that can help you.
As programmers often rely on rubber duck as a teaching tool where they would attempt to explain their problems to and in doing so allows them to gain perspective and often times find a solution to those problems.
As an aspiring data scientist or a practicing data scientist learning a new tool, it is also the case that the best way to learn is to teach it to others as also stated by the Feynman Learning technique.
So how exactly can you teach? There’s actually a lot of ways as I have listed below:
Teach a colleague — Perhaps you may host an intern for whom you can teach
Write a Blog — Blogs are a great way to teach as there are a vast number of learners who look to blog posts to learn something new. Popular platforms for technical blogs include Medium, Dev.to and Hashnode.
Make a YouTube video — You can make a video to explain about a concept that you’re learning about or even a practical tutorial video showing how to use a particular library, how to build a machine learning model, how to build a web app, etc.
Contributing to open source projects has many benefits. Firstly, you’ll be able to learn from other experts in the field as well as learning from reviewing other people’s code (i.e. by reviewing Issues and Pull requests).
Secondly, you will also get the opportunity to be familiar with the use of Git as you contribute your code (i.e. open source projects are hosted on GitHub as well as related platforms such as BitBucket, GitLab, etc.).
Thirdly, you’ll be able to network with others in the community as you gain community and peer recognition. You will also gain more confidence in your coding abilities. Who knows, maybe you’ll even create your very own open source project!
Fourthly, you’re paying it forward as open source projects relies on developers contributing on a volunteer basis. Contributing to the greater good may also give you a sense of satisfaction that you’re making an impact to the community.
Fifthly, you’ll also gain valuable experience of contributing to a real-world project that may help you in the future in landing your own intern or job placement.
Contributing does not mean that you will have to create a big and complex enhancement to the project. You can start by correcting a small bug that you may have come across and that should get the momentum rolling.
An added benefit is that as you fix the code you may also improve your coding and documentation skills (i.e. writing readable and maintainable code). Moreover, the challenge and accountability that comes from this may also help you stay engaged in coding.
In summary, this article explores the landscape of Python as applied to data science. As a self-taught programmer I know how tough it may be to not only learn coding but also to apply it to solve data problems. The journey won’t be easy, but if you can persevere, you’ll be amazed at how much you can do with Python in your data science journey.
I hope that this article provided some starting points that you can use to adapt as you embark in your learning journey. Please drop a comment to suggest any point that works for you!
As an Amazon Associate and affiliate member of services mentioned herein, I may earn from qualifying purchases, which goes into helping the creation of future contents.
How to Build an AutoML App in Python Step-by-Step Tutorial using the Streamlit Library
Strategies for Learning Data SciencePractical Advice for Breaking into Data Science
How to Build a Simple Portfolio Website for FREE Step-by-step tutorial from scratch in less than 10 minutes
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page).
www.youtube.com
✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof/✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
|
[
{
"code": null,
"e": 541,
"s": 172,
"text": "So you’re embarking on your journey into data science and everyone recommends that you start with learning how to code. You decided on Python and are now paralyzed by the large piles of learning resources that are at your disposal. Perhaps you are overwhelmed and owing to analysis paralysis, you are procrastinating your first steps in learning how to code in Python."
},
{
"code": null,
"e": 1299,
"s": 541,
"text": "In this article, I’ll be your guide and take you on a journey of exploring the essential bare minimal knowledge that you need in order to master Python for getting started in data science. I will assume that you have no prior coding experience or that you may come from a non-technical background. However, if you are coming from a technical or computer science background and have knowledge of a prior programming language and would like to transition to Python, you can use this article as a high-level overview to get acquainted with the gist of the Python language. Either way, it is the aim of this article to navigate you through the landscape of the Python language at their intersection with data science, which will help you get started in no time."
},
{
"code": null,
"e": 1353,
"s": 1299,
"text": "The first (and famous) question that you may have is:"
},
{
"code": null,
"e": 1397,
"s": 1353,
"text": "What programming language should you learn?"
},
{
"code": null,
"e": 1502,
"s": 1397,
"text": "After doing some research on the internet you may have decided on Python owing to the following reasons:"
},
{
"code": null,
"e": 1607,
"s": 1502,
"text": "Python is an interpreted, high-level programming language that is readable and easy to understand syntax"
},
{
"code": null,
"e": 1664,
"s": 1607,
"text": "Python has ample learning resources available for Python"
},
{
"code": null,
"e": 1812,
"s": 1664,
"text": "Python has high versatility and multiple use cases according to Python Developers Survey 2020 conducted by Python Software Foundation and JetBrains"
},
{
"code": null,
"e": 1898,
"s": 1812,
"text": "Python has a vast collection of libraries for performing various operations and tasks"
},
{
"code": null,
"e": 1992,
"s": 1898,
"text": "Python is a popular language according to the TIOBE index and Stack Overflow Developer Survey"
},
{
"code": null,
"e": 2044,
"s": 1992,
"text": "Python is a highly sought after skills by employers"
},
{
"code": null,
"e": 2083,
"s": 2044,
"text": "Another question that you may have is:"
},
{
"code": null,
"e": 2140,
"s": 2083,
"text": "How exactly will Python help your data science projects?"
},
{
"code": null,
"e": 2516,
"s": 2140,
"text": "To answer this question, let’s consider the data life cycle as shown below. In essence there are 5 major steps consisting of data collection, data cleaning, exploratory data analysis, model building and model deployment. All of these steps can be implemented in Python and once coded, the resulting code is reusable and can therefore be repurposed for other related projects."
},
{
"code": null,
"e": 3044,
"s": 2516,
"text": "Aside from data analytics, data science and data engineering, the great versatility of Python allows it to be applied for endless possibilities including automation, robotics, web development, web scraping, game development and software development. Moreover, Python is being used in practically every domain that we can think of, including but not limited to Aerospace, Banking, Business, Consulting, Healthcare, Insurance, Retail and Information Technology (see the Data Sheet made by ActiveState on Top 10 Python Use Cases)."
},
{
"code": null,
"e": 3308,
"s": 3044,
"text": "Figuring out why you’re learning Python may help you stay motivated when life’s getting in the way. Sure, having consistency and good habits may only get you so far. Having a clear reason for learning may help to boost your motivation and steer you back on track."
},
{
"code": null,
"e": 3718,
"s": 3308,
"text": "A part of learning any new technical skills is to take a dive in approach to learning. Don’t be afraid of failing or getting stuck as these are inevitable. Remember that if you’re not stuck, you’re not learning! I have always liked to approach learning new things by making as much mistakes as possible and the plus side is the valuable lessons learned that can be used for tackling it the second time around."
},
{
"code": null,
"e": 3896,
"s": 3718,
"text": "In fact, I have learned about the OODA loop from one of Daniel Bourke’s blog that the faster we can iterate through this loop, the better we will be in attaining intended goals."
},
{
"code": null,
"e": 4278,
"s": 3896,
"text": "The OODA loops stands for Observe, Orient, Decide and Act, which was originally a military strategy designed by US Air Force Colonel John Boyd for use in combat. The key is speed and to achieve that speed, the iteration through the loop must proceed faster. Thus, when applied in implementing coding projects, the faster we can iterate through the OODA loop the more we will learn."
},
{
"code": null,
"e": 4448,
"s": 4278,
"text": "There are ample learning resources available for learning Python. Depending on the approach that resonates with you, select those that maximizes your learning potential."
},
{
"code": null,
"e": 4463,
"s": 4448,
"text": "3.3.1. Reading"
},
{
"code": null,
"e": 4787,
"s": 4463,
"text": "If reading is your thing, there are several great books and written tutorials that you can learn Python from. → Python Basics: A Practical Introduction to Python 3 → Automate the Boring Stuff with Python: Practical Programming for Total Beginners → Python Crash Course: A Hands-On, Project-Based Introduction to Programming"
},
{
"code": null,
"e": 5160,
"s": 4787,
"text": "Some good books using Python in the context of data science and machine learning are as follows: → Python Data Science Handbook: Essential Tools for Working with Data → Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython → Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems"
},
{
"code": null,
"e": 5174,
"s": 5160,
"text": "3.3.2. Visual"
},
{
"code": null,
"e": 5513,
"s": 5174,
"text": "Perhaps you are more of a visual person then there’s a lot of great YouTube channels out there that teaches the concepts as well as practical tutorials. These includes: freeCodeCamp, Data Professor, Coding Professor, CD Dojo, Corey Schafer, Tech with Tim, Python Programmer, Data School, Keith Galli, Kylie Ying and Programming with Mosh."
},
{
"code": null,
"e": 5529,
"s": 5513,
"text": "3.3.3. Projects"
},
{
"code": null,
"e": 6006,
"s": 5529,
"text": "Nothing beats learning by doing. It is also the greatest way to push your learning to the limits. The large collection of datasets available on Kaggle is a great starting point to get inspiration for starting your own projects. Guided Projects by Coursera is also another way to implement projects under the guidance of a course mentor. If you’re into live training, Data Science Dojo has an introductory Python for Data Science program that can be completed in a week’s time."
},
{
"code": null,
"e": 6386,
"s": 6006,
"text": "Being able to successfully follow tutorials and being able to implement your own projects from scratch are two different things. Sure, for the former you can successfully follow each steps of the tutorial but when it comes the time that you have to figure out for your own which approach to use or which libraries/functions to use, you may succumb to the challenge and get stuck."
},
{
"code": null,
"e": 6556,
"s": 6386,
"text": "So how exactly can you make the transition from being a follower of coding tutorials to actually being able to implement your own projects? Find out in the next section."
},
{
"code": null,
"e": 6772,
"s": 6556,
"text": "The answer is quite simple. You have to start doing projects. The more, the merrier. As you accumulate experience from many projects, you’re going to acquire skills pertaining to problem solving and problem framing."
},
{
"code": null,
"e": 6810,
"s": 6772,
"text": "To get started, follow these process:"
},
{
"code": null,
"e": 7063,
"s": 6810,
"text": "Select an interesting problem to work on.Understand the problem.Break down the problem to the smallest parts.Implement the small parts. Next, piece together the results of these parts and holistically see if they addressed the problem.Rinse and repeat."
},
{
"code": null,
"e": 7105,
"s": 7063,
"text": "Select an interesting problem to work on."
},
{
"code": null,
"e": 7129,
"s": 7105,
"text": "Understand the problem."
},
{
"code": null,
"e": 7175,
"s": 7129,
"text": "Break down the problem to the smallest parts."
},
{
"code": null,
"e": 7302,
"s": 7175,
"text": "Implement the small parts. Next, piece together the results of these parts and holistically see if they addressed the problem."
},
{
"code": null,
"e": 7320,
"s": 7302,
"text": "Rinse and repeat."
},
{
"code": null,
"e": 7751,
"s": 7320,
"text": "You may also find the project to be more engaging if you’re passionate about the topic or if it piques your interest. Look around you, what topics are you interested in and think about what you would like to know more about. For example, if you are a YouTube content creator, you may find it interesting to analyze your content in relation to its performance (e.g. views, hours watched, watch time, video clickthrough rate, etc.)."
},
{
"code": null,
"e": 8014,
"s": 7751,
"text": "You should become familiar with using Python functions to perform various tasks. In a nutshell, the thousands of Python libraries that are available on PyPI, conda or GitHub comes pre-equipped with a wide-range of functions that you can use right out of the box."
},
{
"code": null,
"e": 8347,
"s": 8014,
"text": "The essence of these functions is that it normally takes in input arguments for which it uses to perform a pre-defined task or sets of tasks before returning the output. Input arguments can be explicitly specified when running the function but if none are specified then Python assumes that you’re using a set of default parameters."
},
{
"code": null,
"e": 8664,
"s": 8347,
"text": "Before embarking on writing your own custom function, do some Googling to see if there are already some existing functions from libraries that performs similar functionalities as to what you plan on implementing. Chances are there may already be an existing function for which you just need to simply import and use."
},
{
"code": null,
"e": 9053,
"s": 8664,
"text": "It should be noted that if you’re familiar with one library you’re also likely to be able to pick up other related libraries. For example, if you’re already familiar with using matplotlib, using seaborn or plotly should be fairly easy to learn and implement because the foundations are already in place. Similar with the deep learning libraries (e.g. tensorflow, torch, fastai and mxnet)."
},
{
"code": null,
"e": 9306,
"s": 9053,
"text": "As you code your projects and you’re code throws out errors, it is therefore essential that you learn how to debug the code and problem solve. However, if the error goes beyond your comprehension, it is very important that you know how to ask for help."
},
{
"code": null,
"e": 9629,
"s": 9306,
"text": "The first person that you should ask is yourself. Yes, I know you may be wondering how would that work since you’re clueless right now. By asking yourself, I mean that you first try to solve the problem yourself before you ask others for help. This is important because it goes to show your character and your persistence."
},
{
"code": null,
"e": 9686,
"s": 9629,
"text": "So how exactly can you debug the code and problem solve."
},
{
"code": null,
"e": 10263,
"s": 9686,
"text": "Read the output carefully as the reason for the error is explicitly written in the output. Sometimes even the simplest error may have slipped our mind such as forgetting to install some libraries or forgetting to first defining the variables before using it.If you are still clueless, now it’s time to start Googling. Thus, you will now have to learn how to master the Art of Asking the Right Questions. If you’re asking Google using irrelevant keywords, you may not find any useful answers in the search results. The easiest way is to include keywords related to the problem."
},
{
"code": null,
"e": 10522,
"s": 10263,
"text": "Read the output carefully as the reason for the error is explicitly written in the output. Sometimes even the simplest error may have slipped our mind such as forgetting to install some libraries or forgetting to first defining the variables before using it."
},
{
"code": null,
"e": 10841,
"s": 10522,
"text": "If you are still clueless, now it’s time to start Googling. Thus, you will now have to learn how to master the Art of Asking the Right Questions. If you’re asking Google using irrelevant keywords, you may not find any useful answers in the search results. The easiest way is to include keywords related to the problem."
},
{
"code": null,
"e": 10900,
"s": 10841,
"text": "In the search query, I would use the following as keywords"
},
{
"code": null,
"e": 10965,
"s": 10900,
"text": "<name of Python or R library> <copy and paste the error message>"
},
{
"code": null,
"e": 11229,
"s": 10965,
"text": "Yes, that’s basically it. But let’s say I would like to limit my search from only Stack Overflow I would add site:stackoverflow.com as an additional statement in the search query. Or alternatively, you can head over to Stack Overflow and perform the search there."
},
{
"code": null,
"e": 11503,
"s": 11229,
"text": "A recurring theme in any learning journey is to develop a habit of learning, which will help you to become consistent in your learning journey. Coding consistently will put your momentum in action and the more you use it the more skillful you’ll become. As the saying goes:"
},
{
"code": null,
"e": 11522,
"s": 11503,
"text": "Use it or lose it."
},
{
"code": null,
"e": 11731,
"s": 11522,
"text": "The 66 Days of Data initiative started by Ken Jee is a great way to build good habits of learning, maintain consistency and gain accountability for your learning. Taking part in this initiative is quite easy:"
},
{
"code": null,
"e": 11881,
"s": 11731,
"text": "Spend at least 5 minutes a day coding or doing data scienceShare what you’ve done and learned using the #66daysofdata hashtag on Twitter or Linkedin."
},
{
"code": null,
"e": 11941,
"s": 11881,
"text": "Spend at least 5 minutes a day coding or doing data science"
},
{
"code": null,
"e": 12032,
"s": 11941,
"text": "Share what you’ve done and learned using the #66daysofdata hashtag on Twitter or Linkedin."
},
{
"code": null,
"e": 12246,
"s": 12032,
"text": "Integrated Development Environment (IDE) can be thought of as the work space that will house your code and not only that, it also provides additional amenities and convenience that can augment your coding process."
},
{
"code": null,
"e": 12566,
"s": 12246,
"text": "Basic features of an IDE include syntax highlighting, code folding and bracket matching, path awareness of files in the project as well as the ability to run selected code blocks or the entire file. More advanced features might include code suggestions/completion, debugging tool as well as support for version control."
},
{
"code": null,
"e": 12600,
"s": 12566,
"text": "Popular IDEs for Python includes:"
},
{
"code": null,
"e": 12650,
"s": 12600,
"text": "VS Code — A powerful and highly customizable IDE."
},
{
"code": null,
"e": 12836,
"s": 12650,
"text": "PyCharm — Another powerful IDE but may require a paid subscription to unlock all features available in the Pro version, other than that the community version offers a good standard IDE."
},
{
"code": null,
"e": 12910,
"s": 12836,
"text": "Spyder — R and MATLAB users will find this to have a RStudio/MATLAB vibe."
},
{
"code": null,
"e": 12983,
"s": 12910,
"text": "Atom — Sports a beginner friendly interface that is highly customizable."
},
{
"code": null,
"e": 13258,
"s": 12983,
"text": "Jupyter notebook can be installed locally to any operating system of your choice (i.e. be it Windows, Linux or Mac OSX) via pip or conda. Other flavors of Jupyter is the Jupyterlab that also provides a workspace and IDE-like environment for larger and more complex projects."
},
{
"code": null,
"e": 13466,
"s": 13258,
"text": "Cloud deviants of the Jupyter notebook have been a blessing to all aspiring and practicing data scientists as it enables everyone access to powerful computational resources (i.e. both CPU and GPU computing)."
},
{
"code": null,
"e": 13642,
"s": 13466,
"text": "I conducted a survey in the community section of my YouTube channel (Data Professor) to see which of the cloud-based Jupyter notebooks were most popular amongst the community."
},
{
"code": null,
"e": 13708,
"s": 13642,
"text": "As can be seen above, the five popular Jupyter notebooks include:"
},
{
"code": null,
"e": 13721,
"s": 13708,
"text": "Google Colab"
},
{
"code": null,
"e": 13738,
"s": 13721,
"text": "Kaggle Notebooks"
},
{
"code": null,
"e": 13747,
"s": 13738,
"text": "Deepnote"
},
{
"code": null,
"e": 13756,
"s": 13747,
"text": "Datalore"
},
{
"code": null,
"e": 13786,
"s": 13756,
"text": "Paperspace Gradient Notebooks"
},
{
"code": null,
"e": 14088,
"s": 13786,
"text": "It should be noted that all of these notebooks provide a free tier (with access to limited computational resources) as well as pro tier (with access to more powerful computational resources) that may require some upfront cost. There may be more but the above are those that I have frequently heard of."
},
{
"code": null,
"e": 14669,
"s": 14088,
"text": "Code suggestion and completion plug-ins such as the one offered by Kite provides immense support for speeding up the coding process as it helps to suggest the completion of lines of codes. This comes in handy especially when you have to sit long hours to code. A couple of seconds saved here and there may accumulate drastically over time. Such code suggestion may also double as an educational or reinforcement tool (i.e. sometimes our mind gets bogged down over long periods of coding) as it may suggest certain code blocks based on the context of the code that we have written."
},
{
"code": null,
"e": 14765,
"s": 14669,
"text": "In this section, we will cover the bare minimum that you need to know to get started in Python."
},
{
"code": null,
"e": 15296,
"s": 14765,
"text": "Variables, Data types and Operators — This is the most important as you’ll be doing this a lot for virtually all your projects. You can think of this as sort of like the alphabets which are the building blocks that you use for spelling words. Defining and using variables allows you to store values for later usage, the various data types allows you the flexibility to make use of data (i.e. whether it be numerical or categorical data that is quantitative or qualitative). Operators will allow you to use process and filter data."
},
{
"code": null,
"e": 15461,
"s": 15296,
"text": "Lists comprehensions and operations — This will be useful for pre-processing data arrays as datasets are essentially collections of numerical or categorical values."
},
{
"code": null,
"e": 15665,
"s": 15461,
"text": "Loops — Loops such as for and while allows us to iterate through each element in an array, list or data frames to perform the same task. At a high-level this allows us to automate the processing of data."
},
{
"code": null,
"e": 16075,
"s": 15665,
"text": "Conditional statements — if, elif and else allows the code to make decisions as to the appropriate paths to proceed with handling or processing the input data. We can use it to perform a certain task if a certain condition is met. For example, we can use it to figure out what is the data type of the input data, if it is numerical we perform processing tasks A otherwise (else) we perform processing tasks B."
},
{
"code": null,
"e": 16279,
"s": 16075,
"text": "Creating and using functions — Function creation helps to group similar processing tasks together in a modular manner that essentially saves your future self’s time as it allows makes your code reusable."
},
{
"code": null,
"e": 16424,
"s": 16279,
"text": "File handling —Reading and writing files; creating, moving and renaming folders; setting environmental paths; navigating through the paths, etc."
},
{
"code": null,
"e": 16601,
"s": 16424,
"text": "Error and exception handling — Errors is inevitable and devising the proper handling of such errors is a great way to prevent the code from stalling and not proceeding further."
},
{
"code": null,
"e": 16836,
"s": 16601,
"text": "Data handling — pandas is the go-to library for handling the common data formats as either 1-dimensional Series (i.e. can be thought of as a single column of a DataFrame) or 2-dimensional DataFrames (i.e. common for tabular datasets)."
},
{
"code": null,
"e": 16995,
"s": 16836,
"text": "Statistical analysis — statsmodels is a library that provides functions for statistical test, statistical models as well as building linear regression models."
},
{
"code": null,
"e": 17252,
"s": 16995,
"text": "Machine learning — scikit-learn is the go-to library for building machine learning models. Aside from model building, the library also contains example datasets, utility functions for pre-processing datasets as well as for evaluating the model performance."
},
{
"code": null,
"e": 17400,
"s": 17252,
"text": "Deep learning — Popular libraries for deep learning includes TensorFlow (tensorflow) and PyTorch (torch). Other libraries include fastai and mxnet."
},
{
"code": null,
"e": 17602,
"s": 17400,
"text": "Scientific computation — scipy is the go-to library for scientific and technical computation that encompasses integration, interpolation, optimization, linear algebra, image and signal processing, etc."
},
{
"code": null,
"e": 17949,
"s": 17602,
"text": "Data visualization — There are several libraries for data visualization and the most popular is matplotlib which allows the generation of a wide range of plots. seaborn is an alternative library that draws its functionality from matplotlib but the resulting plots are more refined and attractive. plotly allows the generation of interactive plots"
},
{
"code": null,
"e": 18259,
"s": 17949,
"text": "Web applications — django and flask are standard web frameworks for web development as well as for deploying machine learning models. In recent years, minimal and more lightweight alternatives have gained popularity as they are simple and quick to implement. Some of these include streamlit, dash and pywebio."
},
{
"code": null,
"e": 18631,
"s": 18259,
"text": "In 2001, Guido van Rossum, Barry Warsaw and Nick Coghlan released a document that establishes a set of guidelines and best practices for writing Python code called the PEP8. Particularly, PEP is an acynoym for Python Enhancement Proposal and PEP8 is just one of many documents released. The major aim of PEP 8 is to improve the readability and consistency of Python code."
},
{
"code": null,
"e": 18660,
"s": 18631,
"text": "As Guido van Rossum puts it:"
},
{
"code": null,
"e": 18710,
"s": 18660,
"text": "“Code is read much more often than it is written”"
},
{
"code": null,
"e": 18980,
"s": 18710,
"text": "Thus, writing readable code is like paying it forward because it will either be read by your future self or by others. A common situation that I often encounter is poorly documented code either by myself or by my colleagues, but luckily we have improved over the years."
},
{
"code": null,
"e": 19503,
"s": 18980,
"text": "It is always a great idea to document your code as soon as you have written it because chances are, as time passes you may have forgot some of the reasons for why you’re using a certain approach over another. I also find it helps to also include my train of thoughts that goes into certain blocks of code, which your future self may appreciate as it may very well serve as a good starting point for improving the code at a future point in time (i.e. when you’re brain is at a fresh mental state and ideas may flow better)."
},
{
"code": null,
"e": 19867,
"s": 19503,
"text": "Doing crossword puzzles or sudoku are good mental exercises and why not do the same for putting your Python skills to the test. Platforms such as Leetcode and HackerRank helps you learn and practice data structures and algorithms as well as prepare for technical interviews. Other similar platforms in the data science realm are Interview Query and StrataScratch."
},
{
"code": null,
"e": 20325,
"s": 19867,
"text": "Kaggle is a great place for aspiring data scientists to learn data science by means of participating in data competitions. Aside from this, there are ample datasets from which to practice with as well as a large collection of community published notebooks from which to draw inspirations from. If you’re keen on making it to the top as a Kaggler, there’s a Coursera course on How to Win a Data Science Competition: Learn from Top Kagglers that can help you."
},
{
"code": null,
"e": 20538,
"s": 20325,
"text": "As programmers often rely on rubber duck as a teaching tool where they would attempt to explain their problems to and in doing so allows them to gain perspective and often times find a solution to those problems."
},
{
"code": null,
"e": 20742,
"s": 20538,
"text": "As an aspiring data scientist or a practicing data scientist learning a new tool, it is also the case that the best way to learn is to teach it to others as also stated by the Feynman Learning technique."
},
{
"code": null,
"e": 20827,
"s": 20742,
"text": "So how exactly can you teach? There’s actually a lot of ways as I have listed below:"
},
{
"code": null,
"e": 20901,
"s": 20827,
"text": "Teach a colleague — Perhaps you may host an intern for whom you can teach"
},
{
"code": null,
"e": 21108,
"s": 20901,
"text": "Write a Blog — Blogs are a great way to teach as there are a vast number of learners who look to blog posts to learn something new. Popular platforms for technical blogs include Medium, Dev.to and Hashnode."
},
{
"code": null,
"e": 21350,
"s": 21108,
"text": "Make a YouTube video — You can make a video to explain about a concept that you’re learning about or even a practical tutorial video showing how to use a particular library, how to build a machine learning model, how to build a web app, etc."
},
{
"code": null,
"e": 21572,
"s": 21350,
"text": "Contributing to open source projects has many benefits. Firstly, you’ll be able to learn from other experts in the field as well as learning from reviewing other people’s code (i.e. by reviewing Issues and Pull requests)."
},
{
"code": null,
"e": 21790,
"s": 21572,
"text": "Secondly, you will also get the opportunity to be familiar with the use of Git as you contribute your code (i.e. open source projects are hosted on GitHub as well as related platforms such as BitBucket, GitLab, etc.)."
},
{
"code": null,
"e": 22030,
"s": 21790,
"text": "Thirdly, you’ll be able to network with others in the community as you gain community and peer recognition. You will also gain more confidence in your coding abilities. Who knows, maybe you’ll even create your very own open source project!"
},
{
"code": null,
"e": 22267,
"s": 22030,
"text": "Fourthly, you’re paying it forward as open source projects relies on developers contributing on a volunteer basis. Contributing to the greater good may also give you a sense of satisfaction that you’re making an impact to the community."
},
{
"code": null,
"e": 22430,
"s": 22267,
"text": "Fifthly, you’ll also gain valuable experience of contributing to a real-world project that may help you in the future in landing your own intern or job placement."
},
{
"code": null,
"e": 22644,
"s": 22430,
"text": "Contributing does not mean that you will have to create a big and complex enhancement to the project. You can start by correcting a small bug that you may have come across and that should get the momentum rolling."
},
{
"code": null,
"e": 22900,
"s": 22644,
"text": "An added benefit is that as you fix the code you may also improve your coding and documentation skills (i.e. writing readable and maintainable code). Moreover, the challenge and accountability that comes from this may also help you stay engaged in coding."
},
{
"code": null,
"e": 23246,
"s": 22900,
"text": "In summary, this article explores the landscape of Python as applied to data science. As a self-taught programmer I know how tough it may be to not only learn coding but also to apply it to solve data problems. The journey won’t be easy, but if you can persevere, you’ll be amazed at how much you can do with Python in your data science journey."
},
{
"code": null,
"e": 23430,
"s": 23246,
"text": "I hope that this article provided some starting points that you can use to adapt as you embark in your learning journey. Please drop a comment to suggest any point that works for you!"
},
{
"code": null,
"e": 23599,
"s": 23430,
"text": "As an Amazon Associate and affiliate member of services mentioned herein, I may earn from qualifying purchases, which goes into helping the creation of future contents."
},
{
"code": null,
"e": 23686,
"s": 23599,
"text": "How to Build an AutoML App in Python Step-by-Step Tutorial using the Streamlit Library"
},
{
"code": null,
"e": 23770,
"s": 23686,
"text": "Strategies for Learning Data SciencePractical Advice for Breaking into Data Science"
},
{
"code": null,
"e": 23878,
"s": 23770,
"text": "How to Build a Simple Portfolio Website for FREE Step-by-step tutorial from scratch in less than 10 minutes"
},
{
"code": null,
"e": 24240,
"s": 23878,
"text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)."
},
{
"code": null,
"e": 24256,
"s": 24240,
"text": "www.youtube.com"
}
] |
Statistical Simulation in R with Code — Part 1 | by Leihua Ye, PhD | Towards Data Science
|
This is part 1of a dual post on Statistical Simulation. Please check out part 2 here if you haven’t:
towardsdatascience.com
For the past few months, I’ve received several Data Science interviews from the top tech companies. Almost all of the interviewers asked me to perform statistical simulation for a real business scenario, which I failed to impress.
You know, they are reasonable questions and not super difficult to answer if I had been exposed to the topic before.
Until today, I’ve spent hundreds of hours learning simulations and preparing for the next technical interviews.
Statistical simulation is a rather broad field, and it’s impossible to cover every detail in just one writing. Serving as a starter, I plan to lay out the nuances and applications of simulation through a sequence of posts.
In the real world, things happen randomly, and there is an infinite number of possibilities. We may only be able to observe only a fraction of, but not, the entire possibilities.
Simulation comes in handy and offers a quick overview of the distribution of the possibilities that match real-world outcomes. By studying simulated outcomes, we gain insights into the real world.
Let’s start with the easiest code and move up to more sophisticated scenarios.
The command runif(x, min=a, max=b) generates x number of values within the range between a and b.
library(dplyr)set.seed(2)runif(25,min=0,max=10)
The set.seed() function sets a seed for R’s random number generator, so that we get the same values consistently each time we run the code. Otherwise, we will get different results. Try yourself.
To get integers, we use the round function, as follows:
runif(25,min=0,max=10) %>% round(.,digits = 0)
Here, the pipe, %>%, comes from magrittr package and allows you to write cleaner and easily understandable code. It can be translated into plain English as ‘then.’
In English, the above two lines of code mean:
generate 25 numbers within the range from 0 and 10then (%>%), round the number up to the nearest integer.
generate 25 numbers within the range from 0 and 10
then (%>%), round the number up to the nearest integer.
Try what happens if you tweak the digits = 1.
Another way of generating a random number is via the sample function:
> sample(x, size, replace=TRUE, prob=NULL)
x: a vector, or a positive integer
size: a non-negative integer giving the number of items to choose
replace: sample with replacement, or not?
prob: a vector of probability weights for obtaining the elements of the vector being sampled
(Please refer to R documentation for more information, link)
A quick example.
set.seed(24)sample(seq(1,10),8)
The set.seed() function makes the result reproducible.
The above code generates a random sample of 8 numbers from the sequence [1,10]. As you can see, we do not set rules for replacement and probability of selection.
By default, R sets replacement to FALSE and adopts equal probabilities of selection.
x = 1:10sample(x,replace=TRUE)
The process of resampling with replacement is called bootstrapping, a more advanced topic that will be covered in the next chapter.
Besides numbers, we can sample words, as follows:
set.seed(1)sample(letters,18)
We generate a random sample of size 10 from the sequence [1,5] with equal probabilities.
equal_prob_dist = sample(5,10000,prob=rep(0.1,5),replace=T)hist(equal_prob_dist)
If we set prob=rep(0.1,5), then numbers 1 to 5 will be equally sampled, as shown in the histogram above.
What does the distribution look like if the probabilities of selection are not equal (e.g., a loaded dice)?
We generate a random sample of size 10 from sequence[1,5] with unequal probabilities
unequal_prob_dist = sample(5,10000,prob =c(0.1,0.25,0.4,0.25,0.1), replace=T)hist(unequal_prob_dist)
We set the following selection probability rules for the sequence:
1 & 5: 0.12 & 4: 0.25 3: 0.4
As it turns out, number 3 is the most selected and 1 & 5 are the least selected.
These equal/unequal scenarios could be tremendously helpful if the question of interest needs differentiated treatments of selection probability.
To sample observations (rows) from a data frame or a list, we don’t sample the rows directly but the indices into an object.
head(mtcars)
# step 1: create an index vector for the elements/rows index <- seq_len(nrow(mtcars)) # step 2: sample the index vectorset.seed(12)#to obtain a random sample of 10sample_index <- sample(index,10)# step 3: to show the sampled elements/rows mtcars[sample_index,]
In this section, let’s get some practice and solve real-life business scenarios.
set.seed(1)die = 1:6# sample 10000 times with replacements for dice 1die1 = sample(die,10000,replace = TRUE,prob=NULL)# sample 10000 times with replacements for dice 2die2= sample(die,10000,replace=TRUE,prob = NULL)# the combined value of die_1 and die_2 outcomes = die1+die2# the probability of getting a 7mean(outcomes == 7)
Similarly, we can use a for loop for the same purpose.
set.seed(1)for (i in 10000){ die_1 = sample(die,prob=NULL,replace=TRUE) die_2 = sample(die,prob=NULL,replace=TRUE) die_sum = die_1+die_2 print(mean(die_sum==7))}
These two outcomes are almost the same.
Instead of simulating each outcome, there is an easier way of getting what we need using sapply.
sapply(2:13,function(x) mean(outcomes==x))
According to R documentation, sapply() function is a “user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = "array", an array if appropriate, by applying simplify2array(). sapply(x, f, simplify = FALSE, USE.NAMES = FALSE) is the same as lapply(x, f).”
Briefly, the function applies the function mean(outcomes) to the sequence [2,13].
Question for you: what is the probability of rolling a 7 if you have 3 dices?
set.seed(1)n=10000included_obs = length(unique(sample(1:n, replace = TRUE)))included_obsmissing_obs = n-included_obsmissing_obs
After sampling, we use unique() to find the distinctive observations and length() to count. In a 10k sample, 6316 unique cases are sampled and 3684 (10k — 6316) cases are not.
As a further note, the reason why we only get 6316 out of 10k is that we sample with replacements, and so some numbers are sampled repetitively. In other words, some numbers are sampled multiple times.
(credits to discussions on R-bloggers, here)
In the original post, the authors introduce multiple methods, and I focus on the first approaches here.
First, we can use a for loop.
m <- 10n <- 10# create an empty matrixm00 <- matrix(0,m,n)for (i in 1:m) { for (j in 1:n) { m00[i,j] <- sample(c(0,1),1) }}m00
Here, matrix(0,m,n) creates an empty matrix by m*n, and the two for loops dictate the values of each cell.
Most of the time, a for loop in R may not be the most efficient solution, and we shall use other options if the sample size is big enough.
With that in mind, the authors contribute the second method using apply() function.
m <-10n<-10m0 <- matrix(0,m,n)apply(m0,c(1,2),function(x) sample(c(0,1),1))
So far, everything should be quite familiar except the apply() function. It returns “a vector/array/list of values obtained by applying a function to margins of an array or matrix” (original definition, link).
It has the following form:
> apply(x, margin, fun,...)
x: an array, or matrix
margin: a vector giving the subscripts in which the function will be applied over. For a matrix, 1 indicates rows, and 2 indicates columns. c(1,2) indicates rows and columns, where x has named dimnames, it can be a character vector selecting dimension names
fun: the function to be applied
# create an empty list total_heads = c()# use a for loop to simulate coin-flipping 10 times # repeat it for 10,000 timesfor (i in 1:10000){ sum_heads = sum(round(runif(10,0,1))) total_heads = c(total_heads, sum_heads) }hist(total_heads)
Here, I’ll explain three lines of code, and the rest is pretty self-explanatory.
for (1 in 1:1000). Unlike other programming languages, you have to specify the range as 1:10000.sum(round(runif(10,0,1))). This is a structured way of coding, which has three separate functionalities: runif() → round() → sum(). It runs the runif() function first and sum() last. Basically, the lines of code generate 10 random numbers between 0 and 1, round it up to the nearest integer (0 or 1), and lastly sum it up.total_heads = c(total_heads, sum_heads). Since total_heads is an empty list in the beginning, we use the line of code to assign the value of sum_heads to total_heads.
for (1 in 1:1000). Unlike other programming languages, you have to specify the range as 1:10000.
sum(round(runif(10,0,1))). This is a structured way of coding, which has three separate functionalities: runif() → round() → sum(). It runs the runif() function first and sum() last. Basically, the lines of code generate 10 random numbers between 0 and 1, round it up to the nearest integer (0 or 1), and lastly sum it up.
total_heads = c(total_heads, sum_heads). Since total_heads is an empty list in the beginning, we use the line of code to assign the value of sum_heads to total_heads.
Thank you for reading!
This is an intro post on statistical simulation, and we will explore more advanced topics in the next posts.
Stay tuned!
Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees.
leihua-ye.medium.com
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.
|
[
{
"code": null,
"e": 272,
"s": 171,
"text": "This is part 1of a dual post on Statistical Simulation. Please check out part 2 here if you haven’t:"
},
{
"code": null,
"e": 295,
"s": 272,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 526,
"s": 295,
"text": "For the past few months, I’ve received several Data Science interviews from the top tech companies. Almost all of the interviewers asked me to perform statistical simulation for a real business scenario, which I failed to impress."
},
{
"code": null,
"e": 643,
"s": 526,
"text": "You know, they are reasonable questions and not super difficult to answer if I had been exposed to the topic before."
},
{
"code": null,
"e": 755,
"s": 643,
"text": "Until today, I’ve spent hundreds of hours learning simulations and preparing for the next technical interviews."
},
{
"code": null,
"e": 978,
"s": 755,
"text": "Statistical simulation is a rather broad field, and it’s impossible to cover every detail in just one writing. Serving as a starter, I plan to lay out the nuances and applications of simulation through a sequence of posts."
},
{
"code": null,
"e": 1157,
"s": 978,
"text": "In the real world, things happen randomly, and there is an infinite number of possibilities. We may only be able to observe only a fraction of, but not, the entire possibilities."
},
{
"code": null,
"e": 1354,
"s": 1157,
"text": "Simulation comes in handy and offers a quick overview of the distribution of the possibilities that match real-world outcomes. By studying simulated outcomes, we gain insights into the real world."
},
{
"code": null,
"e": 1433,
"s": 1354,
"text": "Let’s start with the easiest code and move up to more sophisticated scenarios."
},
{
"code": null,
"e": 1531,
"s": 1433,
"text": "The command runif(x, min=a, max=b) generates x number of values within the range between a and b."
},
{
"code": null,
"e": 1579,
"s": 1531,
"text": "library(dplyr)set.seed(2)runif(25,min=0,max=10)"
},
{
"code": null,
"e": 1775,
"s": 1579,
"text": "The set.seed() function sets a seed for R’s random number generator, so that we get the same values consistently each time we run the code. Otherwise, we will get different results. Try yourself."
},
{
"code": null,
"e": 1831,
"s": 1775,
"text": "To get integers, we use the round function, as follows:"
},
{
"code": null,
"e": 1880,
"s": 1831,
"text": "runif(25,min=0,max=10) %>% round(.,digits = 0)"
},
{
"code": null,
"e": 2044,
"s": 1880,
"text": "Here, the pipe, %>%, comes from magrittr package and allows you to write cleaner and easily understandable code. It can be translated into plain English as ‘then.’"
},
{
"code": null,
"e": 2090,
"s": 2044,
"text": "In English, the above two lines of code mean:"
},
{
"code": null,
"e": 2196,
"s": 2090,
"text": "generate 25 numbers within the range from 0 and 10then (%>%), round the number up to the nearest integer."
},
{
"code": null,
"e": 2247,
"s": 2196,
"text": "generate 25 numbers within the range from 0 and 10"
},
{
"code": null,
"e": 2303,
"s": 2247,
"text": "then (%>%), round the number up to the nearest integer."
},
{
"code": null,
"e": 2349,
"s": 2303,
"text": "Try what happens if you tweak the digits = 1."
},
{
"code": null,
"e": 2419,
"s": 2349,
"text": "Another way of generating a random number is via the sample function:"
},
{
"code": null,
"e": 2462,
"s": 2419,
"text": "> sample(x, size, replace=TRUE, prob=NULL)"
},
{
"code": null,
"e": 2497,
"s": 2462,
"text": "x: a vector, or a positive integer"
},
{
"code": null,
"e": 2563,
"s": 2497,
"text": "size: a non-negative integer giving the number of items to choose"
},
{
"code": null,
"e": 2605,
"s": 2563,
"text": "replace: sample with replacement, or not?"
},
{
"code": null,
"e": 2698,
"s": 2605,
"text": "prob: a vector of probability weights for obtaining the elements of the vector being sampled"
},
{
"code": null,
"e": 2759,
"s": 2698,
"text": "(Please refer to R documentation for more information, link)"
},
{
"code": null,
"e": 2776,
"s": 2759,
"text": "A quick example."
},
{
"code": null,
"e": 2808,
"s": 2776,
"text": "set.seed(24)sample(seq(1,10),8)"
},
{
"code": null,
"e": 2863,
"s": 2808,
"text": "The set.seed() function makes the result reproducible."
},
{
"code": null,
"e": 3025,
"s": 2863,
"text": "The above code generates a random sample of 8 numbers from the sequence [1,10]. As you can see, we do not set rules for replacement and probability of selection."
},
{
"code": null,
"e": 3110,
"s": 3025,
"text": "By default, R sets replacement to FALSE and adopts equal probabilities of selection."
},
{
"code": null,
"e": 3141,
"s": 3110,
"text": "x = 1:10sample(x,replace=TRUE)"
},
{
"code": null,
"e": 3273,
"s": 3141,
"text": "The process of resampling with replacement is called bootstrapping, a more advanced topic that will be covered in the next chapter."
},
{
"code": null,
"e": 3323,
"s": 3273,
"text": "Besides numbers, we can sample words, as follows:"
},
{
"code": null,
"e": 3353,
"s": 3323,
"text": "set.seed(1)sample(letters,18)"
},
{
"code": null,
"e": 3442,
"s": 3353,
"text": "We generate a random sample of size 10 from the sequence [1,5] with equal probabilities."
},
{
"code": null,
"e": 3523,
"s": 3442,
"text": "equal_prob_dist = sample(5,10000,prob=rep(0.1,5),replace=T)hist(equal_prob_dist)"
},
{
"code": null,
"e": 3628,
"s": 3523,
"text": "If we set prob=rep(0.1,5), then numbers 1 to 5 will be equally sampled, as shown in the histogram above."
},
{
"code": null,
"e": 3736,
"s": 3628,
"text": "What does the distribution look like if the probabilities of selection are not equal (e.g., a loaded dice)?"
},
{
"code": null,
"e": 3821,
"s": 3736,
"text": "We generate a random sample of size 10 from sequence[1,5] with unequal probabilities"
},
{
"code": null,
"e": 3922,
"s": 3821,
"text": "unequal_prob_dist = sample(5,10000,prob =c(0.1,0.25,0.4,0.25,0.1), replace=T)hist(unequal_prob_dist)"
},
{
"code": null,
"e": 3989,
"s": 3922,
"text": "We set the following selection probability rules for the sequence:"
},
{
"code": null,
"e": 4018,
"s": 3989,
"text": "1 & 5: 0.12 & 4: 0.25 3: 0.4"
},
{
"code": null,
"e": 4099,
"s": 4018,
"text": "As it turns out, number 3 is the most selected and 1 & 5 are the least selected."
},
{
"code": null,
"e": 4245,
"s": 4099,
"text": "These equal/unequal scenarios could be tremendously helpful if the question of interest needs differentiated treatments of selection probability."
},
{
"code": null,
"e": 4370,
"s": 4245,
"text": "To sample observations (rows) from a data frame or a list, we don’t sample the rows directly but the indices into an object."
},
{
"code": null,
"e": 4383,
"s": 4370,
"text": "head(mtcars)"
},
{
"code": null,
"e": 4644,
"s": 4383,
"text": "# step 1: create an index vector for the elements/rows index <- seq_len(nrow(mtcars)) # step 2: sample the index vectorset.seed(12)#to obtain a random sample of 10sample_index <- sample(index,10)# step 3: to show the sampled elements/rows mtcars[sample_index,]"
},
{
"code": null,
"e": 4725,
"s": 4644,
"text": "In this section, let’s get some practice and solve real-life business scenarios."
},
{
"code": null,
"e": 5052,
"s": 4725,
"text": "set.seed(1)die = 1:6# sample 10000 times with replacements for dice 1die1 = sample(die,10000,replace = TRUE,prob=NULL)# sample 10000 times with replacements for dice 2die2= sample(die,10000,replace=TRUE,prob = NULL)# the combined value of die_1 and die_2 outcomes = die1+die2# the probability of getting a 7mean(outcomes == 7)"
},
{
"code": null,
"e": 5107,
"s": 5052,
"text": "Similarly, we can use a for loop for the same purpose."
},
{
"code": null,
"e": 5269,
"s": 5107,
"text": "set.seed(1)for (i in 10000){ die_1 = sample(die,prob=NULL,replace=TRUE) die_2 = sample(die,prob=NULL,replace=TRUE) die_sum = die_1+die_2 print(mean(die_sum==7))}"
},
{
"code": null,
"e": 5309,
"s": 5269,
"text": "These two outcomes are almost the same."
},
{
"code": null,
"e": 5406,
"s": 5309,
"text": "Instead of simulating each outcome, there is an easier way of getting what we need using sapply."
},
{
"code": null,
"e": 5449,
"s": 5406,
"text": "sapply(2:13,function(x) mean(outcomes==x))"
},
{
"code": null,
"e": 5747,
"s": 5449,
"text": "According to R documentation, sapply() function is a “user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = \"array\", an array if appropriate, by applying simplify2array(). sapply(x, f, simplify = FALSE, USE.NAMES = FALSE) is the same as lapply(x, f).”"
},
{
"code": null,
"e": 5829,
"s": 5747,
"text": "Briefly, the function applies the function mean(outcomes) to the sequence [2,13]."
},
{
"code": null,
"e": 5907,
"s": 5829,
"text": "Question for you: what is the probability of rolling a 7 if you have 3 dices?"
},
{
"code": null,
"e": 6035,
"s": 5907,
"text": "set.seed(1)n=10000included_obs = length(unique(sample(1:n, replace = TRUE)))included_obsmissing_obs = n-included_obsmissing_obs"
},
{
"code": null,
"e": 6211,
"s": 6035,
"text": "After sampling, we use unique() to find the distinctive observations and length() to count. In a 10k sample, 6316 unique cases are sampled and 3684 (10k — 6316) cases are not."
},
{
"code": null,
"e": 6413,
"s": 6211,
"text": "As a further note, the reason why we only get 6316 out of 10k is that we sample with replacements, and so some numbers are sampled repetitively. In other words, some numbers are sampled multiple times."
},
{
"code": null,
"e": 6458,
"s": 6413,
"text": "(credits to discussions on R-bloggers, here)"
},
{
"code": null,
"e": 6562,
"s": 6458,
"text": "In the original post, the authors introduce multiple methods, and I focus on the first approaches here."
},
{
"code": null,
"e": 6592,
"s": 6562,
"text": "First, we can use a for loop."
},
{
"code": null,
"e": 6725,
"s": 6592,
"text": "m <- 10n <- 10# create an empty matrixm00 <- matrix(0,m,n)for (i in 1:m) { for (j in 1:n) { m00[i,j] <- sample(c(0,1),1) }}m00"
},
{
"code": null,
"e": 6832,
"s": 6725,
"text": "Here, matrix(0,m,n) creates an empty matrix by m*n, and the two for loops dictate the values of each cell."
},
{
"code": null,
"e": 6971,
"s": 6832,
"text": "Most of the time, a for loop in R may not be the most efficient solution, and we shall use other options if the sample size is big enough."
},
{
"code": null,
"e": 7055,
"s": 6971,
"text": "With that in mind, the authors contribute the second method using apply() function."
},
{
"code": null,
"e": 7131,
"s": 7055,
"text": "m <-10n<-10m0 <- matrix(0,m,n)apply(m0,c(1,2),function(x) sample(c(0,1),1))"
},
{
"code": null,
"e": 7341,
"s": 7131,
"text": "So far, everything should be quite familiar except the apply() function. It returns “a vector/array/list of values obtained by applying a function to margins of an array or matrix” (original definition, link)."
},
{
"code": null,
"e": 7368,
"s": 7341,
"text": "It has the following form:"
},
{
"code": null,
"e": 7397,
"s": 7368,
"text": "> apply(x, margin, fun,...) "
},
{
"code": null,
"e": 7420,
"s": 7397,
"text": "x: an array, or matrix"
},
{
"code": null,
"e": 7678,
"s": 7420,
"text": "margin: a vector giving the subscripts in which the function will be applied over. For a matrix, 1 indicates rows, and 2 indicates columns. c(1,2) indicates rows and columns, where x has named dimnames, it can be a character vector selecting dimension names"
},
{
"code": null,
"e": 7710,
"s": 7678,
"text": "fun: the function to be applied"
},
{
"code": null,
"e": 7947,
"s": 7710,
"text": "# create an empty list total_heads = c()# use a for loop to simulate coin-flipping 10 times # repeat it for 10,000 timesfor (i in 1:10000){ sum_heads = sum(round(runif(10,0,1))) total_heads = c(total_heads, sum_heads) }hist(total_heads)"
},
{
"code": null,
"e": 8028,
"s": 7947,
"text": "Here, I’ll explain three lines of code, and the rest is pretty self-explanatory."
},
{
"code": null,
"e": 8613,
"s": 8028,
"text": "for (1 in 1:1000). Unlike other programming languages, you have to specify the range as 1:10000.sum(round(runif(10,0,1))). This is a structured way of coding, which has three separate functionalities: runif() → round() → sum(). It runs the runif() function first and sum() last. Basically, the lines of code generate 10 random numbers between 0 and 1, round it up to the nearest integer (0 or 1), and lastly sum it up.total_heads = c(total_heads, sum_heads). Since total_heads is an empty list in the beginning, we use the line of code to assign the value of sum_heads to total_heads."
},
{
"code": null,
"e": 8710,
"s": 8613,
"text": "for (1 in 1:1000). Unlike other programming languages, you have to specify the range as 1:10000."
},
{
"code": null,
"e": 9033,
"s": 8710,
"text": "sum(round(runif(10,0,1))). This is a structured way of coding, which has three separate functionalities: runif() → round() → sum(). It runs the runif() function first and sum() last. Basically, the lines of code generate 10 random numbers between 0 and 1, round it up to the nearest integer (0 or 1), and lastly sum it up."
},
{
"code": null,
"e": 9200,
"s": 9033,
"text": "total_heads = c(total_heads, sum_heads). Since total_heads is an empty list in the beginning, we use the line of code to assign the value of sum_heads to total_heads."
},
{
"code": null,
"e": 9223,
"s": 9200,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 9332,
"s": 9223,
"text": "This is an intro post on statistical simulation, and we will explore more advanced topics in the next posts."
},
{
"code": null,
"e": 9344,
"s": 9332,
"text": "Stay tuned!"
},
{
"code": null,
"e": 9556,
"s": 9344,
"text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees."
},
{
"code": null,
"e": 9577,
"s": 9556,
"text": "leihua-ye.medium.com"
},
{
"code": null,
"e": 9617,
"s": 9577,
"text": "Please find me on LinkedIn and Youtube."
}
] |
Max Heap in Java
|
Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node.
Below is an implementation of Max Heap using library functions.
Live Demo
import java.util.*;
public class Demo{
public static void main(String args[]){
PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());
my_p_queue.add(43);
my_p_queue.add(56);
my_p_queue.add(99);
System.out.println("The elements in the priority queue are : ");
Iterator my_iter = my_p_queue.iterator();
while (my_iter.hasNext())
System.out.println(my_iter.next());
my_p_queue.poll();
System.out.println("After removing an element using the poll function, the queue elements are :");
Iterator<Integer> my_iter_2 = my_p_queue.iterator();
while (my_iter_2.hasNext())
System.out.println(my_iter_2.next());
Object[] my_arr = my_p_queue.toArray();
System.out.println("The array representation of max heap : ");
for (int i = 0; i < my_arr.length; i++)
System.out.println("Value: " + my_arr[i].toString());
}
}
The elements in the priority queue are :
99
43
56
After removing an element using the poll function, the queue elements are :
56
43
The array representation of max heap :
Value: 56
Value: 43
A class named Demo contains the main function. Inside the main function, an instance of priority queue is defined and elements are added into it using the ‘add’ function. An iterator is defined and it
is used to iterate over the elements in the priority queue. The ‘poll’ function is used to remove an element from the list. Next, the elements are iterated over and displayed on the screen.
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node."
},
{
"code": null,
"e": 1262,
"s": 1198,
"text": "Below is an implementation of Max Heap using library functions."
},
{
"code": null,
"e": 1273,
"s": 1262,
"text": " Live Demo"
},
{
"code": null,
"e": 2219,
"s": 1273,
"text": "import java.util.*;\npublic class Demo{\n public static void main(String args[]){\n PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());\n my_p_queue.add(43);\n my_p_queue.add(56);\n my_p_queue.add(99);\n System.out.println(\"The elements in the priority queue are : \");\n Iterator my_iter = my_p_queue.iterator();\n while (my_iter.hasNext())\n System.out.println(my_iter.next());\n my_p_queue.poll();\n System.out.println(\"After removing an element using the poll function, the queue elements are :\");\n Iterator<Integer> my_iter_2 = my_p_queue.iterator();\n while (my_iter_2.hasNext())\n System.out.println(my_iter_2.next());\n Object[] my_arr = my_p_queue.toArray();\n System.out.println(\"The array representation of max heap : \");\n for (int i = 0; i < my_arr.length; i++)\n System.out.println(\"Value: \" + my_arr[i].toString());\n }\n}"
},
{
"code": null,
"e": 2410,
"s": 2219,
"text": "The elements in the priority queue are :\n99\n43\n56\nAfter removing an element using the poll function, the queue elements are :\n56\n43\nThe array representation of max heap :\nValue: 56\nValue: 43"
},
{
"code": null,
"e": 2611,
"s": 2410,
"text": "A class named Demo contains the main function. Inside the main function, an instance of priority queue is defined and elements are added into it using the ‘add’ function. An iterator is defined and it"
},
{
"code": null,
"e": 2801,
"s": 2611,
"text": "is used to iterate over the elements in the priority queue. The ‘poll’ function is used to remove an element from the list. Next, the elements are iterated over and displayed on the screen."
}
] |
Predicting Airbnb prices with machine learning and deep learning | by Laura Lewis | Towards Data Science
|
Airbnb is a home-sharing platform that allows home-owners and renters (‘hosts’) to put their properties (‘listings’) online, so that guests can pay to stay in them. Hosts are expected to set their own prices for their listings. Although Airbnb and other sites provide some general guidance, there are currently no free and accurate services which help hosts price their properties using a wide range of data points.
Paid third party pricing software is available, but generally you are required to put in your own expected average nightly price (‘base price’), and the algorithm will vary the daily price around that base price on each day depending on day of the week, seasonality, how far away the date is, and other factors.
Airbnb pricing is important to get right, particularly in big cities like London where there is lots of competition and even small differences in prices can make a big difference. It is also a difficult thing to do correctly — price too high and no one will book. Price too low and you’ll be missing out on a lot of potential income.
This project aims to solve this problem, by using machine learning and deep learning to predict the base price for properties in London. I’ve explored the preparation and cleaning of Airbnb data and conducted some exploratory data analysis in previous posts. This post is all about the creation of models to predict Airbnb prices.
The dataset used for this project comes from Insideairbnb.com, an anti-Airbnb lobby group that scrapes Airbnb listings, reviews and calendar data from multiple cities around the world. The dataset was scraped on 9 April 2019 and contains information on all London Airbnb listings that were live on the site on that date (about 80,000).
The data is quite messy, and has some limitations. The major one is that it only includes the advertised price (sometimes called the ‘sticker’ price). The sticker price is the overall nightly price that is advertised to potential guests, rather than the actual average amount paid per night by previous guests. The advertised prices can be set to any amount by the host.
Nevertheless, this dataset can still be used as a proof of concept. A more accurate version could be built using data on the actual average nightly rates paid by guests, e.g. from sites like AirDNA that scrape and sell higher quality Airbnb data.
After cleaning and dropping collinear columns, the features in the model were:
The number of people the property accommodates
The number of bathrooms
Property type (e.g. apartment) and room type (e.g. entire home)
Location of the property (on the level of borough (discussed further in a previous post), or in one model on the level of latitude and longitude — discussed further below)
Security deposit, cleaning fee and extra person fee
Minimum and maximum nights stay
Number of days available to book in the next 90 days
Total number of reviews
Review ratings for each category (accuracy, cleanliness, check-in, communication, location, value and overall total)
Amount of time since the first and most recent reviews
The type of cancellation policy
Whether the property is instant bookable
The presence or absence of a wide range of amenities (discussed in further depth in a previous post, but including items like TVs, coffee machines, balconies, internet and parking, whether or not the property is child-friendly, allows self check-in or allows pets, and many others)
Host response times and rates
Whether or not a host is a superhost (a mark of quality, requiring various conditions to be met) or has their identity verified (e.g. by verifying government ID, a phone number and an email address)
How many listings the host is responsible for in total
How many days the host has been listing on Airbnb
In the interests of space I’ll skip the data preparation stage here, but all the code for this project can be found in my GitHub repo if you’re interested. To summarise, after cleaning the data, checking for multi-collinearity and removing collinear features, the data was standardised using sklearn’s StandardScaler() unless otherwise stated. Categorical features were one-hot encoded using pd.get_dummies(). A train-test split was performed with a test size of 0.2.
Although I was keen to experiment with deep learning models for price prediction, I first built a vanilla (non-tuned) XGBoost machine learning model (specifically xgb.XGBRegressor()). This was in order to provide a baseline level of accuracy, and also to allow for the measuring of feature importance (something which is notoriously difficult once you enter the realm of deep learning). XGBoost is likely to provide the best achievable accuracy using machine learning models (other than possible small accuracy increases from hyper-parameter tuning) due to its superior performance and general awesomeness as observed in Kaggle competitions.
Because this is a regression task, the evaluation metric chosen was mean squared error (MSE). I was also interested in accuracy, so I also had a look at the r squared value for each model produced.
Here’s my code to fit and evaluate the model:
Results:
Training MSE: 0.1576Validation MSE: 0.159Training r2: 0.7321Validation r2: 0.7274
Not bad for an un-tuned model. Now for the feature importances:
The top 10 most important features are:
How many people the property accommodates
The cleaning fee
How many other listings the host has (and whether they are a multi-listing host)
How many days are available to book out of the next 90
The fee per extra person
The number of reviews
The number of bathrooms
The security deposit
If the property is in Westminster
The minimum nights stay
It is not surprising that the most important feature is how many people the property accommodates, as that’s one of the main things you would use to search for properties in the first place. It is also not surprising that features related to location and reviews are in the top ten.
It is perhaps more surprising that the third most important feature is related to how many other listings the host manages on Airbnb, rather than the listing itself. However, this does not mean that a host that manages more properties will result in a listing gaining higher prices (although this is indeed the direction of the relationship). Firstly, the data appears to be somewhat skewed by a few very large property managers. Secondly, the relationship is with the advertised prices set, rather than actual prices achieved, suggesting that if anything more experienced hosts tend to set (rather than necessarily achieve) higher prices. And thirdly, we cannot necessarily imply a causative relationship — it could be that more experienced multi-listing hosts tend to take on more expensive properties (which is indeed the case for some, e.g. One Fine Stay).
It is also notable that three other fee types — cleaning, security and extra people — all make the top 10 feature list. It is likely that when a host sets a higher price for the nightly stay they are also likely to set other prices high, or vice versa.
Next up, I decided to experiment with neural networks (NN), to see if I could improve upon the XGBoost model’s score. I started off with a relatively shallow three layer NN with densely-connected layers, using a relu activation function for the hidden layers and a linear activation function for the output layer (as it is being used for a regression task). The loss function was mean squared error (again, because this is for regression).
Here’s my code:
And here’s the summary and visualisation:
In order to save time when evaluating multiple methods, I built a handy function to print the MSE and r squared results for the test and train sets, as well as produce a line graph of the loss in each epoch for the test and train sets and a scatterplot of predicted vs. actual values:
Here are the results:
Training MSE: 0.0331Validation MSE: 0.2163Training r2: 0.9438Validation r2: 0.6292
Compared to the XGBoost model the neural network has performed worse. Overfitting also seems to be an issue, as seen from the difference between the train and test MSE and r squared results, as well as the difference between the train and test losses in the line graph, and the fact that the values cluster more closely to the line in the scatterplots.
I then iterated through various other versions of the model in order to try and remove the overfitting and increase the accuracy. Overfitting was removed in each other version, although accuracy did vary. The adjustments that I experimented with were:
Adding a fourth and fifth layer — a fourth layer improved the accuracy but a fifth layer didn’t help.
Using L1 regularization — this proved to be the biggest boost to accuracy.
Using dropout regularization at 30% and 50% dropout rates — 50% turned out to be a terrible idea and significantly increased the MSE. 30% performed better, but not as well as L1 regularization.
Using a stochastic gradient descent (SGD) optimiser instead of Adam — this performed slightly worse.
Changing the batch size — this didn’t make much difference.
Training for more epochs — this helped a bit for some models, but most models minimised the loss function fairly quickly anyway.
Removing most of the review rating columns — high review ratings in one category were fairly highly correlated with other categories, so I tried removing all except the overall rating. I then used this new truncated dataset to train the previously highest performing model architecture (with L1 regularization and an Adam optimizer). This performed essentially the same, but with 18 fewer columns, so would be the preferred model when choosing which model to put into production as it would require less data and be less computationally expensive.
Using latitude and longitude instead of borough — again, this adjusted dataset was used with the best model architecture I had come up with so far. This performed slightly worse.
Using MinMaxScaler() instead of StandardScaler(). This also performed slightly worse.
In the end, the best NN was the four-layer model with L1 regularization and an Adam optimizer, with the extra review columns removed:
Results:
Training MSE: 0.1708Validation MSE: 0.1689Training r2: 0.7096Validation r2: 0.7105
However, even this model architecture did not perform quite as well as the XGBoost model. Overall, the XGBoost model is the preferred model, as it performs ever so slightly better than the best neural network and is less computationally expensive. It could possibly be improved even further with hyper-parameter tuning.
This is one of those situations where deep learning simply isn’t necessary for prediction, and a machine learning model performs just as well.
However, even in the best performing model, the model was only able to explain 73% of the variation in price. The remaining 27% is probably made up of features that were not present in the data. It is likely that a significant proportion of this unexplained variance is due to variations in the listing photos. The photos of properties on Airbnb are very important in encouraging guests to book, and so can also be expected to have a significant impact on price — better photos (primarily better quality properties and furnishings, but also better quality photography) equal higher prices.
Find a way to incorporate image quality into the model, e.g. by using the output of a convolutional neural network to assess image quality as an input into the pricing model.
Use better quality/more accurate data which includes the actual average prices paid per night.
Include a wider geographic area, e.g. the rest of the UK or other major cities around the world.
Augment the model with natural language processing (NLP) of listing descriptions and/or reviews, e.g. for sentiment analysis or looking for keywords.
In addition to predicting base prices, a sequence model could be created to calculate daily rates using data on seasonality and occupancy, which would allow the creation of actual pricing software.
Tailor the model more specifically to new listings in order to help hosts set prices for new properties, by removing features that would not be known at the time — e.g. other fees, availability and reviews.
I hope you found this post interesting and/or helpful. Thanks for reading!
|
[
{
"code": null,
"e": 588,
"s": 172,
"text": "Airbnb is a home-sharing platform that allows home-owners and renters (‘hosts’) to put their properties (‘listings’) online, so that guests can pay to stay in them. Hosts are expected to set their own prices for their listings. Although Airbnb and other sites provide some general guidance, there are currently no free and accurate services which help hosts price their properties using a wide range of data points."
},
{
"code": null,
"e": 900,
"s": 588,
"text": "Paid third party pricing software is available, but generally you are required to put in your own expected average nightly price (‘base price’), and the algorithm will vary the daily price around that base price on each day depending on day of the week, seasonality, how far away the date is, and other factors."
},
{
"code": null,
"e": 1234,
"s": 900,
"text": "Airbnb pricing is important to get right, particularly in big cities like London where there is lots of competition and even small differences in prices can make a big difference. It is also a difficult thing to do correctly — price too high and no one will book. Price too low and you’ll be missing out on a lot of potential income."
},
{
"code": null,
"e": 1565,
"s": 1234,
"text": "This project aims to solve this problem, by using machine learning and deep learning to predict the base price for properties in London. I’ve explored the preparation and cleaning of Airbnb data and conducted some exploratory data analysis in previous posts. This post is all about the creation of models to predict Airbnb prices."
},
{
"code": null,
"e": 1901,
"s": 1565,
"text": "The dataset used for this project comes from Insideairbnb.com, an anti-Airbnb lobby group that scrapes Airbnb listings, reviews and calendar data from multiple cities around the world. The dataset was scraped on 9 April 2019 and contains information on all London Airbnb listings that were live on the site on that date (about 80,000)."
},
{
"code": null,
"e": 2272,
"s": 1901,
"text": "The data is quite messy, and has some limitations. The major one is that it only includes the advertised price (sometimes called the ‘sticker’ price). The sticker price is the overall nightly price that is advertised to potential guests, rather than the actual average amount paid per night by previous guests. The advertised prices can be set to any amount by the host."
},
{
"code": null,
"e": 2519,
"s": 2272,
"text": "Nevertheless, this dataset can still be used as a proof of concept. A more accurate version could be built using data on the actual average nightly rates paid by guests, e.g. from sites like AirDNA that scrape and sell higher quality Airbnb data."
},
{
"code": null,
"e": 2598,
"s": 2519,
"text": "After cleaning and dropping collinear columns, the features in the model were:"
},
{
"code": null,
"e": 2645,
"s": 2598,
"text": "The number of people the property accommodates"
},
{
"code": null,
"e": 2669,
"s": 2645,
"text": "The number of bathrooms"
},
{
"code": null,
"e": 2733,
"s": 2669,
"text": "Property type (e.g. apartment) and room type (e.g. entire home)"
},
{
"code": null,
"e": 2905,
"s": 2733,
"text": "Location of the property (on the level of borough (discussed further in a previous post), or in one model on the level of latitude and longitude — discussed further below)"
},
{
"code": null,
"e": 2957,
"s": 2905,
"text": "Security deposit, cleaning fee and extra person fee"
},
{
"code": null,
"e": 2989,
"s": 2957,
"text": "Minimum and maximum nights stay"
},
{
"code": null,
"e": 3042,
"s": 2989,
"text": "Number of days available to book in the next 90 days"
},
{
"code": null,
"e": 3066,
"s": 3042,
"text": "Total number of reviews"
},
{
"code": null,
"e": 3183,
"s": 3066,
"text": "Review ratings for each category (accuracy, cleanliness, check-in, communication, location, value and overall total)"
},
{
"code": null,
"e": 3238,
"s": 3183,
"text": "Amount of time since the first and most recent reviews"
},
{
"code": null,
"e": 3270,
"s": 3238,
"text": "The type of cancellation policy"
},
{
"code": null,
"e": 3311,
"s": 3270,
"text": "Whether the property is instant bookable"
},
{
"code": null,
"e": 3593,
"s": 3311,
"text": "The presence or absence of a wide range of amenities (discussed in further depth in a previous post, but including items like TVs, coffee machines, balconies, internet and parking, whether or not the property is child-friendly, allows self check-in or allows pets, and many others)"
},
{
"code": null,
"e": 3623,
"s": 3593,
"text": "Host response times and rates"
},
{
"code": null,
"e": 3822,
"s": 3623,
"text": "Whether or not a host is a superhost (a mark of quality, requiring various conditions to be met) or has their identity verified (e.g. by verifying government ID, a phone number and an email address)"
},
{
"code": null,
"e": 3877,
"s": 3822,
"text": "How many listings the host is responsible for in total"
},
{
"code": null,
"e": 3927,
"s": 3877,
"text": "How many days the host has been listing on Airbnb"
},
{
"code": null,
"e": 4395,
"s": 3927,
"text": "In the interests of space I’ll skip the data preparation stage here, but all the code for this project can be found in my GitHub repo if you’re interested. To summarise, after cleaning the data, checking for multi-collinearity and removing collinear features, the data was standardised using sklearn’s StandardScaler() unless otherwise stated. Categorical features were one-hot encoded using pd.get_dummies(). A train-test split was performed with a test size of 0.2."
},
{
"code": null,
"e": 5037,
"s": 4395,
"text": "Although I was keen to experiment with deep learning models for price prediction, I first built a vanilla (non-tuned) XGBoost machine learning model (specifically xgb.XGBRegressor()). This was in order to provide a baseline level of accuracy, and also to allow for the measuring of feature importance (something which is notoriously difficult once you enter the realm of deep learning). XGBoost is likely to provide the best achievable accuracy using machine learning models (other than possible small accuracy increases from hyper-parameter tuning) due to its superior performance and general awesomeness as observed in Kaggle competitions."
},
{
"code": null,
"e": 5235,
"s": 5037,
"text": "Because this is a regression task, the evaluation metric chosen was mean squared error (MSE). I was also interested in accuracy, so I also had a look at the r squared value for each model produced."
},
{
"code": null,
"e": 5281,
"s": 5235,
"text": "Here’s my code to fit and evaluate the model:"
},
{
"code": null,
"e": 5290,
"s": 5281,
"text": "Results:"
},
{
"code": null,
"e": 5372,
"s": 5290,
"text": "Training MSE: 0.1576Validation MSE: 0.159Training r2: 0.7321Validation r2: 0.7274"
},
{
"code": null,
"e": 5436,
"s": 5372,
"text": "Not bad for an un-tuned model. Now for the feature importances:"
},
{
"code": null,
"e": 5476,
"s": 5436,
"text": "The top 10 most important features are:"
},
{
"code": null,
"e": 5518,
"s": 5476,
"text": "How many people the property accommodates"
},
{
"code": null,
"e": 5535,
"s": 5518,
"text": "The cleaning fee"
},
{
"code": null,
"e": 5616,
"s": 5535,
"text": "How many other listings the host has (and whether they are a multi-listing host)"
},
{
"code": null,
"e": 5671,
"s": 5616,
"text": "How many days are available to book out of the next 90"
},
{
"code": null,
"e": 5696,
"s": 5671,
"text": "The fee per extra person"
},
{
"code": null,
"e": 5718,
"s": 5696,
"text": "The number of reviews"
},
{
"code": null,
"e": 5742,
"s": 5718,
"text": "The number of bathrooms"
},
{
"code": null,
"e": 5763,
"s": 5742,
"text": "The security deposit"
},
{
"code": null,
"e": 5797,
"s": 5763,
"text": "If the property is in Westminster"
},
{
"code": null,
"e": 5821,
"s": 5797,
"text": "The minimum nights stay"
},
{
"code": null,
"e": 6104,
"s": 5821,
"text": "It is not surprising that the most important feature is how many people the property accommodates, as that’s one of the main things you would use to search for properties in the first place. It is also not surprising that features related to location and reviews are in the top ten."
},
{
"code": null,
"e": 6965,
"s": 6104,
"text": "It is perhaps more surprising that the third most important feature is related to how many other listings the host manages on Airbnb, rather than the listing itself. However, this does not mean that a host that manages more properties will result in a listing gaining higher prices (although this is indeed the direction of the relationship). Firstly, the data appears to be somewhat skewed by a few very large property managers. Secondly, the relationship is with the advertised prices set, rather than actual prices achieved, suggesting that if anything more experienced hosts tend to set (rather than necessarily achieve) higher prices. And thirdly, we cannot necessarily imply a causative relationship — it could be that more experienced multi-listing hosts tend to take on more expensive properties (which is indeed the case for some, e.g. One Fine Stay)."
},
{
"code": null,
"e": 7218,
"s": 6965,
"text": "It is also notable that three other fee types — cleaning, security and extra people — all make the top 10 feature list. It is likely that when a host sets a higher price for the nightly stay they are also likely to set other prices high, or vice versa."
},
{
"code": null,
"e": 7658,
"s": 7218,
"text": "Next up, I decided to experiment with neural networks (NN), to see if I could improve upon the XGBoost model’s score. I started off with a relatively shallow three layer NN with densely-connected layers, using a relu activation function for the hidden layers and a linear activation function for the output layer (as it is being used for a regression task). The loss function was mean squared error (again, because this is for regression)."
},
{
"code": null,
"e": 7674,
"s": 7658,
"text": "Here’s my code:"
},
{
"code": null,
"e": 7716,
"s": 7674,
"text": "And here’s the summary and visualisation:"
},
{
"code": null,
"e": 8001,
"s": 7716,
"text": "In order to save time when evaluating multiple methods, I built a handy function to print the MSE and r squared results for the test and train sets, as well as produce a line graph of the loss in each epoch for the test and train sets and a scatterplot of predicted vs. actual values:"
},
{
"code": null,
"e": 8023,
"s": 8001,
"text": "Here are the results:"
},
{
"code": null,
"e": 8106,
"s": 8023,
"text": "Training MSE: 0.0331Validation MSE: 0.2163Training r2: 0.9438Validation r2: 0.6292"
},
{
"code": null,
"e": 8459,
"s": 8106,
"text": "Compared to the XGBoost model the neural network has performed worse. Overfitting also seems to be an issue, as seen from the difference between the train and test MSE and r squared results, as well as the difference between the train and test losses in the line graph, and the fact that the values cluster more closely to the line in the scatterplots."
},
{
"code": null,
"e": 8711,
"s": 8459,
"text": "I then iterated through various other versions of the model in order to try and remove the overfitting and increase the accuracy. Overfitting was removed in each other version, although accuracy did vary. The adjustments that I experimented with were:"
},
{
"code": null,
"e": 8813,
"s": 8711,
"text": "Adding a fourth and fifth layer — a fourth layer improved the accuracy but a fifth layer didn’t help."
},
{
"code": null,
"e": 8888,
"s": 8813,
"text": "Using L1 regularization — this proved to be the biggest boost to accuracy."
},
{
"code": null,
"e": 9082,
"s": 8888,
"text": "Using dropout regularization at 30% and 50% dropout rates — 50% turned out to be a terrible idea and significantly increased the MSE. 30% performed better, but not as well as L1 regularization."
},
{
"code": null,
"e": 9183,
"s": 9082,
"text": "Using a stochastic gradient descent (SGD) optimiser instead of Adam — this performed slightly worse."
},
{
"code": null,
"e": 9243,
"s": 9183,
"text": "Changing the batch size — this didn’t make much difference."
},
{
"code": null,
"e": 9372,
"s": 9243,
"text": "Training for more epochs — this helped a bit for some models, but most models minimised the loss function fairly quickly anyway."
},
{
"code": null,
"e": 9920,
"s": 9372,
"text": "Removing most of the review rating columns — high review ratings in one category were fairly highly correlated with other categories, so I tried removing all except the overall rating. I then used this new truncated dataset to train the previously highest performing model architecture (with L1 regularization and an Adam optimizer). This performed essentially the same, but with 18 fewer columns, so would be the preferred model when choosing which model to put into production as it would require less data and be less computationally expensive."
},
{
"code": null,
"e": 10099,
"s": 9920,
"text": "Using latitude and longitude instead of borough — again, this adjusted dataset was used with the best model architecture I had come up with so far. This performed slightly worse."
},
{
"code": null,
"e": 10185,
"s": 10099,
"text": "Using MinMaxScaler() instead of StandardScaler(). This also performed slightly worse."
},
{
"code": null,
"e": 10319,
"s": 10185,
"text": "In the end, the best NN was the four-layer model with L1 regularization and an Adam optimizer, with the extra review columns removed:"
},
{
"code": null,
"e": 10328,
"s": 10319,
"text": "Results:"
},
{
"code": null,
"e": 10411,
"s": 10328,
"text": "Training MSE: 0.1708Validation MSE: 0.1689Training r2: 0.7096Validation r2: 0.7105"
},
{
"code": null,
"e": 10731,
"s": 10411,
"text": "However, even this model architecture did not perform quite as well as the XGBoost model. Overall, the XGBoost model is the preferred model, as it performs ever so slightly better than the best neural network and is less computationally expensive. It could possibly be improved even further with hyper-parameter tuning."
},
{
"code": null,
"e": 10874,
"s": 10731,
"text": "This is one of those situations where deep learning simply isn’t necessary for prediction, and a machine learning model performs just as well."
},
{
"code": null,
"e": 11464,
"s": 10874,
"text": "However, even in the best performing model, the model was only able to explain 73% of the variation in price. The remaining 27% is probably made up of features that were not present in the data. It is likely that a significant proportion of this unexplained variance is due to variations in the listing photos. The photos of properties on Airbnb are very important in encouraging guests to book, and so can also be expected to have a significant impact on price — better photos (primarily better quality properties and furnishings, but also better quality photography) equal higher prices."
},
{
"code": null,
"e": 11639,
"s": 11464,
"text": "Find a way to incorporate image quality into the model, e.g. by using the output of a convolutional neural network to assess image quality as an input into the pricing model."
},
{
"code": null,
"e": 11734,
"s": 11639,
"text": "Use better quality/more accurate data which includes the actual average prices paid per night."
},
{
"code": null,
"e": 11831,
"s": 11734,
"text": "Include a wider geographic area, e.g. the rest of the UK or other major cities around the world."
},
{
"code": null,
"e": 11981,
"s": 11831,
"text": "Augment the model with natural language processing (NLP) of listing descriptions and/or reviews, e.g. for sentiment analysis or looking for keywords."
},
{
"code": null,
"e": 12179,
"s": 11981,
"text": "In addition to predicting base prices, a sequence model could be created to calculate daily rates using data on seasonality and occupancy, which would allow the creation of actual pricing software."
},
{
"code": null,
"e": 12386,
"s": 12179,
"text": "Tailor the model more specifically to new listings in order to help hosts set prices for new properties, by removing features that would not be known at the time — e.g. other fees, availability and reviews."
}
] |
Identify last document from MongoDB find() result set?
|
To identify the last document from MongoDB find() result set, you can use sort() in descending order. The syntax is as follows −
db.yourCollectionName.find().sort( { _id : -1 } ).limit(1).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.identifyLastDocuementDemo.insertOne({"UserName":"Larry","UserAge":24,"UserCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a2ff4cf1f7a64fa4df57")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a3094cf1f7a64fa4df58")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"David","UserAge":25,"UserCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a3174cf1f7a64fa4df59")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Sam","UserAge":26,"UserCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a3224cf1f7a64fa4df5a")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Mike","UserAge":27,"UserCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a32e4cf1f7a64fa4df5b")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Carol","UserAge":28,"UserCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c94a33c4cf1f7a64fa4df5c")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.identifyLastDocuementDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c94a2ff4cf1f7a64fa4df57"),
"UserName" : "Larry",
"UserAge" : 24,
"UserCountryName" : "US"
}
{
"_id" : ObjectId("5c94a3094cf1f7a64fa4df58"),
"UserName" : "Chris",
"UserAge" : 21,
"UserCountryName" : "UK"
}
{
"_id" : ObjectId("5c94a3174cf1f7a64fa4df59"),
"UserName" : "David",
"UserAge" : 25,
"UserCountryName" : "AUS"
}
{
"_id" : ObjectId("5c94a3224cf1f7a64fa4df5a"),
"UserName" : "Sam",
"UserAge" : 26,
"UserCountryName" : "US"
}
{
"_id" : ObjectId("5c94a32e4cf1f7a64fa4df5b"),
"UserName" : "Mike",
"UserAge" : 27,
"UserCountryName" : "AUS"
}
{
"_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
"UserName" : "Carol",
"UserAge" : 28,
"UserCountryName" : "UK"
}
Here is the query to identify the last document from MongoDB find() result set −
> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();
The following is the output −
{
"_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
"UserName" : "Carol",
"UserAge" : 28,
"UserCountryName" : "UK"
}
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "To identify the last document from MongoDB find() result set, you can use sort() in descending order. The syntax is as follows −"
},
{
"code": null,
"e": 1260,
"s": 1191,
"text": "db.yourCollectionName.find().sort( { _id : -1 } ).limit(1).pretty();"
},
{
"code": null,
"e": 1403,
"s": 1260,
"text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 2512,
"s": 1403,
"text": "> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"Larry\",\"UserAge\":24,\"UserCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a2ff4cf1f7a64fa4df57\")\n}\n> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"Chris\",\"UserAge\":21,\"UserCountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a3094cf1f7a64fa4df58\")\n}\n> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"David\",\"UserAge\":25,\"UserCountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a3174cf1f7a64fa4df59\")\n}\n> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"Sam\",\"UserAge\":26,\"UserCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a3224cf1f7a64fa4df5a\")\n}\n> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"Mike\",\"UserAge\":27,\"UserCountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a32e4cf1f7a64fa4df5b\")\n}\n> db.identifyLastDocuementDemo.insertOne({\"UserName\":\"Carol\",\"UserAge\":28,\"UserCountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c94a33c4cf1f7a64fa4df5c\")\n}"
},
{
"code": null,
"e": 2610,
"s": 2512,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2658,
"s": 2610,
"text": "> db.identifyLastDocuementDemo.find().pretty();"
},
{
"code": null,
"e": 2688,
"s": 2658,
"text": "The following is the output −"
},
{
"code": null,
"e": 3437,
"s": 2688,
"text": "{\n \"_id\" : ObjectId(\"5c94a2ff4cf1f7a64fa4df57\"),\n \"UserName\" : \"Larry\",\n \"UserAge\" : 24,\n \"UserCountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5c94a3094cf1f7a64fa4df58\"),\n \"UserName\" : \"Chris\",\n \"UserAge\" : 21,\n \"UserCountryName\" : \"UK\"\n}\n{\n \"_id\" : ObjectId(\"5c94a3174cf1f7a64fa4df59\"),\n \"UserName\" : \"David\",\n \"UserAge\" : 25,\n \"UserCountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5c94a3224cf1f7a64fa4df5a\"),\n \"UserName\" : \"Sam\",\n \"UserAge\" : 26,\n \"UserCountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5c94a32e4cf1f7a64fa4df5b\"),\n \"UserName\" : \"Mike\",\n \"UserAge\" : 27,\n \"UserCountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5c94a33c4cf1f7a64fa4df5c\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 28,\n \"UserCountryName\" : \"UK\"\n}"
},
{
"code": null,
"e": 3518,
"s": 3437,
"text": "Here is the query to identify the last document from MongoDB find() result set −"
},
{
"code": null,
"e": 3596,
"s": 3518,
"text": "> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();"
},
{
"code": null,
"e": 3626,
"s": 3596,
"text": "The following is the output −"
},
{
"code": null,
"e": 3751,
"s": 3626,
"text": "{\n \"_id\" : ObjectId(\"5c94a33c4cf1f7a64fa4df5c\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 28,\n \"UserCountryName\" : \"UK\"\n}"
}
] |
Is it impossible to add a column in MySQL specifically before another column?
|
No, you can easily add a column before another column using ALTER.
Note − To add a column at a specific position within a table row, use FIRST or AFTER col_name Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int,
-> Name varchar(20),
-> CountryName varchar(100)
-> );
Query OK, 0 rows affected (0.67 sec)
Let us check all the column names from the table −
mysql> show columns from DemoTable;
This will produce the following output −
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
| Name | varchar(20) | YES | | NULL | |
| CountryName | varchar(100) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Following is the query to add a column before another column in MySQL.
mysql> alter table DemoTable add Age int AFTER Name;
Query OK, 0 rows affected (1.50 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check all the column names from the above table once again −
mysql> show columns from DemoTable;
This will produce the following output. We have successfully added a column name −
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
| Name | varchar(20) | YES | | NULL | |
| Age | int(11) | YES | | NULL | |
| CountryName | varchar(100) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "No, you can easily add a column before another column using ALTER."
},
{
"code": null,
"e": 1253,
"s": 1129,
"text": "Note − To add a column at a specific position within a table row, use FIRST or AFTER col_name Let us first create a table −"
},
{
"code": null,
"e": 1406,
"s": 1253,
"text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20),\n -> CountryName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1457,
"s": 1406,
"text": "Let us check all the column names from the table −"
},
{
"code": null,
"e": 1493,
"s": 1457,
"text": "mysql> show columns from DemoTable;"
},
{
"code": null,
"e": 1534,
"s": 1493,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1993,
"s": 1534,
"text": "+-------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| Name | varchar(20) | YES | | NULL | |\n| CountryName | varchar(100) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2064,
"s": 1993,
"text": "Following is the query to add a column before another column in MySQL."
},
{
"code": null,
"e": 2191,
"s": 2064,
"text": "mysql> alter table DemoTable add Age int AFTER Name;\nQuery OK, 0 rows affected (1.50 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2259,
"s": 2191,
"text": "Let us check all the column names from the above table once again −"
},
{
"code": null,
"e": 2295,
"s": 2259,
"text": "mysql> show columns from DemoTable;"
},
{
"code": null,
"e": 2378,
"s": 2295,
"text": "This will produce the following output. We have successfully added a column name −"
},
{
"code": null,
"e": 2899,
"s": 2378,
"text": "+-------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| Name | varchar(20) | YES | | NULL | |\n| Age | int(11) | YES | | NULL | |\n| CountryName | varchar(100) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+-------+\n4 rows in set (0.00 sec)"
}
] |
xgbse: Improving XGBoost for Survival Analysis | by Guilherme Marmerola | Towards Data Science
|
“There are two cultures in the use of statistical modeling to reach conclusions from data. One assumes that the data are generated by a given stochastic data model. The other uses algorithmic models and treats the data mechanism as unknown.” — Leo Breiman, Statistical Modeling: The Two Cultures
Survival Analysis is a branch of statistics concerned with modeling the duration of events, most importantly providing tools to deal with (and not simply discard) censored data, partial but useful information about durations. For instance, if an apartment is on the market for 90 days, we don't know how long it will take to actually sell it, but we do know that it took at least 90 days (where 90 days is the time of censoring). Survival analysis is useful for a wide range of applications, such as predictive maintenance, customer churn, credit risk, asset liquidity risk, and many others.
The most common output of survival analysis models is a survival curve, which shows the cumulative probability of survival (event not happening) over time. Other models may output risk, which is a number proportional to how fast the curve decays, or an expected time, obtained by direct optimization or by numerically integrating the curve.
At Loft, we're a big user of survival analysis models, as the journey of finding a new home is rather long in Brazil, with several milestones along the way (visits, offers, deeds, renovation, etc). Particularly, as Loft operates an iBuyer (using its own equity to buy, renovate, and sell apartments), we're interested in modeling the time to sell an apartment, as holding it for too long represents the biggest risk we are subject to. The models that produce these estimates are used to make million-dollar decisions and thus have strict requirements on discrimination performance and calibration.
Therefore, we invested a lot of time exploring survival analysis packages. In our quest we found that most implementations embraced one of two cultures:
Models with sound statistical properties (such as calibrated survival curves), but lacking in expressiveness and computational efficiencyHighly efficient and expressive models, but lacking some statistical properties (producing only risk or uncalibrated expected survival times — XGBoost fits here)
Models with sound statistical properties (such as calibrated survival curves), but lacking in expressiveness and computational efficiency
Highly efficient and expressive models, but lacking some statistical properties (producing only risk or uncalibrated expected survival times — XGBoost fits here)
Given this scenario, we embarked on a journey to unite the two cultures in a single package that would meet our requirements: XGBoost Survival Embeddings (xgbse). And now we’re open sourcing it!
We chose XGBoost as our "base model" for its efficient and easy-to-use implementation, and leveraged some tricks to add nice statistical properties to it. We provide more details about XGBoost's shortcomings and these tricks next.
The XGBoost implementation provides two methods for survival analysis: Cox and Accelerated Failure Time (AFT). When it comes to ordering individuals by risk (discrimination), both show competitive performance (as measured by C-index, the ROC AUC equivalent for survival) while being lightning fast.
However, we can observe shortcomings when it comes to other desirable statistical properties. Specifically, three properties are of concern:
prediction of survival curves rather than point estimates
estimation of confidence intervals
calibrated (unbiased) expected survival times
Let us take the AFT implementation as an example (as Cox only outputs risk and not time or survival). The AFT model outputs a value that should be interpreted as the expected survival time for each sample. To compute this time, it assumes an underlying distribution for times and events, controlled by the aft_loss_distribution and aft_loss_distribution_scale hyperparameters. As they control hard-wired assumptions of the model, we would expect that they could drastically change its output.
To confirm this is true, let us perform an experiment using the METABRIC dataset. We will test different values for aft_loss_distribution_scale while keeping aft_loss_distribution as "normal" and check how this will affect model performance. We test the following values: [0.5, 1.0, 1.5]. The following gist gives a rough idea on how to run this simple experiment but you can find the full code here. The results are very interesting, if not alarming:
aft_loss_distribution_scale: 1.5C-index: 0.645Average predicted survival time: 203 days----aft_loss_distribution_scale: 1.0C-index: 0.648Average predicted survival time: 165 days----aft_loss_distribution_scale: 0.5C-index: 0.646Average predicted survival time: 125 days----
In all three scenarios, we can build models with C-index results close to the state of the art [8]. However, our predictions change drastically, with two models showing an average predicted survival time difference of 78 days. This difference would perhaps be understandable if we were analyzing a single sample. But we're looking across the full validation dataset where the average prediction should be fairly stable regardless of which model we use.
If we plot these results alongside an unbiased survival estimator such as the Kaplan Meier we can check that for each step of 0.5 in aft_loss_distribution_scale we move roughly one decile to the right in the curve. Also, we don't see a full survival curve: XGBoost only outputs point time-to-event predictions (no confidence intervals either).
Given these results, we raise the question: "what model should we trust?". Although we could try to optimize for some error measure such as L1-loss [9], we would like more guarantees for applications that are dependent on stable and calibrated time-to-event estimates. Having only point estimates, no confidence intervals, and no "calibration by design" mines trust and prevents shipping survival analysis models to production.
Although in need of an extension for better statistical properties, XGBoost is undoubtedly a powerhouse. C-index results show that the model has great discrimination performance, being competitive with the state of the art. We just need to adapt how we use it.
Besides being leveraged for prediction tasks, Gradient Boosted Trees (GBTs) can also be used as feature transformers of the input data. Trees in the ensemble perform splits on features that discriminate the target, encoding relevant information in their structure. In particular, the terminal nodes (leaves) at each tree in the ensemble define a very nice feature transformation (embedding) of the input data.
This kind of tree ensemble embedding has very convenient properties:
sparsity and high-dimensionality: trees deal with nonlinearity and cast original features to a sparse, high-dimensional embedding, which helps linear models perform well when trained on it. For instance, a logistic regression trained on the embedding (with features as one-hot encoded leaf indices) can show comparable performance to the actual ensemble, with the added benefit of probability calibration (see [1], [2], and [3])supervision: trees also work as a noise filter, performing splits only through features that have predictive power. Thus, the embedding actually has a lower intrinsic dimension than the input data (see [4]). This mitigates the curse of dimensionality and allows a kNN model trained on the embedding (using hamming distance) to have comparable performance to the actual ensemble. With neighbor-sets at hand, we can use robust estimators such as the Kaplan-Meier to get predictions.
sparsity and high-dimensionality: trees deal with nonlinearity and cast original features to a sparse, high-dimensional embedding, which helps linear models perform well when trained on it. For instance, a logistic regression trained on the embedding (with features as one-hot encoded leaf indices) can show comparable performance to the actual ensemble, with the added benefit of probability calibration (see [1], [2], and [3])
supervision: trees also work as a noise filter, performing splits only through features that have predictive power. Thus, the embedding actually has a lower intrinsic dimension than the input data (see [4]). This mitigates the curse of dimensionality and allows a kNN model trained on the embedding (using hamming distance) to have comparable performance to the actual ensemble. With neighbor-sets at hand, we can use robust estimators such as the Kaplan-Meier to get predictions.
These two properties are the foundation upon which we built xgbse. We show how we put them to good use next.
Our first approach, XGBSEDebiasedBCE, takes inspiration from the multi-task logistic regression method in [5], the BCE (binary cross-entropy) approach in [6], and the probability calibration ideas from [1], [2] and [3].
It consists of training a set of logistic regressions on top of the embedding produced by the underlying XGBoost model, each predicting survival at different user-defined discrete time windows. The classifiers remove individuals as they are censored, with targets that are indicators of surviving at each window.
As the embedding is sparse and high dimensional, the linear models actually can improve the ensemble performance, while also adding nice statistical properties to it, such as probability calibration (as logistic regressions are calibrated by design).
The naive approach tends to give biased survival curves, due to the removal of censored individuals. Thus, we made some adaptations such that logistic regressions estimate the di/ni term (point probabilities) in the Kaplan-Meier formula and then use the KM estimator to get nearly unbiased survival curves.
This way, we can get full survival curves from XGBoost, and confidence intervals with minor adaptations (such as performing some rounds of bootstrap). Training and scoring of logistic regression models is efficient, being performed in parallel through joblib, so the model can scale to hundreds of thousands or millions of samples.
As explained in the previous section, even though the embedding produced by XGBoost is sparse and high dimensional, its intrinsic dimensionality actually should be lower than the input data. This enables us to "convert" XGBoost into a nearest neighbor model, where we use hamming distance to define similar elements as the ones that co-occurred the most at the ensemble terminal nodes. Then, at each neighbor-set we can get survival estimates with robust methods such as the Kaplan-Meier estimator.
We recommend using dart as the booster to prevent any tree to dominate variance in the ensemble and break the leaf co-occurrence similarity logic. We built a high-performing implementation of the KM estimator to calculate several survival curves in a vectorized fashion, including upper and lower confidence intervals based on the Exponential Greenwood formula [7].
However, this method can be very expensive at scales of hundreds of thousands of samples, due to the nearest neighbor search, both on training (construction of search index) and scoring (actual search).
As a simplification to XGBSEKaplanNeighbors, we also provide a single tree implementation. Instead of doing expensive nearest neighbor searches, we fit a single tree via XGBoost and calculate KM curves at each of its leaves.
It is by far the most efficient implementation, able to scale to millions of examples easily. At fit time, the tree is built and all KM curves are pre-calculated, so that at scoring time a simple query will suffice to get the model’s estimates.
However, as we’re fitting a single tree, predictive power may be worse. That could be a sensible tradeoff, but we also provide XGBSEBootstrapEstimator, a bootstrap abstraction where we can fit a forest of XGBSEKaplanTree's to improve accuracy and reduce variance.
Now we return to the first example and check how XGBEmbedKaplanNeighbors performs:
aft_loss_distribution_scale: 1.5C-index: 0.640Average probability of survival at [30, 90, 150] days: [0.9109, 0.6854, 0.528]----aft_loss_distribution_scale: 1.0C-index: 0.644Average probability of survival at [30, 90, 150] days: [0.9111, 0.6889, 0.5333]----aft_loss_distribution_scale: 0.5C-index: 0.650Average probability of survival at [30, 90, 150] days: [0.913, 0.6904, 0.5289]----
As measured by the average probability of survival in 30, 90 and 150 days the model shows good results, with comparable C-index results and predictions being very close and independent of aft_loss_distribution_scale choice. Visually, the comparison of the average model predictions to a Kaplan Meier yields much better results:
Much less bias, full survival curves and stability! Although is too harsh to claim that the problem is solved, we believe that the we could build a strong survival analysis package and bring the "two cultures" much closer together.
XGBoost Survival Embeddings shows great results in several survival analysis benchmarks, outperforming vanilla XGBoost and parametric methods in most cases. It is pip installable and scikit-learn compatible. There are more features to try, such as confidence intervals, extrapolation of survival curves, explainability through prototypes, metrics, and more. We’re committed to improving the lib and adding new content in the future.
For more details, please check the the library on github, the docs, and examples! We invite the community to contribute. Please help by trying it out, reporting bugs, and letting us know what you think!
By Davi Vieira, Guilherme Marmerola, Gabriel Gimenez and Vitor Estima.
[1] X. He, J. Pan, O. Jin, T. Xu, B. Liu, T. Xu, Y. Shi, A. Atallah, R. Herbrich, S. Bowers, and J. Q. Candela. Practical Lessons from Predicting Clicks on Ads at Facebook (2014). In Proceedings of the Eighth International Workshop on Data Mining for Online Advertising (ADKDD’14).
[2] Feature transformations with ensembles of trees. Scikit-learn documentation at https://scikit-learn.org/.
[3] G. Marmerola. Calibration of probabilities for tree-based models. Personal Blog at https://gdmarmerola.github.io/.
[4] G. Marmerola. Supervised dimensionality reduction and clustering at scale with RFs with UMAP. Personal Blog at https://gdmarmerola.github.io/.
[5] C. Yu, R. Greiner, H. Lin, V. Baracos. Learning Patient-Specific Cancer Survival Distributions as a Sequence of Dependent Regressors. Advances in Neural Information Processing Systems 24 (NIPS 2011).
[6] H. Kvamme, Ø. Borgan. The Brier Score under Administrative Censoring: Problems and Solutions. arXiv preprint arXiv:1912.08581.
[7] S. Sawyer. The Greenwood and Exponential Greenwood Confidence Intervals in Survival Analysis. Handout on Washington University in St. Louis website.
[8] H. Kvamme, Ø. Borgan, and I. Scheel. Time-to-event prediction with neural networks and Cox regression. Journal of Machine Learning Research, 20(129):1–30, 2019.
[9] H. Haider, B. Hoehn, S. Davis, R. Greiner. Effective Ways to Build and Evaluate Individual Survival Distributions. Journal of Machine Learning Research 21 (2020) 1–63.
|
[
{
"code": null,
"e": 468,
"s": 172,
"text": "“There are two cultures in the use of statistical modeling to reach conclusions from data. One assumes that the data are generated by a given stochastic data model. The other uses algorithmic models and treats the data mechanism as unknown.” — Leo Breiman, Statistical Modeling: The Two Cultures"
},
{
"code": null,
"e": 1060,
"s": 468,
"text": "Survival Analysis is a branch of statistics concerned with modeling the duration of events, most importantly providing tools to deal with (and not simply discard) censored data, partial but useful information about durations. For instance, if an apartment is on the market for 90 days, we don't know how long it will take to actually sell it, but we do know that it took at least 90 days (where 90 days is the time of censoring). Survival analysis is useful for a wide range of applications, such as predictive maintenance, customer churn, credit risk, asset liquidity risk, and many others."
},
{
"code": null,
"e": 1401,
"s": 1060,
"text": "The most common output of survival analysis models is a survival curve, which shows the cumulative probability of survival (event not happening) over time. Other models may output risk, which is a number proportional to how fast the curve decays, or an expected time, obtained by direct optimization or by numerically integrating the curve."
},
{
"code": null,
"e": 1999,
"s": 1401,
"text": "At Loft, we're a big user of survival analysis models, as the journey of finding a new home is rather long in Brazil, with several milestones along the way (visits, offers, deeds, renovation, etc). Particularly, as Loft operates an iBuyer (using its own equity to buy, renovate, and sell apartments), we're interested in modeling the time to sell an apartment, as holding it for too long represents the biggest risk we are subject to. The models that produce these estimates are used to make million-dollar decisions and thus have strict requirements on discrimination performance and calibration."
},
{
"code": null,
"e": 2152,
"s": 1999,
"text": "Therefore, we invested a lot of time exploring survival analysis packages. In our quest we found that most implementations embraced one of two cultures:"
},
{
"code": null,
"e": 2451,
"s": 2152,
"text": "Models with sound statistical properties (such as calibrated survival curves), but lacking in expressiveness and computational efficiencyHighly efficient and expressive models, but lacking some statistical properties (producing only risk or uncalibrated expected survival times — XGBoost fits here)"
},
{
"code": null,
"e": 2589,
"s": 2451,
"text": "Models with sound statistical properties (such as calibrated survival curves), but lacking in expressiveness and computational efficiency"
},
{
"code": null,
"e": 2751,
"s": 2589,
"text": "Highly efficient and expressive models, but lacking some statistical properties (producing only risk or uncalibrated expected survival times — XGBoost fits here)"
},
{
"code": null,
"e": 2946,
"s": 2751,
"text": "Given this scenario, we embarked on a journey to unite the two cultures in a single package that would meet our requirements: XGBoost Survival Embeddings (xgbse). And now we’re open sourcing it!"
},
{
"code": null,
"e": 3177,
"s": 2946,
"text": "We chose XGBoost as our \"base model\" for its efficient and easy-to-use implementation, and leveraged some tricks to add nice statistical properties to it. We provide more details about XGBoost's shortcomings and these tricks next."
},
{
"code": null,
"e": 3476,
"s": 3177,
"text": "The XGBoost implementation provides two methods for survival analysis: Cox and Accelerated Failure Time (AFT). When it comes to ordering individuals by risk (discrimination), both show competitive performance (as measured by C-index, the ROC AUC equivalent for survival) while being lightning fast."
},
{
"code": null,
"e": 3617,
"s": 3476,
"text": "However, we can observe shortcomings when it comes to other desirable statistical properties. Specifically, three properties are of concern:"
},
{
"code": null,
"e": 3675,
"s": 3617,
"text": "prediction of survival curves rather than point estimates"
},
{
"code": null,
"e": 3710,
"s": 3675,
"text": "estimation of confidence intervals"
},
{
"code": null,
"e": 3756,
"s": 3710,
"text": "calibrated (unbiased) expected survival times"
},
{
"code": null,
"e": 4249,
"s": 3756,
"text": "Let us take the AFT implementation as an example (as Cox only outputs risk and not time or survival). The AFT model outputs a value that should be interpreted as the expected survival time for each sample. To compute this time, it assumes an underlying distribution for times and events, controlled by the aft_loss_distribution and aft_loss_distribution_scale hyperparameters. As they control hard-wired assumptions of the model, we would expect that they could drastically change its output."
},
{
"code": null,
"e": 4701,
"s": 4249,
"text": "To confirm this is true, let us perform an experiment using the METABRIC dataset. We will test different values for aft_loss_distribution_scale while keeping aft_loss_distribution as \"normal\" and check how this will affect model performance. We test the following values: [0.5, 1.0, 1.5]. The following gist gives a rough idea on how to run this simple experiment but you can find the full code here. The results are very interesting, if not alarming:"
},
{
"code": null,
"e": 4975,
"s": 4701,
"text": "aft_loss_distribution_scale: 1.5C-index: 0.645Average predicted survival time: 203 days----aft_loss_distribution_scale: 1.0C-index: 0.648Average predicted survival time: 165 days----aft_loss_distribution_scale: 0.5C-index: 0.646Average predicted survival time: 125 days----"
},
{
"code": null,
"e": 5428,
"s": 4975,
"text": "In all three scenarios, we can build models with C-index results close to the state of the art [8]. However, our predictions change drastically, with two models showing an average predicted survival time difference of 78 days. This difference would perhaps be understandable if we were analyzing a single sample. But we're looking across the full validation dataset where the average prediction should be fairly stable regardless of which model we use."
},
{
"code": null,
"e": 5772,
"s": 5428,
"text": "If we plot these results alongside an unbiased survival estimator such as the Kaplan Meier we can check that for each step of 0.5 in aft_loss_distribution_scale we move roughly one decile to the right in the curve. Also, we don't see a full survival curve: XGBoost only outputs point time-to-event predictions (no confidence intervals either)."
},
{
"code": null,
"e": 6200,
"s": 5772,
"text": "Given these results, we raise the question: \"what model should we trust?\". Although we could try to optimize for some error measure such as L1-loss [9], we would like more guarantees for applications that are dependent on stable and calibrated time-to-event estimates. Having only point estimates, no confidence intervals, and no \"calibration by design\" mines trust and prevents shipping survival analysis models to production."
},
{
"code": null,
"e": 6461,
"s": 6200,
"text": "Although in need of an extension for better statistical properties, XGBoost is undoubtedly a powerhouse. C-index results show that the model has great discrimination performance, being competitive with the state of the art. We just need to adapt how we use it."
},
{
"code": null,
"e": 6871,
"s": 6461,
"text": "Besides being leveraged for prediction tasks, Gradient Boosted Trees (GBTs) can also be used as feature transformers of the input data. Trees in the ensemble perform splits on features that discriminate the target, encoding relevant information in their structure. In particular, the terminal nodes (leaves) at each tree in the ensemble define a very nice feature transformation (embedding) of the input data."
},
{
"code": null,
"e": 6940,
"s": 6871,
"text": "This kind of tree ensemble embedding has very convenient properties:"
},
{
"code": null,
"e": 7849,
"s": 6940,
"text": "sparsity and high-dimensionality: trees deal with nonlinearity and cast original features to a sparse, high-dimensional embedding, which helps linear models perform well when trained on it. For instance, a logistic regression trained on the embedding (with features as one-hot encoded leaf indices) can show comparable performance to the actual ensemble, with the added benefit of probability calibration (see [1], [2], and [3])supervision: trees also work as a noise filter, performing splits only through features that have predictive power. Thus, the embedding actually has a lower intrinsic dimension than the input data (see [4]). This mitigates the curse of dimensionality and allows a kNN model trained on the embedding (using hamming distance) to have comparable performance to the actual ensemble. With neighbor-sets at hand, we can use robust estimators such as the Kaplan-Meier to get predictions."
},
{
"code": null,
"e": 8278,
"s": 7849,
"text": "sparsity and high-dimensionality: trees deal with nonlinearity and cast original features to a sparse, high-dimensional embedding, which helps linear models perform well when trained on it. For instance, a logistic regression trained on the embedding (with features as one-hot encoded leaf indices) can show comparable performance to the actual ensemble, with the added benefit of probability calibration (see [1], [2], and [3])"
},
{
"code": null,
"e": 8759,
"s": 8278,
"text": "supervision: trees also work as a noise filter, performing splits only through features that have predictive power. Thus, the embedding actually has a lower intrinsic dimension than the input data (see [4]). This mitigates the curse of dimensionality and allows a kNN model trained on the embedding (using hamming distance) to have comparable performance to the actual ensemble. With neighbor-sets at hand, we can use robust estimators such as the Kaplan-Meier to get predictions."
},
{
"code": null,
"e": 8868,
"s": 8759,
"text": "These two properties are the foundation upon which we built xgbse. We show how we put them to good use next."
},
{
"code": null,
"e": 9088,
"s": 8868,
"text": "Our first approach, XGBSEDebiasedBCE, takes inspiration from the multi-task logistic regression method in [5], the BCE (binary cross-entropy) approach in [6], and the probability calibration ideas from [1], [2] and [3]."
},
{
"code": null,
"e": 9401,
"s": 9088,
"text": "It consists of training a set of logistic regressions on top of the embedding produced by the underlying XGBoost model, each predicting survival at different user-defined discrete time windows. The classifiers remove individuals as they are censored, with targets that are indicators of surviving at each window."
},
{
"code": null,
"e": 9652,
"s": 9401,
"text": "As the embedding is sparse and high dimensional, the linear models actually can improve the ensemble performance, while also adding nice statistical properties to it, such as probability calibration (as logistic regressions are calibrated by design)."
},
{
"code": null,
"e": 9959,
"s": 9652,
"text": "The naive approach tends to give biased survival curves, due to the removal of censored individuals. Thus, we made some adaptations such that logistic regressions estimate the di/ni term (point probabilities) in the Kaplan-Meier formula and then use the KM estimator to get nearly unbiased survival curves."
},
{
"code": null,
"e": 10291,
"s": 9959,
"text": "This way, we can get full survival curves from XGBoost, and confidence intervals with minor adaptations (such as performing some rounds of bootstrap). Training and scoring of logistic regression models is efficient, being performed in parallel through joblib, so the model can scale to hundreds of thousands or millions of samples."
},
{
"code": null,
"e": 10790,
"s": 10291,
"text": "As explained in the previous section, even though the embedding produced by XGBoost is sparse and high dimensional, its intrinsic dimensionality actually should be lower than the input data. This enables us to \"convert\" XGBoost into a nearest neighbor model, where we use hamming distance to define similar elements as the ones that co-occurred the most at the ensemble terminal nodes. Then, at each neighbor-set we can get survival estimates with robust methods such as the Kaplan-Meier estimator."
},
{
"code": null,
"e": 11156,
"s": 10790,
"text": "We recommend using dart as the booster to prevent any tree to dominate variance in the ensemble and break the leaf co-occurrence similarity logic. We built a high-performing implementation of the KM estimator to calculate several survival curves in a vectorized fashion, including upper and lower confidence intervals based on the Exponential Greenwood formula [7]."
},
{
"code": null,
"e": 11359,
"s": 11156,
"text": "However, this method can be very expensive at scales of hundreds of thousands of samples, due to the nearest neighbor search, both on training (construction of search index) and scoring (actual search)."
},
{
"code": null,
"e": 11584,
"s": 11359,
"text": "As a simplification to XGBSEKaplanNeighbors, we also provide a single tree implementation. Instead of doing expensive nearest neighbor searches, we fit a single tree via XGBoost and calculate KM curves at each of its leaves."
},
{
"code": null,
"e": 11829,
"s": 11584,
"text": "It is by far the most efficient implementation, able to scale to millions of examples easily. At fit time, the tree is built and all KM curves are pre-calculated, so that at scoring time a simple query will suffice to get the model’s estimates."
},
{
"code": null,
"e": 12093,
"s": 11829,
"text": "However, as we’re fitting a single tree, predictive power may be worse. That could be a sensible tradeoff, but we also provide XGBSEBootstrapEstimator, a bootstrap abstraction where we can fit a forest of XGBSEKaplanTree's to improve accuracy and reduce variance."
},
{
"code": null,
"e": 12176,
"s": 12093,
"text": "Now we return to the first example and check how XGBEmbedKaplanNeighbors performs:"
},
{
"code": null,
"e": 12562,
"s": 12176,
"text": "aft_loss_distribution_scale: 1.5C-index: 0.640Average probability of survival at [30, 90, 150] days: [0.9109, 0.6854, 0.528]----aft_loss_distribution_scale: 1.0C-index: 0.644Average probability of survival at [30, 90, 150] days: [0.9111, 0.6889, 0.5333]----aft_loss_distribution_scale: 0.5C-index: 0.650Average probability of survival at [30, 90, 150] days: [0.913, 0.6904, 0.5289]----"
},
{
"code": null,
"e": 12890,
"s": 12562,
"text": "As measured by the average probability of survival in 30, 90 and 150 days the model shows good results, with comparable C-index results and predictions being very close and independent of aft_loss_distribution_scale choice. Visually, the comparison of the average model predictions to a Kaplan Meier yields much better results:"
},
{
"code": null,
"e": 13122,
"s": 12890,
"text": "Much less bias, full survival curves and stability! Although is too harsh to claim that the problem is solved, we believe that the we could build a strong survival analysis package and bring the \"two cultures\" much closer together."
},
{
"code": null,
"e": 13555,
"s": 13122,
"text": "XGBoost Survival Embeddings shows great results in several survival analysis benchmarks, outperforming vanilla XGBoost and parametric methods in most cases. It is pip installable and scikit-learn compatible. There are more features to try, such as confidence intervals, extrapolation of survival curves, explainability through prototypes, metrics, and more. We’re committed to improving the lib and adding new content in the future."
},
{
"code": null,
"e": 13758,
"s": 13555,
"text": "For more details, please check the the library on github, the docs, and examples! We invite the community to contribute. Please help by trying it out, reporting bugs, and letting us know what you think!"
},
{
"code": null,
"e": 13829,
"s": 13758,
"text": "By Davi Vieira, Guilherme Marmerola, Gabriel Gimenez and Vitor Estima."
},
{
"code": null,
"e": 14111,
"s": 13829,
"text": "[1] X. He, J. Pan, O. Jin, T. Xu, B. Liu, T. Xu, Y. Shi, A. Atallah, R. Herbrich, S. Bowers, and J. Q. Candela. Practical Lessons from Predicting Clicks on Ads at Facebook (2014). In Proceedings of the Eighth International Workshop on Data Mining for Online Advertising (ADKDD’14)."
},
{
"code": null,
"e": 14221,
"s": 14111,
"text": "[2] Feature transformations with ensembles of trees. Scikit-learn documentation at https://scikit-learn.org/."
},
{
"code": null,
"e": 14340,
"s": 14221,
"text": "[3] G. Marmerola. Calibration of probabilities for tree-based models. Personal Blog at https://gdmarmerola.github.io/."
},
{
"code": null,
"e": 14487,
"s": 14340,
"text": "[4] G. Marmerola. Supervised dimensionality reduction and clustering at scale with RFs with UMAP. Personal Blog at https://gdmarmerola.github.io/."
},
{
"code": null,
"e": 14691,
"s": 14487,
"text": "[5] C. Yu, R. Greiner, H. Lin, V. Baracos. Learning Patient-Specific Cancer Survival Distributions as a Sequence of Dependent Regressors. Advances in Neural Information Processing Systems 24 (NIPS 2011)."
},
{
"code": null,
"e": 14822,
"s": 14691,
"text": "[6] H. Kvamme, Ø. Borgan. The Brier Score under Administrative Censoring: Problems and Solutions. arXiv preprint arXiv:1912.08581."
},
{
"code": null,
"e": 14975,
"s": 14822,
"text": "[7] S. Sawyer. The Greenwood and Exponential Greenwood Confidence Intervals in Survival Analysis. Handout on Washington University in St. Louis website."
},
{
"code": null,
"e": 15140,
"s": 14975,
"text": "[8] H. Kvamme, Ø. Borgan, and I. Scheel. Time-to-event prediction with neural networks and Cox regression. Journal of Machine Learning Research, 20(129):1–30, 2019."
}
] |
How to parse json string in android?
|
This example demonstrates How to parse JSON string in android.
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:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken a text view to show the json element name.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
String json = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " ]"
+ "}";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
try {
final JSONObject obj = new JSONObject(json);
final JSONArray geodata = obj.getJSONArray("geodata");
final JSONObject person = geodata.getJSONObject(0);
textView.setText(person.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "This example demonstrates How to parse JSON string in android."
},
{
"code": null,
"e": 1254,
"s": 1125,
"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": 1319,
"s": 1254,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1879,
"s": 1319,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1955,
"s": 1879,
"text": "In the above code, we have taken a text view to show the json element name."
},
{
"code": null,
"e": 2012,
"s": 1955,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3674,
"s": 2012,
"text": "package com.example.myapplication;\nimport android.app.KeyguardManager;\nimport android.app.admin.DevicePolicyManager;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.Network;\nimport android.net.NetworkInfo;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.KeyEvent;\nimport android.widget.TextView;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n String json = \"{\"\n + \" \\\"geodata\\\": [\"\n + \" {\"\n + \" \\\"id\\\": \\\"1\\\",\"\n + \" \\\"name\\\": \\\"Julie Sherman\\\",\"\n + \" \\\"gender\\\" : \\\"female\\\",\"\n + \" \\\"latitude\\\" : \\\"37.33774833333334\\\",\"\n + \" \\\"longitude\\\" : \\\"-121.88670166666667\\\"\"\n + \" },\"\n + \" ]\"\n + \"}\";\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n try {\n final JSONObject obj = new JSONObject(json);\n final JSONArray geodata = obj.getJSONArray(\"geodata\");\n final JSONObject person = geodata.getJSONObject(0);\n textView.setText(person.getString(\"name\"));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 4021,
"s": 3674,
"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": 4061,
"s": 4021,
"text": "Click here to download the project code"
}
] |
Explain the components of DBMS?
|
The database management system (DBMS) software is divided into several components. Each component will perform a specific operation. Some of the functions of the DBMS are supported by operating systems.
The DBMS accepts the SQL commands that are generated from a variety of user interfaces, which produces a query evaluation plan, executes these plans against the database, and returns the answers.
Let’s have a look on the major software components of DBMS with pictorial representation −
The components of the DBMS are as follows −
DBA − The Data Base Administrator (DBA) responsibility is to create the DBMS structure and have the ability to control the structure.
DBA − The Data Base Administrator (DBA) responsibility is to create the DBMS structure and have the ability to control the structure.
Application Programs − It is used to create the records, change and update the records. It is mainly useful in designing the interface.
Application Programs − It is used to create the records, change and update the records. It is mainly useful in designing the interface.
DML processor − Data Manipulation language, it is helpful to update data, manipulate data based on user request, checks according to syntax of SQL.
DML processor − Data Manipulation language, it is helpful to update data, manipulate data based on user request, checks according to syntax of SQL.
DDL Processor − Data Definition language checks the structure of the database. It checks the improper statements and the syntax of statements according to the SQL.
DDL Processor − Data Definition language checks the structure of the database. It checks the improper statements and the syntax of statements according to the SQL.
Data Dictionary − Store all the queries. Queries are checked according to the SQL configuration, if the queries are valid ok. Otherwise, it generates errors.
Data Dictionary − Store all the queries. Queries are checked according to the SQL configuration, if the queries are valid ok. Otherwise, it generates errors.
Integrity Checker − Here data is stored which is designed by Database administrator. Check the primary or unique key.
Integrity Checker − Here data is stored which is designed by Database administrator. Check the primary or unique key.
Authenticate control − Authenticate control checks whether a user is valid or not.
Authenticate control − Authenticate control checks whether a user is valid or not.
Command Processor − It processes the query ->SQL. For example, SQL ->Oracle -> optimize -> generate file.
Command Processor − It processes the query ->SQL. For example, SQL ->Oracle -> optimize -> generate file.
Query optimizer − It updates the query, Reduces response time at end.
Query optimizer − It updates the query, Reduces response time at end.
Transaction manager − Transaction manager, manage changes in query.
Transaction manager − Transaction manager, manage changes in query.
Scheduler − Send number of requests at a time, A queue is formed according to time.
Scheduler − Send number of requests at a time, A queue is formed according to time.
Buffer manager − Buffer manager performs storage management operation.
Buffer manager − Buffer manager performs storage management operation.
Recovery manager − Recovery manager recovers the data from main memory and manages the log files or recovery files.
Recovery manager − Recovery manager recovers the data from main memory and manages the log files or recovery files.
Query processor − Query processor processes the query coming from the user side. Its responsibility is to manage DML and DDL commands.
Query processor − Query processor processes the query coming from the user side. Its responsibility is to manage DML and DDL commands.
Example
Select emp name, address from emp;
Select is a DML command.
Both processors work at the same time.
Syntax table is created or not.
Syntax table is created or not.
Run select query which is retrieved from hard disk.
Run select query which is retrieved from hard disk.
Run-time database performs the operations mentioned below −
Authenticate control
Authenticate control
Integrity checker
Integrity checker
Command processor
Command processor
Data manager performs the physical level working and monitors how much space to be allocated to the database (DB).
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "The database management system (DBMS) software is divided into several components. Each component will perform a specific operation. Some of the functions of the DBMS are supported by operating systems."
},
{
"code": null,
"e": 1461,
"s": 1265,
"text": "The DBMS accepts the SQL commands that are generated from a variety of user interfaces, which produces a query evaluation plan, executes these plans against the database, and returns the answers."
},
{
"code": null,
"e": 1552,
"s": 1461,
"text": "Let’s have a look on the major software components of DBMS with pictorial representation −"
},
{
"code": null,
"e": 1596,
"s": 1552,
"text": "The components of the DBMS are as follows −"
},
{
"code": null,
"e": 1730,
"s": 1596,
"text": "DBA − The Data Base Administrator (DBA) responsibility is to create the DBMS structure and have the ability to control the structure."
},
{
"code": null,
"e": 1864,
"s": 1730,
"text": "DBA − The Data Base Administrator (DBA) responsibility is to create the DBMS structure and have the ability to control the structure."
},
{
"code": null,
"e": 2000,
"s": 1864,
"text": "Application Programs − It is used to create the records, change and update the records. It is mainly useful in designing the interface."
},
{
"code": null,
"e": 2136,
"s": 2000,
"text": "Application Programs − It is used to create the records, change and update the records. It is mainly useful in designing the interface."
},
{
"code": null,
"e": 2284,
"s": 2136,
"text": "DML processor − Data Manipulation language, it is helpful to update data, manipulate data based on user request, checks according to syntax of SQL."
},
{
"code": null,
"e": 2432,
"s": 2284,
"text": "DML processor − Data Manipulation language, it is helpful to update data, manipulate data based on user request, checks according to syntax of SQL."
},
{
"code": null,
"e": 2596,
"s": 2432,
"text": "DDL Processor − Data Definition language checks the structure of the database. It checks the improper statements and the syntax of statements according to the SQL."
},
{
"code": null,
"e": 2760,
"s": 2596,
"text": "DDL Processor − Data Definition language checks the structure of the database. It checks the improper statements and the syntax of statements according to the SQL."
},
{
"code": null,
"e": 2918,
"s": 2760,
"text": "Data Dictionary − Store all the queries. Queries are checked according to the SQL configuration, if the queries are valid ok. Otherwise, it generates errors."
},
{
"code": null,
"e": 3076,
"s": 2918,
"text": "Data Dictionary − Store all the queries. Queries are checked according to the SQL configuration, if the queries are valid ok. Otherwise, it generates errors."
},
{
"code": null,
"e": 3194,
"s": 3076,
"text": "Integrity Checker − Here data is stored which is designed by Database administrator. Check the primary or unique key."
},
{
"code": null,
"e": 3312,
"s": 3194,
"text": "Integrity Checker − Here data is stored which is designed by Database administrator. Check the primary or unique key."
},
{
"code": null,
"e": 3395,
"s": 3312,
"text": "Authenticate control − Authenticate control checks whether a user is valid or not."
},
{
"code": null,
"e": 3478,
"s": 3395,
"text": "Authenticate control − Authenticate control checks whether a user is valid or not."
},
{
"code": null,
"e": 3584,
"s": 3478,
"text": "Command Processor − It processes the query ->SQL. For example, SQL ->Oracle -> optimize -> generate file."
},
{
"code": null,
"e": 3690,
"s": 3584,
"text": "Command Processor − It processes the query ->SQL. For example, SQL ->Oracle -> optimize -> generate file."
},
{
"code": null,
"e": 3760,
"s": 3690,
"text": "Query optimizer − It updates the query, Reduces response time at end."
},
{
"code": null,
"e": 3830,
"s": 3760,
"text": "Query optimizer − It updates the query, Reduces response time at end."
},
{
"code": null,
"e": 3898,
"s": 3830,
"text": "Transaction manager − Transaction manager, manage changes in query."
},
{
"code": null,
"e": 3966,
"s": 3898,
"text": "Transaction manager − Transaction manager, manage changes in query."
},
{
"code": null,
"e": 4050,
"s": 3966,
"text": "Scheduler − Send number of requests at a time, A queue is formed according to time."
},
{
"code": null,
"e": 4134,
"s": 4050,
"text": "Scheduler − Send number of requests at a time, A queue is formed according to time."
},
{
"code": null,
"e": 4205,
"s": 4134,
"text": "Buffer manager − Buffer manager performs storage management operation."
},
{
"code": null,
"e": 4276,
"s": 4205,
"text": "Buffer manager − Buffer manager performs storage management operation."
},
{
"code": null,
"e": 4392,
"s": 4276,
"text": "Recovery manager − Recovery manager recovers the data from main memory and manages the log files or recovery files."
},
{
"code": null,
"e": 4508,
"s": 4392,
"text": "Recovery manager − Recovery manager recovers the data from main memory and manages the log files or recovery files."
},
{
"code": null,
"e": 4643,
"s": 4508,
"text": "Query processor − Query processor processes the query coming from the user side. Its responsibility is to manage DML and DDL commands."
},
{
"code": null,
"e": 4778,
"s": 4643,
"text": "Query processor − Query processor processes the query coming from the user side. Its responsibility is to manage DML and DDL commands."
},
{
"code": null,
"e": 4786,
"s": 4778,
"text": "Example"
},
{
"code": null,
"e": 4846,
"s": 4786,
"text": "Select emp name, address from emp;\nSelect is a DML command."
},
{
"code": null,
"e": 4885,
"s": 4846,
"text": "Both processors work at the same time."
},
{
"code": null,
"e": 4917,
"s": 4885,
"text": "Syntax table is created or not."
},
{
"code": null,
"e": 4949,
"s": 4917,
"text": "Syntax table is created or not."
},
{
"code": null,
"e": 5001,
"s": 4949,
"text": "Run select query which is retrieved from hard disk."
},
{
"code": null,
"e": 5053,
"s": 5001,
"text": "Run select query which is retrieved from hard disk."
},
{
"code": null,
"e": 5113,
"s": 5053,
"text": "Run-time database performs the operations mentioned below −"
},
{
"code": null,
"e": 5134,
"s": 5113,
"text": "Authenticate control"
},
{
"code": null,
"e": 5155,
"s": 5134,
"text": "Authenticate control"
},
{
"code": null,
"e": 5173,
"s": 5155,
"text": "Integrity checker"
},
{
"code": null,
"e": 5191,
"s": 5173,
"text": "Integrity checker"
},
{
"code": null,
"e": 5209,
"s": 5191,
"text": "Command processor"
},
{
"code": null,
"e": 5227,
"s": 5209,
"text": "Command processor"
},
{
"code": null,
"e": 5342,
"s": 5227,
"text": "Data manager performs the physical level working and monitors how much space to be allocated to the database (DB)."
}
] |
TypeScript - Ifâ¦else Statement
|
An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false.
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true.
The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.
var num:number = 12;
if (num % 2==0) {
console.log("Even");
} else {
console.log("Odd");
}
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var num = 12;
if (num % 2 == 0) {
console.log("Even");
} else {
console.log("Odd");
}
The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code −
Even
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2198,
"s": 2048,
"text": "An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false."
},
{
"code": null,
"e": 2372,
"s": 2198,
"text": "if(boolean_expression) { \n // statement(s) will execute if the boolean expression is true\n} else {\n // statement(s) will execute if the boolean expression is false \n}\n"
},
{
"code": null,
"e": 2520,
"s": 2372,
"text": "The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true."
},
{
"code": null,
"e": 2683,
"s": 2520,
"text": "The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false."
},
{
"code": null,
"e": 2785,
"s": 2683,
"text": "var num:number = 12; \nif (num % 2==0) { \n console.log(\"Even\"); \n} else {\n console.log(\"Odd\"); \n}\n"
},
{
"code": null,
"e": 2848,
"s": 2785,
"text": "On compiling, it will generate the following JavaScript code −"
},
{
"code": null,
"e": 2974,
"s": 2848,
"text": "//Generated by typescript 1.8.10\nvar num = 12;\nif (num % 2 == 0) {\n console.log(\"Even\");\n} else {\n console.log(\"Odd\");\n}\n"
},
{
"code": null,
"e": 3164,
"s": 2974,
"text": "The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code −"
},
{
"code": null,
"e": 3171,
"s": 3164,
"text": "Even \n"
},
{
"code": null,
"e": 3204,
"s": 3171,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3218,
"s": 3204,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3251,
"s": 3218,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3265,
"s": 3251,
"text": " Haider Malik"
},
{
"code": null,
"e": 3300,
"s": 3265,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3320,
"s": 3300,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3353,
"s": 3320,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3367,
"s": 3353,
"text": " Sean Bradley"
},
{
"code": null,
"e": 3402,
"s": 3367,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3418,
"s": 3402,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3451,
"s": 3418,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3471,
"s": 3451,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3478,
"s": 3471,
"text": " Print"
},
{
"code": null,
"e": 3489,
"s": 3478,
"text": " Add Notes"
}
] |
Report Sections
|
We discussed the structure of a simple report template in the chapter Getting Started. On similar lines, JasperReports structures the report template into multiple sections. Sections are portions of the report that have a specified height and can contain report objects like lines, rectangles, images, or text fields.
The report engine iterates through the virtual records of the supplied report data source, at report filling time. Depending on each section's defined behavior, the engine then renders each report section when appropriate. For instance, the detail section is rendered for each record in the data source. When page breaks occur, the page header and page footer sections are rendered as needed.
In JasperReports, terminology and report sections are also called as report bands. Sections are made up of one or more bands. These sections are filled repeatedly at report-generating time and prepare the final document.
A report template in JasperReports has the following main sections −
<title></title>
<pageheader></pageheader>
<columnheader></columnheader>
<groupheader></groupheader>
<detail></detail>
<groupfooter></groupfooter>
<columnfooter></columnfooter>
<pagefooter></pagefooter>
<lastpagefooter></lastpagefooter>
<summary></summary>
<nodata></nodata>
<background></background>
The following table summarizes each of the sections −
Title
This section appears only once at the beginning of the report.
Page Header
This section appears at the beginning of each page in the generated document.
Column Header
This section appears at the beginning of each column in the generated document. If the report has only one column defined, then column header and footer sections are ignored.
Group Header
This section is introduced by a report group (chapter Groups). Each time the grouping expression changes its value, the group header section is printed above the detail section. In case, if more than one group is defined, the group header is printed in the order of group definition.
Detail
This section is repeated for each line of data supplied by the report's data source. The detail section can be made of multiple bands.
Group Footer
This section is introduced by a report group (chapter Groups). The group footer section is printed below the detail section before the value of the grouping expression changes. The group footer is always printed for the last line of data in data source. In case, if more than one group is defined, the group footer is printed in the reverse order of group definition.
Column Footer
This section appears at the bottom of each column. If the report's column count is 1, then column header and footer sections are ignored.
Page Footer
This section appears at the bottom of each page.
Last Page Footer
This section replaces the regular page footer on the last page of the report. In case, the summary section is also present, then this might not be the very last page of the document. This section is sometimes useful when summary information has to be displayed at the bottom of the last page.
Summary
This section appears only once at the end of the report.
No Data
This section is printed when the When No Data Print report property is set to No Data Section. If the <noData> section is defined in the report template, and if the data source is empty, then the <noData> section will be the only one taken into account at fill time, and its content will produce the report output.
Background
The background section is displayed on every page and cannot overflow to the next page. Elements placed on this section are evaluated at page initialization time and are displayed in the background. All other page objects are displayed on top of the background objects. This section is useful for creating page watermarks.
The following diagram shows the elements and attributes relationship in a section of a report.
All the above mentioned report sections are optional. But any report template will have at least one such section. Each of these sections contains a single <band> element as its only sub-element. A <band> can contain zero or more following sub-elements −
<line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport>, or <elementGroup>
Each of these elements must contain a single <reportElement> as its first element (except elementGroup). A <reportElement> determines how data is laid out for that particular element. Unlike variables and parameters, report elements are not required to have a name, because normally you do not need to obtain any individual element inside a report template.
The table below summarizes the attributes of <reportElement> −
NoStretch (default) − The element will not stretch.
RelativeToTallestObject − The element will stretch to accommodate the tallest object in its group.
RelativeToBand − The element will stretch to fit the band's height.
Float − The element will move depending on the size of the surrounding elements.
FixRelativeToTop (default) − The element will maintain a fixed position relative to the band's top.
FixRelativeToBottom − The element will maintain a fixed position relative to the band's bottom.
true (default) − Repeated values will be printed.
false − Repeated values will not be printed.
Following are the attributes of a report section −
Height of the section specifies the height in pixels for that particular section and is very important in the overall report design.
A Boolean expression that determines whether the section should be printed or not.
A flag indicating whether the section is allowed to split when it does not fit on the current page. If true, the section will be transferred to the next page. Note that in case, the section does not fit on the next page, then the section will be split regardless of the flag's value. splitType can take following values −
splitType="Stretch:" Splits stretched content. If the section stretches on the current page (if the available space is less than declared height), the region that is added to the original height is allowed to split onto the next page.
splitType="Stretch:" Splits stretched content. If the section stretches on the current page (if the available space is less than declared height), the region that is added to the original height is allowed to split onto the next page.
splitType="Prevent:" Prevent split on first attempt. If the section does not fit on the next page, the split occurs normally, as band split prevention is effective only on the first split attempt.
splitType="Prevent:" Prevent split on first attempt. If the section does not fit on the next page, the split occurs normally, as band split prevention is effective only on the first split attempt.
splitType="Immediate:" Split immediately. The band is allowed to split anywhere except above, its topmost element.
splitType="Immediate:" Split immediately. The band is allowed to split anywhere except above, its topmost element.
To demonstrate each section, let's write report template (jasper_report_template.jrxml). Save this file to C:\tools\jasperreports-5.0.1\test directory. In this file, we would be displaying a text in each of the sections (we discussed above). The contents of the file are as given below −
<?xml version = "1.0" encoding = "UTF-8"?>
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" pageWidth = "300" pageHeight = "300"
columnWidth = "300" leftMargin = "0" rightMargin = "0"
topMargin = "0" bottomMargin = "0" >
<title>
<band height = "50">
<textField>
<reportElement x = "100" y = "16" width = "100" height = "20"/>
<textElement/>
<textFieldExpression>
<![CDATA["Title"]]>
</textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height = "40">
<textField>
<reportElement mode = "Opaque" x = "100" y = "10"
width = "90" height = "20"/>
<textElement>
<font isBold = "true"/>
</textElement>
<textFieldExpression>
<![CDATA["Page Header"]]>
</textFieldExpression>
</textField>
</band>
</pageHeader>
<columnHeader>
<band height = "40">
<textField>
<reportElement x = "100" y = "10" width = "90" height = "20"/>
<textElement>
<font isItalic = "true"/>
</textElement>
<textFieldExpression>
<![CDATA["Column Header"]]>
</textFieldExpression>
</textField>
</band>
</columnHeader>
<detail>
<band height ="40">
<textField>
<reportElement mode = "Opaque" x = "100" y = "10"
width = "90" height = "20" backcolor = "#99CCFF"/>
<textElement/>
<textFieldExpression>
<![CDATA["Report Details"]]>
</textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height = "40">
<textField>
<reportElement x = "100" y = "10" width = "90" height = "20"/>
<textElement/>
<textFieldExpression>
<![CDATA["Column Footer"]]>
</textFieldExpression>
</textField>
</band>
</columnFooter>
<pageFooter>
<band height = "40">
<textField>
<reportElement x = "100" y = "10" width = "90" height = "20"/>
<textElement/>
<textFieldExpression>
<![CDATA["Page Footer"]]>
</textFieldExpression>
</textField>
</band>
</pageFooter>
<lastPageFooter>
<band height = "40">
<textField>
<reportElement x = "100" y = "10" width = "90" height = "20"/>
<textElement/>
<textFieldExpression>
<![CDATA["Last Page Footer"]]>
</textFieldExpression>
</textField>
</band>
</lastPageFooter>
<summary>
<band height = "40">
<textField>
<reportElement x = "100" y = "10" width = "90" height = "20"/>
<textElement/>
<textFieldExpression>
<![CDATA["Summary"]]>
</textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>
The java code to fill and generate the report is given below. Let's save this file JasperReportFill.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory.
package com.tutorialspoint;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
public class JasperReportFill {
public static void main(String[] args) {
String sourceFileName = "C://tools/jasperreports-5.0.1/test/" +
"jasper_report_template.jasper";
try {
JasperFillManager.fillReportToFile(sourceFileName, null,
new JREmptyDataSource());
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields in this single record being null.
We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as below.
The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewFillReport" depends = "compile,compilereportdesing,run"
description = "Launches the report viewer to preview
the report stored in the .JRprint file.">
<java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
<arg value = "-F${file.name}.JRprint" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc"
classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
warning: 'includeantruntime' was not set, defau
[javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFac
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.JasperReportFill
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnviro
[java] log4j:WARN Please initialize the log4j system properly.
viewFillReport:
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnviro
[java] log4j:WARN Please initialize the log4j system properly.
BUILD SUCCESSFUL
Total time: 18 minutes 22 seconds
As a result of above compilation, a JasperViewer window opens up as in the screen below −
Here, we can see in each of the sections a text is printed. It is to be noted that as JRXML contains a <lastPageFooter> element, it will be displayed in the last page of the report instead of the <pageFooter> element being displayed. The <columnHeader> and <columnFooter> elements will only be displayed on the report, if it has more than one column.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2572,
"s": 2254,
"text": "We discussed the structure of a simple report template in the chapter Getting Started. On similar lines, JasperReports structures the report template into multiple sections. Sections are portions of the report that have a specified height and can contain report objects like lines, rectangles, images, or text fields."
},
{
"code": null,
"e": 2965,
"s": 2572,
"text": "The report engine iterates through the virtual records of the supplied report data source, at report filling time. Depending on each section's defined behavior, the engine then renders each report section when appropriate. For instance, the detail section is rendered for each record in the data source. When page breaks occur, the page header and page footer sections are rendered as needed."
},
{
"code": null,
"e": 3186,
"s": 2965,
"text": "In JasperReports, terminology and report sections are also called as report bands. Sections are made up of one or more bands. These sections are filled repeatedly at report-generating time and prepare the final document."
},
{
"code": null,
"e": 3255,
"s": 3186,
"text": "A report template in JasperReports has the following main sections −"
},
{
"code": null,
"e": 3566,
"s": 3255,
"text": "<title></title>\n\n<pageheader></pageheader>\n\n<columnheader></columnheader>\n\n<groupheader></groupheader>\n\n<detail></detail>\n\n<groupfooter></groupfooter>\n\n<columnfooter></columnfooter>\n\n<pagefooter></pagefooter>\n\n<lastpagefooter></lastpagefooter>\n\n<summary></summary>\n\n<nodata></nodata>\n\n<background></background>"
},
{
"code": null,
"e": 3620,
"s": 3566,
"text": "The following table summarizes each of the sections −"
},
{
"code": null,
"e": 3626,
"s": 3620,
"text": "Title"
},
{
"code": null,
"e": 3689,
"s": 3626,
"text": "This section appears only once at the beginning of the report."
},
{
"code": null,
"e": 3701,
"s": 3689,
"text": "Page Header"
},
{
"code": null,
"e": 3779,
"s": 3701,
"text": "This section appears at the beginning of each page in the generated document."
},
{
"code": null,
"e": 3793,
"s": 3779,
"text": "Column Header"
},
{
"code": null,
"e": 3968,
"s": 3793,
"text": "This section appears at the beginning of each column in the generated document. If the report has only one column defined, then column header and footer sections are ignored."
},
{
"code": null,
"e": 3981,
"s": 3968,
"text": "Group Header"
},
{
"code": null,
"e": 4265,
"s": 3981,
"text": "This section is introduced by a report group (chapter Groups). Each time the grouping expression changes its value, the group header section is printed above the detail section. In case, if more than one group is defined, the group header is printed in the order of group definition."
},
{
"code": null,
"e": 4272,
"s": 4265,
"text": "Detail"
},
{
"code": null,
"e": 4407,
"s": 4272,
"text": "This section is repeated for each line of data supplied by the report's data source. The detail section can be made of multiple bands."
},
{
"code": null,
"e": 4420,
"s": 4407,
"text": "Group Footer"
},
{
"code": null,
"e": 4788,
"s": 4420,
"text": "This section is introduced by a report group (chapter Groups). The group footer section is printed below the detail section before the value of the grouping expression changes. The group footer is always printed for the last line of data in data source. In case, if more than one group is defined, the group footer is printed in the reverse order of group definition."
},
{
"code": null,
"e": 4802,
"s": 4788,
"text": "Column Footer"
},
{
"code": null,
"e": 4940,
"s": 4802,
"text": "This section appears at the bottom of each column. If the report's column count is 1, then column header and footer sections are ignored."
},
{
"code": null,
"e": 4952,
"s": 4940,
"text": "Page Footer"
},
{
"code": null,
"e": 5001,
"s": 4952,
"text": "This section appears at the bottom of each page."
},
{
"code": null,
"e": 5018,
"s": 5001,
"text": "Last Page Footer"
},
{
"code": null,
"e": 5311,
"s": 5018,
"text": "This section replaces the regular page footer on the last page of the report. In case, the summary section is also present, then this might not be the very last page of the document. This section is sometimes useful when summary information has to be displayed at the bottom of the last page."
},
{
"code": null,
"e": 5319,
"s": 5311,
"text": "Summary"
},
{
"code": null,
"e": 5376,
"s": 5319,
"text": "This section appears only once at the end of the report."
},
{
"code": null,
"e": 5384,
"s": 5376,
"text": "No Data"
},
{
"code": null,
"e": 5699,
"s": 5384,
"text": "This section is printed when the When No Data Print report property is set to No Data Section. If the <noData> section is defined in the report template, and if the data source is empty, then the <noData> section will be the only one taken into account at fill time, and its content will produce the report output."
},
{
"code": null,
"e": 5710,
"s": 5699,
"text": "Background"
},
{
"code": null,
"e": 6033,
"s": 5710,
"text": "The background section is displayed on every page and cannot overflow to the next page. Elements placed on this section are evaluated at page initialization time and are displayed in the background. All other page objects are displayed on top of the background objects. This section is useful for creating page watermarks."
},
{
"code": null,
"e": 6128,
"s": 6033,
"text": "The following diagram shows the elements and attributes relationship in a section of a report."
},
{
"code": null,
"e": 6383,
"s": 6128,
"text": "All the above mentioned report sections are optional. But any report template will have at least one such section. Each of these sections contains a single <band> element as its only sub-element. A <band> can contain zero or more following sub-elements −"
},
{
"code": null,
"e": 6482,
"s": 6383,
"text": "<line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport>, or <elementGroup>"
},
{
"code": null,
"e": 6840,
"s": 6482,
"text": "Each of these elements must contain a single <reportElement> as its first element (except elementGroup). A <reportElement> determines how data is laid out for that particular element. Unlike variables and parameters, report elements are not required to have a name, because normally you do not need to obtain any individual element inside a report template."
},
{
"code": null,
"e": 6903,
"s": 6840,
"text": "The table below summarizes the attributes of <reportElement> −"
},
{
"code": null,
"e": 6955,
"s": 6903,
"text": "NoStretch (default) − The element will not stretch."
},
{
"code": null,
"e": 7054,
"s": 6955,
"text": "RelativeToTallestObject − The element will stretch to accommodate the tallest object in its group."
},
{
"code": null,
"e": 7122,
"s": 7054,
"text": "RelativeToBand − The element will stretch to fit the band's height."
},
{
"code": null,
"e": 7203,
"s": 7122,
"text": "Float − The element will move depending on the size of the surrounding elements."
},
{
"code": null,
"e": 7303,
"s": 7203,
"text": "FixRelativeToTop (default) − The element will maintain a fixed position relative to the band's top."
},
{
"code": null,
"e": 7399,
"s": 7303,
"text": "FixRelativeToBottom − The element will maintain a fixed position relative to the band's bottom."
},
{
"code": null,
"e": 7449,
"s": 7399,
"text": "true (default) − Repeated values will be printed."
},
{
"code": null,
"e": 7494,
"s": 7449,
"text": "false − Repeated values will not be printed."
},
{
"code": null,
"e": 7545,
"s": 7494,
"text": "Following are the attributes of a report section −"
},
{
"code": null,
"e": 7678,
"s": 7545,
"text": "Height of the section specifies the height in pixels for that particular section and is very important in the overall report design."
},
{
"code": null,
"e": 7761,
"s": 7678,
"text": "A Boolean expression that determines whether the section should be printed or not."
},
{
"code": null,
"e": 8083,
"s": 7761,
"text": "A flag indicating whether the section is allowed to split when it does not fit on the current page. If true, the section will be transferred to the next page. Note that in case, the section does not fit on the next page, then the section will be split regardless of the flag's value. splitType can take following values −"
},
{
"code": null,
"e": 8318,
"s": 8083,
"text": "splitType=\"Stretch:\" Splits stretched content. If the section stretches on the current page (if the available space is less than declared height), the region that is added to the original height is allowed to split onto the next page."
},
{
"code": null,
"e": 8553,
"s": 8318,
"text": "splitType=\"Stretch:\" Splits stretched content. If the section stretches on the current page (if the available space is less than declared height), the region that is added to the original height is allowed to split onto the next page."
},
{
"code": null,
"e": 8750,
"s": 8553,
"text": "splitType=\"Prevent:\" Prevent split on first attempt. If the section does not fit on the next page, the split occurs normally, as band split prevention is effective only on the first split attempt."
},
{
"code": null,
"e": 8947,
"s": 8750,
"text": "splitType=\"Prevent:\" Prevent split on first attempt. If the section does not fit on the next page, the split occurs normally, as band split prevention is effective only on the first split attempt."
},
{
"code": null,
"e": 9062,
"s": 8947,
"text": "splitType=\"Immediate:\" Split immediately. The band is allowed to split anywhere except above, its topmost element."
},
{
"code": null,
"e": 9177,
"s": 9062,
"text": "splitType=\"Immediate:\" Split immediately. The band is allowed to split anywhere except above, its topmost element."
},
{
"code": null,
"e": 9465,
"s": 9177,
"text": "To demonstrate each section, let's write report template (jasper_report_template.jrxml). Save this file to C:\\tools\\jasperreports-5.0.1\\test directory. In this file, we would be displaying a text in each of the sections (we discussed above). The contents of the file are as given below −"
},
{
"code": null,
"e": 13128,
"s": 9465,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"300\" pageHeight = \"300\" \n columnWidth = \"300\" leftMargin = \"0\" rightMargin = \"0\" \n topMargin = \"0\" bottomMargin = \"0\" >\n\n <title>\n <band height = \"50\">\n \n <textField>\n <reportElement x = \"100\" y = \"16\" width = \"100\" height = \"20\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Title\"]]>\n </textFieldExpression>\n \n </textField>\n \n </band>\n </title>\n \n <pageHeader>\n <band height = \"40\">\n \n <textField>\n <reportElement mode = \"Opaque\" x = \"100\" y = \"10\" \n width = \"90\" height = \"20\"/>\n \n <textElement>\n <font isBold = \"true\"/>\n </textElement>\n \n <textFieldExpression>\n <![CDATA[\"Page Header\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </pageHeader>\n \n <columnHeader>\n <band height = \"40\">\n \n <textField>\n <reportElement x = \"100\" y = \"10\" width = \"90\" height = \"20\"/>\n \n <textElement>\n <font isItalic = \"true\"/>\n </textElement>\n \n <textFieldExpression>\n <![CDATA[\"Column Header\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </columnHeader>\n \n <detail>\n <band height =\"40\">\n \n <textField>\n <reportElement mode = \"Opaque\" x = \"100\" y = \"10\" \n width = \"90\" height = \"20\" backcolor = \"#99CCFF\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Report Details\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n \n <columnFooter>\n <band height = \"40\">\n \n <textField>\n <reportElement x = \"100\" y = \"10\" width = \"90\" height = \"20\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Column Footer\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </columnFooter>\n \n <pageFooter>\n <band height = \"40\">\n \n <textField>\n <reportElement x = \"100\" y = \"10\" width = \"90\" height = \"20\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Page Footer\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </pageFooter>\n \n <lastPageFooter>\n <band height = \"40\">\n \n <textField>\n <reportElement x = \"100\" y = \"10\" width = \"90\" height = \"20\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Last Page Footer\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </lastPageFooter>\n \n <summary>\n <band height = \"40\">\n \n <textField>\n <reportElement x = \"100\" y = \"10\" width = \"90\" height = \"20\"/>\n <textElement/>\n \n <textFieldExpression>\n <![CDATA[\"Summary\"]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </summary>\n\t\n</jasperReport>"
},
{
"code": null,
"e": 13304,
"s": 13128,
"text": "The java code to fill and generate the report is given below. Let's save this file JasperReportFill.java to C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint directory."
},
{
"code": null,
"e": 13918,
"s": 13304,
"text": "package com.tutorialspoint;\n\nimport net.sf.jasperreports.engine.JREmptyDataSource;\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\n\npublic class JasperReportFill {\n public static void main(String[] args) {\n String sourceFileName = \"C://tools/jasperreports-5.0.1/test/\" + \n \"jasper_report_template.jasper\";\n\n try {\n JasperFillManager.fillReportToFile(sourceFileName, null,\n new JREmptyDataSource());\n } catch (JRException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n }\n}"
},
{
"code": null,
"e": 14092,
"s": 13918,
"text": "Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields in this single record being null."
},
{
"code": null,
"e": 14279,
"s": 14092,
"text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as below."
},
{
"code": null,
"e": 14420,
"s": 14279,
"text": "The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 15509,
"s": 14420,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n \n <import file = \"baseBuild.xml\" />\n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview \n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n\t\t\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\"\n classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>"
},
{
"code": null,
"e": 15731,
"s": 15509,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −"
},
{
"code": null,
"e": 17320,
"s": 15731,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defau\n [javac] Compiling 1 source file to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFac\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnviro\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnviro\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 18 minutes 22 seconds\n"
},
{
"code": null,
"e": 17410,
"s": 17320,
"text": "As a result of above compilation, a JasperViewer window opens up as in the screen below −"
},
{
"code": null,
"e": 17761,
"s": 17410,
"text": "Here, we can see in each of the sections a text is printed. It is to be noted that as JRXML contains a <lastPageFooter> element, it will be displayed in the last page of the report instead of the <pageFooter> element being displayed. The <columnHeader> and <columnFooter> elements will only be displayed on the report, if it has more than one column."
},
{
"code": null,
"e": 17768,
"s": 17761,
"text": " Print"
},
{
"code": null,
"e": 17779,
"s": 17768,
"text": " Add Notes"
}
] |
CSS Central, Horizontal and Vertical Alignment
|
We can align an element or the content inside it by using CSS which provides various options for alignment of an element and its content horizontally, vertically or in center.
Inline-elementsInline elements or inline-block elements such as text, anchor, span, etc. can be aligned horizontally with the help of CSS text-align property.
Inline elements or inline-block elements such as text, anchor, span, etc. can be aligned horizontally with the help of CSS text-align property.
Block-level elementsBlock-level elements such as div, p, etc. can be aligned horizontally with the help of CSS margin property, but width of element should not be 100% relative to the parent as then it wouldn’t need alignment.
Block-level elements such as div, p, etc. can be aligned horizontally with the help of CSS margin property, but width of element should not be 100% relative to the parent as then it wouldn’t need alignment.
Block-level elements using float or position schemeElements can be aligned horizontally with the help of CSS float property which aligns multiple elements to either left/right and not in center or using CSS positioning scheme absolute method.
Elements can be aligned horizontally with the help of CSS float property which aligns multiple elements to either left/right and not in center or using CSS positioning scheme absolute method.
Let’s see an example of CSS horizontal alignment −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Horizontal Alignment</title>
<style>
.screen {
padding: 10px;
width: 70%;
margin: 0 auto;
background-color: #f06d06;
text-align: center;
color: white;
border-radius: 0 0 50px 50px;
border: 4px solid #000;
}
.seats span, .backSeats div{
margin: 10px;
padding: 10px;
color: white;
border: 4px solid #000;
}
.seats span{
width: 120px;
display: inline-block;
background-color: #48C9B0;
}
.left{
text-align: left;
}
.right{
text-align: right;
}
.center{
text-align: center;
}
.seats{
text-align: center;
}
.backSeats div {
background-color: #dc3545;
}
.leftFloat{
float: left;
}
.rightAbsolute{
position: absolute;
right: 150px;
}
</style>
</head>
<body>
<div class="screen">Screen</div>
<div class="seats">
<span class="left">Adam</span>
<span class="center">Martha</span>
<span class="right">Samantha</span>
<div class="backSeats">
<div class="leftFloat">Premium 1</div>
<div class="leftFloat">Premium 2</div>
<div class="rightAbsolute">Premium 3</div>
</div>
</div>
</body>
</html>
This will produce the following output −
Inline-elementsInline elements or inline-block elements such as text, anchor, etc. can be aligned vertically with the help of CSS padding, CSS line-height, or CSS vertical-align property.
Inline elements or inline-block elements such as text, anchor, etc. can be aligned vertically with the help of CSS padding, CSS line-height, or CSS vertical-align property.
Block-level elementsBlock-level elements such as div, p, etc. can be aligned vertically with the help of CSS margin property, CSS flex property along with CSS align-items, or with positioning scheme method absolute with CSS transform property.
Block-level elements such as div, p, etc. can be aligned vertically with the help of CSS margin property, CSS flex property along with CSS align-items, or with positioning scheme method absolute with CSS transform property.
Let’s see an example of CSS vertical alignment −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Horizontal Alignment</title>
<style>
.screen {
padding: 10px;
width: 70%;
margin: 0 auto;
background-color: #f06d06;
text-align: center;
color: white;
border-radius: 0 0 50px 50px;
border: 4px solid #000;
}
.seats span:not(.withPadding){
margin: 10px;
padding: 10px;
color: white;
border: 4px solid #000;
}
.seats span:not(.vertical){
height: 40px;
display: inline-block;
background-color: #48C9B0;
}
.withPadding{
padding: 20px 20px 0px;
height: 20px;
color: white;
border: 4px solid #000;
}
.vertical{
display: inline-table;
background-color: #48C9B0;
height: 40px;
}
.verticalText {
display: table-cell;
vertical-align: middle;
}
.withLineHeight{
line-height: 40px;
}
.seats{
text-align: center;
}
.backLeftSeat{
background-color: #dc3545;
max-height: 100px;
height: 70px;
margin: 20px;
width: 300px;
display: inline-block;
position: relative;
resize: vertical;
overflow: auto;
border: 4px solid #000;
}
.withPosition{
position: absolute;
top: 50%;
left: 2px;
right: 2px;
color: white;
padding: 20px;
transform: translateY(-50%);
}
.backRightSeats{
height: 122px;
width: 800px;
float: right;
display: inline-flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.withFlex {
background-color: #dc3545;
border: 4px solid #000;
margin-right: 10px;
color: white;
padding: 20px;
}
</style></head>
<body>
<div class="screen">Screen</div>
<div class="seats">
<span class="withPadding">Adam</span>
<span class="withLineHeight">Martha</span>
<span class="vertical"><p class="verticalText">Samantha</p></span>
<div>
<div class="backLeftSeat">
<div class="withPosition">Premium Readjustable Sofa</div>
</div>
<div class="backRightSeats">
<div class="withFlex">Premium Solo 1</div>
<div class="withFlex">Premium Solo 2</div>
<div class="withFlex">Premium Solo 3</div>
</div>
</div>
</body>
</html>
This will produce the following output −
When div is not adjusted
When div is adjusted
Central Alignment
We can align elements centrally with methods mentioned above in Horizontal, and Vertical alignment.
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "We can align an element or the content inside it by using CSS which provides various options for alignment of an element and its content horizontally, vertically or in center."
},
{
"code": null,
"e": 1397,
"s": 1238,
"text": "Inline-elementsInline elements or inline-block elements such as text, anchor, span, etc. can be aligned horizontally with the help of CSS text-align property."
},
{
"code": null,
"e": 1541,
"s": 1397,
"text": "Inline elements or inline-block elements such as text, anchor, span, etc. can be aligned horizontally with the help of CSS text-align property."
},
{
"code": null,
"e": 1768,
"s": 1541,
"text": "Block-level elementsBlock-level elements such as div, p, etc. can be aligned horizontally with the help of CSS margin property, but width of element should not be 100% relative to the parent as then it wouldn’t need alignment."
},
{
"code": null,
"e": 1975,
"s": 1768,
"text": "Block-level elements such as div, p, etc. can be aligned horizontally with the help of CSS margin property, but width of element should not be 100% relative to the parent as then it wouldn’t need alignment."
},
{
"code": null,
"e": 2218,
"s": 1975,
"text": "Block-level elements using float or position schemeElements can be aligned horizontally with the help of CSS float property which aligns multiple elements to either left/right and not in center or using CSS positioning scheme absolute method."
},
{
"code": null,
"e": 2410,
"s": 2218,
"text": "Elements can be aligned horizontally with the help of CSS float property which aligns multiple elements to either left/right and not in center or using CSS positioning scheme absolute method."
},
{
"code": null,
"e": 2461,
"s": 2410,
"text": "Let’s see an example of CSS horizontal alignment −"
},
{
"code": null,
"e": 2472,
"s": 2461,
"text": " Live Demo"
},
{
"code": null,
"e": 3562,
"s": 2472,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Horizontal Alignment</title>\n<style>\n.screen {\n padding: 10px;\n width: 70%;\n margin: 0 auto;\n background-color: #f06d06;\n text-align: center;\n color: white;\n border-radius: 0 0 50px 50px;\n border: 4px solid #000;\n}\n.seats span, .backSeats div{\n margin: 10px;\n padding: 10px;\n color: white;\n border: 4px solid #000;\n}\n.seats span{\n width: 120px;\n display: inline-block;\n background-color: #48C9B0;\n}\n.left{\n text-align: left;\n}\n.right{\n text-align: right;\n}\n.center{\n text-align: center;\n}\n.seats{\n text-align: center;\n}\n.backSeats div {\n background-color: #dc3545;\n}\n.leftFloat{\n float: left;\n}\n.rightAbsolute{\n position: absolute;\n right: 150px;\n}\n</style>\n</head>\n<body>\n<div class=\"screen\">Screen</div>\n<div class=\"seats\">\n<span class=\"left\">Adam</span>\n<span class=\"center\">Martha</span>\n<span class=\"right\">Samantha</span>\n<div class=\"backSeats\">\n<div class=\"leftFloat\">Premium 1</div>\n<div class=\"leftFloat\">Premium 2</div>\n<div class=\"rightAbsolute\">Premium 3</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 3603,
"s": 3562,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3791,
"s": 3603,
"text": "Inline-elementsInline elements or inline-block elements such as text, anchor, etc. can be aligned vertically with the help of CSS padding, CSS line-height, or CSS vertical-align property."
},
{
"code": null,
"e": 3964,
"s": 3791,
"text": "Inline elements or inline-block elements such as text, anchor, etc. can be aligned vertically with the help of CSS padding, CSS line-height, or CSS vertical-align property."
},
{
"code": null,
"e": 4208,
"s": 3964,
"text": "Block-level elementsBlock-level elements such as div, p, etc. can be aligned vertically with the help of CSS margin property, CSS flex property along with CSS align-items, or with positioning scheme method absolute with CSS transform property."
},
{
"code": null,
"e": 4432,
"s": 4208,
"text": "Block-level elements such as div, p, etc. can be aligned vertically with the help of CSS margin property, CSS flex property along with CSS align-items, or with positioning scheme method absolute with CSS transform property."
},
{
"code": null,
"e": 4481,
"s": 4432,
"text": "Let’s see an example of CSS vertical alignment −"
},
{
"code": null,
"e": 4492,
"s": 4481,
"text": " Live Demo"
},
{
"code": null,
"e": 6508,
"s": 4492,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Horizontal Alignment</title>\n<style>\n.screen {\n padding: 10px;\n width: 70%;\n margin: 0 auto;\n background-color: #f06d06;\n text-align: center;\n color: white;\n border-radius: 0 0 50px 50px;\n border: 4px solid #000;\n}\n.seats span:not(.withPadding){\n margin: 10px;\n padding: 10px;\n color: white;\n border: 4px solid #000;\n}\n.seats span:not(.vertical){\n height: 40px;\n display: inline-block;\n background-color: #48C9B0;\n}\n.withPadding{\n padding: 20px 20px 0px;\n height: 20px;\n color: white;\n border: 4px solid #000;\n}\n.vertical{\n display: inline-table;\n background-color: #48C9B0;\n height: 40px;\n}\n.verticalText {\n display: table-cell;\n vertical-align: middle;\n}\n.withLineHeight{\n line-height: 40px;\n}\n.seats{\n text-align: center;\n}\n.backLeftSeat{\n background-color: #dc3545;\n max-height: 100px;\n height: 70px;\n margin: 20px;\n width: 300px;\n display: inline-block;\n position: relative;\n resize: vertical;\n overflow: auto;\n border: 4px solid #000;\n}\n.withPosition{\n position: absolute;\n top: 50%;\n left: 2px;\n right: 2px;\n color: white;\n padding: 20px;\n transform: translateY(-50%);\n}\n.backRightSeats{\n height: 122px;\n width: 800px;\n float: right;\n display: inline-flex;\n flex-direction: row;\n justify-content: center;\n align-items: center;\n}\n.withFlex {\n background-color: #dc3545;\n border: 4px solid #000;\n margin-right: 10px;\n color: white;\n padding: 20px;\n}\n</style></head>\n<body>\n<div class=\"screen\">Screen</div>\n<div class=\"seats\">\n<span class=\"withPadding\">Adam</span>\n<span class=\"withLineHeight\">Martha</span>\n<span class=\"vertical\"><p class=\"verticalText\">Samantha</p></span>\n<div>\n<div class=\"backLeftSeat\">\n<div class=\"withPosition\">Premium Readjustable Sofa</div>\n</div>\n<div class=\"backRightSeats\">\n<div class=\"withFlex\">Premium Solo 1</div>\n<div class=\"withFlex\">Premium Solo 2</div>\n<div class=\"withFlex\">Premium Solo 3</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 6549,
"s": 6508,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 6574,
"s": 6549,
"text": "When div is not adjusted"
},
{
"code": null,
"e": 6595,
"s": 6574,
"text": "When div is adjusted"
},
{
"code": null,
"e": 6613,
"s": 6595,
"text": "Central Alignment"
},
{
"code": null,
"e": 6713,
"s": 6613,
"text": "We can align elements centrally with methods mentioned above in Horizontal, and Vertical alignment."
}
] |
Traffic sign recognition using deep neural networks | by Piyush Malhotra | Towards Data Science
|
by Piyush Malhotra, Puneet and Tanishq Chamola
In today’s world as the number of vehicles are increasing so are the road accidents and according to reports, India is on 1st spot in most number of accidents in a country. This is caused due to many reasons such as poor enforcement of laws, carelessness etc. One of the reason is that people don’t recognize or follow traffic sign boards. So we have made a traffic sign recognizer which can inform the driver of the vehicle about the traffic sign coming ahead and to follow it. This can reduce the road accidents.
Convolutional neural networks are a part of deep learning and extensively used in image recogntion. These convolutional neural networks consists of several layers. First a Conv2D layer is used for feature extraction with the help of filters. Number of filters are generally in power of 2 like 32, 64 or 128. An activation function is used in this layer. Generally ReLU(Rectified Linear Unit) activation function is used. ReLU function is defined as maximum(0, x).
Next is the max pooling layer which is used reduce the dimensions of the image. This is done to reduce the computation power required for processing the image. Third is dropout layer. This dropout layer is used to prevent overfitting and to reduce the complexity of the model. In this layer some neurons are removed randomly.
The combination of first 3 layers is called feature learning phase. These 3 layers are used multiple times to improve the training.
Fourth is the flatten layer which converts the 2-D data into a long 1-D vector of features for a fully connected layer that can be fed into the neural network.
The last layer is the dense layer which is used as a output layer. The last layer has number of nodes same as the number of classes. The last dense layer uses softmax activation function. Softmax function gives the probability value (between 0 and 1) so that the model can predict which class has the highest probability.
We have taken the dataset from German Traffic Sign Benchmark single-image classification challenge held at the International Joint Conference on Neural Networks (IJCNN) 2011 . Link — kaggle.com/meowmeowmeowmeowmeow/gtsrb-german-traffic-sign
The dataset consists of 39,209 traffic sign images.
We will be using Python language for this. First we will import the neccessary libraries such as keras for building the main model, sklearn for splitting the training and test data, PIL for converting the images into array of numbers and other libraries such as pandas, numpy , matplotlib and tensorflow.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 import tensorflow as tf from PIL import Image ]import os from sklearn.model_selection import train_test_splitfrom keras.utils import to_categorical from keras.models import Sequential, load_modelfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropoutimport tqdm import warnings
We will retrieve the images and their labels. Then resize the images to (30,30) as all images should have same size for recognition. Then convert the images into numpy array.
data = []labels = []classes = 43for i in range(classes): path = os.path.join(os.getcwd(),'train',str(i)) images = os.listdir(path) for j in images: try: image = Image.open(path + '\\'+ j) image = image.resize((30,30)) image = np.array(image) data.append(image) labels.append(i) except: print("Error loading image")#Converting lists into numpy arrays bcoz its faster and takes lesser #memorydata = np.array(data)labels = np.array(labels)print(data.shape, labels.shape)
Split the dataset into train and test. 80% train data and 20% test data.
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=68)print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
For building the we will use sequential model from keras library. Then we will add the layers to make convolutional neural network. In the first 2 Conv2D layers we have used 32 filters and the kernel size is (5,5).
In the MaxPool2D layer we have kept pool size (2,2) which means it will select the maximum value of every 2 x 2 area of the image. By doing this dimensions of the image will reduce by factor of 2. In dropout layer we have kept dropout rate = 0.25 that means 25% of neurons are removed randomly.
We apply these 3 layers again with some change in parameters. Then we apply flatten layer to convert 2-D data to 1-D vector. This layer is followed by dense layer, dropout layer and dense layer again. The last dense layer outputs 43 nodes as the traffic signs are divided into 43 categories in our dataset. This layer uses the softmax activation function which gives probability value and predicts which of the 43 options has the highest probability.
model = Sequential()model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))model.add(MaxPool2D(pool_size=(2, 2)))model.add(Dropout(rate=0.25))model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))model.add(MaxPool2D(pool_size=(2, 2)))model.add(Dropout(rate=0.25))model.add(Flatten())model.add(Dense(256, activation='relu'))model.add(Dropout(rate=0.5))model.add(Dense(43, activation='softmax'))
We will compile the model and apply it using fit function. The batch size will be 32. Then we will plot the graphs for accuracy and loss. We got average validation accuracy of 97.6% and average training accuracy of 93.3%.
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])history = model.fit(X_train, y_train, batch_size=32, epochs=2, validation_data=(X_test, y_test))model.save("Trafic_signs_model.h5")#plotting graphs for accuracy plt.figure(0)plt.plot(history.history['accuracy'], label='training accuracy')plt.plot(history.history['val_accuracy'], label='val accuracy')plt.title('Accuracy')plt.xlabel('epochs')plt.ylabel('accuracy')plt.legend()plt.show()#plotting graphs for loss plt.figure(1)plt.plot(history.history['loss'], label='training loss')plt.plot(history.history['val_loss'], label='val loss')plt.title('Loss')plt.xlabel('epochs')plt.ylabel('loss')plt.legend()plt.show()
We got a accuracy of 94.7% on test set.
from sklearn.metrics import accuracy_scorey_test = pd.read_csv('Test.csv')labels = y_test["ClassId"].valuesimgs = y_test["Path"].valuesdata=[]for img in imgs: image = Image.open(img) image = image.resize((30,30)) data.append(np.array(image))X_test=np.array(data)pred = model.predict_classes(X_test)#Accuracy with the test dataprint(accuracy_score(labels, pred))
Now as the model is ready, so we can make a Graphical user inetrface(GUI). We have used tkinter library to make the GUI. Code of GUI :
So we got to know about convolutional networks and how they can be used in image recognition. We made a traffic sign recognizer with the use of convolutional neural networks and got an accuracy of 97.6% on validation set and 94.7% on test set.
The complete code is available in the following github repository: Traffic sign recognition
|
[
{
"code": null,
"e": 218,
"s": 171,
"text": "by Piyush Malhotra, Puneet and Tanishq Chamola"
},
{
"code": null,
"e": 733,
"s": 218,
"text": "In today’s world as the number of vehicles are increasing so are the road accidents and according to reports, India is on 1st spot in most number of accidents in a country. This is caused due to many reasons such as poor enforcement of laws, carelessness etc. One of the reason is that people don’t recognize or follow traffic sign boards. So we have made a traffic sign recognizer which can inform the driver of the vehicle about the traffic sign coming ahead and to follow it. This can reduce the road accidents."
},
{
"code": null,
"e": 1197,
"s": 733,
"text": "Convolutional neural networks are a part of deep learning and extensively used in image recogntion. These convolutional neural networks consists of several layers. First a Conv2D layer is used for feature extraction with the help of filters. Number of filters are generally in power of 2 like 32, 64 or 128. An activation function is used in this layer. Generally ReLU(Rectified Linear Unit) activation function is used. ReLU function is defined as maximum(0, x)."
},
{
"code": null,
"e": 1523,
"s": 1197,
"text": "Next is the max pooling layer which is used reduce the dimensions of the image. This is done to reduce the computation power required for processing the image. Third is dropout layer. This dropout layer is used to prevent overfitting and to reduce the complexity of the model. In this layer some neurons are removed randomly."
},
{
"code": null,
"e": 1655,
"s": 1523,
"text": "The combination of first 3 layers is called feature learning phase. These 3 layers are used multiple times to improve the training."
},
{
"code": null,
"e": 1815,
"s": 1655,
"text": "Fourth is the flatten layer which converts the 2-D data into a long 1-D vector of features for a fully connected layer that can be fed into the neural network."
},
{
"code": null,
"e": 2137,
"s": 1815,
"text": "The last layer is the dense layer which is used as a output layer. The last layer has number of nodes same as the number of classes. The last dense layer uses softmax activation function. Softmax function gives the probability value (between 0 and 1) so that the model can predict which class has the highest probability."
},
{
"code": null,
"e": 2378,
"s": 2137,
"text": "We have taken the dataset from German Traffic Sign Benchmark single-image classification challenge held at the International Joint Conference on Neural Networks (IJCNN) 2011 . Link — kaggle.com/meowmeowmeowmeowmeow/gtsrb-german-traffic-sign"
},
{
"code": null,
"e": 2430,
"s": 2378,
"text": "The dataset consists of 39,209 traffic sign images."
},
{
"code": null,
"e": 2735,
"s": 2430,
"text": "We will be using Python language for this. First we will import the neccessary libraries such as keras for building the main model, sklearn for splitting the training and test data, PIL for converting the images into array of numbers and other libraries such as pandas, numpy , matplotlib and tensorflow."
},
{
"code": null,
"e": 3323,
"s": 2735,
"text": "import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 import tensorflow as tf from PIL import Image ]import os from sklearn.model_selection import train_test_splitfrom keras.utils import to_categorical from keras.models import Sequential, load_modelfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropoutimport tqdm import warnings"
},
{
"code": null,
"e": 3498,
"s": 3323,
"text": "We will retrieve the images and their labels. Then resize the images to (30,30) as all images should have same size for recognition. Then convert the images into numpy array."
},
{
"code": null,
"e": 4059,
"s": 3498,
"text": "data = []labels = []classes = 43for i in range(classes): path = os.path.join(os.getcwd(),'train',str(i)) images = os.listdir(path) for j in images: try: image = Image.open(path + '\\\\'+ j) image = image.resize((30,30)) image = np.array(image) data.append(image) labels.append(i) except: print(\"Error loading image\")#Converting lists into numpy arrays bcoz its faster and takes lesser #memorydata = np.array(data)labels = np.array(labels)print(data.shape, labels.shape)"
},
{
"code": null,
"e": 4132,
"s": 4059,
"text": "Split the dataset into train and test. 80% train data and 20% test data."
},
{
"code": null,
"e": 4293,
"s": 4132,
"text": "X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=68)print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)"
},
{
"code": null,
"e": 4508,
"s": 4293,
"text": "For building the we will use sequential model from keras library. Then we will add the layers to make convolutional neural network. In the first 2 Conv2D layers we have used 32 filters and the kernel size is (5,5)."
},
{
"code": null,
"e": 4803,
"s": 4508,
"text": "In the MaxPool2D layer we have kept pool size (2,2) which means it will select the maximum value of every 2 x 2 area of the image. By doing this dimensions of the image will reduce by factor of 2. In dropout layer we have kept dropout rate = 0.25 that means 25% of neurons are removed randomly."
},
{
"code": null,
"e": 5254,
"s": 4803,
"text": "We apply these 3 layers again with some change in parameters. Then we apply flatten layer to convert 2-D data to 1-D vector. This layer is followed by dense layer, dropout layer and dense layer again. The last dense layer outputs 43 nodes as the traffic signs are divided into 43 categories in our dataset. This layer uses the softmax activation function which gives probability value and predicts which of the 43 options has the highest probability."
},
{
"code": null,
"e": 5840,
"s": 5254,
"text": "model = Sequential()model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))model.add(MaxPool2D(pool_size=(2, 2)))model.add(Dropout(rate=0.25))model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))model.add(MaxPool2D(pool_size=(2, 2)))model.add(Dropout(rate=0.25))model.add(Flatten())model.add(Dense(256, activation='relu'))model.add(Dropout(rate=0.5))model.add(Dense(43, activation='softmax'))"
},
{
"code": null,
"e": 6062,
"s": 5840,
"text": "We will compile the model and apply it using fit function. The batch size will be 32. Then we will plot the graphs for accuracy and loss. We got average validation accuracy of 97.6% and average training accuracy of 93.3%."
},
{
"code": null,
"e": 6762,
"s": 6062,
"text": "model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])history = model.fit(X_train, y_train, batch_size=32, epochs=2, validation_data=(X_test, y_test))model.save(\"Trafic_signs_model.h5\")#plotting graphs for accuracy plt.figure(0)plt.plot(history.history['accuracy'], label='training accuracy')plt.plot(history.history['val_accuracy'], label='val accuracy')plt.title('Accuracy')plt.xlabel('epochs')plt.ylabel('accuracy')plt.legend()plt.show()#plotting graphs for loss plt.figure(1)plt.plot(history.history['loss'], label='training loss')plt.plot(history.history['val_loss'], label='val loss')plt.title('Loss')plt.xlabel('epochs')plt.ylabel('loss')plt.legend()plt.show()"
},
{
"code": null,
"e": 6802,
"s": 6762,
"text": "We got a accuracy of 94.7% on test set."
},
{
"code": null,
"e": 7173,
"s": 6802,
"text": "from sklearn.metrics import accuracy_scorey_test = pd.read_csv('Test.csv')labels = y_test[\"ClassId\"].valuesimgs = y_test[\"Path\"].valuesdata=[]for img in imgs: image = Image.open(img) image = image.resize((30,30)) data.append(np.array(image))X_test=np.array(data)pred = model.predict_classes(X_test)#Accuracy with the test dataprint(accuracy_score(labels, pred))"
},
{
"code": null,
"e": 7308,
"s": 7173,
"text": "Now as the model is ready, so we can make a Graphical user inetrface(GUI). We have used tkinter library to make the GUI. Code of GUI :"
},
{
"code": null,
"e": 7552,
"s": 7308,
"text": "So we got to know about convolutional networks and how they can be used in image recognition. We made a traffic sign recognizer with the use of convolutional neural networks and got an accuracy of 97.6% on validation set and 94.7% on test set."
}
] |
How do I use PIL with Tkinter?
|
The PIL or Pillow package in Python provides a way to process images in a program. We can open an image, manipulate the image for different use, and can use it to visualize the data as well. In order to use the PIL package in Tkinter, you've to install the Python Pillow library in your environment.
To install Pillow, just type pip install pillow. Once the installation has been successful, you can import the module in your project and use it for further implementation.
In this example, we've displayed an image in the canvas widget using Python Pillow package.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()
# Load the image
img=ImageTk.PhotoImage(file="opera.jpg")
# Add the image in the canvas
canvas.create_image(350, 200, image=img, anchor="center")
win.mainloop()
If we run the above code, it will display an image in the window.
|
[
{
"code": null,
"e": 1362,
"s": 1062,
"text": "The PIL or Pillow package in Python provides a way to process images in a program. We can open an image, manipulate the image for different use, and can use it to visualize the data as well. In order to use the PIL package in Tkinter, you've to install the Python Pillow library in your environment."
},
{
"code": null,
"e": 1535,
"s": 1362,
"text": "To install Pillow, just type pip install pillow. Once the installation has been successful, you can import the module in your project and use it for further implementation."
},
{
"code": null,
"e": 1627,
"s": 1535,
"text": "In this example, we've displayed an image in the canvas widget using Python Pillow package."
},
{
"code": null,
"e": 2070,
"s": 1627,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a canvas widget\ncanvas=Canvas(win, width=700, height=350)\ncanvas.pack()\n\n# Load the image\nimg=ImageTk.PhotoImage(file=\"opera.jpg\")\n\n# Add the image in the canvas\ncanvas.create_image(350, 200, image=img, anchor=\"center\")\n\nwin.mainloop()"
},
{
"code": null,
"e": 2136,
"s": 2070,
"text": "If we run the above code, it will display an image in the window."
}
] |
Apache Pig - Cross Operator
|
The CROSS operator computes the cross-product of two or more relations. This chapter explains with example how to use the cross operator in Pig Latin.
Given below is the syntax of the CROSS operator.
grunt> Relation3_name = CROSS Relation1_name, Relation2_name;
Assume that we have two files namely customers.txt and orders.txt in the /pig_data/ directory of HDFS as shown below.
customers.txt
1,Ramesh,32,Ahmedabad,2000.00
2,Khilan,25,Delhi,1500.00
3,kaushik,23,Kota,2000.00
4,Chaitali,25,Mumbai,6500.00
5,Hardik,27,Bhopal,8500.00
6,Komal,22,MP,4500.00
7,Muffy,24,Indore,10000.00
orders.txt
102,2009-10-08 00:00:00,3,3000
100,2009-10-08 00:00:00,3,1500
101,2009-11-20 00:00:00,2,1560
103,2008-05-20 00:00:00,4,2060
And we have loaded these two files into Pig with the relations customers and orders as shown below.
grunt> customers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(',')
as (id:int, name:chararray, age:int, address:chararray, salary:int);
grunt> orders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(',')
as (oid:int, date:chararray, customer_id:int, amount:int);
Let us now get the cross-product of these two relations using the cross operator on these two relations as shown below.
grunt> cross_data = CROSS customers, orders;
Verify the relation cross_data using the DUMP operator as shown below.
grunt> Dump cross_data;
It will produce the following output, displaying the contents of the relation cross_data.
(7,Muffy,24,Indore,10000,103,2008-05-20 00:00:00,4,2060)
(7,Muffy,24,Indore,10000,101,2009-11-20 00:00:00,2,1560)
(7,Muffy,24,Indore,10000,100,2009-10-08 00:00:00,3,1500)
(7,Muffy,24,Indore,10000,102,2009-10-08 00:00:00,3,3000)
(6,Komal,22,MP,4500,103,2008-05-20 00:00:00,4,2060)
(6,Komal,22,MP,4500,101,2009-11-20 00:00:00,2,1560)
(6,Komal,22,MP,4500,100,2009-10-08 00:00:00,3,1500)
(6,Komal,22,MP,4500,102,2009-10-08 00:00:00,3,3000)
(5,Hardik,27,Bhopal,8500,103,2008-05-20 00:00:00,4,2060)
(5,Hardik,27,Bhopal,8500,101,2009-11-20 00:00:00,2,1560)
(5,Hardik,27,Bhopal,8500,100,2009-10-08 00:00:00,3,1500)
(5,Hardik,27,Bhopal,8500,102,2009-10-08 00:00:00,3,3000)
(4,Chaitali,25,Mumbai,6500,103,2008-05-20 00:00:00,4,2060)
(4,Chaitali,25,Mumbai,6500,101,2009-20 00:00:00,4,2060)
(2,Khilan,25,Delhi,1500,101,2009-11-20 00:00:00,2,1560)
(2,Khilan,25,Delhi,1500,100,2009-10-08 00:00:00,3,1500)
(2,Khilan,25,Delhi,1500,102,2009-10-08 00:00:00,3,3000)
(1,Ramesh,32,Ahmedabad,2000,103,2008-05-20 00:00:00,4,2060)
(1,Ramesh,32,Ahmedabad,2000,101,2009-11-20 00:00:00,2,1560)
(1,Ramesh,32,Ahmedabad,2000,100,2009-10-08 00:00:00,3,1500)
(1,Ramesh,32,Ahmedabad,2000,102,2009-10-08 00:00:00,3,3000)-11-20 00:00:00,2,1560)
(4,Chaitali,25,Mumbai,6500,100,2009-10-08 00:00:00,3,1500)
(4,Chaitali,25,Mumbai,6500,102,2009-10-08 00:00:00,3,3000)
(3,kaushik,23,Kota,2000,103,2008-05-20 00:00:00,4,2060)
(3,kaushik,23,Kota,2000,101,2009-11-20 00:00:00,2,1560)
(3,kaushik,23,Kota,2000,100,2009-10-08 00:00:00,3,1500)
(3,kaushik,23,Kota,2000,102,2009-10-08 00:00:00,3,3000)
(2,Khilan,25,Delhi,1500,103,2008-05-20 00:00:00,4,2060)
(2,Khilan,25,Delhi,1500,101,2009-11-20 00:00:00,2,1560)
(2,Khilan,25,Delhi,1500,100,2009-10-08 00:00:00,3,1500)
(2,Khilan,25,Delhi,1500,102,2009-10-08 00:00:00,3,3000)
(1,Ramesh,32,Ahmedabad,2000,103,2008-05-20 00:00:00,4,2060)
(1,Ramesh,32,Ahmedabad,2000,101,2009-11-20 00:00:00,2,1560)
(1,Ramesh,32,Ahmedabad,2000,100,2009-10-08 00:00:00,3,1500)
(1,Ramesh,32,Ahmedabad,2000,102,2009-10-08 00:00:00,3,3000)
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2835,
"s": 2684,
"text": "The CROSS operator computes the cross-product of two or more relations. This chapter explains with example how to use the cross operator in Pig Latin."
},
{
"code": null,
"e": 2884,
"s": 2835,
"text": "Given below is the syntax of the CROSS operator."
},
{
"code": null,
"e": 2947,
"s": 2884,
"text": "grunt> Relation3_name = CROSS Relation1_name, Relation2_name;\n"
},
{
"code": null,
"e": 3065,
"s": 2947,
"text": "Assume that we have two files namely customers.txt and orders.txt in the /pig_data/ directory of HDFS as shown below."
},
{
"code": null,
"e": 3079,
"s": 3065,
"text": "customers.txt"
},
{
"code": null,
"e": 3267,
"s": 3079,
"text": "1,Ramesh,32,Ahmedabad,2000.00\n2,Khilan,25,Delhi,1500.00\n3,kaushik,23,Kota,2000.00\n4,Chaitali,25,Mumbai,6500.00\n5,Hardik,27,Bhopal,8500.00\n6,Komal,22,MP,4500.00\n7,Muffy,24,Indore,10000.00\n"
},
{
"code": null,
"e": 3278,
"s": 3267,
"text": "orders.txt"
},
{
"code": null,
"e": 3403,
"s": 3278,
"text": "102,2009-10-08 00:00:00,3,3000\n100,2009-10-08 00:00:00,3,1500\n101,2009-11-20 00:00:00,2,1560\n103,2008-05-20 00:00:00,4,2060\n"
},
{
"code": null,
"e": 3503,
"s": 3403,
"text": "And we have loaded these two files into Pig with the relations customers and orders as shown below."
},
{
"code": null,
"e": 3820,
"s": 3503,
"text": "grunt> customers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(',')\n as (id:int, name:chararray, age:int, address:chararray, salary:int);\n \ngrunt> orders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(',')\n as (oid:int, date:chararray, customer_id:int, amount:int);"
},
{
"code": null,
"e": 3940,
"s": 3820,
"text": "Let us now get the cross-product of these two relations using the cross operator on these two relations as shown below."
},
{
"code": null,
"e": 3985,
"s": 3940,
"text": "grunt> cross_data = CROSS customers, orders;"
},
{
"code": null,
"e": 4056,
"s": 3985,
"text": "Verify the relation cross_data using the DUMP operator as shown below."
},
{
"code": null,
"e": 4080,
"s": 4056,
"text": "grunt> Dump cross_data;"
},
{
"code": null,
"e": 4170,
"s": 4080,
"text": "It will produce the following output, displaying the contents of the relation cross_data."
},
{
"code": null,
"e": 6222,
"s": 4170,
"text": "(7,Muffy,24,Indore,10000,103,2008-05-20 00:00:00,4,2060) \n(7,Muffy,24,Indore,10000,101,2009-11-20 00:00:00,2,1560) \n(7,Muffy,24,Indore,10000,100,2009-10-08 00:00:00,3,1500) \n(7,Muffy,24,Indore,10000,102,2009-10-08 00:00:00,3,3000) \n(6,Komal,22,MP,4500,103,2008-05-20 00:00:00,4,2060) \n(6,Komal,22,MP,4500,101,2009-11-20 00:00:00,2,1560) \n(6,Komal,22,MP,4500,100,2009-10-08 00:00:00,3,1500) \n(6,Komal,22,MP,4500,102,2009-10-08 00:00:00,3,3000) \n(5,Hardik,27,Bhopal,8500,103,2008-05-20 00:00:00,4,2060) \n(5,Hardik,27,Bhopal,8500,101,2009-11-20 00:00:00,2,1560) \n(5,Hardik,27,Bhopal,8500,100,2009-10-08 00:00:00,3,1500) \n(5,Hardik,27,Bhopal,8500,102,2009-10-08 00:00:00,3,3000) \n(4,Chaitali,25,Mumbai,6500,103,2008-05-20 00:00:00,4,2060) \n(4,Chaitali,25,Mumbai,6500,101,2009-20 00:00:00,4,2060) \n(2,Khilan,25,Delhi,1500,101,2009-11-20 00:00:00,2,1560) \n(2,Khilan,25,Delhi,1500,100,2009-10-08 00:00:00,3,1500) \n(2,Khilan,25,Delhi,1500,102,2009-10-08 00:00:00,3,3000) \n(1,Ramesh,32,Ahmedabad,2000,103,2008-05-20 00:00:00,4,2060) \n(1,Ramesh,32,Ahmedabad,2000,101,2009-11-20 00:00:00,2,1560) \n(1,Ramesh,32,Ahmedabad,2000,100,2009-10-08 00:00:00,3,1500) \n(1,Ramesh,32,Ahmedabad,2000,102,2009-10-08 00:00:00,3,3000)-11-20 00:00:00,2,1560) \n(4,Chaitali,25,Mumbai,6500,100,2009-10-08 00:00:00,3,1500) \n(4,Chaitali,25,Mumbai,6500,102,2009-10-08 00:00:00,3,3000) \n(3,kaushik,23,Kota,2000,103,2008-05-20 00:00:00,4,2060) \n(3,kaushik,23,Kota,2000,101,2009-11-20 00:00:00,2,1560) \n(3,kaushik,23,Kota,2000,100,2009-10-08 00:00:00,3,1500) \n(3,kaushik,23,Kota,2000,102,2009-10-08 00:00:00,3,3000) \n(2,Khilan,25,Delhi,1500,103,2008-05-20 00:00:00,4,2060) \n(2,Khilan,25,Delhi,1500,101,2009-11-20 00:00:00,2,1560) \n(2,Khilan,25,Delhi,1500,100,2009-10-08 00:00:00,3,1500)\n(2,Khilan,25,Delhi,1500,102,2009-10-08 00:00:00,3,3000) \n(1,Ramesh,32,Ahmedabad,2000,103,2008-05-20 00:00:00,4,2060) \n(1,Ramesh,32,Ahmedabad,2000,101,2009-11-20 00:00:00,2,1560) \n(1,Ramesh,32,Ahmedabad,2000,100,2009-10-08 00:00:00,3,1500) \n(1,Ramesh,32,Ahmedabad,2000,102,2009-10-08 00:00:00,3,3000) \n"
},
{
"code": null,
"e": 6257,
"s": 6222,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6276,
"s": 6257,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6311,
"s": 6276,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6332,
"s": 6311,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6365,
"s": 6332,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6378,
"s": 6365,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6413,
"s": 6378,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6431,
"s": 6413,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6464,
"s": 6431,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6482,
"s": 6464,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6515,
"s": 6482,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6533,
"s": 6515,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6540,
"s": 6533,
"text": " Print"
},
{
"code": null,
"e": 6551,
"s": 6540,
"text": " Add Notes"
}
] |
Java program to find the percentage of uppercase, lowercase, digits and special characters in a String
|
Convert the given string into an array of characters for each character of the array verify whether it is upper case, lower case, digit or, any other character using isUpperCase(), isLowerCase(), isDigit() method of the Character class.
Live Demo
public class Sample2 {
public static void main(String args[]) {
String data = "Hello HOW are you MR 51";
char [] charArray = data.toCharArray();
int upper = 0;
int lower = 0;
int digit = 0;
int others = 0;
int totalChars = data.length();
for(int i=0; i<data.length(); i++) {
if (Character.isUpperCase(charArray[i])) {
upper++;
} else if(Character.isLowerCase(charArray[i])) {
lower++;
} else if(Character.isDigit(charArray[i])){
digit++;
} else {
others++;
}
}
System.out.println("Total length of the string :"+totalChars);
System.out.println("Upper case :"+upper);
System.out.println("Percentage of upper case letters: "+(upper*100)/totalChars);
System.out.println("Lower case :"+lower);
System.out.println("Percentage of lower case letters:"+(lower*100)/totalChars);
System.out.println("Digit :"+digit);
System.out.println("Percentage of digits :"+(digit*100)/totalChars);
System.out.println("Others :"+others);
System.out.println("Percentage of other characters :"+(others*100)/totalChars);
}
}
Total length of the string :23
Upper case :6
Percentage of upper case letters: 26
Lower case :10
Percentage of lower case letters:43
Digit :2
Percentage of digits :8
Others :5
Percentage of other characters :21
|
[
{
"code": null,
"e": 1299,
"s": 1062,
"text": "Convert the given string into an array of characters for each character of the array verify whether it is upper case, lower case, digit or, any other character using isUpperCase(), isLowerCase(), isDigit() method of the Character class."
},
{
"code": null,
"e": 1309,
"s": 1299,
"text": "Live Demo"
},
{
"code": null,
"e": 2515,
"s": 1309,
"text": "public class Sample2 {\n public static void main(String args[]) {\n String data = \"Hello HOW are you MR 51\";\n char [] charArray = data.toCharArray();\n int upper = 0;\n int lower = 0;\n int digit = 0;\n int others = 0;\n\n int totalChars = data.length();\n for(int i=0; i<data.length(); i++) {\n if (Character.isUpperCase(charArray[i])) {\n upper++;\n } else if(Character.isLowerCase(charArray[i])) {\n lower++;\n } else if(Character.isDigit(charArray[i])){\n digit++;\n } else {\n others++;\n }\n }\n System.out.println(\"Total length of the string :\"+totalChars);\n System.out.println(\"Upper case :\"+upper);\n System.out.println(\"Percentage of upper case letters: \"+(upper*100)/totalChars);\n System.out.println(\"Lower case :\"+lower);\n System.out.println(\"Percentage of lower case letters:\"+(lower*100)/totalChars);\n System.out.println(\"Digit :\"+digit);\n System.out.println(\"Percentage of digits :\"+(digit*100)/totalChars);\n System.out.println(\"Others :\"+others);\n System.out.println(\"Percentage of other characters :\"+(others*100)/totalChars);\n }\n}"
},
{
"code": null,
"e": 2726,
"s": 2515,
"text": "Total length of the string :23\nUpper case :6\nPercentage of upper case letters: 26\nLower case :10\nPercentage of lower case letters:43\nDigit :2\nPercentage of digits :8\nOthers :5\nPercentage of other characters :21"
}
] |
Program to print hollow pyramid, diamond pattern and their modifications
|
12 Jul, 2022
For Prerequisite : Loops, If Else Statement1. Hollow pyramid/triangle pattern The pattern is similar to pyramid pattern. The only difference is, we will replace all internal ‘#’ or ‘*’ characters by space character and we will print 2*N-1 (N = number of rows in pattern) ‘#’ or ‘*’ characters in last row. Examples:
Input: n=6
Output:
#
# #
# #
# #
# #
# #
###########
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.
C++14
Java
Python
PHP
Javascript
// CPP program to print a hollow pyramid pattern#include <iostream>using namespace std;void printPattern(int);int main(){ int n = 6; printPattern(n);}void printPattern(int n){ int i, j, k = 0; for (i = 1; i <= n; i++) // row=6 { // Print spaces for (j = i; j < n; j++) { cout << " "; } // Print # while (k != (2 * i - 1)) { if (k == 0 || k == 2 * i - 2) cout << "#"; else cout << " "; k++; } k = 0; cout << endl; // print next row } // print last row for (i = 0; i < 2 * n - 1; i++) { cout << "#"; }}// this article is contributed by Shivani Ghughtyal
// JAVA program to print a hollow// pyramid patternclass GFG{ public static void main(String args[]) { int n = 6; printPattern(n); } static void printPattern(int n) { int i, j, k = 0; for (i = 1; i <= n; i++) // row=6 { // Print spaces for (j = i; j < n; j++) { System.out.print(" "); } // Print # while (k != (2 * i - 1)) { if (k == 0 || k == 2 * i - 2) System.out.print("#"); else System.out.print(" "); k++; ; } k = 0; // print next row System.out.println(); } // print last row for (i = 0; i < 2 * n - 1; i++) { System.out.print("#"); } }} /*This code is contributed by Nikita Tiwari.*/
# Python program to print a hollow# pyramid pattern def printPattern( n) : k = 0 for i in range(1,n+1) : #row 6 # Print spaces for j in range(i,n) : print(' ', end='') # Print # while (k != (2 * i - 1)) : if (k == 0 or k == 2 * i - 2) : print('#', end='') else : print(' ', end ='') k = k + 1 k = 0; print ("") # print next row # print last row for i in range(0, 2 * n -1) : print ('#', end = '') # Driver coden = 6printPattern(n) # This code is contributed by Nikita Tiwari.
<?php// php program to print a// hollow pyramid pattern function printPattern($n){ $k = 0; // row=6 for ($i = 1; $i <= $n; $i++) { // Print spaces for ($j = $i; $j < $n; $j++) { echo " "; } // Print # while ($k != (2 * $i - 1)) { if ($k == 0 || $k == 2 * $i - 2) echo "#"; else echo " "; $k++; } $k = 0; // print next row echo "\n"; } // print last row for ($i = 0; $i < 2 * $n - 1; $i++) { echo "#"; }} //Driver Code$n = 6;printPattern($n); // This code is contributed by mits?>
<script> // JavaScript program to print a hollow pyramid pattern var n = 6; printPattern(n); function printPattern(n) { var i, j, k = 0; for (i = 1; i <= n; i++)// row=6 { // Print spaces for (j = i; j < n; j++) { document.write(" "); } // Print # while (k != 2 * i - 1) { if (k == 0 || k == 2 * i - 2) document.write("#"); else document.write(" "); k++;d spaces"> } k = 0; document.write("<br>"); // print next row } // print last row for (i = 0; i < 2 * n - 1; i++) { document.write("#"); } } // This code is contributed by rdtank. </script>
#
# #
# #
# #
# #
# #
###########
2. Hollow Diamond
Note: For even input, print the pattern for n-1.
Example:
Input: 1
Output:
For n=1
Input: 7
Output:
For n=7
Input: 9
Output:
For n=9
Approach: To print diamond we need to print spaces before star and after the star to achieve constant increasing distance of stars.
To print the box shape we need to print ‘-‘ for i==1 (first row) & i==n (last row) and ‘|’ for j==1 (first column) and j==n (last column).
Algorithm: 1. If n is odd increment n.
2. Find mid=n/2.
3. Traverse from 1 to mid to print upper half of the pattern (say i).
4. Traverse from 1 to mid-i to print spaces for upper left most outer box (say j).
5. If (i==1) print ‘*’ (since for first row we need only one star).
6. else print ‘*’ and traverse from 1 to 2*i-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over.
7. Traverse from 1 to mid-i to print spaces again for upper right most outer box (say j).
8. Close the loop at step 3.
9. Traverse from mid+1 to n-1 to print lower half of the pattern (say i).
4. Traverse from 1 to i-mid to print spaces for lower left most outer box (say j).
5. If (i==n-1) print ‘*’ (since for last row we need only one star).
6. else print ‘*’ and traverse from 1 to 2*(n-i)-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over.
7. Traverse from 1 to i-mid to print spaces again for lower right most outer box (say j).
8. Close the loop at step 9.
C++14
Java
#include <bits/stdc++.h>using namespace std; // function to print the patternvoid printPattern(int& n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box before star cout<<" "; if(i == 1) { cout << "*"; }else{ cout << "*"; //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow cout << " "; } cout << "*"; } for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box after star cout<<" "; cout << endl; } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box before star cout<<" "; if(i == n-1) { cout << "*"; }else{ cout << "*"; //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow cout << " "; } cout << "*"; } for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box after star cout<<" "; cout << endl; }} // driver's codeint main() { int n=7; printPattern(n);}// this code is contributed by prophet1999
// JAVA programclass GFG{ // function to print the patternstatic void printPattern(int n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box before star System.out.print(" "); if(i == 1) { System.out.print("*"); }else{ System.out.print("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow System.out.print(" "); } System.out.print("*"); } for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box after star System.out.print(" "); System.out.println(); } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box before star System.out.print(" "); if(i == n-1) { System.out.print("*"); }else{ System.out.print("*"); //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow System.out.print(" "); } System.out.print("*"); } for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box after star System.out.print(" "); System.out.println(); } } // driver's code public static void main(String args[]) { int n = 7; printPattern(n); }} // This code is contributed by Pushpesh Raj.
*
* *
* *
* *
* *
* *
*
3. Hollow Diamond bounded inside a rectangular box made of horizontal and vertical dashes(-).
Write a program to Print hollow diamond pattern bound inside a box made of dash(-) and bitwise-OR(|) as shown below.
Note: For even input, print the pattern for n-1.
Example:
Input: 1
Output:
For n=1
Input: 7
Output:
For n=7
Input: 9
Output:
For n=9
Approach: To print diamond we need to print spaces before star and after the star to achieve constant increasing distance of stars.
To print the box shape we need to print ‘-‘ for i==1 (first row) & i==n (last row) and ‘|’ for j==1 (first column) and j==n (last column).
Algorithm: 1. If n is odd increment n.
2. Find mid=n/2.
3. Traverse from 1 to mid to print upper half of the pattern (say i).
4. Traverse from 1 to mid-i to print upper left most outer box (say j).
5. If (i==1) print ‘*’ (since for first row we need only one star).
6. else print ‘*’ and traverse from 1 to 2*i-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over.
7. Traverse from 1 to mid-i to print upper right most outer box (say j).
8. Close the loop at step 3.
9. Traverse from mid+1 to n-1 to print lower half of the pattern (say i).
4. Traverse from 1 to i-mid to print lower left most outer box (say j).
5. If (i==n-1) print ‘*’ (since for last row we need only one star).
6. else print ‘*’ and traverse from 1 to 2*(n-i)-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over.
7. Traverse from 1 to i-mid to print lower right most outer box (say j).
8. Close the loop at step 9.
C++14
#include <bits/stdc++.h>using namespace std; // function to print the patternvoid printPattern(int& n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) { //print the blank spaces and outer box before star if(i==1) cout<<"-"; else if(j==1) cout << "|"; else cout<<" "; } if(i == 1) { cout << "*"; }else{ cout << "*"; //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow cout << " "; } cout << "*"; } for(j = 1; j<=mid-i; j++) { //print the blank spaces and outer box after star if(i==1) cout<<"-"; else if(j==mid-i) cout << "|"; else cout<<" "; } cout << endl; } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) { //print the blank spaces and outer box before star if(i==n-1) cout<<"-"; else if(j==1) cout << "|"; else cout<<" "; } if(i == n-1) { cout << "*"; }else{ cout << "*"; //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow cout << " "; } cout << "*"; } for(j = 1; j<=i-mid; j++) { //print the blank spaces and outer box after star if(i==n-1) cout<<"-"; else if(j==i-mid) cout << "|"; else cout<<" "; } cout << endl; }} // driver's codeint main() { int n=12; printPattern(n);}// this code is contributed by prophet1999
-----*-----
| * * |
| * * |
| * * |
|* *|
* *
|* *|
| * * |
| * * |
| * * |
-----*-----
Time Complexity: O(n*n)
Auxiliary Space: O(1)
This article is contributed by Shivani Ghughtyal and improved by Himanshu Patel(@prophet1999). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
Mithun Kumar
rdtank
anikakapoor
prophet1999
pushpeshrajdx01
pattern-printing
C Language
C++
School Programming
pattern-printing
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 372,
"s": 54,
"text": "For Prerequisite : Loops, If Else Statement1. Hollow pyramid/triangle pattern The pattern is similar to pyramid pattern. The only difference is, we will replace all internal ‘#’ or ‘*’ characters by space character and we will print 2*N-1 (N = number of rows in pattern) ‘#’ or ‘*’ characters in last row. Examples: "
},
{
"code": null,
"e": 464,
"s": 372,
"text": "Input: n=6\nOutput:\n #\n # #\n # #\n # #\n # #\n# #\n########### "
},
{
"code": null,
"e": 475,
"s": 466,
"text": "Chapters"
},
{
"code": null,
"e": 502,
"s": 475,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 552,
"s": 502,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 575,
"s": 552,
"text": "captions off, selected"
},
{
"code": null,
"e": 583,
"s": 575,
"text": "English"
},
{
"code": null,
"e": 607,
"s": 583,
"text": "This is a modal window."
},
{
"code": null,
"e": 676,
"s": 607,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 698,
"s": 676,
"text": "End of dialog window."
},
{
"code": null,
"e": 704,
"s": 698,
"text": "C++14"
},
{
"code": null,
"e": 709,
"s": 704,
"text": "Java"
},
{
"code": null,
"e": 716,
"s": 709,
"text": "Python"
},
{
"code": null,
"e": 720,
"s": 716,
"text": "PHP"
},
{
"code": null,
"e": 731,
"s": 720,
"text": "Javascript"
},
{
"code": "// CPP program to print a hollow pyramid pattern#include <iostream>using namespace std;void printPattern(int);int main(){ int n = 6; printPattern(n);}void printPattern(int n){ int i, j, k = 0; for (i = 1; i <= n; i++) // row=6 { // Print spaces for (j = i; j < n; j++) { cout << \" \"; } // Print # while (k != (2 * i - 1)) { if (k == 0 || k == 2 * i - 2) cout << \"#\"; else cout << \" \"; k++; } k = 0; cout << endl; // print next row } // print last row for (i = 0; i < 2 * n - 1; i++) { cout << \"#\"; }}// this article is contributed by Shivani Ghughtyal",
"e": 1448,
"s": 731,
"text": null
},
{
"code": "// JAVA program to print a hollow// pyramid patternclass GFG{ public static void main(String args[]) { int n = 6; printPattern(n); } static void printPattern(int n) { int i, j, k = 0; for (i = 1; i <= n; i++) // row=6 { // Print spaces for (j = i; j < n; j++) { System.out.print(\" \"); } // Print # while (k != (2 * i - 1)) { if (k == 0 || k == 2 * i - 2) System.out.print(\"#\"); else System.out.print(\" \"); k++; ; } k = 0; // print next row System.out.println(); } // print last row for (i = 0; i < 2 * n - 1; i++) { System.out.print(\"#\"); } }} /*This code is contributed by Nikita Tiwari.*/",
"e": 2371,
"s": 1448,
"text": null
},
{
"code": "# Python program to print a hollow# pyramid pattern def printPattern( n) : k = 0 for i in range(1,n+1) : #row 6 # Print spaces for j in range(i,n) : print(' ', end='') # Print # while (k != (2 * i - 1)) : if (k == 0 or k == 2 * i - 2) : print('#', end='') else : print(' ', end ='') k = k + 1 k = 0; print (\"\") # print next row # print last row for i in range(0, 2 * n -1) : print ('#', end = '') # Driver coden = 6printPattern(n) # This code is contributed by Nikita Tiwari.",
"e": 3005,
"s": 2371,
"text": null
},
{
"code": "<?php// php program to print a// hollow pyramid pattern function printPattern($n){ $k = 0; // row=6 for ($i = 1; $i <= $n; $i++) { // Print spaces for ($j = $i; $j < $n; $j++) { echo \" \"; } // Print # while ($k != (2 * $i - 1)) { if ($k == 0 || $k == 2 * $i - 2) echo \"#\"; else echo \" \"; $k++; } $k = 0; // print next row echo \"\\n\"; } // print last row for ($i = 0; $i < 2 * $n - 1; $i++) { echo \"#\"; }} //Driver Code$n = 6;printPattern($n); // This code is contributed by mits?>",
"e": 3735,
"s": 3005,
"text": null
},
{
"code": "<script> // JavaScript program to print a hollow pyramid pattern var n = 6; printPattern(n); function printPattern(n) { var i, j, k = 0; for (i = 1; i <= n; i++)// row=6 { // Print spaces for (j = i; j < n; j++) { document.write(\" \"); } // Print # while (k != 2 * i - 1) { if (k == 0 || k == 2 * i - 2) document.write(\"#\"); else document.write(\" \"); k++;d spaces\"> } k = 0; document.write(\"<br>\"); // print next row } // print last row for (i = 0; i < 2 * n - 1; i++) { document.write(\"#\"); } } // This code is contributed by rdtank. </script>",
"e": 4575,
"s": 3735,
"text": null
},
{
"code": null,
"e": 4644,
"s": 4575,
"text": " #\n # #\n # #\n # #\n # #\n# #\n###########"
},
{
"code": null,
"e": 4662,
"s": 4644,
"text": "2. Hollow Diamond"
},
{
"code": null,
"e": 4711,
"s": 4662,
"text": "Note: For even input, print the pattern for n-1."
},
{
"code": null,
"e": 4720,
"s": 4711,
"text": "Example:"
},
{
"code": null,
"e": 4729,
"s": 4720,
"text": "Input: 1"
},
{
"code": null,
"e": 4737,
"s": 4729,
"text": "Output:"
},
{
"code": null,
"e": 4745,
"s": 4737,
"text": "For n=1"
},
{
"code": null,
"e": 4754,
"s": 4745,
"text": "Input: 7"
},
{
"code": null,
"e": 4762,
"s": 4754,
"text": "Output:"
},
{
"code": null,
"e": 4770,
"s": 4762,
"text": "For n=7"
},
{
"code": null,
"e": 4779,
"s": 4770,
"text": "Input: 9"
},
{
"code": null,
"e": 4787,
"s": 4779,
"text": "Output:"
},
{
"code": null,
"e": 4795,
"s": 4787,
"text": "For n=9"
},
{
"code": null,
"e": 4927,
"s": 4795,
"text": "Approach: To print diamond we need to print spaces before star and after the star to achieve constant increasing distance of stars."
},
{
"code": null,
"e": 5066,
"s": 4927,
"text": "To print the box shape we need to print ‘-‘ for i==1 (first row) & i==n (last row) and ‘|’ for j==1 (first column) and j==n (last column)."
},
{
"code": null,
"e": 5105,
"s": 5066,
"text": "Algorithm: 1. If n is odd increment n."
},
{
"code": null,
"e": 5122,
"s": 5105,
"text": "2. Find mid=n/2."
},
{
"code": null,
"e": 5192,
"s": 5122,
"text": "3. Traverse from 1 to mid to print upper half of the pattern (say i)."
},
{
"code": null,
"e": 5275,
"s": 5192,
"text": "4. Traverse from 1 to mid-i to print spaces for upper left most outer box (say j)."
},
{
"code": null,
"e": 5343,
"s": 5275,
"text": "5. If (i==1) print ‘*’ (since for first row we need only one star)."
},
{
"code": null,
"e": 5467,
"s": 5343,
"text": "6. else print ‘*’ and traverse from 1 to 2*i-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over."
},
{
"code": null,
"e": 5557,
"s": 5467,
"text": "7. Traverse from 1 to mid-i to print spaces again for upper right most outer box (say j)."
},
{
"code": null,
"e": 5586,
"s": 5557,
"text": "8. Close the loop at step 3."
},
{
"code": null,
"e": 5660,
"s": 5586,
"text": "9. Traverse from mid+1 to n-1 to print lower half of the pattern (say i)."
},
{
"code": null,
"e": 5743,
"s": 5660,
"text": "4. Traverse from 1 to i-mid to print spaces for lower left most outer box (say j)."
},
{
"code": null,
"e": 5812,
"s": 5743,
"text": "5. If (i==n-1) print ‘*’ (since for last row we need only one star)."
},
{
"code": null,
"e": 5940,
"s": 5812,
"text": "6. else print ‘*’ and traverse from 1 to 2*(n-i)-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over."
},
{
"code": null,
"e": 6030,
"s": 5940,
"text": "7. Traverse from 1 to i-mid to print spaces again for lower right most outer box (say j)."
},
{
"code": null,
"e": 6059,
"s": 6030,
"text": "8. Close the loop at step 9."
},
{
"code": null,
"e": 6065,
"s": 6059,
"text": "C++14"
},
{
"code": null,
"e": 6070,
"s": 6065,
"text": "Java"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // function to print the patternvoid printPattern(int& n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box before star cout<<\" \"; if(i == 1) { cout << \"*\"; }else{ cout << \"*\"; //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow cout << \" \"; } cout << \"*\"; } for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box after star cout<<\" \"; cout << endl; } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box before star cout<<\" \"; if(i == n-1) { cout << \"*\"; }else{ cout << \"*\"; //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow cout << \" \"; } cout << \"*\"; } for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box after star cout<<\" \"; cout << endl; }} // driver's codeint main() { int n=7; printPattern(n);}// this code is contributed by prophet1999",
"e": 7492,
"s": 6070,
"text": null
},
{
"code": "// JAVA programclass GFG{ // function to print the patternstatic void printPattern(int n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box before star System.out.print(\" \"); if(i == 1) { System.out.print(\"*\"); }else{ System.out.print(\"*\"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow System.out.print(\" \"); } System.out.print(\"*\"); } for(j = 1; j<=mid-i; j++) //print the blank spaces and outer box after star System.out.print(\" \"); System.out.println(); } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box before star System.out.print(\" \"); if(i == n-1) { System.out.print(\"*\"); }else{ System.out.print(\"*\"); //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow System.out.print(\" \"); } System.out.print(\"*\"); } for(j = 1; j<=i-mid; j++) //print the blank spaces and outer box after star System.out.print(\" \"); System.out.println(); } } // driver's code public static void main(String args[]) { int n = 7; printPattern(n); }} // This code is contributed by Pushpesh Raj.",
"e": 9128,
"s": 7492,
"text": null
},
{
"code": null,
"e": 9184,
"s": 9128,
"text": " * \n * * \n * * \n* *\n * * \n * * \n * "
},
{
"code": null,
"e": 9278,
"s": 9184,
"text": "3. Hollow Diamond bounded inside a rectangular box made of horizontal and vertical dashes(-)."
},
{
"code": null,
"e": 9395,
"s": 9278,
"text": "Write a program to Print hollow diamond pattern bound inside a box made of dash(-) and bitwise-OR(|) as shown below."
},
{
"code": null,
"e": 9444,
"s": 9395,
"text": "Note: For even input, print the pattern for n-1."
},
{
"code": null,
"e": 9453,
"s": 9444,
"text": "Example:"
},
{
"code": null,
"e": 9462,
"s": 9453,
"text": "Input: 1"
},
{
"code": null,
"e": 9470,
"s": 9462,
"text": "Output:"
},
{
"code": null,
"e": 9478,
"s": 9470,
"text": "For n=1"
},
{
"code": null,
"e": 9487,
"s": 9478,
"text": "Input: 7"
},
{
"code": null,
"e": 9495,
"s": 9487,
"text": "Output:"
},
{
"code": null,
"e": 9503,
"s": 9495,
"text": "For n=7"
},
{
"code": null,
"e": 9512,
"s": 9503,
"text": "Input: 9"
},
{
"code": null,
"e": 9520,
"s": 9512,
"text": "Output:"
},
{
"code": null,
"e": 9528,
"s": 9520,
"text": "For n=9"
},
{
"code": null,
"e": 9660,
"s": 9528,
"text": "Approach: To print diamond we need to print spaces before star and after the star to achieve constant increasing distance of stars."
},
{
"code": null,
"e": 9799,
"s": 9660,
"text": "To print the box shape we need to print ‘-‘ for i==1 (first row) & i==n (last row) and ‘|’ for j==1 (first column) and j==n (last column)."
},
{
"code": null,
"e": 9838,
"s": 9799,
"text": "Algorithm: 1. If n is odd increment n."
},
{
"code": null,
"e": 9855,
"s": 9838,
"text": "2. Find mid=n/2."
},
{
"code": null,
"e": 9925,
"s": 9855,
"text": "3. Traverse from 1 to mid to print upper half of the pattern (say i)."
},
{
"code": null,
"e": 9997,
"s": 9925,
"text": "4. Traverse from 1 to mid-i to print upper left most outer box (say j)."
},
{
"code": null,
"e": 10065,
"s": 9997,
"text": "5. If (i==1) print ‘*’ (since for first row we need only one star)."
},
{
"code": null,
"e": 10189,
"s": 10065,
"text": "6. else print ‘*’ and traverse from 1 to 2*i-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over."
},
{
"code": null,
"e": 10262,
"s": 10189,
"text": "7. Traverse from 1 to mid-i to print upper right most outer box (say j)."
},
{
"code": null,
"e": 10291,
"s": 10262,
"text": "8. Close the loop at step 3."
},
{
"code": null,
"e": 10365,
"s": 10291,
"text": "9. Traverse from mid+1 to n-1 to print lower half of the pattern (say i)."
},
{
"code": null,
"e": 10437,
"s": 10365,
"text": "4. Traverse from 1 to i-mid to print lower left most outer box (say j)."
},
{
"code": null,
"e": 10506,
"s": 10437,
"text": "5. If (i==n-1) print ‘*’ (since for last row we need only one star)."
},
{
"code": null,
"e": 10634,
"s": 10506,
"text": "6. else print ‘*’ and traverse from 1 to 2*(n-i)-3 to print spaces for hollow diamond (say j) and print ‘*’ after loop is over."
},
{
"code": null,
"e": 10707,
"s": 10634,
"text": "7. Traverse from 1 to i-mid to print lower right most outer box (say j)."
},
{
"code": null,
"e": 10736,
"s": 10707,
"text": "8. Close the loop at step 9."
},
{
"code": null,
"e": 10742,
"s": 10736,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // function to print the patternvoid printPattern(int& n){ int i,j,mid; if(n%2==1) //when n is odd, increase it by 1 to make it even n++; mid = n/2; // upper half pattern for(i = 1; i<= mid; i++) { for(j = 1; j<=mid-i; j++) { //print the blank spaces and outer box before star if(i==1) cout<<\"-\"; else if(j==1) cout << \"|\"; else cout<<\" \"; } if(i == 1) { cout << \"*\"; }else{ cout << \"*\"; //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow cout << \" \"; } cout << \"*\"; } for(j = 1; j<=mid-i; j++) { //print the blank spaces and outer box after star if(i==1) cout<<\"-\"; else if(j==mid-i) cout << \"|\"; else cout<<\" \"; } cout << endl; } // lower half pattern for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) { //print the blank spaces and outer box before star if(i==n-1) cout<<\"-\"; else if(j==1) cout << \"|\"; else cout<<\" \"; } if(i == n-1) { cout << \"*\"; }else{ cout << \"*\"; //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow cout << \" \"; } cout << \"*\"; } for(j = 1; j<=i-mid; j++) { //print the blank spaces and outer box after star if(i==n-1) cout<<\"-\"; else if(j==i-mid) cout << \"|\"; else cout<<\" \"; } cout << endl; }} // driver's codeint main() { int n=12; printPattern(n);}// this code is contributed by prophet1999",
"e": 12509,
"s": 10742,
"text": null
},
{
"code": null,
"e": 12641,
"s": 12509,
"text": "-----*-----\n| * * |\n| * * |\n| * * |\n|* *|\n* *\n|* *|\n| * * |\n| * * |\n| * * |\n-----*-----"
},
{
"code": null,
"e": 12665,
"s": 12641,
"text": "Time Complexity: O(n*n)"
},
{
"code": null,
"e": 12687,
"s": 12665,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13158,
"s": 12687,
"text": "This article is contributed by Shivani Ghughtyal and improved by Himanshu Patel(@prophet1999). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 13171,
"s": 13158,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 13178,
"s": 13171,
"text": "rdtank"
},
{
"code": null,
"e": 13190,
"s": 13178,
"text": "anikakapoor"
},
{
"code": null,
"e": 13202,
"s": 13190,
"text": "prophet1999"
},
{
"code": null,
"e": 13218,
"s": 13202,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 13235,
"s": 13218,
"text": "pattern-printing"
},
{
"code": null,
"e": 13246,
"s": 13235,
"text": "C Language"
},
{
"code": null,
"e": 13250,
"s": 13246,
"text": "C++"
},
{
"code": null,
"e": 13269,
"s": 13250,
"text": "School Programming"
},
{
"code": null,
"e": 13286,
"s": 13269,
"text": "pattern-printing"
},
{
"code": null,
"e": 13290,
"s": 13286,
"text": "CPP"
}
] |
Difference between fundamental data types and derived data types
|
25 Mar, 2022
In computer programming, data type is a classification that specifies to compiler or interpreter which type of data user is intending to use.
There are two types of data types –
Primitive/Fundamental data type: Each variable in C/C++ has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Example of fundamental data types –
C++
Java
Python
C#
PHP
Javascript
// C++ program to illustrate// primitive data types#include <bits/stdc++.h>using namespace std; // main method starts from hereint main(){ int a = 2; float b = 2.0; double c = 2.0003; char d = 'D'; cout<<"Integer value is = "<< a <<"\nFloat value is = "<< b <<"\nDouble value is = "<< c <<"\nChar value is = "<< d <<endl;} // This code has been contributed by cmaggio
// Java program to illustrate// primitive data types class GFG { public static void main(String[] args) { // Integer value int a = 2; // Float value float b = 2.0f; // Double value double c = 2.0003; // Character char d = 'D'; System.out.printf("Integer value is = %d", a); System.out.printf("\nFloat value is = %f", b); System.out.printf("\nDouble value is = %f", c); System.out.printf("\nChar value is = %c", d); }} // This code has been contributed by 29AjayKumar
# Python program to illustrate# primitive data types # Integer valuea = 2 # Float valueb = 2.0 # Double valuec = 2.0003 # Characterd ='D'print("Integer value is = ", a);print("\nFloat value is = ", b);print("\nDouble value is = ", c);print("\nChar value is = ", d); # This code has been contributed by Code_Mech
// C# program to illustrate// primitive data typesusing System; class GFG { public static void Main() { // Integer value int a = 2; // Float value float b = 2.0f; // Double value double c = 2.0003; // Character char d = 'D'; Console.WriteLine("Integer value is = " + a); Console.WriteLine("\nFloat value is = " + b); Console.WriteLine("\nDouble value is = " + c); Console.WriteLine("\nChar value is = " + d); }} // This code has been contributed by Code_Mech.
<?php// PHP program to illustrate// primitive data types{ // Integer value $a = 2; // Float value $b = 2.0; // Double value $c = 2.0003; // Character $d = 'D'; echo("Integer value is = ". $a); echo("\nFloat value is = ". $b); echo("\nDouble value is = ". $c); echo("\nChar value is = ". $d);} // This code has been contributed by Code_Mech.
<script> // JavaScript program to illustrate// primitive data types // Integer value var a = 2; // Float value var b = 2.0; // Double value var c = 2.0003; // Character var d = 'D'; document.write("Integer value is = ", a + "<br>"); document.write("\nFloat value is = ", b + "<br>"); document.write("\nDouble value is = ", c + "<br>"); document.write("\nChar value is = ", d + "<br>"); // This code has been contributed by shivanisinghss2110 </script>
Integer value is = 2
Float value is = 2.000000
Double value is = 2.000300
Char value is = D
Derived data type : These data types are defined by user itself. Like, defining a class in C++ or a structure. These include Arrays, Structures, Class, Union, Enumeration, Pointers etc. Examples of derived data type : Pointer :
Pointer :
C++
C
// C++ program to illustrate pointer// as derived data type#include <iostream>using namespace std; // main methodint main(){ // integer variable int variable = 10; // Pointer for storing address int* pointr; // Assigning address of variable to pointer pointr = &variable; cout << "Value of variable = " << variable; // cout << "\nValue at pointer = "<< pointr; cout << "\nValue at *pointer = "<< *pointr; return 0;} // This code is contributed by shubhamsingh10
// C program to illustrate pointer// as derived data type#include <stdio.h>// main method starts from hereint main(){ // integer variable int variable = 10; // Pointer for storing address int* pointr; // Assigning address of variable to pointer pointr = &variable; printf("Value of variable = %d", variable); // printf("\nValue at pointer = %d", pointr); printf("\nValue at *pointer = %d", *pointr); return 0;}
Value of variable = 10
Value at *pointer = 10
Array :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to illustrate array// derived data type#include <bits/stdc++.h>using namespace std;// main method starts from hereint main(){ // array of size 5 int a[5] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) cout << ("%d ", a[i]); return 0;} // This code is contributed by Code_Mech.
// C program to illustrate array// derived data type#include <stdio.h>// main method starts from hereint main(){ // array of size 5 int a[5] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) printf("%d ", a[i]); return 0;}
// Java program to illustrate array// derived data typeimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // array of size 5 int a[] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) System.out.printf("%d ", a[i]); }} /* This code contributed by PrinciRaj1992 */
# Python3 program to illustrate array# derived data type # Driver code # array of size 5a = [1, 2, 3, 4, 5]; # indexing variablefor i in range(5): print(a[i], end = " "); # This code contributed by mits
// C# program to illustrate array// derived data typeusing System; class GFG { // Driver code public static void Main(String[] args) { // array of size 5 int[] a = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) Console.Write("{0} ", a[i]); }} // This code contributed by Rajput-Ji
<?php// PHP program to illustrate array// derived data type // Driver code // array of size 5$a = array(1, 2, 3, 4, 5); // indexing variablefor ($i = 0; $i < 5; $i++) print($a[$i] . " "); // This code contributed by mits?>
<script> // Javascript program to illustrate// array derived data type // Array of size 5let a = [ 1, 2, 3, 4, 5 ]; // Indexing variablelet i;for(i = 0; i < 5; i++) document.write(a[i] + " "); // This code is contributed by decode2207 </script>
1 2 3 4 5
Structures –
C++
C
// C++ program to illustrate structure// derived data type#include <bits/stdc++.h>using namespace std; // structurestruct structure_example{ int integer; float decimal; char character[20];}; // Main Methodint main(){ struct structure_example s = { 15, 98.9, "geeksforgeeks" }; cout << "Structure data -"<< endl; cout << "integer = " << s.integer << endl; cout << fixed<<setprecision(6)<< "decimal = " << s.decimal << endl; cout << "name = " << s.character << endl; return 0;} // This code is contributed by shubhamsingh10
// C program to illustrate structure// derived data type#include <stdio.h>// structurestruct structure_example { int integer; float decimal; char character[20];};// main method starts from herevoid main(){ struct structure_example s = { 15, 98.9, "geeksforgeeks" }; printf("Structure data - \n integer = %d \n decimal = %f \n name = %s", s.integer, s.decimal, s.character);}
Structure data -
integer = 15
decimal = 98.900002
name = geeksforgeeks
29AjayKumar
Code_Mech
princiraj1992
Rajput-Ji
Mithun Kumar
SHUBHAMSINGH10
decode2207
shivanisinghss2110
cmaggio
CBSE - Class 11
Picked
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "In computer programming, data type is a classification that specifies to compiler or interpreter which type of data user is intending to use. "
},
{
"code": null,
"e": 232,
"s": 195,
"text": "There are two types of data types – "
},
{
"code": null,
"e": 470,
"s": 232,
"text": "Primitive/Fundamental data type: Each variable in C/C++ has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Example of fundamental data types –"
},
{
"code": null,
"e": 474,
"s": 470,
"text": "C++"
},
{
"code": null,
"e": 479,
"s": 474,
"text": "Java"
},
{
"code": null,
"e": 486,
"s": 479,
"text": "Python"
},
{
"code": null,
"e": 489,
"s": 486,
"text": "C#"
},
{
"code": null,
"e": 493,
"s": 489,
"text": "PHP"
},
{
"code": null,
"e": 504,
"s": 493,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate// primitive data types#include <bits/stdc++.h>using namespace std; // main method starts from hereint main(){ int a = 2; float b = 2.0; double c = 2.0003; char d = 'D'; cout<<\"Integer value is = \"<< a <<\"\\nFloat value is = \"<< b <<\"\\nDouble value is = \"<< c <<\"\\nChar value is = \"<< d <<endl;} // This code has been contributed by cmaggio",
"e": 926,
"s": 504,
"text": null
},
{
"code": "// Java program to illustrate// primitive data types class GFG { public static void main(String[] args) { // Integer value int a = 2; // Float value float b = 2.0f; // Double value double c = 2.0003; // Character char d = 'D'; System.out.printf(\"Integer value is = %d\", a); System.out.printf(\"\\nFloat value is = %f\", b); System.out.printf(\"\\nDouble value is = %f\", c); System.out.printf(\"\\nChar value is = %c\", d); }} // This code has been contributed by 29AjayKumar",
"e": 1491,
"s": 926,
"text": null
},
{
"code": "# Python program to illustrate# primitive data types # Integer valuea = 2 # Float valueb = 2.0 # Double valuec = 2.0003 # Characterd ='D'print(\"Integer value is = \", a);print(\"\\nFloat value is = \", b);print(\"\\nDouble value is = \", c);print(\"\\nChar value is = \", d); # This code has been contributed by Code_Mech",
"e": 1807,
"s": 1491,
"text": null
},
{
"code": "// C# program to illustrate// primitive data typesusing System; class GFG { public static void Main() { // Integer value int a = 2; // Float value float b = 2.0f; // Double value double c = 2.0003; // Character char d = 'D'; Console.WriteLine(\"Integer value is = \" + a); Console.WriteLine(\"\\nFloat value is = \" + b); Console.WriteLine(\"\\nDouble value is = \" + c); Console.WriteLine(\"\\nChar value is = \" + d); }} // This code has been contributed by Code_Mech.",
"e": 2365,
"s": 1807,
"text": null
},
{
"code": "<?php// PHP program to illustrate// primitive data types{ // Integer value $a = 2; // Float value $b = 2.0; // Double value $c = 2.0003; // Character $d = 'D'; echo(\"Integer value is = \". $a); echo(\"\\nFloat value is = \". $b); echo(\"\\nDouble value is = \". $c); echo(\"\\nChar value is = \". $d);} // This code has been contributed by Code_Mech.",
"e": 2747,
"s": 2365,
"text": null
},
{
"code": "<script> // JavaScript program to illustrate// primitive data types // Integer value var a = 2; // Float value var b = 2.0; // Double value var c = 2.0003; // Character var d = 'D'; document.write(\"Integer value is = \", a + \"<br>\"); document.write(\"\\nFloat value is = \", b + \"<br>\"); document.write(\"\\nDouble value is = \", c + \"<br>\"); document.write(\"\\nChar value is = \", d + \"<br>\"); // This code has been contributed by shivanisinghss2110 </script>",
"e": 3283,
"s": 2747,
"text": null
},
{
"code": null,
"e": 3375,
"s": 3283,
"text": "Integer value is = 2\nFloat value is = 2.000000\nDouble value is = 2.000300\nChar value is = D"
},
{
"code": null,
"e": 3605,
"s": 3377,
"text": "Derived data type : These data types are defined by user itself. Like, defining a class in C++ or a structure. These include Arrays, Structures, Class, Union, Enumeration, Pointers etc. Examples of derived data type : Pointer :"
},
{
"code": null,
"e": 3615,
"s": 3605,
"text": "Pointer :"
},
{
"code": null,
"e": 3619,
"s": 3615,
"text": "C++"
},
{
"code": null,
"e": 3621,
"s": 3619,
"text": "C"
},
{
"code": "// C++ program to illustrate pointer// as derived data type#include <iostream>using namespace std; // main methodint main(){ // integer variable int variable = 10; // Pointer for storing address int* pointr; // Assigning address of variable to pointer pointr = &variable; cout << \"Value of variable = \" << variable; // cout << \"\\nValue at pointer = \"<< pointr; cout << \"\\nValue at *pointer = \"<< *pointr; return 0;} // This code is contributed by shubhamsingh10",
"e": 4118,
"s": 3621,
"text": null
},
{
"code": "// C program to illustrate pointer// as derived data type#include <stdio.h>// main method starts from hereint main(){ // integer variable int variable = 10; // Pointer for storing address int* pointr; // Assigning address of variable to pointer pointr = &variable; printf(\"Value of variable = %d\", variable); // printf(\"\\nValue at pointer = %d\", pointr); printf(\"\\nValue at *pointer = %d\", *pointr); return 0;}",
"e": 4562,
"s": 4118,
"text": null
},
{
"code": null,
"e": 4608,
"s": 4562,
"text": "Value of variable = 10\nValue at *pointer = 10"
},
{
"code": null,
"e": 4619,
"s": 4610,
"text": "Array : "
},
{
"code": null,
"e": 4623,
"s": 4619,
"text": "C++"
},
{
"code": null,
"e": 4625,
"s": 4623,
"text": "C"
},
{
"code": null,
"e": 4630,
"s": 4625,
"text": "Java"
},
{
"code": null,
"e": 4638,
"s": 4630,
"text": "Python3"
},
{
"code": null,
"e": 4641,
"s": 4638,
"text": "C#"
},
{
"code": null,
"e": 4645,
"s": 4641,
"text": "PHP"
},
{
"code": null,
"e": 4656,
"s": 4645,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate array// derived data type#include <bits/stdc++.h>using namespace std;// main method starts from hereint main(){ // array of size 5 int a[5] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) cout << (\"%d \", a[i]); return 0;} // This code is contributed by Code_Mech.",
"e": 5000,
"s": 4656,
"text": null
},
{
"code": "// C program to illustrate array// derived data type#include <stdio.h>// main method starts from hereint main(){ // array of size 5 int a[5] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) printf(\"%d \", a[i]); return 0;}",
"e": 5273,
"s": 5000,
"text": null
},
{
"code": "// Java program to illustrate array// derived data typeimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // array of size 5 int a[] = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) System.out.printf(\"%d \", a[i]); }} /* This code contributed by PrinciRaj1992 */",
"e": 5656,
"s": 5273,
"text": null
},
{
"code": "# Python3 program to illustrate array# derived data type # Driver code # array of size 5a = [1, 2, 3, 4, 5]; # indexing variablefor i in range(5): print(a[i], end = \" \"); # This code contributed by mits",
"e": 5862,
"s": 5656,
"text": null
},
{
"code": "// C# program to illustrate array// derived data typeusing System; class GFG { // Driver code public static void Main(String[] args) { // array of size 5 int[] a = { 1, 2, 3, 4, 5 }; // indexing variable int i; for (i = 0; i < 5; i++) Console.Write(\"{0} \", a[i]); }} // This code contributed by Rajput-Ji",
"e": 6226,
"s": 5862,
"text": null
},
{
"code": "<?php// PHP program to illustrate array// derived data type // Driver code // array of size 5$a = array(1, 2, 3, 4, 5); // indexing variablefor ($i = 0; $i < 5; $i++) print($a[$i] . \" \"); // This code contributed by mits?>",
"e": 6452,
"s": 6226,
"text": null
},
{
"code": "<script> // Javascript program to illustrate// array derived data type // Array of size 5let a = [ 1, 2, 3, 4, 5 ]; // Indexing variablelet i;for(i = 0; i < 5; i++) document.write(a[i] + \" \"); // This code is contributed by decode2207 </script>",
"e": 6704,
"s": 6452,
"text": null
},
{
"code": null,
"e": 6718,
"s": 6704,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 6733,
"s": 6720,
"text": "Structures –"
},
{
"code": null,
"e": 6737,
"s": 6733,
"text": "C++"
},
{
"code": null,
"e": 6739,
"s": 6737,
"text": "C"
},
{
"code": "// C++ program to illustrate structure// derived data type#include <bits/stdc++.h>using namespace std; // structurestruct structure_example{ int integer; float decimal; char character[20];}; // Main Methodint main(){ struct structure_example s = { 15, 98.9, \"geeksforgeeks\" }; cout << \"Structure data -\"<< endl; cout << \"integer = \" << s.integer << endl; cout << fixed<<setprecision(6)<< \"decimal = \" << s.decimal << endl; cout << \"name = \" << s.character << endl; return 0;} // This code is contributed by shubhamsingh10",
"e": 7288,
"s": 6739,
"text": null
},
{
"code": "// C program to illustrate structure// derived data type#include <stdio.h>// structurestruct structure_example { int integer; float decimal; char character[20];};// main method starts from herevoid main(){ struct structure_example s = { 15, 98.9, \"geeksforgeeks\" }; printf(\"Structure data - \\n integer = %d \\n decimal = %f \\n name = %s\", s.integer, s.decimal, s.character);}",
"e": 7681,
"s": 7288,
"text": null
},
{
"code": null,
"e": 7758,
"s": 7681,
"text": "Structure data - \n integer = 15 \n decimal = 98.900002 \n name = geeksforgeeks"
},
{
"code": null,
"e": 7774,
"s": 7762,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7784,
"s": 7774,
"text": "Code_Mech"
},
{
"code": null,
"e": 7798,
"s": 7784,
"text": "princiraj1992"
},
{
"code": null,
"e": 7808,
"s": 7798,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7821,
"s": 7808,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7836,
"s": 7821,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 7847,
"s": 7836,
"text": "decode2207"
},
{
"code": null,
"e": 7866,
"s": 7847,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 7874,
"s": 7866,
"text": "cmaggio"
},
{
"code": null,
"e": 7890,
"s": 7874,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 7897,
"s": 7890,
"text": "Picked"
},
{
"code": null,
"e": 7908,
"s": 7897,
"text": "C Language"
},
{
"code": null,
"e": 7912,
"s": 7908,
"text": "C++"
},
{
"code": null,
"e": 7931,
"s": 7912,
"text": "School Programming"
},
{
"code": null,
"e": 7935,
"s": 7931,
"text": "CPP"
}
] |
Count occurrences of a substring recursively
|
06 May, 2022
Given two strings str1 and str2, the task is to count the number of times str2 occurs in str1 using recursion.
Examples:
Input: str1 = “geeksforgeeks”, str2 = “geek”Output: 2Explanation: The occurrences of str2 in str1 are starting at index {0, 8}
Input: str1 = “aaaaa”, str2 = “aaa”Output: 3Explanation: The occurrences of str2 in str1 are starting at index {0,1,2
Approach: We have already discussed other approaches in our previous article but here we are going to solve this problem using recursion.
Algorithm:
If size of string str2 is greater then string str1 or size of string str1 is 0 then, return 0.
Otherwise, Check if string str2 is present in str1 as substring or not.if present then, increment the count of occurrence and recursively call for other substring.else, recursively call for other substring.return count from every recursively call as answer.
if present then, increment the count of occurrence and recursively call for other substring.
else, recursively call for other substring.
return count from every recursively call as answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// Recursive C++ program to count the number of// times string str2 occurs in string str1 #include <iostream>#include <string>using namespace std; // Function to count the number of// times string str2 occurs in string str1int countSubstring(string str1, string str2){ int n1 = str1.length(); int n2 = str2.length(); // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first substring matches if (str1.substr(0, n2).compare(str2) == 0) return countSubstring(str1.substr(1), str2) + 1; // Otherwise, return the count from // the remaining index return countSubstring(str1.substr(1), str2);} // Driver functionint main(){ string str1 = "geeksforgeeks", str2 = "geeks"; cout << countSubstring(str1, str2) << endl; str1 = "aaaaa", str2 = "aaa"; cout << countSubstring(str1, str2) << endl; return 0;}
// Recursive Java program for// counting number of substringsclass GFG{ // Recursive function to// count the number of// occurrences of "hi" in str.static int countSubstring(String str1, String str2){ int n1 = str1.length(); int n2 = str2.length(); // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first // substring matches if (str1.substring(0, n2).equals(str2)) return countSubstring(str1.substring(1), str2) + 1; // Otherwise, return the count // from the remaining index return countSubstring(str1.substring(1), str2);} // Driver Codepublic static void main(String args[]){ String str1 = "geeksforgeeks", str2 = "geeks"; System.out.println(countSubstring(str1, str2)); str1 = "aaaaa"; str2 = "aaa"; System.out.println(countSubstring(str1, str2)); }} // This code is contributed// by Arnab Kundu
# Recursive Python3 program for# counting number of substrings # Recursive function to# count the number of# occurrences of "hi" in str.def countSubstring(str1, str2): n1 = len(str1); n2 = len(str2); # Base Case if (n1 == 0 or n1 < n2): return 0; # Recursive Case # Checking if the first # substring matches if (str1[0 : n2] == str2): return countSubstring(str1[1:], str2) + 1; # Otherwise, return the count # from the remaining index return countSubstring(str1[1:], str2); # Driver Codeif __name__ == '__main__': str1 = "geeksforgeeks"; str2 = "geeks"; print(countSubstring(str1, str2)); str1 = "aaaaa"; str2 = "aaa"; print(countSubstring(str1, str2)); # This code is contributed by Princi Singh
// Recursive C# program for// counting number of substringsusing System;class GFG{ // Recursive function to// count the number of// occurrences of "hi" in str.static int countSubstring(String str1, String str2){ int n1 = str1.Length; int n2 = str2.Length; // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first // substring matches if (str1.Substring(0, n2).Equals(str2)) return countSubstring(str1.Substring(1), str2) + 1; // Otherwise, return the // count from the remaining // index return countSubstring(str1.Substring(1), str2);} // Driver Codepublic static void Main(){ string str1 = "geeksforgeeks", str2 = "geeks"; Console.Write(countSubstring(str1, str2)); Console.Write("\n"); str1 = "aaaaa"; str2 = "aaa"; Console.Write(countSubstring(str1, str2)); }} // This code is contributed// by Smita
<script> // Recursive js program for counting number of substrings // Recursive function to count// the number of occurrences of "hi" in str.function countSubstring( str1, str2){ let n1 = str1.length; let n2 = str2.length; // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first substring matches if (str1.substr(0, n2) == (str2)) return countSubstring(str1.substr(1), str2) + 1; // Otherwise, return the count from // the remaining index return countSubstring(str1.substr(1), str2);} // Driver functionlet str1 = "geeksforgeeks", str2 = "geeks";document.write( countSubstring(str1, str2),'<br>');str1 = "aaaaa", str2 = "aaa";document.write( countSubstring(str1, str2),'<br>'); </script>
2
3
Time Complexity: O(N2) , (i.e. N is maximum length between str1 and str2)Auxiliary Space: O(1)
andrew1234
Smitha Dinesh Semwal
princi singh
rohitsingh07052
kunwarhardik1999
sagartomar9927
avtarkumar719
germanshephered48
cpp-string
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 163,
"s": 52,
"text": "Given two strings str1 and str2, the task is to count the number of times str2 occurs in str1 using recursion."
},
{
"code": null,
"e": 174,
"s": 163,
"text": "Examples: "
},
{
"code": null,
"e": 301,
"s": 174,
"text": "Input: str1 = “geeksforgeeks”, str2 = “geek”Output: 2Explanation: The occurrences of str2 in str1 are starting at index {0, 8}"
},
{
"code": null,
"e": 419,
"s": 301,
"text": "Input: str1 = “aaaaa”, str2 = “aaa”Output: 3Explanation: The occurrences of str2 in str1 are starting at index {0,1,2"
},
{
"code": null,
"e": 557,
"s": 419,
"text": "Approach: We have already discussed other approaches in our previous article but here we are going to solve this problem using recursion."
},
{
"code": null,
"e": 569,
"s": 557,
"text": "Algorithm: "
},
{
"code": null,
"e": 664,
"s": 569,
"text": "If size of string str2 is greater then string str1 or size of string str1 is 0 then, return 0."
},
{
"code": null,
"e": 922,
"s": 664,
"text": "Otherwise, Check if string str2 is present in str1 as substring or not.if present then, increment the count of occurrence and recursively call for other substring.else, recursively call for other substring.return count from every recursively call as answer."
},
{
"code": null,
"e": 1015,
"s": 922,
"text": "if present then, increment the count of occurrence and recursively call for other substring."
},
{
"code": null,
"e": 1059,
"s": 1015,
"text": "else, recursively call for other substring."
},
{
"code": null,
"e": 1111,
"s": 1059,
"text": "return count from every recursively call as answer."
},
{
"code": null,
"e": 1162,
"s": 1111,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1166,
"s": 1162,
"text": "C++"
},
{
"code": null,
"e": 1171,
"s": 1166,
"text": "Java"
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Python3"
},
{
"code": null,
"e": 1182,
"s": 1179,
"text": "C#"
},
{
"code": null,
"e": 1193,
"s": 1182,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to count the number of// times string str2 occurs in string str1 #include <iostream>#include <string>using namespace std; // Function to count the number of// times string str2 occurs in string str1int countSubstring(string str1, string str2){ int n1 = str1.length(); int n2 = str2.length(); // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first substring matches if (str1.substr(0, n2).compare(str2) == 0) return countSubstring(str1.substr(1), str2) + 1; // Otherwise, return the count from // the remaining index return countSubstring(str1.substr(1), str2);} // Driver functionint main(){ string str1 = \"geeksforgeeks\", str2 = \"geeks\"; cout << countSubstring(str1, str2) << endl; str1 = \"aaaaa\", str2 = \"aaa\"; cout << countSubstring(str1, str2) << endl; return 0;}",
"e": 2090,
"s": 1193,
"text": null
},
{
"code": "// Recursive Java program for// counting number of substringsclass GFG{ // Recursive function to// count the number of// occurrences of \"hi\" in str.static int countSubstring(String str1, String str2){ int n1 = str1.length(); int n2 = str2.length(); // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first // substring matches if (str1.substring(0, n2).equals(str2)) return countSubstring(str1.substring(1), str2) + 1; // Otherwise, return the count // from the remaining index return countSubstring(str1.substring(1), str2);} // Driver Codepublic static void main(String args[]){ String str1 = \"geeksforgeeks\", str2 = \"geeks\"; System.out.println(countSubstring(str1, str2)); str1 = \"aaaaa\"; str2 = \"aaa\"; System.out.println(countSubstring(str1, str2)); }} // This code is contributed// by Arnab Kundu",
"e": 3179,
"s": 2090,
"text": null
},
{
"code": "# Recursive Python3 program for# counting number of substrings # Recursive function to# count the number of# occurrences of \"hi\" in str.def countSubstring(str1, str2): n1 = len(str1); n2 = len(str2); # Base Case if (n1 == 0 or n1 < n2): return 0; # Recursive Case # Checking if the first # substring matches if (str1[0 : n2] == str2): return countSubstring(str1[1:], str2) + 1; # Otherwise, return the count # from the remaining index return countSubstring(str1[1:], str2); # Driver Codeif __name__ == '__main__': str1 = \"geeksforgeeks\"; str2 = \"geeks\"; print(countSubstring(str1, str2)); str1 = \"aaaaa\"; str2 = \"aaa\"; print(countSubstring(str1, str2)); # This code is contributed by Princi Singh",
"e": 4011,
"s": 3179,
"text": null
},
{
"code": "// Recursive C# program for// counting number of substringsusing System;class GFG{ // Recursive function to// count the number of// occurrences of \"hi\" in str.static int countSubstring(String str1, String str2){ int n1 = str1.Length; int n2 = str2.Length; // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first // substring matches if (str1.Substring(0, n2).Equals(str2)) return countSubstring(str1.Substring(1), str2) + 1; // Otherwise, return the // count from the remaining // index return countSubstring(str1.Substring(1), str2);} // Driver Codepublic static void Main(){ string str1 = \"geeksforgeeks\", str2 = \"geeks\"; Console.Write(countSubstring(str1, str2)); Console.Write(\"\\n\"); str1 = \"aaaaa\"; str2 = \"aaa\"; Console.Write(countSubstring(str1, str2)); }} // This code is contributed// by Smita",
"e": 5102,
"s": 4011,
"text": null
},
{
"code": "<script> // Recursive js program for counting number of substrings // Recursive function to count// the number of occurrences of \"hi\" in str.function countSubstring( str1, str2){ let n1 = str1.length; let n2 = str2.length; // Base Case if (n1 == 0 || n1 < n2) return 0; // Recursive Case // Checking if the first substring matches if (str1.substr(0, n2) == (str2)) return countSubstring(str1.substr(1), str2) + 1; // Otherwise, return the count from // the remaining index return countSubstring(str1.substr(1), str2);} // Driver functionlet str1 = \"geeksforgeeks\", str2 = \"geeks\";document.write( countSubstring(str1, str2),'<br>');str1 = \"aaaaa\", str2 = \"aaa\";document.write( countSubstring(str1, str2),'<br>'); </script>",
"e": 5872,
"s": 5102,
"text": null
},
{
"code": null,
"e": 5876,
"s": 5872,
"text": "2\n3"
},
{
"code": null,
"e": 5971,
"s": 5876,
"text": "Time Complexity: O(N2) , (i.e. N is maximum length between str1 and str2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5982,
"s": 5971,
"text": "andrew1234"
},
{
"code": null,
"e": 6003,
"s": 5982,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 6016,
"s": 6003,
"text": "princi singh"
},
{
"code": null,
"e": 6032,
"s": 6016,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 6049,
"s": 6032,
"text": "kunwarhardik1999"
},
{
"code": null,
"e": 6064,
"s": 6049,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6078,
"s": 6064,
"text": "avtarkumar719"
},
{
"code": null,
"e": 6096,
"s": 6078,
"text": "germanshephered48"
},
{
"code": null,
"e": 6107,
"s": 6096,
"text": "cpp-string"
},
{
"code": null,
"e": 6117,
"s": 6107,
"text": "Recursion"
},
{
"code": null,
"e": 6125,
"s": 6117,
"text": "Strings"
},
{
"code": null,
"e": 6133,
"s": 6125,
"text": "Strings"
},
{
"code": null,
"e": 6143,
"s": 6133,
"text": "Recursion"
}
] |
How to remove all Global Modules in Node.js ?
|
01 Jul, 2020
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It is used in production by large companies such as Paypal, Uber, Netflix, Wallmart, and so on.
We can remove all the module globally in Node.js by the following ways:
For Linux (Ubuntu) users: In order to uninstall the globally installed package_name package, the following command can be used (using sudo if necessary, depending on your setup and permissions).
sudo npm rm --global package_name
To check whether the package is installed globally or not, use below command:
npm ls --global packae_name
Below images display the use of above command to uninstall express package globally:
For Window users: The Windows user can remove all the Node.js modules globally by just deleting the content of the following directory:
C:\Users\username\AppData\Roaming\npm
Steps to remove Global Modules:
Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:Now delete the content of this directory.
Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:
Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:
The directory will have files and folders as shown below:
Now delete the content of this directory.
All the global node modules are removed properly.
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 512,
"s": 28,
"text": "Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It is used in production by large companies such as Paypal, Uber, Netflix, Wallmart, and so on."
},
{
"code": null,
"e": 584,
"s": 512,
"text": "We can remove all the module globally in Node.js by the following ways:"
},
{
"code": null,
"e": 779,
"s": 584,
"text": "For Linux (Ubuntu) users: In order to uninstall the globally installed package_name package, the following command can be used (using sudo if necessary, depending on your setup and permissions)."
},
{
"code": null,
"e": 814,
"s": 779,
"text": "sudo npm rm --global package_name\n"
},
{
"code": null,
"e": 892,
"s": 814,
"text": "To check whether the package is installed globally or not, use below command:"
},
{
"code": null,
"e": 921,
"s": 892,
"text": "npm ls --global packae_name\n"
},
{
"code": null,
"e": 1006,
"s": 921,
"text": "Below images display the use of above command to uninstall express package globally:"
},
{
"code": null,
"e": 1142,
"s": 1006,
"text": "For Window users: The Windows user can remove all the Node.js modules globally by just deleting the content of the following directory:"
},
{
"code": null,
"e": 1180,
"s": 1142,
"text": "C:\\Users\\username\\AppData\\Roaming\\npm"
},
{
"code": null,
"e": 1212,
"s": 1180,
"text": "Steps to remove Global Modules:"
},
{
"code": null,
"e": 1485,
"s": 1212,
"text": "Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:Now delete the content of this directory."
},
{
"code": null,
"e": 1581,
"s": 1485,
"text": "Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:"
},
{
"code": null,
"e": 1718,
"s": 1581,
"text": "Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:"
},
{
"code": null,
"e": 1776,
"s": 1718,
"text": "The directory will have files and folders as shown below:"
},
{
"code": null,
"e": 1818,
"s": 1776,
"text": "Now delete the content of this directory."
},
{
"code": null,
"e": 1868,
"s": 1818,
"text": "All the global node modules are removed properly."
},
{
"code": null,
"e": 1881,
"s": 1868,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 1888,
"s": 1881,
"text": "Picked"
},
{
"code": null,
"e": 1896,
"s": 1888,
"text": "Node.js"
},
{
"code": null,
"e": 1913,
"s": 1896,
"text": "Web Technologies"
}
] |
Working of Keyword long in C programming
|
13 Oct, 2018
long is a keyword in Java that symbolises the Long datatype. The long data type is a 64-bit two’s complement integer with:
Size: 64 bit
Value: -263 to 263-1.
Output of 64 bit GCC compiler would give the size of long as 8 whereas on 32 bit GCC compiler the size would be 4. So it varies from compiler to compiler. Now the question is what exactly is happening here? Let’s discuss it in the way of how compiler allocates memory internally.
CPU calls data from RAM by giving the address of the location to MAR (Memory Address Register). The location is found and the data is transferred to MDR (Memory Data Register). This data is recorded in one of the Registers in the Processor for further processing. That’s why size of Data Bus determines the size of Registers in Processor. Now, a 32 bit register can call data of 4 bytes size only, at a time. And if the data size exceeds 32 bits, then it would required two cycles of fetching to have the data in it. This slows down the speed of 32 bit Machine compared to 64 bit, which would complete the operation in ONE fetch cycle only. So, obviously for the smaller data, it makes no difference if my processors are clocked at the same speed. Compilers are designed to generate the most efficient code for the target machine architecture.
Note: Interestingly we don’t have any need of “long” data type as their replacement(int, long long) is already available from C99 standard.
In the below program, all the possible variables with long datatype are defined and their sizes are calculated and print using sizeof() operator.
Below is the C program to find the demonstrate working of long keyword:
// C program to demonstrate the working// of long keyword #include <stdio.h> int main(){ long longType; int integerType; long int longIntegerType; long long int longLongIntegerType; float floatType; double doubleType; long double longDoubleType; // Calculate and Print the size of all variables printf("Size of longType is: %ld\n", sizeof(longType)); printf("Size of integerType is: %ld\n", sizeof(integerType)); printf("Size of longIntegerType is: %ld\n", sizeof(longIntegerType)); printf("Size of longLongIntegerType is: %ld\n", sizeof(longLongIntegerType)); printf("Size of floatType is: %ld\n", sizeof(floatType)); printf("Size of doubleType is: %ld\n", sizeof(doubleType)); printf("Size of longDoubleType is: %ld\n", sizeof(longDoubleType)); return 0;}
Output:
Size of longType is: 8
Size of integerType is: 4
Size of longIntegerType is: 8
Size of longLongIntegerType is: 8
Size of floatType is: 4
Size of doubleType is: 8
Size of longDoubleType is: 16
C-Data Types
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Oct, 2018"
},
{
"code": null,
"e": 176,
"s": 53,
"text": "long is a keyword in Java that symbolises the Long datatype. The long data type is a 64-bit two’s complement integer with:"
},
{
"code": null,
"e": 189,
"s": 176,
"text": "Size: 64 bit"
},
{
"code": null,
"e": 211,
"s": 189,
"text": "Value: -263 to 263-1."
},
{
"code": null,
"e": 491,
"s": 211,
"text": "Output of 64 bit GCC compiler would give the size of long as 8 whereas on 32 bit GCC compiler the size would be 4. So it varies from compiler to compiler. Now the question is what exactly is happening here? Let’s discuss it in the way of how compiler allocates memory internally."
},
{
"code": null,
"e": 1335,
"s": 491,
"text": "CPU calls data from RAM by giving the address of the location to MAR (Memory Address Register). The location is found and the data is transferred to MDR (Memory Data Register). This data is recorded in one of the Registers in the Processor for further processing. That’s why size of Data Bus determines the size of Registers in Processor. Now, a 32 bit register can call data of 4 bytes size only, at a time. And if the data size exceeds 32 bits, then it would required two cycles of fetching to have the data in it. This slows down the speed of 32 bit Machine compared to 64 bit, which would complete the operation in ONE fetch cycle only. So, obviously for the smaller data, it makes no difference if my processors are clocked at the same speed. Compilers are designed to generate the most efficient code for the target machine architecture."
},
{
"code": null,
"e": 1475,
"s": 1335,
"text": "Note: Interestingly we don’t have any need of “long” data type as their replacement(int, long long) is already available from C99 standard."
},
{
"code": null,
"e": 1621,
"s": 1475,
"text": "In the below program, all the possible variables with long datatype are defined and their sizes are calculated and print using sizeof() operator."
},
{
"code": null,
"e": 1693,
"s": 1621,
"text": "Below is the C program to find the demonstrate working of long keyword:"
},
{
"code": "// C program to demonstrate the working// of long keyword #include <stdio.h> int main(){ long longType; int integerType; long int longIntegerType; long long int longLongIntegerType; float floatType; double doubleType; long double longDoubleType; // Calculate and Print the size of all variables printf(\"Size of longType is: %ld\\n\", sizeof(longType)); printf(\"Size of integerType is: %ld\\n\", sizeof(integerType)); printf(\"Size of longIntegerType is: %ld\\n\", sizeof(longIntegerType)); printf(\"Size of longLongIntegerType is: %ld\\n\", sizeof(longLongIntegerType)); printf(\"Size of floatType is: %ld\\n\", sizeof(floatType)); printf(\"Size of doubleType is: %ld\\n\", sizeof(doubleType)); printf(\"Size of longDoubleType is: %ld\\n\", sizeof(longDoubleType)); return 0;}",
"e": 2575,
"s": 1693,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2575,
"text": "Output:"
},
{
"code": null,
"e": 2776,
"s": 2583,
"text": "Size of longType is: 8\nSize of integerType is: 4\nSize of longIntegerType is: 8\nSize of longLongIntegerType is: 8\nSize of floatType is: 4\nSize of doubleType is: 8\nSize of longDoubleType is: 16\n"
},
{
"code": null,
"e": 2789,
"s": 2776,
"text": "C-Data Types"
},
{
"code": null,
"e": 2804,
"s": 2789,
"text": "cpp-data-types"
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": "C Language"
}
] |
Schnorr Digital Signature
|
02 Jun, 2020
In cryptography, a Schnorr signature is a digital signature produced by the Schnorr signature algorithm that was described by Claus Schnorr. It is a digital signature scheme known for its simplicity, is efficient and generates short signatures. It is one of the protocols used to implement “Proof Of Knowledge”.In cryptography, a proof of knowledge is an interactive proof in which the prover succeeds in ‘convincing’ a verifier that the prover knows something ‘X’. For a machine to know ‘X’ is defined in terms of computation. A machine knows ‘X’ if this ‘X’ can be computed. The Verifier either accepts or rejects the proof. The signature proof is supposed to convince the Verifier that they are communicating with a user who knows the private key corresponding to the public key. In other words, the Verifier should be convinced that they are communicating with the Prover without knowing the private key.
Schnorr Digital Signature to implement Zero Knowledge Proof :Let’s take an example of two friends Sachin and Sanchita. Sanchita has announced to the world that she has a public key and can accept and receive information through it. Sachin thinks that Sanchita is lying. Sanchita wants to prove her honesty without showing her private keys. Here is where Schnorr’s protocol will help us.
Consider the following parameters:
p, q, a, s, v, r, x, y
where,
"p" is any prime number
"q" is factor of p-1
“a” such that a^q = 1 mod p
The above three variables are global and public which means anyone can see these three variables at a given scenario.
We will have two keys.
"s" is the secret key or the private key (0<s<q).
"v" is the public key = a^-s mod q.
The public key “v” will be global and public knowledge along with p, q and a. However only Sanchita will have the knowledge of the private key "s".
Now Sanchita signs wants to sends an encrypted message "M". She will follow the following steps to use Schnorr's signature:-
She will first choose a random number “r” such that 0<r<q.She will now compute a value X such that: X= a^r mod p.Now that she has computed the value of X, she is going concatenate this with the original message (same as string concatenation).So, she is going to concatenate M and X to get M||X. and she is going to store the hash of this value in e.e = H(M||X) where H() is the hash function She is going to get a value “y” such that:y = (r + s*e) mod q
She will first choose a random number “r” such that 0<r<q.
She will now compute a value X such that: X= a^r mod p.
Now that she has computed the value of X, she is going concatenate this with the original message (same as string concatenation).So, she is going to concatenate M and X to get M||X. and she is going to store the hash of this value in e.e = H(M||X) where H() is the hash function
e = H(M||X) where H() is the hash function
She is going to get a value “y” such that:y = (r + s*e) mod q
y = (r + s*e) mod q
Now that all the computations are over, she is going to send the following to Sachin.
The message “M”.The signatures e and y.
The message “M”.
The signatures e and y.
Along with this, Sachin has the following public piece of information:-
Sanchita's public key “v”.The prime number that Sanchita chose “p”.“q” which is the factor of “p-1” which Sanchita chose.“a” such that a^q = 1 mod p, chosen by Sanchita.
Sanchita's public key “v”.
The prime number that Sanchita chose “p”.
“q” which is the factor of “p-1” which Sanchita chose.
“a” such that a^q = 1 mod p, chosen by Sanchita.
Now, Sachin will have to compute X’ such that:
X’ = a^y * v^e mod p
We know that v = a^-s, let’s substitute that in the equation above and we get:
X’ = a^y * a^-se = a ^ (y-s*e)
Now we also know that,
y = r + s*e
Which means:
r = y-s*e
Let’s substitute this value in the equation above:
We get: X’ = a^r
As we have already seen above:
X= a^r
So technically:
X = X’
But Sachin doesn’t know the value of “X” because he never received that value. All that he received are the following: The message M, the signatures (e and y) and the host of public variables (public key “v”, p, q, and a).
So he is going to solve for e by doing the following:
e = H ( M||X’)
Note that earlier we solved for e by doing:
H(M||X))
So, by that logic, if the two values of e come up to be the same then that means
X = X’
This follows all three Properties of Zero Knowledge Proof :
Completeness –Sachin was convinced of Sanchita’s honesty because at the end X = X’.Soundness –The plan was sound because Sanchita only had one way to prove her honesty and that was through her private key.Zero Knowledge –Sachin never got to know about Sanchita’s private key.
Completeness –Sachin was convinced of Sanchita’s honesty because at the end X = X’.
Soundness –The plan was sound because Sanchita only had one way to prove her honesty and that was through her private key.
Zero Knowledge –Sachin never got to know about Sanchita’s private key.
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Wireless Application Protocol
Types of Network Topology
RSA Algorithm in Cryptography
Mobile Internet Protocol (or Mobile IP)
GSM in Wireless Communication
Differences between IPv4 and IPv6
TCP Server-Client implementation in C
Secure Socket Layer (SSL)
Socket Programming in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 963,
"s": 54,
"text": "In cryptography, a Schnorr signature is a digital signature produced by the Schnorr signature algorithm that was described by Claus Schnorr. It is a digital signature scheme known for its simplicity, is efficient and generates short signatures. It is one of the protocols used to implement “Proof Of Knowledge”.In cryptography, a proof of knowledge is an interactive proof in which the prover succeeds in ‘convincing’ a verifier that the prover knows something ‘X’. For a machine to know ‘X’ is defined in terms of computation. A machine knows ‘X’ if this ‘X’ can be computed. The Verifier either accepts or rejects the proof. The signature proof is supposed to convince the Verifier that they are communicating with a user who knows the private key corresponding to the public key. In other words, the Verifier should be convinced that they are communicating with the Prover without knowing the private key."
},
{
"code": null,
"e": 1350,
"s": 963,
"text": "Schnorr Digital Signature to implement Zero Knowledge Proof :Let’s take an example of two friends Sachin and Sanchita. Sanchita has announced to the world that she has a public key and can accept and receive information through it. Sachin thinks that Sanchita is lying. Sanchita wants to prove her honesty without showing her private keys. Here is where Schnorr’s protocol will help us."
},
{
"code": null,
"e": 1491,
"s": 1350,
"text": "Consider the following parameters: \np, q, a, s, v, r, x, y\n\nwhere,\n\"p\" is any prime number\n\"q\" is factor of p-1\n“a” such that a^q = 1 mod p "
},
{
"code": null,
"e": 1609,
"s": 1491,
"text": "The above three variables are global and public which means anyone can see these three variables at a given scenario."
},
{
"code": null,
"e": 1632,
"s": 1609,
"text": "We will have two keys."
},
{
"code": null,
"e": 1719,
"s": 1632,
"text": "\"s\" is the secret key or the private key (0<s<q).\n\"v\" is the public key = a^-s mod q. "
},
{
"code": null,
"e": 1867,
"s": 1719,
"text": "The public key “v” will be global and public knowledge along with p, q and a. However only Sanchita will have the knowledge of the private key \"s\"."
},
{
"code": null,
"e": 1992,
"s": 1867,
"text": "Now Sanchita signs wants to sends an encrypted message \"M\". She will follow the following steps to use Schnorr's signature:-"
},
{
"code": null,
"e": 2447,
"s": 1992,
"text": "She will first choose a random number “r” such that 0<r<q.She will now compute a value X such that: X= a^r mod p.Now that she has computed the value of X, she is going concatenate this with the original message (same as string concatenation).So, she is going to concatenate M and X to get M||X. and she is going to store the hash of this value in e.e = H(M||X) where H() is the hash function She is going to get a value “y” such that:y = (r + s*e) mod q "
},
{
"code": null,
"e": 2506,
"s": 2447,
"text": "She will first choose a random number “r” such that 0<r<q."
},
{
"code": null,
"e": 2562,
"s": 2506,
"text": "She will now compute a value X such that: X= a^r mod p."
},
{
"code": null,
"e": 2842,
"s": 2562,
"text": "Now that she has computed the value of X, she is going concatenate this with the original message (same as string concatenation).So, she is going to concatenate M and X to get M||X. and she is going to store the hash of this value in e.e = H(M||X) where H() is the hash function "
},
{
"code": null,
"e": 2886,
"s": 2842,
"text": "e = H(M||X) where H() is the hash function "
},
{
"code": null,
"e": 2949,
"s": 2886,
"text": "She is going to get a value “y” such that:y = (r + s*e) mod q "
},
{
"code": null,
"e": 2970,
"s": 2949,
"text": "y = (r + s*e) mod q "
},
{
"code": null,
"e": 3056,
"s": 2970,
"text": "Now that all the computations are over, she is going to send the following to Sachin."
},
{
"code": null,
"e": 3096,
"s": 3056,
"text": "The message “M”.The signatures e and y."
},
{
"code": null,
"e": 3113,
"s": 3096,
"text": "The message “M”."
},
{
"code": null,
"e": 3137,
"s": 3113,
"text": "The signatures e and y."
},
{
"code": null,
"e": 3209,
"s": 3137,
"text": "Along with this, Sachin has the following public piece of information:-"
},
{
"code": null,
"e": 3379,
"s": 3209,
"text": "Sanchita's public key “v”.The prime number that Sanchita chose “p”.“q” which is the factor of “p-1” which Sanchita chose.“a” such that a^q = 1 mod p, chosen by Sanchita."
},
{
"code": null,
"e": 3406,
"s": 3379,
"text": "Sanchita's public key “v”."
},
{
"code": null,
"e": 3448,
"s": 3406,
"text": "The prime number that Sanchita chose “p”."
},
{
"code": null,
"e": 3503,
"s": 3448,
"text": "“q” which is the factor of “p-1” which Sanchita chose."
},
{
"code": null,
"e": 3552,
"s": 3503,
"text": "“a” such that a^q = 1 mod p, chosen by Sanchita."
},
{
"code": null,
"e": 3599,
"s": 3552,
"text": "Now, Sachin will have to compute X’ such that:"
},
{
"code": null,
"e": 3621,
"s": 3599,
"text": "X’ = a^y * v^e mod p "
},
{
"code": null,
"e": 3700,
"s": 3621,
"text": "We know that v = a^-s, let’s substitute that in the equation above and we get:"
},
{
"code": null,
"e": 3732,
"s": 3700,
"text": "X’ = a^y * a^-se = a ^ (y-s*e) "
},
{
"code": null,
"e": 3755,
"s": 3732,
"text": "Now we also know that,"
},
{
"code": null,
"e": 3793,
"s": 3755,
"text": "y = r + s*e\n\nWhich means: \nr = y-s*e "
},
{
"code": null,
"e": 3844,
"s": 3793,
"text": "Let’s substitute this value in the equation above:"
},
{
"code": null,
"e": 3862,
"s": 3844,
"text": "We get: X’ = a^r "
},
{
"code": null,
"e": 3893,
"s": 3862,
"text": "As we have already seen above:"
},
{
"code": null,
"e": 3901,
"s": 3893,
"text": "X= a^r "
},
{
"code": null,
"e": 3917,
"s": 3901,
"text": "So technically:"
},
{
"code": null,
"e": 3925,
"s": 3917,
"text": "X = X’ "
},
{
"code": null,
"e": 4148,
"s": 3925,
"text": "But Sachin doesn’t know the value of “X” because he never received that value. All that he received are the following: The message M, the signatures (e and y) and the host of public variables (public key “v”, p, q, and a)."
},
{
"code": null,
"e": 4202,
"s": 4148,
"text": "So he is going to solve for e by doing the following:"
},
{
"code": null,
"e": 4218,
"s": 4202,
"text": "e = H ( M||X’) "
},
{
"code": null,
"e": 4262,
"s": 4218,
"text": "Note that earlier we solved for e by doing:"
},
{
"code": null,
"e": 4272,
"s": 4262,
"text": "H(M||X)) "
},
{
"code": null,
"e": 4353,
"s": 4272,
"text": "So, by that logic, if the two values of e come up to be the same then that means"
},
{
"code": null,
"e": 4361,
"s": 4353,
"text": "X = X’ "
},
{
"code": null,
"e": 4421,
"s": 4361,
"text": "This follows all three Properties of Zero Knowledge Proof :"
},
{
"code": null,
"e": 4697,
"s": 4421,
"text": "Completeness –Sachin was convinced of Sanchita’s honesty because at the end X = X’.Soundness –The plan was sound because Sanchita only had one way to prove her honesty and that was through her private key.Zero Knowledge –Sachin never got to know about Sanchita’s private key."
},
{
"code": null,
"e": 4781,
"s": 4697,
"text": "Completeness –Sachin was convinced of Sanchita’s honesty because at the end X = X’."
},
{
"code": null,
"e": 4904,
"s": 4781,
"text": "Soundness –The plan was sound because Sanchita only had one way to prove her honesty and that was through her private key."
},
{
"code": null,
"e": 4975,
"s": 4904,
"text": "Zero Knowledge –Sachin never got to know about Sanchita’s private key."
},
{
"code": null,
"e": 4988,
"s": 4975,
"text": "cryptography"
},
{
"code": null,
"e": 5006,
"s": 4988,
"text": "Computer Networks"
},
{
"code": null,
"e": 5019,
"s": 5006,
"text": "cryptography"
},
{
"code": null,
"e": 5037,
"s": 5019,
"text": "Computer Networks"
},
{
"code": null,
"e": 5135,
"s": 5037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5167,
"s": 5135,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 5197,
"s": 5167,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5223,
"s": 5197,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 5253,
"s": 5223,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 5293,
"s": 5253,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 5323,
"s": 5293,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5357,
"s": 5323,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5395,
"s": 5357,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 5421,
"s": 5395,
"text": "Secure Socket Layer (SSL)"
}
] |
Scrap books using Beautifulsoup from books.toscrape in Python
|
02 Jul, 2021
Web Scraping is the technique of extracting large amounts of data from websites where the extracted data is saved in a local file on your computer. The simplest form of Web Scrapping is manually copying and pasting data from a web page into a text file or spreadsheet. Sometimes this is the only solution when the websites set up barriers. But in most cases, a huge amount of data is required which is difficult for a human to scrape. Therefore, we have Web Scrapping tools to automate the process. One such Web Scrapping tool is BeautifulSoup.
BeautifulSoup is a Python Web Scrapping library for pulling data out and parsing of HTML and XML files. To install BeautifulSoup type the below command in the terminal.
pip install BeautifulSoup4
BeautifulSoup is a tool for HTML parsing but we will need a web client to grab something from the internet. This can be achieved in Python by using the package urllib.
In this article, our task will be to –
Collect the name of the product and price.
Save the collected data in .csv format.
As an example, we will collect the title and price of the book from the website: BookToScrape
BooksToScrape Website with All Products in 1st Page
Import the libraries: BeautifulSoup and urllib.
Read HTML link using urllib.
Allow parsing of the link using Beautiful soup.
Look for the tag that contains all the products of that particular webpage and extract it.
Look for the tag that displays the name and price of the book and extract it.
With all the information extracted, print and save everything in a csv file.
All books and its underlying information.
Below is the implementation.
Python3
# import web grabbing client and# HTML parserfrom urllib.request import urlopen as uReqfrom bs4 import BeautifulSoup as soup # variable to store website link as stringmyurl = 'http://books.toscrape.com/index.html' # grab website and store in variable uclientuClient = uReq(myurl) # read and close HTMLpage_html = uClient.read()uClient.close() # call BeautifulSoup for parsingpage_soup = soup(page_html, "html.parser") # grabs all the products under list tagbookshelf = page_soup.findAll( "li", {"class": "col-xs-6 col-sm-4 col-md-3 col-lg-3"}) # create csv file of all productsfilename = ("Books.csv")f = open(filename, "w") headers = "Book title, Price\n"f.write(headers) for books in bookshelf: # collect title of all books book_title = books.h3.a["title"] # collect book price of all books book_price = books.findAll("p", {"class": "price_color"}) price = book_price[0].text.strip() print("Title of the book :" + book_title) print("Price of the book :" + price) f.write(book_title + "," + price+"\n") f.close()
Output :
CSV File:
Let’s explain the above code. In this example, a single book and its information are contained under the <li> tag. So we use –
The findAll() function looks for all the li tags with class(can be ID if its ID) named “col-xs-6 col-sm-4 col-md-3 col-lg-3” and stores it in the variable bookshelf.
bookshelf = page_soup.findAll(“li” , {“class” : “col-xs-6 col-sm-4 col-md-3 col-lg-3”})
It will store all information about that <li> class which are the books. You can see in the picture above, each <li> tag and class : “col-xs-6 col-sm-4 col-md-3 col-lg-3” represents one book.
Now that we have all our books, we need to select which particular information we must extract from each book and that is Title and Price.
You can see in the image above , the title of each book is under <h3> tag which is under the <a> tag with ‘title’. So the above function is used for extracting the Title of each book.
book_title = books.h3.a["title"]
For the price we can see that it is under <p> tag in class : “price_color” so we use findAll()
book_price = books.findAll("p", {"class" : "price_color"})
price = book_price[0].text.strip()
The 0 index takes in the price of the first book of the page and stores it in variable price. The function .text.strip() collects only the text and strips of any spaces forwards and backwards.
surinderdawra388
Python-projects
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 573,
"s": 28,
"text": "Web Scraping is the technique of extracting large amounts of data from websites where the extracted data is saved in a local file on your computer. The simplest form of Web Scrapping is manually copying and pasting data from a web page into a text file or spreadsheet. Sometimes this is the only solution when the websites set up barriers. But in most cases, a huge amount of data is required which is difficult for a human to scrape. Therefore, we have Web Scrapping tools to automate the process. One such Web Scrapping tool is BeautifulSoup."
},
{
"code": null,
"e": 742,
"s": 573,
"text": "BeautifulSoup is a Python Web Scrapping library for pulling data out and parsing of HTML and XML files. To install BeautifulSoup type the below command in the terminal."
},
{
"code": null,
"e": 769,
"s": 742,
"text": "pip install BeautifulSoup4"
},
{
"code": null,
"e": 937,
"s": 769,
"text": "BeautifulSoup is a tool for HTML parsing but we will need a web client to grab something from the internet. This can be achieved in Python by using the package urllib."
},
{
"code": null,
"e": 976,
"s": 937,
"text": "In this article, our task will be to –"
},
{
"code": null,
"e": 1019,
"s": 976,
"text": "Collect the name of the product and price."
},
{
"code": null,
"e": 1059,
"s": 1019,
"text": "Save the collected data in .csv format."
},
{
"code": null,
"e": 1153,
"s": 1059,
"text": "As an example, we will collect the title and price of the book from the website: BookToScrape"
},
{
"code": null,
"e": 1205,
"s": 1153,
"text": "BooksToScrape Website with All Products in 1st Page"
},
{
"code": null,
"e": 1253,
"s": 1205,
"text": "Import the libraries: BeautifulSoup and urllib."
},
{
"code": null,
"e": 1282,
"s": 1253,
"text": "Read HTML link using urllib."
},
{
"code": null,
"e": 1330,
"s": 1282,
"text": "Allow parsing of the link using Beautiful soup."
},
{
"code": null,
"e": 1421,
"s": 1330,
"text": "Look for the tag that contains all the products of that particular webpage and extract it."
},
{
"code": null,
"e": 1499,
"s": 1421,
"text": "Look for the tag that displays the name and price of the book and extract it."
},
{
"code": null,
"e": 1576,
"s": 1499,
"text": "With all the information extracted, print and save everything in a csv file."
},
{
"code": null,
"e": 1618,
"s": 1576,
"text": "All books and its underlying information."
},
{
"code": null,
"e": 1648,
"s": 1618,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1656,
"s": 1648,
"text": "Python3"
},
{
"code": "# import web grabbing client and# HTML parserfrom urllib.request import urlopen as uReqfrom bs4 import BeautifulSoup as soup # variable to store website link as stringmyurl = 'http://books.toscrape.com/index.html' # grab website and store in variable uclientuClient = uReq(myurl) # read and close HTMLpage_html = uClient.read()uClient.close() # call BeautifulSoup for parsingpage_soup = soup(page_html, \"html.parser\") # grabs all the products under list tagbookshelf = page_soup.findAll( \"li\", {\"class\": \"col-xs-6 col-sm-4 col-md-3 col-lg-3\"}) # create csv file of all productsfilename = (\"Books.csv\")f = open(filename, \"w\") headers = \"Book title, Price\\n\"f.write(headers) for books in bookshelf: # collect title of all books book_title = books.h3.a[\"title\"] # collect book price of all books book_price = books.findAll(\"p\", {\"class\": \"price_color\"}) price = book_price[0].text.strip() print(\"Title of the book :\" + book_title) print(\"Price of the book :\" + price) f.write(book_title + \",\" + price+\"\\n\") f.close()",
"e": 2701,
"s": 1656,
"text": null
},
{
"code": null,
"e": 2710,
"s": 2701,
"text": "Output :"
},
{
"code": null,
"e": 2720,
"s": 2710,
"text": "CSV File:"
},
{
"code": null,
"e": 2847,
"s": 2720,
"text": "Let’s explain the above code. In this example, a single book and its information are contained under the <li> tag. So we use –"
},
{
"code": null,
"e": 3013,
"s": 2847,
"text": "The findAll() function looks for all the li tags with class(can be ID if its ID) named “col-xs-6 col-sm-4 col-md-3 col-lg-3” and stores it in the variable bookshelf."
},
{
"code": null,
"e": 3103,
"s": 3013,
"text": "bookshelf = page_soup.findAll(“li” , {“class” : “col-xs-6 col-sm-4 col-md-3 col-lg-3”}) "
},
{
"code": null,
"e": 3295,
"s": 3103,
"text": "It will store all information about that <li> class which are the books. You can see in the picture above, each <li> tag and class : “col-xs-6 col-sm-4 col-md-3 col-lg-3” represents one book."
},
{
"code": null,
"e": 3436,
"s": 3295,
"text": "Now that we have all our books, we need to select which particular information we must extract from each book and that is Title and Price. "
},
{
"code": null,
"e": 3620,
"s": 3436,
"text": "You can see in the image above , the title of each book is under <h3> tag which is under the <a> tag with ‘title’. So the above function is used for extracting the Title of each book."
},
{
"code": null,
"e": 3653,
"s": 3620,
"text": "book_title = books.h3.a[\"title\"]"
},
{
"code": null,
"e": 3748,
"s": 3653,
"text": "For the price we can see that it is under <p> tag in class : “price_color” so we use findAll()"
},
{
"code": null,
"e": 3842,
"s": 3748,
"text": "book_price = books.findAll(\"p\", {\"class\" : \"price_color\"})\nprice = book_price[0].text.strip()"
},
{
"code": null,
"e": 4035,
"s": 3842,
"text": "The 0 index takes in the price of the first book of the page and stores it in variable price. The function .text.strip() collects only the text and strips of any spaces forwards and backwards."
},
{
"code": null,
"e": 4052,
"s": 4035,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4068,
"s": 4052,
"text": "Python-projects"
},
{
"code": null,
"e": 4075,
"s": 4068,
"text": "Python"
}
] |
Python | Sort list of tuples by specific ordering
|
26 Feb, 2019
The normal sorting of tuples has been dealt previously. This article aims at sorting the given list of tuples by the second element, based on the order provided in some list.
Method #1 : Using list comprehension + filter() + lambdaAbove three functions can be combined to perform the particular task in which list comprehension performs the iteration, lambda function is used as helper function for filtering to sort according to second element of tuple.
# Python3 code to demonstrate# sort list of tuples according to second# using list comprehension + filter() + lambda # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)] # initializing sort order sort_order = [4, 2, 3] # printing the original listprint ("The original list is : " + str(test_list)) # printing sort order list print ("The sort order list is : " + str(sort_order)) # using list comprehension + filter() + lambda# sort list of tuples according to secondres = [i for j in sort_order for i in filter(lambda k: k[1] == j, test_list)] # printing resultprint ("The list after appropriate sorting : " + str(res))
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]
Method #2 : Using sorted() + index() + lambdaThe sorted function can be used to sort according to order specified. The index function specifies that second element of tuple has to be taken into considerations and all are joined with help of lambda.
# Python3 code to demonstrate# sort list of tuples according to second# using sorted() + index() + lambda # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)] # initializing sort order sort_order = [4, 2, 3] # printing the original listprint ("The original list is : " + str(test_list)) # printing sort order list print ("The sort order list is : " + str(sort_order)) # using sorted() + index() + lambda# sort list of tuples according to secondres = list(sorted(test_list, key = lambda i: sort_order.index(i[1]))) # printing resultprint ("The list after appropriate sorting : " + str(res))
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]
Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 229,
"s": 54,
"text": "The normal sorting of tuples has been dealt previously. This article aims at sorting the given list of tuples by the second element, based on the order provided in some list."
},
{
"code": null,
"e": 509,
"s": 229,
"text": "Method #1 : Using list comprehension + filter() + lambdaAbove three functions can be combined to perform the particular task in which list comprehension performs the iteration, lambda function is used as helper function for filtering to sort according to second element of tuple."
},
{
"code": "# Python3 code to demonstrate# sort list of tuples according to second# using list comprehension + filter() + lambda # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)] # initializing sort order sort_order = [4, 2, 3] # printing the original listprint (\"The original list is : \" + str(test_list)) # printing sort order list print (\"The sort order list is : \" + str(sort_order)) # using list comprehension + filter() + lambda# sort list of tuples according to secondres = [i for j in sort_order for i in filter(lambda k: k[1] == j, test_list)] # printing resultprint (\"The list after appropriate sorting : \" + str(res))",
"e": 1160,
"s": 509,
"text": null
},
{
"code": null,
"e": 1318,
"s": 1160,
"text": "The original list is : [('a', 2), ('c', 3), ('d', 4)]\nThe sort order list is : [4, 2, 3]\nThe list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]\n"
},
{
"code": null,
"e": 1568,
"s": 1318,
"text": " Method #2 : Using sorted() + index() + lambdaThe sorted function can be used to sort according to order specified. The index function specifies that second element of tuple has to be taken into considerations and all are joined with help of lambda."
},
{
"code": "# Python3 code to demonstrate# sort list of tuples according to second# using sorted() + index() + lambda # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)] # initializing sort order sort_order = [4, 2, 3] # printing the original listprint (\"The original list is : \" + str(test_list)) # printing sort order list print (\"The sort order list is : \" + str(sort_order)) # using sorted() + index() + lambda# sort list of tuples according to secondres = list(sorted(test_list, key = lambda i: sort_order.index(i[1]))) # printing resultprint (\"The list after appropriate sorting : \" + str(res))",
"e": 2189,
"s": 1568,
"text": null
},
{
"code": null,
"e": 2347,
"s": 2189,
"text": "The original list is : [('a', 2), ('c', 3), ('d', 4)]\nThe sort order list is : [4, 2, 3]\nThe list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]\n"
},
{
"code": null,
"e": 2368,
"s": 2347,
"text": "Python list-programs"
},
{
"code": null,
"e": 2390,
"s": 2368,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2402,
"s": 2390,
"text": "python-list"
},
{
"code": null,
"e": 2415,
"s": 2402,
"text": "python-tuple"
},
{
"code": null,
"e": 2422,
"s": 2415,
"text": "Python"
},
{
"code": null,
"e": 2438,
"s": 2422,
"text": "Python Programs"
},
{
"code": null,
"e": 2450,
"s": 2438,
"text": "python-list"
},
{
"code": null,
"e": 2548,
"s": 2450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2566,
"s": 2548,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2608,
"s": 2566,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2630,
"s": 2608,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2665,
"s": 2630,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2697,
"s": 2665,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2740,
"s": 2697,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2762,
"s": 2740,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2801,
"s": 2762,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2839,
"s": 2801,
"text": "Python | Convert a list to dictionary"
}
] |
HTML Text Formatting
|
13 Dec, 2021
In this article, we will know HTML Text Formatting, & will understand various ways of formatting the text. HTML facilitates the ability for formatting text just like we do in MS Word or any text editing software. We will go through a few such options.
Example: In this example, we simply display text in HTML strong, small, and Highlight formatting respectively.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <!--Text in Strong--> <strong>Hello Geeks</strong> <br> <!--Text in small--> <small>Hello Geeks</small> <br> <!--Text in Highlight--> <mark>Hello Geeks</mark></body> </html>
Output:
Formatting the text using various HTML tags
The below are the various options available to format the text:
Making text Bold or Strong: We can make the text bold using the <b> tag. The tag uses both opening and closing tags. The text that needs to be made bold must be within <b> and </b> tag. We can also use the <strong> tag to make the text strong, with added semantic importance. It also opens with <strong> and ends with </strong> tag.
Example 1: The below example describes the formatting of the text to normal, bold, & strong.
HTML
<!DOCTYPE html><html> <head> <title>Bold Text</title></head> <body> <!--Normal text--> <p>Hello GeeksforGeeks</p> <!--Text in Bold--> <p> <b>Hello GeeksforGeeks</b> </p> <!--Text in Strong--> <p> <strong>Hello GeeksforGeeks</strong> </p> </body> </html>
Output:
Formatting the text using different tags
Making text Italic or emphasize: The <i> tag is used to italicise the text. It opens with <i> and ends with </i> tag. The <em> tag is used to emphasize the text, with added semantic importance. It opens with <em> and ends with </em> tag.
Example 2: The below example describes the formatting of the text to Italic or emphasize.
HTML
<!DOCTYPE html><html> <head> <title>Italic</title></head> <body> <!--Normal text--> <p>Hello GeeksforGeeks</p> <!--Text in Italics--> <p> <i>Hello GeeksforGeeks</i> </p> <!--Text in Emphasize--> <p> <em>Hello GeeksforGeeks</em> </p> </body> </html>
Output:
Formatting the text using <I> & <em> tags
Highlighting a text: It is also possible to highlight a text in HTML using the <mark> tag. It has a opening tag <mark> and a closing tag </mark>.
Example: The below example describes the use of the <mark> tag that is used to define the marked text.
HTML
<!DOCTYPE html><html> <head> <title>Highlight</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Highlight--> <p> <mark>Hello GeeksforGeeks</mark> </p> </body> </html>
Output:
Using <mark> Tag
Example: The below example describes the use of the <sup> & <sub> tags that are used to add the superscript & subscript texts to the HTML document.
HTML
<!DOCTYPE html><html> <head> <title>Superscript and Subscript</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Superscript--> <p>Hello <sup>GeeksforGeeks</sup> </p> <!--Text in Subscript--> <p>Hello <sub>GeeksforGeeks</sub> </p> </body> </html>
Output:
Using <sub> & <sup> Tag
Making text smaller: The <small> element is used to make the text smaller. The text that needs to be displayed smaller should be written inside <small> and </small> tag.
Example: The below example describes the use of the <small> tag that is used to set small font size.
HTML
<!DOCTYPE html><html> <head> <title>Small</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in small--> <p> <small>Hello GeeksforGeeks</small> </p> </body> </html>
Output:
Using <small> Tag
Striking through the text: The <del> element is used to strike through the text marking the part as deleted. It also has an opening and a closing tag.
Example: The below example describes the use of the <del> tag that is used to mark a portion of text which has been deleted from the document.
HTML
<!DOCTYPE html><html> <head> <title>Delete</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Delete--> <p> <del>Hello GeeksforGeeks</del> </p> </body> </html>
Output:
Using <del> Tag
Adding a text: The <ins> element is used to underline a text marking the part as inserted or added. It also has an opening and a closing tag.
Example: This example describes the use of the <ins> tag to used to specify a block of inserted text.
HTML
<!DOCTYPE html><html> <head> <title>Inserting the Text</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Insert--> <p><ins>Hello GeeksforGeeks</ins></p> </body> </html>
Output:
Using <ins> tag
Supported Browsers:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
simranarora5sos
ysachin2314
singghakshay
bhaskargeeksforgeeks
HTML and XML
HTML-Basics
Web technologies-HTML and XML
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 304,
"s": 52,
"text": "In this article, we will know HTML Text Formatting, & will understand various ways of formatting the text. HTML facilitates the ability for formatting text just like we do in MS Word or any text editing software. We will go through a few such options."
},
{
"code": null,
"e": 415,
"s": 304,
"text": "Example: In this example, we simply display text in HTML strong, small, and Highlight formatting respectively."
},
{
"code": null,
"e": 420,
"s": 415,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <!--Text in Strong--> <strong>Hello Geeks</strong> <br> <!--Text in small--> <small>Hello Geeks</small> <br> <!--Text in Highlight--> <mark>Hello Geeks</mark></body> </html>",
"e": 704,
"s": 420,
"text": null
},
{
"code": null,
"e": 712,
"s": 704,
"text": "Output:"
},
{
"code": null,
"e": 756,
"s": 712,
"text": "Formatting the text using various HTML tags"
},
{
"code": null,
"e": 820,
"s": 756,
"text": "The below are the various options available to format the text:"
},
{
"code": null,
"e": 1153,
"s": 820,
"text": "Making text Bold or Strong: We can make the text bold using the <b> tag. The tag uses both opening and closing tags. The text that needs to be made bold must be within <b> and </b> tag. We can also use the <strong> tag to make the text strong, with added semantic importance. It also opens with <strong> and ends with </strong> tag."
},
{
"code": null,
"e": 1246,
"s": 1153,
"text": "Example 1: The below example describes the formatting of the text to normal, bold, & strong."
},
{
"code": null,
"e": 1251,
"s": 1246,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bold Text</title></head> <body> <!--Normal text--> <p>Hello GeeksforGeeks</p> <!--Text in Bold--> <p> <b>Hello GeeksforGeeks</b> </p> <!--Text in Strong--> <p> <strong>Hello GeeksforGeeks</strong> </p> </body> </html>",
"e": 1572,
"s": 1251,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1572,
"text": "Output: "
},
{
"code": null,
"e": 1622,
"s": 1581,
"text": "Formatting the text using different tags"
},
{
"code": null,
"e": 1860,
"s": 1622,
"text": "Making text Italic or emphasize: The <i> tag is used to italicise the text. It opens with <i> and ends with </i> tag. The <em> tag is used to emphasize the text, with added semantic importance. It opens with <em> and ends with </em> tag."
},
{
"code": null,
"e": 1950,
"s": 1860,
"text": "Example 2: The below example describes the formatting of the text to Italic or emphasize."
},
{
"code": null,
"e": 1955,
"s": 1950,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Italic</title></head> <body> <!--Normal text--> <p>Hello GeeksforGeeks</p> <!--Text in Italics--> <p> <i>Hello GeeksforGeeks</i> </p> <!--Text in Emphasize--> <p> <em>Hello GeeksforGeeks</em> </p> </body> </html>",
"e": 2266,
"s": 1955,
"text": null
},
{
"code": null,
"e": 2274,
"s": 2266,
"text": "Output:"
},
{
"code": null,
"e": 2316,
"s": 2274,
"text": "Formatting the text using <I> & <em> tags"
},
{
"code": null,
"e": 2462,
"s": 2316,
"text": "Highlighting a text: It is also possible to highlight a text in HTML using the <mark> tag. It has a opening tag <mark> and a closing tag </mark>."
},
{
"code": null,
"e": 2565,
"s": 2462,
"text": "Example: The below example describes the use of the <mark> tag that is used to define the marked text."
},
{
"code": null,
"e": 2570,
"s": 2565,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Highlight</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Highlight--> <p> <mark>Hello GeeksforGeeks</mark> </p> </body> </html>",
"e": 2813,
"s": 2570,
"text": null
},
{
"code": null,
"e": 2821,
"s": 2813,
"text": "Output:"
},
{
"code": null,
"e": 2838,
"s": 2821,
"text": "Using <mark> Tag"
},
{
"code": null,
"e": 2986,
"s": 2838,
"text": "Example: The below example describes the use of the <sup> & <sub> tags that are used to add the superscript & subscript texts to the HTML document."
},
{
"code": null,
"e": 2991,
"s": 2986,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Superscript and Subscript</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Superscript--> <p>Hello <sup>GeeksforGeeks</sup> </p> <!--Text in Subscript--> <p>Hello <sub>GeeksforGeeks</sub> </p> </body> </html>",
"e": 3332,
"s": 2991,
"text": null
},
{
"code": null,
"e": 3340,
"s": 3332,
"text": "Output:"
},
{
"code": null,
"e": 3364,
"s": 3340,
"text": "Using <sub> & <sup> Tag"
},
{
"code": null,
"e": 3534,
"s": 3364,
"text": "Making text smaller: The <small> element is used to make the text smaller. The text that needs to be displayed smaller should be written inside <small> and </small> tag."
},
{
"code": null,
"e": 3635,
"s": 3534,
"text": "Example: The below example describes the use of the <small> tag that is used to set small font size."
},
{
"code": null,
"e": 3640,
"s": 3635,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Small</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in small--> <p> <small>Hello GeeksforGeeks</small> </p> </body> </html>",
"e": 3877,
"s": 3640,
"text": null
},
{
"code": null,
"e": 3885,
"s": 3877,
"text": "Output:"
},
{
"code": null,
"e": 3903,
"s": 3885,
"text": "Using <small> Tag"
},
{
"code": null,
"e": 4054,
"s": 3903,
"text": "Striking through the text: The <del> element is used to strike through the text marking the part as deleted. It also has an opening and a closing tag."
},
{
"code": null,
"e": 4197,
"s": 4054,
"text": "Example: The below example describes the use of the <del> tag that is used to mark a portion of text which has been deleted from the document."
},
{
"code": null,
"e": 4202,
"s": 4197,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Delete</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Delete--> <p> <del>Hello GeeksforGeeks</del> </p> </body> </html>",
"e": 4431,
"s": 4202,
"text": null
},
{
"code": null,
"e": 4439,
"s": 4431,
"text": "Output:"
},
{
"code": null,
"e": 4455,
"s": 4439,
"text": "Using <del> Tag"
},
{
"code": null,
"e": 4597,
"s": 4455,
"text": "Adding a text: The <ins> element is used to underline a text marking the part as inserted or added. It also has an opening and a closing tag."
},
{
"code": null,
"e": 4699,
"s": 4597,
"text": "Example: This example describes the use of the <ins> tag to used to specify a block of inserted text."
},
{
"code": null,
"e": 4704,
"s": 4699,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Inserting the Text</title></head> <body> <!--Text in Normal--> <p>Hello GeeksforGeeks</p> <!--Text in Insert--> <p><ins>Hello GeeksforGeeks</ins></p> </body> </html>",
"e": 4943,
"s": 4704,
"text": null
},
{
"code": null,
"e": 4951,
"s": 4943,
"text": "Output:"
},
{
"code": null,
"e": 4967,
"s": 4951,
"text": "Using <ins> tag"
},
{
"code": null,
"e": 4987,
"s": 4967,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 5001,
"s": 4987,
"text": "Google Chrome"
},
{
"code": null,
"e": 5016,
"s": 5001,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 5024,
"s": 5016,
"text": "Firefox"
},
{
"code": null,
"e": 5030,
"s": 5024,
"text": "Opera"
},
{
"code": null,
"e": 5037,
"s": 5030,
"text": "Safari"
},
{
"code": null,
"e": 5053,
"s": 5037,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5065,
"s": 5053,
"text": "ysachin2314"
},
{
"code": null,
"e": 5078,
"s": 5065,
"text": "singghakshay"
},
{
"code": null,
"e": 5099,
"s": 5078,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 5112,
"s": 5099,
"text": "HTML and XML"
},
{
"code": null,
"e": 5124,
"s": 5112,
"text": "HTML-Basics"
},
{
"code": null,
"e": 5154,
"s": 5124,
"text": "Web technologies-HTML and XML"
},
{
"code": null,
"e": 5159,
"s": 5154,
"text": "HTML"
},
{
"code": null,
"e": 5176,
"s": 5159,
"text": "Web Technologies"
},
{
"code": null,
"e": 5181,
"s": 5176,
"text": "HTML"
},
{
"code": null,
"e": 5279,
"s": 5181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5327,
"s": 5279,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5389,
"s": 5327,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5439,
"s": 5389,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5463,
"s": 5439,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5516,
"s": 5463,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5549,
"s": 5516,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5611,
"s": 5549,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5672,
"s": 5611,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5722,
"s": 5672,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Sort the character array based on ASCII % N
|
08 Oct, 2021
Given an array arr[] of characters and an integer M, the task is to sort the array based on ASCII % M i.e. the character whose ASCII value % M is minimum should appear first.
Examples:
Input: arr[] = {‘a’, ‘b’, ‘c’, ‘e’}, M = 2 Output: b a c e The ASCII % M for the array are {97 % 2, 98 % 2, 99 % 2, 101 % 2} i.e. {1, 0, 1, 1}
Input: arr[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}, M = 8 Output: k s e e g
Method 1: Write a function to sort the array and instead of comparing the values of the characters, compare their ASCII values % M to sort the array. Print the sorted array in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A utility function to swap two elementsvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} /* This function takes last element as pivot, placesthe pivot element at its correct position in sorted array, and places all smaller (smaller than pivot)to left of pivot and all greater elements to rightof pivot */int partition(char arr[], int low, int high, int mod){ // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */void quickSort(char arr[], int low, int high, int mod){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); }} // Function to print the given arrayvoid printArray(char arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " ";} // Driver codeint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = sizeof(arr) / sizeof(arr[0]); int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); return 0;}
// Java implementation of the approachclass GFG{ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(char arr[], int low, int high, int mod) { // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap char t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } char t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(char arr[], int low, int high, int mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array static void printArray(char arr[], int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + " "); } // Driver code public static void main(String [] args) { char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = arr.length; int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); }} // This code is contributed by ihritik
# Python3 implementation of the above approach """ This function takes last element as pivot,places the pivot element at its correct positionin sorted array, and places all smaller (smaller than pivot) to left of pivot andall greater elements to right of pivot """def partition(arr, low, high, mod) : # pivot pivot = ord(arr[high]); # Index of smaller element i = (low - 1); piv = pivot % mod; for j in range(low, high) : a = ord(arr[j]) % mod; # If current element is smaller than or # equal to pivot # Instead of values, ASCII % m values # are compared if (a <= piv) : # Increment index of smaller element i += 1; arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1); """ The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index """ def quickSort(arr, low, high, mod) : if (low < high) : ''' pi is partitioning index, arr[p] is now at right place ''' pi = partition(arr, low, high, mod); # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); return arr # Function to print the given arraydef printArray(arr, size) : for i in range(0, size) : print(arr[i], end = " "); # Driver codeif __name__ == "__main__" : arr = [ 'g', 'e', 'e', 'k', 's' ]; n = len(arr); mod = 8; # Sort the given array arr = quickSort(arr, 0, n - 1, mod); # Print the sorted array printArray(arr, n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(char []arr, int low, int high, int mod) { // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); char t; int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than o // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(char []arr, int low, int high, int mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array static void printArray(char []arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main() { char []arr = { 'g', 'e', 'e', 'k', 's' }; int n = arr.Length; int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); }} // This code is contributed by ihritik
// JavaScript implementation of the approach /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition( arr, low, high, mod) { // pivot var pivot = arr[high]; // Index of smaller element var i = (low - 1); var piv = pivot % mod; for (var j = low; j <= high - 1; j++) { var a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap var t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } var t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function quickSort(arr, low, high, mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ var pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array function printArray( arr, size) { for (var i = 0; i < size; i++) document.write(arr[i] + " "); } // Driver code var arr = ['g', 'e', 'e', 'k', 's' ]; var n = arr.length; var mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); // This code is contributed by shivanisinghss2110
k s e e g
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Method 2: The sorting can also be done using std::sort() and modifying the comparator.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int M; // Comparator used to sort the array// according to ASCII % Mbool comparator(char ch1, char ch2){ int i = ch1 % M; int j = ch2 % M; return (i < j);} // Function to print the given arrayvoid printArray(char arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " ";} // Driver codeint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = sizeof(arr) / sizeof(arr[0]); M = 8; // Sort the given array sort(arr, arr + n, comparator); // Print the sorted array printArray(arr, n); return 0;}
k s e e g
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
ankthon
ihritik
subhammahato348
surinderdawra388
ruhelaa48
shivanisinghss2110
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Introduction to Arrays
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 203,
"s": 28,
"text": "Given an array arr[] of characters and an integer M, the task is to sort the array based on ASCII % M i.e. the character whose ASCII value % M is minimum should appear first."
},
{
"code": null,
"e": 214,
"s": 203,
"text": "Examples: "
},
{
"code": null,
"e": 357,
"s": 214,
"text": "Input: arr[] = {‘a’, ‘b’, ‘c’, ‘e’}, M = 2 Output: b a c e The ASCII % M for the array are {97 % 2, 98 % 2, 99 % 2, 101 % 2} i.e. {1, 0, 1, 1}"
},
{
"code": null,
"e": 424,
"s": 357,
"text": "Input: arr[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}, M = 8 Output: k s e e g "
},
{
"code": null,
"e": 609,
"s": 424,
"text": "Method 1: Write a function to sort the array and instead of comparing the values of the characters, compare their ASCII values % M to sort the array. Print the sorted array in the end."
},
{
"code": null,
"e": 661,
"s": 609,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 665,
"s": 661,
"text": "C++"
},
{
"code": null,
"e": 670,
"s": 665,
"text": "Java"
},
{
"code": null,
"e": 678,
"s": 670,
"text": "Python3"
},
{
"code": null,
"e": 681,
"s": 678,
"text": "C#"
},
{
"code": null,
"e": 692,
"s": 681,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A utility function to swap two elementsvoid swap(char* a, char* b){ char t = *a; *a = *b; *b = t;} /* This function takes last element as pivot, placesthe pivot element at its correct position in sorted array, and places all smaller (smaller than pivot)to left of pivot and all greater elements to rightof pivot */int partition(char arr[], int low, int high, int mod){ // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1);} /* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */void quickSort(char arr[], int low, int high, int mod){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); }} // Function to print the given arrayvoid printArray(char arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \";} // Driver codeint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = sizeof(arr) / sizeof(arr[0]); int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); return 0;}",
"e": 2578,
"s": 692,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(char arr[], int low, int high, int mod) { // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap char t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } char t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(char arr[], int low, int high, int mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array static void printArray(char arr[], int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + \" \"); } // Driver code public static void main(String [] args) { char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = arr.length; int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); }} // This code is contributed by ihritik",
"e": 4864,
"s": 2578,
"text": null
},
{
"code": "# Python3 implementation of the above approach \"\"\" This function takes last element as pivot,places the pivot element at its correct positionin sorted array, and places all smaller (smaller than pivot) to left of pivot andall greater elements to right of pivot \"\"\"def partition(arr, low, high, mod) : # pivot pivot = ord(arr[high]); # Index of smaller element i = (low - 1); piv = pivot % mod; for j in range(low, high) : a = ord(arr[j]) % mod; # If current element is smaller than or # equal to pivot # Instead of values, ASCII % m values # are compared if (a <= piv) : # Increment index of smaller element i += 1; arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return (i + 1); \"\"\" The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index \"\"\" def quickSort(arr, low, high, mod) : if (low < high) : ''' pi is partitioning index, arr[p] is now at right place ''' pi = partition(arr, low, high, mod); # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); return arr # Function to print the given arraydef printArray(arr, size) : for i in range(0, size) : print(arr[i], end = \" \"); # Driver codeif __name__ == \"__main__\" : arr = [ 'g', 'e', 'e', 'k', 's' ]; n = len(arr); mod = 8; # Sort the given array arr = quickSort(arr, 0, n - 1, mod); # Print the sorted array printArray(arr, n); # This code is contributed by AnkitRai01",
"e": 6605,
"s": 4864,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(char []arr, int low, int high, int mod) { // pivot char pivot = arr[high]; // Index of smaller element int i = (low - 1); char t; int piv = pivot % mod; for (int j = low; j <= high - 1; j++) { int a = arr[j] % mod; // If current element is smaller than o // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void quickSort(char []arr, int low, int high, int mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array static void printArray(char []arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main() { char []arr = { 'g', 'e', 'e', 'k', 's' }; int n = arr.Length; int mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); }} // This code is contributed by ihritik",
"e": 8872,
"s": 6605,
"text": null
},
{
"code": "// JavaScript implementation of the approach /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition( arr, low, high, mod) { // pivot var pivot = arr[high]; // Index of smaller element var i = (low - 1); var piv = pivot % mod; for (var j = low; j <= high - 1; j++) { var a = arr[j] % mod; // If current element is smaller than or // equal to pivot // Instead of values, ASCII % m values // are compared if (a <= piv) { // Increment index of smaller element i++; // swap var t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } var t = arr[i+1]; arr[i+1] = arr[high]; arr[high] = t; return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function quickSort(arr, low, high, mod) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ var pi = partition(arr, low, high, mod); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1, mod); quickSort(arr, pi + 1, high, mod); } } // Function to print the given array function printArray( arr, size) { for (var i = 0; i < size; i++) document.write(arr[i] + \" \"); } // Driver code var arr = ['g', 'e', 'e', 'k', 's' ]; var n = arr.length; var mod = 8; // Sort the given array quickSort(arr, 0, n - 1, mod); // Print the sorted array printArray(arr, n); // This code is contributed by shivanisinghss2110",
"e": 11046,
"s": 8872,
"text": null
},
{
"code": null,
"e": 11056,
"s": 11046,
"text": "k s e e g"
},
{
"code": null,
"e": 11088,
"s": 11058,
"text": "Time Complexity: O(n * log n)"
},
{
"code": null,
"e": 11110,
"s": 11088,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11197,
"s": 11110,
"text": "Method 2: The sorting can also be done using std::sort() and modifying the comparator."
},
{
"code": null,
"e": 11248,
"s": 11197,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 11252,
"s": 11248,
"text": "C++"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int M; // Comparator used to sort the array// according to ASCII % Mbool comparator(char ch1, char ch2){ int i = ch1 % M; int j = ch2 % M; return (i < j);} // Function to print the given arrayvoid printArray(char arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \";} // Driver codeint main(){ char arr[] = { 'g', 'e', 'e', 'k', 's' }; int n = sizeof(arr) / sizeof(arr[0]); M = 8; // Sort the given array sort(arr, arr + n, comparator); // Print the sorted array printArray(arr, n); return 0;}",
"e": 11892,
"s": 11252,
"text": null
},
{
"code": null,
"e": 11902,
"s": 11892,
"text": "k s e e g"
},
{
"code": null,
"e": 11934,
"s": 11904,
"text": "Time Complexity: O(n * log n)"
},
{
"code": null,
"e": 11956,
"s": 11934,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11964,
"s": 11956,
"text": "ankthon"
},
{
"code": null,
"e": 11972,
"s": 11964,
"text": "ihritik"
},
{
"code": null,
"e": 11988,
"s": 11972,
"text": "subhammahato348"
},
{
"code": null,
"e": 12005,
"s": 11988,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12015,
"s": 12005,
"text": "ruhelaa48"
},
{
"code": null,
"e": 12034,
"s": 12015,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 12041,
"s": 12034,
"text": "Arrays"
},
{
"code": null,
"e": 12049,
"s": 12041,
"text": "Sorting"
},
{
"code": null,
"e": 12056,
"s": 12049,
"text": "Arrays"
},
{
"code": null,
"e": 12064,
"s": 12056,
"text": "Sorting"
},
{
"code": null,
"e": 12162,
"s": 12064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12230,
"s": 12162,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 12274,
"s": 12230,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 12306,
"s": 12274,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12320,
"s": 12306,
"text": "Linear Search"
},
{
"code": null,
"e": 12343,
"s": 12320,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 12354,
"s": 12343,
"text": "Merge Sort"
},
{
"code": null,
"e": 12376,
"s": 12354,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 12386,
"s": 12376,
"text": "QuickSort"
},
{
"code": null,
"e": 12401,
"s": 12386,
"text": "Insertion Sort"
}
] |
Find number of pairs in an array such that their XOR is 0
|
12 Jun, 2022
Given an array of size N. Find the number of pairs (i, j) such that XOR = 0, and 1 <= i < j <= N.Examples :
Input : A[] = {1, 3, 4, 1, 4}
Output : 2
Explanation : Index (0, 3) and (2, 4)
Input : A[] = {2, 2, 2}
Output : 3
First Approach : SortingXOR = 0 is only satisfied when . Therefore, we will first sort the array and then count the frequency of each element. By combinatorics, we can observe that if frequency of some element is then, it will contribute to the answer. Below is the implementation of above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find number of pairs in an array such that// their XOR is 0#include <bits/stdc++.h>using namespace std; // Function to calculate the countint calculate(int a[], int n){ // Sorting the list using built in function sort(a, a + n); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer;} // Driver Codeint main(){ int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << calculate(a, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find number of pairs in an array such that// their XOR is 0#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} // Function to calculate the countint calculate(int a[], int n){ // Sorting the list using built in function qsort(a, n, sizeof(int), cmpfunc); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer;} // Driver Codeint main(){ int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); printf("%d", calculate(a, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find number of pairs in an array suchthat// their XOR is 0import java.util.*; class GFG { // Function to calculate the count static int calculate(int a[], int n) { // Sorting the list using built in function Arrays.sort(a); int count = 1; int answer = 0; for (int i = 1; i < n; i++) { // Counting frequency of each elements if (a[i] == a[i - 1]) count += 1; else { // Adding the contribution of the frequency // to the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 1, 2, 4 }; int n = a.length; System.out.println(calculate(a, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to find number of pairs# in an array such that their XOR is 0 # Function to calculate the countdef calculate(a) : # Sorting the list using # built in function a.sort() count = 1 answer = 0 # Traversing through the elements for i in range(1, len(a)) : if a[i] == a[i - 1] : # Counting frequency of each elements count += 1 else : # Adding the contribution of # the frequency to the answer answer = answer + count * (count - 1) // 2 count = 1 answer = answer + count * (count - 1) // 2 return answer # Driver Codeif __name__ == '__main__': a = [1, 2, 1, 2, 4] # Print the count print(calculate(a))
// C# program to find number// of pairs in an array such// that their XOR is 0using System; class GFG{ // Function to calculate // the count static int calculate(int []a, int n) { // Sorting the list using // built in function Array.Sort(a); int count = 1; int answer = 0; // Traversing through the // elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) { // Counting frequency of each // elements count += 1; } else { // Adding the contribution of // the frequency to the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code public static void Main () { int []a = { 1, 2, 1, 2, 4 }; int n = a.Length; // Print the count Console.WriteLine(calculate(a, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate// the countfunction calculate($a, $n){ // Sorting the list using // built in function sort($a); $count = 1; $answer = 0; // Traversing through the // elements for ($i = 1; $i < $n; $i++) { if ($a[$i] == $a[$i - 1]) { // Counting frequency of // each elements $count += 1; } else { // Adding the contribution of // the frequency to the answer $answer = $answer + ($count * ($count - 1)) / 2; $count = 1; } } $answer = $answer + ($count * ($count - 1)) / 2; return $answer;} // Driver Code $a = array(1, 2, 1, 2, 4); $n = count($a); // Print the count echo calculate($a, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate the// countfunction calculate(a, n){ // Sorting the list using // built in function a.sort(); let count = 1; let answer = 0; // Traversing through the // elements for (let i = 1; i < n; i++) { if (a[i] == a[i - 1]){ // Counting frequency of each // elements count += 1; } else { // Adding the contribution of // the frequency to the answer answer = answer + Math.floor((count * (count - 1)) / 2); count = 1; } } answer = answer + Math.floor((count * (count - 1)) / 2); return answer;} // Driver Code let a = [ 1, 2, 1, 2, 4 ]; let n = a.length; // Print the count document.write(calculate(a, n)); // This code is contributed by Surbhi Tyagi. </script>
Output :
2
Time Complexity : O(N Log N)
Auxiliary Space: O(1), as no extra space is used
Second Approach : Hashing (Index Mapping)Solution is handy, if we can count the frequency of each element in the array. Index mapping technique can be used to count the frequency of each element.Below is the implementation of above approach :
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find number of pairs// in an array such that their XOR is 0#include <bits/stdc++.h>using namespace std; // Function to calculate the answerint calculate(int a[], int n){ // Finding the maximum of the array int *maximum = max_element(a, a + n); // Creating frequency array // With initial value 0 int frequency[*maximum + 1] = {0}; // Traversing through the array for(int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for(int i = 0; i < (*maximum)+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return answer/2;} // Driver Codeint main(){ int a[] = {1, 2, 1, 2, 4}; int n = sizeof(a) / sizeof(a[0]); // Function calling cout << (calculate(a,n));} // This code is contributed by Smitha
// Java program to find number of pairs// in an array such that their XOR is 0import java.util.*; class GFG{ // Function to calculate the answer static int calculate(int a[], int n) { // Finding the maximum of the array int maximum = Arrays.stream(a).max().getAsInt(); // Creating frequency array // With initial value 0 int frequency[] = new int[maximum + 1]; // Traversing through the array for (int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for (int i = 0; i < (maximum) + 1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1); } return answer / 2; } // Driver Code public static void main(String[] args) { int a[] = {1, 2, 1, 2, 4}; int n = a.length; // Function calling System.out.println(calculate(a, n)); }} // This code is contributed by 29AjayKumar
# Python3 program to find number of pairs# in an array such that their XOR is 0 # Function to calculate the answerdef calculate(a) : # Finding the maximum of the array maximum = max(a) # Creating frequency array # With initial value 0 frequency = [0 for x in range(maximum + 1)] # Traversing through the array for i in a : # Counting frequency frequency[i] += 1 answer = 0 # Traversing through the frequency array for i in frequency : # Calculating answer answer = answer + i * (i - 1) // 2 return answer # Driver Codea = [1, 2, 1, 2, 4]print(calculate(a))
// C# program to find number of pairs// in an array such that their XOR is 0using System;using System.Linq;class GFG{ // Function to calculate the answer static int calculate(int []a, int n) { // Finding the maximum of the array int maximum = a.Max(); // Creating frequency array // With initial value 0 int []frequency = new int[maximum + 1]; // Traversing through the array for (int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for (int i = 0; i < (maximum) + 1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1); } return answer / 2; } // Driver Code public static void Main(String[] args) { int []a = {1, 2, 1, 2, 4}; int n = a.Length; // Function calling Console.WriteLine(calculate(a, n)); }} // This code is contributed by PrinciRaj1992
<?php// PHP program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate the answerfunction calculate($a, $n){ // Finding the maximum of the array $maximum = max($a); // Creating frequency array // With initial value 0 $frequency = array_fill(0, $maximum + 1, 0); // Traversing through the array for($i = 0; $i < $n; $i++) { // Counting frequency $frequency[$a[$i]] += 1; } $answer = 0; // Traversing through // the frequency array for($i = 0; $i < ($maximum) + 1; $i++) { // Calculating answer $answer = $answer + $frequency[$i] * ($frequency[$i] - 1); } return $answer / 2;} // Driver Code$a = array(1, 2, 1, 2, 4);$n = count($a);// Function callingecho (calculate($a,$n)); // This code is contributed by Smitha?>
<script>// Javascript program to find number of pairs// in an array such that their XOR is 0 // Function to calculate the answerfunction calculate(a, n){ // Finding the maximum of the array let maximum = Math.max(...a); // Creating frequency array // With initial value 0 let frequency = new Array(maximum + 1).fill(0); // Traversing through the array for(let i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } let answer = 0; // Traversing through the frequency array for(let i = 0; i < maximum+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return parseInt(answer/2);} // Driver Code let a = [1, 2, 1, 2, 4]; let n = a.length; // Function calling document.write(calculate(a,n)); </script>
Output :
2
Time Complexity : O(N)Auxiliary Space: O(N),
Note : Index Mapping method can only be used when the numbers in the array are not large. In such cases, sorting method can be used.
vt_m
Smitha Dinesh Semwal
K359
29AjayKumar
princiraj1992
dogofin
surbhityagi15
rishavmahato348
akshaysingh98088
adityakumar129
_shinchancode
Bitwise-XOR
Arrays
Bit Magic
Hash
Searching
Sorting
Arrays
Searching
Hash
Bit Magic
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 162,
"s": 52,
"text": "Given an array of size N. Find the number of pairs (i, j) such that XOR = 0, and 1 <= i < j <= N.Examples : "
},
{
"code": null,
"e": 277,
"s": 162,
"text": "Input : A[] = {1, 3, 4, 1, 4}\nOutput : 2\nExplanation : Index (0, 3) and (2, 4)\n\nInput : A[] = {2, 2, 2}\nOutput : 3"
},
{
"code": null,
"e": 579,
"s": 277,
"text": "First Approach : SortingXOR = 0 is only satisfied when . Therefore, we will first sort the array and then count the frequency of each element. By combinatorics, we can observe that if frequency of some element is then, it will contribute to the answer. Below is the implementation of above approach:"
},
{
"code": null,
"e": 583,
"s": 579,
"text": "C++"
},
{
"code": null,
"e": 585,
"s": 583,
"text": "C"
},
{
"code": null,
"e": 590,
"s": 585,
"text": "Java"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Python3"
},
{
"code": null,
"e": 601,
"s": 598,
"text": "C#"
},
{
"code": null,
"e": 605,
"s": 601,
"text": "PHP"
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Javascript"
},
{
"code": "// C++ program to find number of pairs in an array such that// their XOR is 0#include <bits/stdc++.h>using namespace std; // Function to calculate the countint calculate(int a[], int n){ // Sorting the list using built in function sort(a, a + n); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer;} // Driver Codeint main(){ int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << calculate(a, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1460,
"s": 616,
"text": null
},
{
"code": "// C program to find number of pairs in an array such that// their XOR is 0#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} // Function to calculate the countint calculate(int a[], int n){ // Sorting the list using built in function qsort(a, n, sizeof(int), cmpfunc); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer;} // Driver Codeint main(){ int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); printf(\"%d\", calculate(a, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2471,
"s": 1460,
"text": null
},
{
"code": "// Java program to find number of pairs in an array suchthat// their XOR is 0import java.util.*; class GFG { // Function to calculate the count static int calculate(int a[], int n) { // Sorting the list using built in function Arrays.sort(a); int count = 1; int answer = 0; for (int i = 1; i < n; i++) { // Counting frequency of each elements if (a[i] == a[i - 1]) count += 1; else { // Adding the contribution of the frequency // to the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 1, 2, 4 }; int n = a.length; System.out.println(calculate(a, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3464,
"s": 2471,
"text": null
},
{
"code": "# Python3 program to find number of pairs# in an array such that their XOR is 0 # Function to calculate the countdef calculate(a) : # Sorting the list using # built in function a.sort() count = 1 answer = 0 # Traversing through the elements for i in range(1, len(a)) : if a[i] == a[i - 1] : # Counting frequency of each elements count += 1 else : # Adding the contribution of # the frequency to the answer answer = answer + count * (count - 1) // 2 count = 1 answer = answer + count * (count - 1) // 2 return answer # Driver Codeif __name__ == '__main__': a = [1, 2, 1, 2, 4] # Print the count print(calculate(a))",
"e": 4234,
"s": 3464,
"text": null
},
{
"code": "// C# program to find number// of pairs in an array such// that their XOR is 0using System; class GFG{ // Function to calculate // the count static int calculate(int []a, int n) { // Sorting the list using // built in function Array.Sort(a); int count = 1; int answer = 0; // Traversing through the // elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) { // Counting frequency of each // elements count += 1; } else { // Adding the contribution of // the frequency to the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code public static void Main () { int []a = { 1, 2, 1, 2, 4 }; int n = a.Length; // Print the count Console.WriteLine(calculate(a, n)); }} // This code is contributed by vt_m.",
"e": 5397,
"s": 4234,
"text": null
},
{
"code": "<?php// PHP program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate// the countfunction calculate($a, $n){ // Sorting the list using // built in function sort($a); $count = 1; $answer = 0; // Traversing through the // elements for ($i = 1; $i < $n; $i++) { if ($a[$i] == $a[$i - 1]) { // Counting frequency of // each elements $count += 1; } else { // Adding the contribution of // the frequency to the answer $answer = $answer + ($count * ($count - 1)) / 2; $count = 1; } } $answer = $answer + ($count * ($count - 1)) / 2; return $answer;} // Driver Code $a = array(1, 2, 1, 2, 4); $n = count($a); // Print the count echo calculate($a, $n); // This code is contributed by anuj_67.?>",
"e": 6381,
"s": 5397,
"text": null
},
{
"code": "<script> // JavaScript program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate the// countfunction calculate(a, n){ // Sorting the list using // built in function a.sort(); let count = 1; let answer = 0; // Traversing through the // elements for (let i = 1; i < n; i++) { if (a[i] == a[i - 1]){ // Counting frequency of each // elements count += 1; } else { // Adding the contribution of // the frequency to the answer answer = answer + Math.floor((count * (count - 1)) / 2); count = 1; } } answer = answer + Math.floor((count * (count - 1)) / 2); return answer;} // Driver Code let a = [ 1, 2, 1, 2, 4 ]; let n = a.length; // Print the count document.write(calculate(a, n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 7336,
"s": 6381,
"text": null
},
{
"code": null,
"e": 7346,
"s": 7336,
"text": "Output : "
},
{
"code": null,
"e": 7348,
"s": 7346,
"text": "2"
},
{
"code": null,
"e": 7378,
"s": 7348,
"text": "Time Complexity : O(N Log N) "
},
{
"code": null,
"e": 7427,
"s": 7378,
"text": "Auxiliary Space: O(1), as no extra space is used"
},
{
"code": null,
"e": 7672,
"s": 7427,
"text": " Second Approach : Hashing (Index Mapping)Solution is handy, if we can count the frequency of each element in the array. Index mapping technique can be used to count the frequency of each element.Below is the implementation of above approach : "
},
{
"code": null,
"e": 7676,
"s": 7672,
"text": "C++"
},
{
"code": null,
"e": 7681,
"s": 7676,
"text": "Java"
},
{
"code": null,
"e": 7690,
"s": 7681,
"text": "Python 3"
},
{
"code": null,
"e": 7693,
"s": 7690,
"text": "C#"
},
{
"code": null,
"e": 7697,
"s": 7693,
"text": "PHP"
},
{
"code": null,
"e": 7708,
"s": 7697,
"text": "Javascript"
},
{
"code": "// C++ program to find number of pairs// in an array such that their XOR is 0#include <bits/stdc++.h>using namespace std; // Function to calculate the answerint calculate(int a[], int n){ // Finding the maximum of the array int *maximum = max_element(a, a + n); // Creating frequency array // With initial value 0 int frequency[*maximum + 1] = {0}; // Traversing through the array for(int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for(int i = 0; i < (*maximum)+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return answer/2;} // Driver Codeint main(){ int a[] = {1, 2, 1, 2, 4}; int n = sizeof(a) / sizeof(a[0]); // Function calling cout << (calculate(a,n));} // This code is contributed by Smitha",
"e": 8631,
"s": 7708,
"text": null
},
{
"code": "// Java program to find number of pairs// in an array such that their XOR is 0import java.util.*; class GFG{ // Function to calculate the answer static int calculate(int a[], int n) { // Finding the maximum of the array int maximum = Arrays.stream(a).max().getAsInt(); // Creating frequency array // With initial value 0 int frequency[] = new int[maximum + 1]; // Traversing through the array for (int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for (int i = 0; i < (maximum) + 1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1); } return answer / 2; } // Driver Code public static void main(String[] args) { int a[] = {1, 2, 1, 2, 4}; int n = a.length; // Function calling System.out.println(calculate(a, n)); }} // This code is contributed by 29AjayKumar",
"e": 9736,
"s": 8631,
"text": null
},
{
"code": "# Python3 program to find number of pairs# in an array such that their XOR is 0 # Function to calculate the answerdef calculate(a) : # Finding the maximum of the array maximum = max(a) # Creating frequency array # With initial value 0 frequency = [0 for x in range(maximum + 1)] # Traversing through the array for i in a : # Counting frequency frequency[i] += 1 answer = 0 # Traversing through the frequency array for i in frequency : # Calculating answer answer = answer + i * (i - 1) // 2 return answer # Driver Codea = [1, 2, 1, 2, 4]print(calculate(a))",
"e": 10403,
"s": 9736,
"text": null
},
{
"code": "// C# program to find number of pairs// in an array such that their XOR is 0using System;using System.Linq;class GFG{ // Function to calculate the answer static int calculate(int []a, int n) { // Finding the maximum of the array int maximum = a.Max(); // Creating frequency array // With initial value 0 int []frequency = new int[maximum + 1]; // Traversing through the array for (int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for (int i = 0; i < (maximum) + 1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1); } return answer / 2; } // Driver Code public static void Main(String[] args) { int []a = {1, 2, 1, 2, 4}; int n = a.Length; // Function calling Console.WriteLine(calculate(a, n)); }} // This code is contributed by PrinciRaj1992",
"e": 11520,
"s": 10403,
"text": null
},
{
"code": "<?php// PHP program to find number// of pairs in an array such// that their XOR is 0 // Function to calculate the answerfunction calculate($a, $n){ // Finding the maximum of the array $maximum = max($a); // Creating frequency array // With initial value 0 $frequency = array_fill(0, $maximum + 1, 0); // Traversing through the array for($i = 0; $i < $n; $i++) { // Counting frequency $frequency[$a[$i]] += 1; } $answer = 0; // Traversing through // the frequency array for($i = 0; $i < ($maximum) + 1; $i++) { // Calculating answer $answer = $answer + $frequency[$i] * ($frequency[$i] - 1); } return $answer / 2;} // Driver Code$a = array(1, 2, 1, 2, 4);$n = count($a);// Function callingecho (calculate($a,$n)); // This code is contributed by Smitha?>",
"e": 12392,
"s": 11520,
"text": null
},
{
"code": "<script>// Javascript program to find number of pairs// in an array such that their XOR is 0 // Function to calculate the answerfunction calculate(a, n){ // Finding the maximum of the array let maximum = Math.max(...a); // Creating frequency array // With initial value 0 let frequency = new Array(maximum + 1).fill(0); // Traversing through the array for(let i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } let answer = 0; // Traversing through the frequency array for(let i = 0; i < maximum+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return parseInt(answer/2);} // Driver Code let a = [1, 2, 1, 2, 4]; let n = a.length; // Function calling document.write(calculate(a,n)); </script>",
"e": 13241,
"s": 12392,
"text": null
},
{
"code": null,
"e": 13251,
"s": 13241,
"text": "Output : "
},
{
"code": null,
"e": 13253,
"s": 13251,
"text": "2"
},
{
"code": null,
"e": 13298,
"s": 13253,
"text": "Time Complexity : O(N)Auxiliary Space: O(N),"
},
{
"code": null,
"e": 13432,
"s": 13298,
"text": "Note : Index Mapping method can only be used when the numbers in the array are not large. In such cases, sorting method can be used. "
},
{
"code": null,
"e": 13437,
"s": 13432,
"text": "vt_m"
},
{
"code": null,
"e": 13458,
"s": 13437,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 13463,
"s": 13458,
"text": "K359"
},
{
"code": null,
"e": 13475,
"s": 13463,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13489,
"s": 13475,
"text": "princiraj1992"
},
{
"code": null,
"e": 13497,
"s": 13489,
"text": "dogofin"
},
{
"code": null,
"e": 13511,
"s": 13497,
"text": "surbhityagi15"
},
{
"code": null,
"e": 13527,
"s": 13511,
"text": "rishavmahato348"
},
{
"code": null,
"e": 13544,
"s": 13527,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 13559,
"s": 13544,
"text": "adityakumar129"
},
{
"code": null,
"e": 13573,
"s": 13559,
"text": "_shinchancode"
},
{
"code": null,
"e": 13585,
"s": 13573,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 13592,
"s": 13585,
"text": "Arrays"
},
{
"code": null,
"e": 13602,
"s": 13592,
"text": "Bit Magic"
},
{
"code": null,
"e": 13607,
"s": 13602,
"text": "Hash"
},
{
"code": null,
"e": 13617,
"s": 13607,
"text": "Searching"
},
{
"code": null,
"e": 13625,
"s": 13617,
"text": "Sorting"
},
{
"code": null,
"e": 13632,
"s": 13625,
"text": "Arrays"
},
{
"code": null,
"e": 13642,
"s": 13632,
"text": "Searching"
},
{
"code": null,
"e": 13647,
"s": 13642,
"text": "Hash"
},
{
"code": null,
"e": 13657,
"s": 13647,
"text": "Bit Magic"
},
{
"code": null,
"e": 13665,
"s": 13657,
"text": "Sorting"
}
] |
Map clear() method in Java with Example
|
31 Dec, 2018
The java.util.Map.clear() method in Java is used to clear and remove all of the elements or mappings from a specified Map collection.
Syntax:
void clear()
Parameters: The method does not accept any parameters.
Return Value: The method does not return any value.
Below programs are used to illustrate the working of java.util.Map.clear() Method:
Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the clear() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Clearing the map using clear() map.clear(); // Displaying the final HashMap System.out.println("Finally the maps look like this: " + map); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Finally the maps look like this: {}
Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the clear() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Clearing the map using clear() map.clear(); // Displaying the final Map System.out.println("Finally the maps look like this: " + map); }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Finally the maps look like this: {}
Note: The same operation can be performed with any type of Mapping with variation and combination of different data types.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#clear()
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "The java.util.Map.clear() method in Java is used to clear and remove all of the elements or mappings from a specified Map collection."
},
{
"code": null,
"e": 170,
"s": 162,
"text": "Syntax:"
},
{
"code": null,
"e": 183,
"s": 170,
"text": "void clear()"
},
{
"code": null,
"e": 238,
"s": 183,
"text": "Parameters: The method does not accept any parameters."
},
{
"code": null,
"e": 290,
"s": 238,
"text": "Return Value: The method does not return any value."
},
{
"code": null,
"e": 373,
"s": 290,
"text": "Below programs are used to illustrate the working of java.util.Map.clear() Method:"
},
{
"code": null,
"e": 423,
"s": 373,
"text": "Program 1: Mapping String Values to Integer Keys."
},
{
"code": "// Java code to illustrate the clear() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, \"Geeks\"); map.put(15, \"4\"); map.put(20, \"Geeks\"); map.put(25, \"Welcomes\"); map.put(30, \"You\"); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Clearing the map using clear() map.clear(); // Displaying the final HashMap System.out.println(\"Finally the maps look like this: \" + map); }}",
"e": 1116,
"s": 423,
"text": null
},
{
"code": null,
"e": 1223,
"s": 1116,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nFinally the maps look like this: {}\n"
},
{
"code": null,
"e": 1273,
"s": 1223,
"text": "Program 2: Mapping Integer Values to String Keys."
},
{
"code": "// Java code to illustrate the clear() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put(\"Geeks\", 10); map.put(\"4\", 15); map.put(\"Geeks\", 20); map.put(\"Welcomes\", 25); map.put(\"You\", 30); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Clearing the map using clear() map.clear(); // Displaying the final Map System.out.println(\"Finally the maps look like this: \" + map); }}",
"e": 1964,
"s": 1273,
"text": null
},
{
"code": null,
"e": 2061,
"s": 1964,
"text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nFinally the maps look like this: {}\n"
},
{
"code": null,
"e": 2184,
"s": 2061,
"text": "Note: The same operation can be performed with any type of Mapping with variation and combination of different data types."
},
{
"code": null,
"e": 2264,
"s": 2184,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#clear()"
},
{
"code": null,
"e": 2281,
"s": 2264,
"text": "Java-Collections"
},
{
"code": null,
"e": 2296,
"s": 2281,
"text": "Java-Functions"
},
{
"code": null,
"e": 2305,
"s": 2296,
"text": "java-map"
},
{
"code": null,
"e": 2310,
"s": 2305,
"text": "Java"
},
{
"code": null,
"e": 2315,
"s": 2310,
"text": "Java"
},
{
"code": null,
"e": 2332,
"s": 2315,
"text": "Java-Collections"
}
] |
Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
|
08 Jul, 2021
Below are the steps for finding MST using Kruskal’s algorithm
1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until there are (V-1) edges in the spanning tree.
We have discussed one implementation of Kruskal’s algorithm in previous post. In this post, a simpler implementation for adjacency matrix is discussed.
C++
Java
Python3
C#
Javascript
// Simple C++ implementation for Kruskal's// algorithm#include <bits/stdc++.h>using namespace std; #define V 5int parent[V]; // Find set of vertex iint find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmvoid kruskalMST(int cost[][V]){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INT_MAX, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); printf("Edge %d:(%d, %d) cost:%d \n", edge_count++, a, b, min); mincost += min; } printf("\n Minimum cost= %d \n", mincost);} // driver program to test above functionint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int cost[][V] = { { INT_MAX, 2, INT_MAX, 6, INT_MAX }, { 2, INT_MAX, 3, 8, 5 }, { INT_MAX, 3, INT_MAX, INT_MAX, 7 }, { 6, 8, INT_MAX, INT_MAX, 9 }, { INT_MAX, 5, 7, 9, INT_MAX }, }; // Print the solution kruskalMST(cost); return 0;}
// Simple Java implementation for Kruskal's// algorithmimport java.util.*; class GFG{ static int V = 5;static int[] parent = new int[V];static int INF = Integer.MAX_VALUE; // Find set of vertex istatic int find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.static void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmstatic void kruskalMST(int cost[][]){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INF, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); System.out.printf("Edge %d:(%d, %d) cost:%d \n", edge_count++, a, b, min); mincost += min; } System.out.printf("\n Minimum cost= %d \n", mincost);} // Driver codepublic static void main(String[] args){/* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int cost[][] = { { INF, 2, INF, 6, INF }, { 2, INF, 3, 8, 5 }, { INF, 3, INF, INF, 7 }, { 6, 8, INF, INF, 9 }, { INF, 5, 7, 9, INF }, }; // Print the solution kruskalMST(cost); }} // This code contributed by Rajput-Ji
# Python implementation for Kruskal's# algorithm # Find set of vertex idef find(i): while parent[i] != i: i = parent[i] return i # Does union of i and j. It returns# false if i and j are already in same# set.def union(i, j): a = find(i) b = find(j) parent[a] = b # Finds MST using Kruskal's algorithmdef kruskalMST(cost): mincost = 0 # Cost of min MST # Initialize sets of disjoint sets for i in range(V): parent[i] = i # Include minimum weight edges one by one edge_count = 0 while edge_count < V - 1: min = INF a = -1 b = -1 for i in range(V): for j in range(V): if find(i) != find(j) and cost[i][j] < min: min = cost[i][j] a = i b = j union(a, b) print('Edge {}:({}, {}) cost:{}'.format(edge_count, a, b, min)) edge_count += 1 mincost += min print("Minimum cost= {}".format(mincost)) # Driver code# Let us create the following graph# 2 3# (0)--(1)--(2)# | / \ |# 6| 8/ \5 |7# | / \ |# (3)-------(4)# 9 V = 5parent = [i for i in range(V)]INF = float('inf')cost = [[INF, 2, INF, 6, INF], [2, INF, 3, 8, 5], [INF, 3, INF, INF, 7], [6, 8, INF, INF, 9], [INF, 5, 7, 9, INF]] # Print the solutionkruskalMST(cost) # This code is contributed by ng24_7
// Simple C# implementation for Kruskal's// algorithmusing System; class GFG{ static int V = 5;static int[] parent = new int[V];static int INF = int.MaxValue; // Find set of vertex istatic int find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.static void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmstatic void kruskalMST(int [,]cost){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INF, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i, j] < min) { min = cost[i, j]; a = i; b = j; } } } union1(a, b); Console.Write("Edge {0}:({1}, {2}) cost:{3} \n", edge_count++, a, b, min); mincost += min; } Console.Write("\n Minimum cost= {0} \n", mincost);} // Driver codepublic static void Main(String[] args){/* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int [,]cost = { { INF, 2, INF, 6, INF }, { 2, INF, 3, 8, 5 }, { INF, 3, INF, INF, 7 }, { 6, 8, INF, INF, 9 }, { INF, 5, 7, 9, INF }, }; // Print the solution kruskalMST(cost);}} /* This code contributed by PrinciRaj1992 */
<script> // Simple Javascript implementation for Kruskal's// algorithm var V = 5;var parent = Array(V).fill(0);var INF = 1000000000; // Find set of vertex ifunction find(i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.function union1(i, j){ var a = find(i); var b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmfunction kruskalMST(cost){ var mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (var i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one var edge_count = 0; while (edge_count < V - 1) { var min = INF, a = -1, b = -1; for (var i = 0; i < V; i++) { for (var j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); document.write(`Edge ${edge_count++}:(${a}, ${b}) cost:${min} <br>`); mincost += min; } document.write(`<br> Minimum cost= ${mincost} <br>`);} // Driver code /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */var cost = [ [INF, 2, INF, 6, INF], [2, INF, 3, 8, 5], [INF, 3, INF, INF, 7], [6, 8, INF, INF, 9], [INF, 5, 7, 9, INF]];// Print the solutionkruskalMST(cost); </script>
Edge 0:(0, 1) cost:2
Edge 1:(1, 2) cost:3
Edge 2:(1, 4) cost:5
Edge 3:(0, 3) cost:6
Minimum cost= 16
Note that the above solution is not efficient. The idea is to provide a simple implementation for adjacency matrix representations. Please see below for efficient implementations. Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Kruskal’s Minimum Spanning Tree using STL in C++
Rajput-Ji
princiraj1992
naina024
noob2000
Kruskal
MST
union-find
C++ Programs
Graph
Greedy
Matrix
Greedy
Matrix
Graph
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "Below are the steps for finding MST using Kruskal’s algorithm "
},
{
"code": null,
"e": 400,
"s": 118,
"text": "1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until there are (V-1) edges in the spanning tree."
},
{
"code": null,
"e": 554,
"s": 400,
"text": "We have discussed one implementation of Kruskal’s algorithm in previous post. In this post, a simpler implementation for adjacency matrix is discussed. "
},
{
"code": null,
"e": 558,
"s": 554,
"text": "C++"
},
{
"code": null,
"e": 563,
"s": 558,
"text": "Java"
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Python3"
},
{
"code": null,
"e": 574,
"s": 571,
"text": "C#"
},
{
"code": null,
"e": 585,
"s": 574,
"text": "Javascript"
},
{
"code": "// Simple C++ implementation for Kruskal's// algorithm#include <bits/stdc++.h>using namespace std; #define V 5int parent[V]; // Find set of vertex iint find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmvoid kruskalMST(int cost[][V]){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INT_MAX, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); printf(\"Edge %d:(%d, %d) cost:%d \\n\", edge_count++, a, b, min); mincost += min; } printf(\"\\n Minimum cost= %d \\n\", mincost);} // driver program to test above functionint main(){ /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int cost[][V] = { { INT_MAX, 2, INT_MAX, 6, INT_MAX }, { 2, INT_MAX, 3, 8, 5 }, { INT_MAX, 3, INT_MAX, INT_MAX, 7 }, { 6, 8, INT_MAX, INT_MAX, 9 }, { INT_MAX, 5, 7, 9, INT_MAX }, }; // Print the solution kruskalMST(cost); return 0;}",
"e": 2288,
"s": 585,
"text": null
},
{
"code": "// Simple Java implementation for Kruskal's// algorithmimport java.util.*; class GFG{ static int V = 5;static int[] parent = new int[V];static int INF = Integer.MAX_VALUE; // Find set of vertex istatic int find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.static void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmstatic void kruskalMST(int cost[][]){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INF, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); System.out.printf(\"Edge %d:(%d, %d) cost:%d \\n\", edge_count++, a, b, min); mincost += min; } System.out.printf(\"\\n Minimum cost= %d \\n\", mincost);} // Driver codepublic static void main(String[] args){/* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int cost[][] = { { INF, 2, INF, 6, INF }, { 2, INF, 3, 8, 5 }, { INF, 3, INF, INF, 7 }, { 6, 8, INF, INF, 9 }, { INF, 5, 7, 9, INF }, }; // Print the solution kruskalMST(cost); }} // This code contributed by Rajput-Ji",
"e": 4067,
"s": 2288,
"text": null
},
{
"code": "# Python implementation for Kruskal's# algorithm # Find set of vertex idef find(i): while parent[i] != i: i = parent[i] return i # Does union of i and j. It returns# false if i and j are already in same# set.def union(i, j): a = find(i) b = find(j) parent[a] = b # Finds MST using Kruskal's algorithmdef kruskalMST(cost): mincost = 0 # Cost of min MST # Initialize sets of disjoint sets for i in range(V): parent[i] = i # Include minimum weight edges one by one edge_count = 0 while edge_count < V - 1: min = INF a = -1 b = -1 for i in range(V): for j in range(V): if find(i) != find(j) and cost[i][j] < min: min = cost[i][j] a = i b = j union(a, b) print('Edge {}:({}, {}) cost:{}'.format(edge_count, a, b, min)) edge_count += 1 mincost += min print(\"Minimum cost= {}\".format(mincost)) # Driver code# Let us create the following graph# 2 3# (0)--(1)--(2)# | / \\ |# 6| 8/ \\5 |7# | / \\ |# (3)-------(4)# 9 V = 5parent = [i for i in range(V)]INF = float('inf')cost = [[INF, 2, INF, 6, INF], [2, INF, 3, 8, 5], [INF, 3, INF, INF, 7], [6, 8, INF, INF, 9], [INF, 5, 7, 9, INF]] # Print the solutionkruskalMST(cost) # This code is contributed by ng24_7",
"e": 5475,
"s": 4067,
"text": null
},
{
"code": "// Simple C# implementation for Kruskal's// algorithmusing System; class GFG{ static int V = 5;static int[] parent = new int[V];static int INF = int.MaxValue; // Find set of vertex istatic int find(int i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.static void union1(int i, int j){ int a = find(i); int b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmstatic void kruskalMST(int [,]cost){ int mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (int i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one int edge_count = 0; while (edge_count < V - 1) { int min = INF, a = -1, b = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (find(i) != find(j) && cost[i, j] < min) { min = cost[i, j]; a = i; b = j; } } } union1(a, b); Console.Write(\"Edge {0}:({1}, {2}) cost:{3} \\n\", edge_count++, a, b, min); mincost += min; } Console.Write(\"\\n Minimum cost= {0} \\n\", mincost);} // Driver codepublic static void Main(String[] args){/* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */ int [,]cost = { { INF, 2, INF, 6, INF }, { 2, INF, 3, 8, 5 }, { INF, 3, INF, INF, 7 }, { 6, 8, INF, INF, 9 }, { INF, 5, 7, 9, INF }, }; // Print the solution kruskalMST(cost);}} /* This code contributed by PrinciRaj1992 */",
"e": 7243,
"s": 5475,
"text": null
},
{
"code": "<script> // Simple Javascript implementation for Kruskal's// algorithm var V = 5;var parent = Array(V).fill(0);var INF = 1000000000; // Find set of vertex ifunction find(i){ while (parent[i] != i) i = parent[i]; return i;} // Does union of i and j. It returns// false if i and j are already in same// set.function union1(i, j){ var a = find(i); var b = find(j); parent[a] = b;} // Finds MST using Kruskal's algorithmfunction kruskalMST(cost){ var mincost = 0; // Cost of min MST. // Initialize sets of disjoint sets. for (var i = 0; i < V; i++) parent[i] = i; // Include minimum weight edges one by one var edge_count = 0; while (edge_count < V - 1) { var min = INF, a = -1, b = -1; for (var i = 0; i < V; i++) { for (var j = 0; j < V; j++) { if (find(i) != find(j) && cost[i][j] < min) { min = cost[i][j]; a = i; b = j; } } } union1(a, b); document.write(`Edge ${edge_count++}:(${a}, ${b}) cost:${min} <br>`); mincost += min; } document.write(`<br> Minimum cost= ${mincost} <br>`);} // Driver code /* Let us create the following graph 2 3 (0)--(1)--(2) | / \\ | 6| 8/ \\5 |7 | / \\ | (3)-------(4) 9 */var cost = [ [INF, 2, INF, 6, INF], [2, INF, 3, 8, 5], [INF, 3, INF, INF, 7], [6, 8, INF, INF, 9], [INF, 5, 7, 9, INF]];// Print the solutionkruskalMST(cost); </script>",
"e": 8825,
"s": 7243,
"text": null
},
{
"code": null,
"e": 8932,
"s": 8825,
"text": "Edge 0:(0, 1) cost:2 \nEdge 1:(1, 2) cost:3 \nEdge 2:(1, 4) cost:5 \nEdge 3:(0, 3) cost:6 \n\n Minimum cost= 16"
},
{
"code": null,
"e": 9222,
"s": 8934,
"text": "Note that the above solution is not efficient. The idea is to provide a simple implementation for adjacency matrix representations. Please see below for efficient implementations. Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Kruskal’s Minimum Spanning Tree using STL in C++ "
},
{
"code": null,
"e": 9232,
"s": 9222,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9246,
"s": 9232,
"text": "princiraj1992"
},
{
"code": null,
"e": 9255,
"s": 9246,
"text": "naina024"
},
{
"code": null,
"e": 9264,
"s": 9255,
"text": "noob2000"
},
{
"code": null,
"e": 9272,
"s": 9264,
"text": "Kruskal"
},
{
"code": null,
"e": 9276,
"s": 9272,
"text": "MST"
},
{
"code": null,
"e": 9287,
"s": 9276,
"text": "union-find"
},
{
"code": null,
"e": 9300,
"s": 9287,
"text": "C++ Programs"
},
{
"code": null,
"e": 9306,
"s": 9300,
"text": "Graph"
},
{
"code": null,
"e": 9313,
"s": 9306,
"text": "Greedy"
},
{
"code": null,
"e": 9320,
"s": 9313,
"text": "Matrix"
},
{
"code": null,
"e": 9327,
"s": 9320,
"text": "Greedy"
},
{
"code": null,
"e": 9334,
"s": 9327,
"text": "Matrix"
},
{
"code": null,
"e": 9340,
"s": 9334,
"text": "Graph"
},
{
"code": null,
"e": 9351,
"s": 9340,
"text": "union-find"
}
] |
Create Constant Variable in Python using Pconst Library
|
03 Mar, 2021
Constant variable the name itself says that it is constant. We have to define a constant variable at the time of declaration. After that, we will not able to change the value of a constant variable. In some cases, constant variables are very useful.
Creating constant variables, functions, objects is allowed in languages like c++, Java. But in python creating constant variable, it is not allowed. There is no predefined type for a constant variable in Python. But we can use pconst library for that.
Installation:
pip install pconst
Below are some examples which depict how to use constants in python
Example 1:
You can set constants to const module’s attribute.
Python3
# import modulefrom pconst import const # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG' # displayprint(const.LANGUAGE)print(const.COMPANY_NAME)
Output:
Example 2:
If try to update the constant value, ConstantError will be raised.
Python3
# import modulefrom pconst import const # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG' # updateconst.LANGUAGE="C++"
Output:
Example 3:
The del operator is disallowed.
Python3
# import modulefrom pconst import const # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG' # deletedel const.LANGUAGE
Output:
Example 4:
You can also set dict and list value to const module, and they will be not editable (if dict or list values contains dict or list, then will be applied recursively.).
Python3
# import modulefrom pconst import const # define dictionaryconst.COMPANY_DATA = { 'Name': "GFG", 'Language': ["C", "C++", "Python"]} # displayprint('Name:', const.COMPANY_DATA['Name'])print('Language:', const.COMPANY_DATA['Language'])
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "Constant variable the name itself says that it is constant. We have to define a constant variable at the time of declaration. After that, we will not able to change the value of a constant variable. In some cases, constant variables are very useful."
},
{
"code": null,
"e": 556,
"s": 304,
"text": "Creating constant variables, functions, objects is allowed in languages like c++, Java. But in python creating constant variable, it is not allowed. There is no predefined type for a constant variable in Python. But we can use pconst library for that."
},
{
"code": null,
"e": 570,
"s": 556,
"text": "Installation:"
},
{
"code": null,
"e": 589,
"s": 570,
"text": "pip install pconst"
},
{
"code": null,
"e": 657,
"s": 589,
"text": "Below are some examples which depict how to use constants in python"
},
{
"code": null,
"e": 668,
"s": 657,
"text": "Example 1:"
},
{
"code": null,
"e": 719,
"s": 668,
"text": "You can set constants to const module’s attribute."
},
{
"code": null,
"e": 727,
"s": 719,
"text": "Python3"
},
{
"code": "# import modulefrom pconst import const # declare constantsconst.LANGUAGE = \"PYTHON\"const.COMPANY_NAME = 'GFG' # displayprint(const.LANGUAGE)print(const.COMPANY_NAME)",
"e": 896,
"s": 727,
"text": null
},
{
"code": null,
"e": 904,
"s": 896,
"text": "Output:"
},
{
"code": null,
"e": 915,
"s": 904,
"text": "Example 2:"
},
{
"code": null,
"e": 982,
"s": 915,
"text": "If try to update the constant value, ConstantError will be raised."
},
{
"code": null,
"e": 990,
"s": 982,
"text": "Python3"
},
{
"code": "# import modulefrom pconst import const # declare constantsconst.LANGUAGE = \"PYTHON\"const.COMPANY_NAME = 'GFG' # updateconst.LANGUAGE=\"C++\"",
"e": 1132,
"s": 990,
"text": null
},
{
"code": null,
"e": 1140,
"s": 1132,
"text": "Output:"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": "Example 3:"
},
{
"code": null,
"e": 1183,
"s": 1151,
"text": "The del operator is disallowed."
},
{
"code": null,
"e": 1191,
"s": 1183,
"text": "Python3"
},
{
"code": "# import modulefrom pconst import const # declare constantsconst.LANGUAGE = \"PYTHON\"const.COMPANY_NAME = 'GFG' # deletedel const.LANGUAGE",
"e": 1331,
"s": 1191,
"text": null
},
{
"code": null,
"e": 1340,
"s": 1331,
"text": "Output: "
},
{
"code": null,
"e": 1352,
"s": 1340,
"text": "Example 4: "
},
{
"code": null,
"e": 1519,
"s": 1352,
"text": "You can also set dict and list value to const module, and they will be not editable (if dict or list values contains dict or list, then will be applied recursively.)."
},
{
"code": null,
"e": 1527,
"s": 1519,
"text": "Python3"
},
{
"code": "# import modulefrom pconst import const # define dictionaryconst.COMPANY_DATA = { 'Name': \"GFG\", 'Language': [\"C\", \"C++\", \"Python\"]} # displayprint('Name:', const.COMPANY_DATA['Name'])print('Language:', const.COMPANY_DATA['Language'])",
"e": 1787,
"s": 1527,
"text": null
},
{
"code": null,
"e": 1795,
"s": 1787,
"text": "Output:"
},
{
"code": null,
"e": 1810,
"s": 1795,
"text": "python-modules"
},
{
"code": null,
"e": 1817,
"s": 1810,
"text": "Python"
}
] |
Perl | Greedy and non-greedy match
|
29 Dec, 2019
Regular Expressions(Regex/RE) is a sequence of characters that are used for pattern matching. Or we can say that it is a way of describing a set of strings without having to list all strings in your program. We can apply a regular expression by using the pattern binding operators =~ and !~. Regex operator =~ is for testing a regular expression match.Example: Let us consider /geeks/ as a regular expression. It will match
Geeksforgeeks
Computergeeks
but not
Ge12eksg22eeks
Geeksg*eks
Whereas !~ determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails. Consider the above example, the expressions we got as true will be considered as false and false regex as true. It provides a negation of results obtained while using =~. Pattern Matching: It is a way of finding out a particular sequence of characters or a pattern within a given string. In Perl, we have three regular expression operators. They are:
Match Regular Expression - m//
Substitute Regular Expression - s///
Transliterate Regular Expression - tr///
Example 1: Using match operator
#!usr/bin/perl # Perl program to search the substring "or" # in the word GeeksForGeeks # String to find pattern from$a = "GeeksForGeeks"; # Using m operator to find substringif($a = ~m/or/){ print "Found 'or' in the string "; }
Here in the above example, pattern matching is done for searching a particular substring in a string using the match operator ‘m//‘. It will return true if the pattern is found in the string.
Example 2: Using Substitute operator
#!/usr/bin/perl # Perl program to replace the substring "For" # in the word GeeksForGeeks # String to perform substitution on$a = "GeeksForGeeks"; # Using substitution operator to replace$a = ~s/For/And/; print "$a";
Here, the substitution operator ‘s///‘ is used to substitute a pattern in a string with a given text. If the pattern exists then it will be substituted otherwise it will return false.
Example 3: Using transliterator operator
#!/usr/bin/perl # Perl program to replace all occurrences# of a pattern in the string # String to be used$string = 'GeeksForGeeks'; # Replace 'G' with 'S' using # transliterator operator$string =~ tr/G/S/; # Printing the final stringprint "$string\n";
Here, the string is searched for all the occurrences of a character ‘G’ and is replaced with another character ‘S’ using transliterator operator ‘tr///‘. It will never return false even if no replacement is done.
Greedy Matching And Non-Greedy MatchingThe usual rule for matching in REs is sometimes called “left-most longest“: when a pattern can be matched at more than one place within a string, the chosen match will be the one that starts at the earliest possible position within the string, and then extends as far as possible. Normally Perl pattern matching is greedy. By greedy, we mean that the parser tries to match as much as possible. In the string abcbcbcde, for example, the patternGreedy and non-greedy matching /(bc)+/ can match in six different ways as shown in the figure:
In the above image, the third of these matched patterns is “left-most longest, ” also known as greedy. In some cases, however, it may be desirable to obtain a “left-most shortest” or minimal match. We can make a greedy matching into a non-greedy match using ‘?‘ at the end of RE i.e ‘*?‘ matches the smallest number of instances of the preceding subexpression that will allow the overall match to succeed. Similarly, ‘+?‘ matches at least one instance, but no more than necessary to allow the overall match to succeed, and ‘??‘ matches either zero or one instances, with a preference for zero.
Example: Greedy pattern matching
#!/usr/bin/perl # Perl program to show greedy matching$var = "Geeks For Geeks"; # Matching pattern from k to s$var =~ /(k.*s)(.*)$/; # Printing the resultant stringprint($1, "\n");
Here we can see that the code will start to match from k to s and it matches as much as possible.
Example: Non-greedy pattern matching
#!/usr/bin/perl # Perl program to show non-greedy matchingmy $str = "Geeks For Geeks"; # Matching pattern from k to s$str =~ /.*?\s(.*)/; # Printing Resultant stringprint($1);
When comparing with the non-greedy operator, it will match least code.
Perl-regex
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 452,
"s": 28,
"text": "Regular Expressions(Regex/RE) is a sequence of characters that are used for pattern matching. Or we can say that it is a way of describing a set of strings without having to list all strings in your program. We can apply a regular expression by using the pattern binding operators =~ and !~. Regex operator =~ is for testing a regular expression match.Example: Let us consider /geeks/ as a regular expression. It will match"
},
{
"code": null,
"e": 480,
"s": 452,
"text": "Geeksforgeeks\nComputergeeks"
},
{
"code": null,
"e": 488,
"s": 480,
"text": "but not"
},
{
"code": null,
"e": 514,
"s": 488,
"text": "Ge12eksg22eeks\nGeeksg*eks"
},
{
"code": null,
"e": 1026,
"s": 514,
"text": "Whereas !~ determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails. Consider the above example, the expressions we got as true will be considered as false and false regex as true. It provides a negation of results obtained while using =~. Pattern Matching: It is a way of finding out a particular sequence of characters or a pattern within a given string. In Perl, we have three regular expression operators. They are:"
},
{
"code": null,
"e": 1135,
"s": 1026,
"text": "Match Regular Expression - m//\nSubstitute Regular Expression - s///\nTransliterate Regular Expression - tr///"
},
{
"code": null,
"e": 1167,
"s": 1135,
"text": "Example 1: Using match operator"
},
{
"code": "#!usr/bin/perl # Perl program to search the substring \"or\" # in the word GeeksForGeeks # String to find pattern from$a = \"GeeksForGeeks\"; # Using m operator to find substringif($a = ~m/or/){ print \"Found 'or' in the string \"; }",
"e": 1401,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1593,
"s": 1401,
"text": "Here in the above example, pattern matching is done for searching a particular substring in a string using the match operator ‘m//‘. It will return true if the pattern is found in the string."
},
{
"code": null,
"e": 1630,
"s": 1593,
"text": "Example 2: Using Substitute operator"
},
{
"code": "#!/usr/bin/perl # Perl program to replace the substring \"For\" # in the word GeeksForGeeks # String to perform substitution on$a = \"GeeksForGeeks\"; # Using substitution operator to replace$a = ~s/For/And/; print \"$a\";",
"e": 1850,
"s": 1630,
"text": null
},
{
"code": null,
"e": 2034,
"s": 1850,
"text": "Here, the substitution operator ‘s///‘ is used to substitute a pattern in a string with a given text. If the pattern exists then it will be substituted otherwise it will return false."
},
{
"code": null,
"e": 2075,
"s": 2034,
"text": "Example 3: Using transliterator operator"
},
{
"code": "#!/usr/bin/perl # Perl program to replace all occurrences# of a pattern in the string # String to be used$string = 'GeeksForGeeks'; # Replace 'G' with 'S' using # transliterator operator$string =~ tr/G/S/; # Printing the final stringprint \"$string\\n\";",
"e": 2331,
"s": 2075,
"text": null
},
{
"code": null,
"e": 2544,
"s": 2331,
"text": "Here, the string is searched for all the occurrences of a character ‘G’ and is replaced with another character ‘S’ using transliterator operator ‘tr///‘. It will never return false even if no replacement is done."
},
{
"code": null,
"e": 3121,
"s": 2544,
"text": "Greedy Matching And Non-Greedy MatchingThe usual rule for matching in REs is sometimes called “left-most longest“: when a pattern can be matched at more than one place within a string, the chosen match will be the one that starts at the earliest possible position within the string, and then extends as far as possible. Normally Perl pattern matching is greedy. By greedy, we mean that the parser tries to match as much as possible. In the string abcbcbcde, for example, the patternGreedy and non-greedy matching /(bc)+/ can match in six different ways as shown in the figure:"
},
{
"code": null,
"e": 3715,
"s": 3121,
"text": "In the above image, the third of these matched patterns is “left-most longest, ” also known as greedy. In some cases, however, it may be desirable to obtain a “left-most shortest” or minimal match. We can make a greedy matching into a non-greedy match using ‘?‘ at the end of RE i.e ‘*?‘ matches the smallest number of instances of the preceding subexpression that will allow the overall match to succeed. Similarly, ‘+?‘ matches at least one instance, but no more than necessary to allow the overall match to succeed, and ‘??‘ matches either zero or one instances, with a preference for zero."
},
{
"code": null,
"e": 3748,
"s": 3715,
"text": "Example: Greedy pattern matching"
},
{
"code": "#!/usr/bin/perl # Perl program to show greedy matching$var = \"Geeks For Geeks\"; # Matching pattern from k to s$var =~ /(k.*s)(.*)$/; # Printing the resultant stringprint($1, \"\\n\");",
"e": 3932,
"s": 3748,
"text": null
},
{
"code": null,
"e": 4030,
"s": 3932,
"text": "Here we can see that the code will start to match from k to s and it matches as much as possible."
},
{
"code": null,
"e": 4067,
"s": 4030,
"text": "Example: Non-greedy pattern matching"
},
{
"code": "#!/usr/bin/perl # Perl program to show non-greedy matchingmy $str = \"Geeks For Geeks\"; # Matching pattern from k to s$str =~ /.*?\\s(.*)/; # Printing Resultant stringprint($1);",
"e": 4247,
"s": 4067,
"text": null
},
{
"code": null,
"e": 4318,
"s": 4247,
"text": "When comparing with the non-greedy operator, it will match least code."
},
{
"code": null,
"e": 4329,
"s": 4318,
"text": "Perl-regex"
},
{
"code": null,
"e": 4336,
"s": 4329,
"text": "Picked"
},
{
"code": null,
"e": 4341,
"s": 4336,
"text": "Perl"
},
{
"code": null,
"e": 4346,
"s": 4341,
"text": "Perl"
}
] |
EmBomber – Email Bomber Tool in Kali Linux
|
29 Jun, 2021
EmBomber tool is used to perform call and SMS bombing on the target Email address. You must ensure that you always install the latest version of EmBomber from GitHub in order to not get stuck with the working of the tool. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. EmBomber is a free and an open-source tool available on GitHub. This tool takes your email address. You only have to enter the target email address and the tool will do the rest of the work.
Note: This tool is written in Python. You must have python installed in your kali linux operating system.
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/MazenElzanaty/EmBomber.git
cd EmBomber
Step 2: The tool has been downloaded now, so use the following command to run the tool.
python EmBomber.py
The tool has been downloaded and installed successfully. Now we see an example to use the command.
Example 1: Use the EmBomber tool to perform email bombing on an email address.
1
Now Provide the email by which you want to sent and then provide email at which you wantbombing to send email.
You can see that Bombing has started on the target email address. The tool has started sending the emails, some of them get success some of them failed but you can try again and again for best results. The email failed due to poor internet connection if your internet is good then no emails of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 566,
"s": 28,
"text": "EmBomber tool is used to perform call and SMS bombing on the target Email address. You must ensure that you always install the latest version of EmBomber from GitHub in order to not get stuck with the working of the tool. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. EmBomber is a free and an open-source tool available on GitHub. This tool takes your email address. You only have to enter the target email address and the tool will do the rest of the work."
},
{
"code": null,
"e": 672,
"s": 566,
"text": "Note: This tool is written in Python. You must have python installed in your kali linux operating system."
},
{
"code": null,
"e": 842,
"s": 672,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command."
},
{
"code": null,
"e": 910,
"s": 842,
"text": "git clone https://github.com/MazenElzanaty/EmBomber.git\ncd EmBomber"
},
{
"code": null,
"e": 998,
"s": 910,
"text": "Step 2: The tool has been downloaded now, so use the following command to run the tool."
},
{
"code": null,
"e": 1017,
"s": 998,
"text": "python EmBomber.py"
},
{
"code": null,
"e": 1116,
"s": 1017,
"text": "The tool has been downloaded and installed successfully. Now we see an example to use the command."
},
{
"code": null,
"e": 1195,
"s": 1116,
"text": "Example 1: Use the EmBomber tool to perform email bombing on an email address."
},
{
"code": null,
"e": 1197,
"s": 1195,
"text": "1"
},
{
"code": null,
"e": 1309,
"s": 1197,
"text": "Now Provide the email by which you want to sent and then provide email at which you wantbombing to send email."
},
{
"code": null,
"e": 1620,
"s": 1309,
"text": "You can see that Bombing has started on the target email address. The tool has started sending the emails, some of them get success some of them failed but you can try again and again for best results. The email failed due to poor internet connection if your internet is good then no emails of yours will fail."
},
{
"code": null,
"e": 1631,
"s": 1620,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1643,
"s": 1631,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": "Linux-Unix"
}
] |
SQL | GROUP BY
|
21 Mar, 2018
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group.
Important Points:
GROUP BY clause is used with the SELECT statement.
In the query, GROUP BY clause is placed after the WHERE clause.
In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Sample Table:
Employee
Student
Example:
Group By single column: Group By single column means, to place all the rows with same value of only that particular column in one group. Consider the query as shown below:SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME;
The above query will produce the below output:As you can see in the above output, the rows with duplicate NAMEs are grouped under same NAME and their corresponding SALARY is the sum of the SALARY of duplicate rows. The SUM() function of SQL is used here to calculate the sum.
SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME;
The above query will produce the below output:As you can see in the above output, the rows with duplicate NAMEs are grouped under same NAME and their corresponding SALARY is the sum of the SALARY of duplicate rows. The SUM() function of SQL is used here to calculate the sum.
Group By multiple columns: Group by multiple column is say for example, GROUP BY column1, column2. This means to place all the rows with same values of both the columns column1 and column2 in one group. Consider the below query:SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
Output:As you can see in the above output the students with both same SUBJECT and YEAR are placed in same group. And those whose only SUBJECT is same but not YEAR belongs to different groups. So here we have grouped the table according to two columns or more than one column.
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
Output:As you can see in the above output the students with both same SUBJECT and YEAR are placed in same group. And those whose only SUBJECT is same but not YEAR belongs to different groups. So here we have grouped the table according to two columns or more than one column.
HAVING Clause
We know that WHERE clause is used to place conditions on columns but what if we want to place conditions on groups?
This is where HAVING clause comes into use. We can use HAVING clause to place conditions to decide which group will be the part of final result-set. Also we can not use the aggregate functions like SUM(), COUNT() etc. with WHERE clause. So we have to use HAVING clause if we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Example:
SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME
HAVING SUM(SALARY)>3000;
Output:As you can see in the above output only one group out of the three groups appears in the result-set as it is the only group where sum of SALARY is greater than 3000. So we have used HAVING clause here to place this condition as the condition is required to be placed on groups not columns.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 266,
"s": 52,
"text": "The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group."
},
{
"code": null,
"e": 284,
"s": 266,
"text": "Important Points:"
},
{
"code": null,
"e": 335,
"s": 284,
"text": "GROUP BY clause is used with the SELECT statement."
},
{
"code": null,
"e": 399,
"s": 335,
"text": "In the query, GROUP BY clause is placed after the WHERE clause."
},
{
"code": null,
"e": 475,
"s": 399,
"text": "In the query, GROUP BY clause is placed before ORDER BY clause if used any."
},
{
"code": null,
"e": 483,
"s": 475,
"text": "Syntax:"
},
{
"code": null,
"e": 736,
"s": 483,
"text": "SELECT column1, function_name(column2)\nFROM table_name\nWHERE condition\nGROUP BY column1, column2\nORDER BY column1, column2;\n\nfunction_name: Name of the function used for example, SUM() , AVG().\ntable_name: Name of the table.\ncondition: Condition used.\n"
},
{
"code": null,
"e": 750,
"s": 736,
"text": "Sample Table:"
},
{
"code": null,
"e": 759,
"s": 750,
"text": "Employee"
},
{
"code": null,
"e": 767,
"s": 759,
"text": "Student"
},
{
"code": null,
"e": 776,
"s": 767,
"text": "Example:"
},
{
"code": null,
"e": 1278,
"s": 776,
"text": "Group By single column: Group By single column means, to place all the rows with same value of only that particular column in one group. Consider the query as shown below:SELECT NAME, SUM(SALARY) FROM Employee \nGROUP BY NAME;\nThe above query will produce the below output:As you can see in the above output, the rows with duplicate NAMEs are grouped under same NAME and their corresponding SALARY is the sum of the SALARY of duplicate rows. The SUM() function of SQL is used here to calculate the sum."
},
{
"code": null,
"e": 1334,
"s": 1278,
"text": "SELECT NAME, SUM(SALARY) FROM Employee \nGROUP BY NAME;\n"
},
{
"code": null,
"e": 1610,
"s": 1334,
"text": "The above query will produce the below output:As you can see in the above output, the rows with duplicate NAMEs are grouped under same NAME and their corresponding SALARY is the sum of the SALARY of duplicate rows. The SUM() function of SQL is used here to calculate the sum."
},
{
"code": null,
"e": 2182,
"s": 1610,
"text": "Group By multiple columns: Group by multiple column is say for example, GROUP BY column1, column2. This means to place all the rows with same values of both the columns column1 and column2 in one group. Consider the below query:SELECT SUBJECT, YEAR, Count(*)\nFROM Student\nGROUP BY SUBJECT, YEAR;\nOutput:As you can see in the above output the students with both same SUBJECT and YEAR are placed in same group. And those whose only SUBJECT is same but not YEAR belongs to different groups. So here we have grouped the table according to two columns or more than one column."
},
{
"code": null,
"e": 2251,
"s": 2182,
"text": "SELECT SUBJECT, YEAR, Count(*)\nFROM Student\nGROUP BY SUBJECT, YEAR;\n"
},
{
"code": null,
"e": 2527,
"s": 2251,
"text": "Output:As you can see in the above output the students with both same SUBJECT and YEAR are placed in same group. And those whose only SUBJECT is same but not YEAR belongs to different groups. So here we have grouped the table according to two columns or more than one column."
},
{
"code": null,
"e": 2541,
"s": 2527,
"text": "HAVING Clause"
},
{
"code": null,
"e": 2657,
"s": 2541,
"text": "We know that WHERE clause is used to place conditions on columns but what if we want to place conditions on groups?"
},
{
"code": null,
"e": 2986,
"s": 2657,
"text": "This is where HAVING clause comes into use. We can use HAVING clause to place conditions to decide which group will be the part of final result-set. Also we can not use the aggregate functions like SUM(), COUNT() etc. with WHERE clause. So we have to use HAVING clause if we want to use any of these functions in the conditions."
},
{
"code": null,
"e": 2994,
"s": 2986,
"text": "Syntax:"
},
{
"code": null,
"e": 3264,
"s": 2994,
"text": "SELECT column1, function_name(column2)\nFROM table_name\nWHERE condition\nGROUP BY column1, column2\nHAVING condition\nORDER BY column1, column2;\n\nfunction_name: Name of the function used for example, SUM() , AVG().\ntable_name: Name of the table.\ncondition: Condition used.\n"
},
{
"code": null,
"e": 3273,
"s": 3264,
"text": "Example:"
},
{
"code": null,
"e": 3354,
"s": 3273,
"text": "SELECT NAME, SUM(SALARY) FROM Employee \nGROUP BY NAME\nHAVING SUM(SALARY)>3000; \n"
},
{
"code": null,
"e": 3651,
"s": 3354,
"text": "Output:As you can see in the above output only one group out of the three groups appears in the result-set as it is the only group where sum of SALARY is greater than 3000. So we have used HAVING clause here to place this condition as the condition is required to be placed on groups not columns."
},
{
"code": null,
"e": 3952,
"s": 3651,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4077,
"s": 3952,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4099,
"s": 4077,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 4108,
"s": 4099,
"text": "Articles"
},
{
"code": null,
"e": 4113,
"s": 4108,
"text": "DBMS"
},
{
"code": null,
"e": 4117,
"s": 4113,
"text": "SQL"
},
{
"code": null,
"e": 4122,
"s": 4117,
"text": "DBMS"
},
{
"code": null,
"e": 4126,
"s": 4122,
"text": "SQL"
}
] |
Python | Pandas MultiIndex.droplevel()
|
24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.droplevel() function return Index with requested level removed. If MultiIndex has only 2 levels, the result will be of Index type not MultiIndex..
Syntax: MultiIndex.droplevel(level=0)
Parameters :level : int/level name or list thereof
Returns : index : Index or MultiIndex
Example #1: Use MultiIndex.droplevel() function to drop the 0th level of the MultiIndex.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)
Output :
Now let’s drop the 0th level of the MultiIndex.
# drop the 0th level.midx.droplevel(level = 0)
Output :As we can see in the output, the function has dropped the 0th level and returned an Index object. Example #2: Use MultiIndex.droplevel() function to drop the 1st level of the MultiIndex.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)
Output :
Now let’s drop the 1st level of the MultiIndex.
# drop the 1st level.midx.droplevel(level = 1)
Output :As we can see in the output, the function has dropped the 1st level and returned an Index object.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 407,
"s": 242,
"text": "Pandas MultiIndex.droplevel() function return Index with requested level removed. If MultiIndex has only 2 levels, the result will be of Index type not MultiIndex.."
},
{
"code": null,
"e": 445,
"s": 407,
"text": "Syntax: MultiIndex.droplevel(level=0)"
},
{
"code": null,
"e": 496,
"s": 445,
"text": "Parameters :level : int/level name or list thereof"
},
{
"code": null,
"e": 534,
"s": 496,
"text": "Returns : index : Index or MultiIndex"
},
{
"code": null,
"e": 623,
"s": 534,
"text": "Example #1: Use MultiIndex.droplevel() function to drop the 0th level of the MultiIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)",
"e": 920,
"s": 623,
"text": null
},
{
"code": null,
"e": 929,
"s": 920,
"text": "Output :"
},
{
"code": null,
"e": 977,
"s": 929,
"text": "Now let’s drop the 0th level of the MultiIndex."
},
{
"code": "# drop the 0th level.midx.droplevel(level = 0)",
"e": 1024,
"s": 977,
"text": null
},
{
"code": null,
"e": 1219,
"s": 1024,
"text": "Output :As we can see in the output, the function has dropped the 0th level and returned an Index object. Example #2: Use MultiIndex.droplevel() function to drop the 1st level of the MultiIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)",
"e": 1515,
"s": 1219,
"text": null
},
{
"code": null,
"e": 1524,
"s": 1515,
"text": "Output :"
},
{
"code": null,
"e": 1572,
"s": 1524,
"text": "Now let’s drop the 1st level of the MultiIndex."
},
{
"code": "# drop the 1st level.midx.droplevel(level = 1)",
"e": 1619,
"s": 1572,
"text": null
},
{
"code": null,
"e": 1725,
"s": 1619,
"text": "Output :As we can see in the output, the function has dropped the 1st level and returned an Index object."
},
{
"code": null,
"e": 1750,
"s": 1725,
"text": "Python pandas-multiIndex"
},
{
"code": null,
"e": 1764,
"s": 1750,
"text": "Python-pandas"
},
{
"code": null,
"e": 1771,
"s": 1764,
"text": "Python"
}
] |
offsetWidth, clientWidth, scrollWidth and Height, respectively in CSS
|
28 Mar, 2019
offsetWidth: It returns the width of an HTML element including padding, border and scrollbar in pixels but it does not include margin width. If the element does not have any associated layout box then it returns zero.
Syntax:
element.offsetWidth
clientWidth: It returns the width of an HTML element including padding in pixels but does not include margin, border and scrollbar width.
Syntax:
element.clientWidth
scrollWidth: It returns the width of the content enclosed in an html element including padding but not margin, border and scroll bar.
Syntax:
element.scrollWidth
Example: This example illustrates the use of offsetWidth, clientWidth and scrollWidth property.
<!DOCTYPE html><html> <head> <title> Use of offsetWidth, ClientWidth and scrollWidth property </title> <style> #box { height: 100px; width: 130px; border: 5px black; padding: 10px; margin: 5px; overflow: scroll; background-color: aqua; } </style></head> <body> <div id="box"> It is an example of offsetWidth, ClientWidth and scrollWidth property </div> <p>Click on button to get result</p> <button onClick="display()"> Click Here! </button> <div id="result"></div> <!-- Script to uses offsetWidth, ClientWidth and scrollWidth property --> <script> function display() { var ele = document.getElementById("box"); var osw = ele.offsetWidth; var sw = ele.scrollWidth; var cw = ele.clientWidth; document.getElementById("result").innerHTML = "offsetWidth: " + osw + "px<br>clientWidth: " + cw + "px<br>scrollWidth : " + sw + "px" ; } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
offsetHeight: It returns the height of an HTML element including padding, border and scrollbar in pixels but does not include margin height. If the element does not have any associated layout box then it returns zero.
Syntax:
element.offsetHeight
clientHeight: It returns the height of an HTML element including padding in pixels but does not include margin, border and scrollbar height.
Syntax:
element.clientHeight
scrollHeight: It returns the height of the content enclosed in an html element including padding but not margin, border and scroll bar.
Syntax:
element.scrollHeight
Example: This example illustrates the use of offsetHeight, clientHeight and scrollHeight property.
<!DOCTYPE html><html> <head> <title> Use of offsetHeight, ClientHeight and scrollHeight property </title> <style> #box { height: 100px; width: 150px; border: 5px black; padding: 10px; margin: 5px; overflow: scroll; background-color: aqua; } </style></head> <body> <div id="box"> It is an example of offsetHeight, ClientHeight and scrollHeight property </div> <p>Click on button to get result</p> <button onClick="display()"> Click Here! </button> <div id="result"></div> <script> function display() { var ele = document.getElementById("box"); var osw = ele.offsetHeight; var sw = ele.scrollHeight; var cw = ele.clientHeight; document.getElementById("result").innerHTML = "offsetHeight: " + osw + "px<br>clientHeight: " + cw + "px<br>scrollHeight: " + sw + "px" ; } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "offsetWidth: It returns the width of an HTML element including padding, border and scrollbar in pixels but it does not include margin width. If the element does not have any associated layout box then it returns zero."
},
{
"code": null,
"e": 254,
"s": 246,
"text": "Syntax:"
},
{
"code": null,
"e": 274,
"s": 254,
"text": "element.offsetWidth"
},
{
"code": null,
"e": 412,
"s": 274,
"text": "clientWidth: It returns the width of an HTML element including padding in pixels but does not include margin, border and scrollbar width."
},
{
"code": null,
"e": 420,
"s": 412,
"text": "Syntax:"
},
{
"code": null,
"e": 440,
"s": 420,
"text": "element.clientWidth"
},
{
"code": null,
"e": 574,
"s": 440,
"text": "scrollWidth: It returns the width of the content enclosed in an html element including padding but not margin, border and scroll bar."
},
{
"code": null,
"e": 582,
"s": 574,
"text": "Syntax:"
},
{
"code": null,
"e": 602,
"s": 582,
"text": "element.scrollWidth"
},
{
"code": null,
"e": 698,
"s": 602,
"text": "Example: This example illustrates the use of offsetWidth, clientWidth and scrollWidth property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Use of offsetWidth, ClientWidth and scrollWidth property </title> <style> #box { height: 100px; width: 130px; border: 5px black; padding: 10px; margin: 5px; overflow: scroll; background-color: aqua; } </style></head> <body> <div id=\"box\"> It is an example of offsetWidth, ClientWidth and scrollWidth property </div> <p>Click on button to get result</p> <button onClick=\"display()\"> Click Here! </button> <div id=\"result\"></div> <!-- Script to uses offsetWidth, ClientWidth and scrollWidth property --> <script> function display() { var ele = document.getElementById(\"box\"); var osw = ele.offsetWidth; var sw = ele.scrollWidth; var cw = ele.clientWidth; document.getElementById(\"result\").innerHTML = \"offsetWidth: \" + osw + \"px<br>clientWidth: \" + cw + \"px<br>scrollWidth : \" + sw + \"px\" ; } </script></body> </html> ",
"e": 1893,
"s": 698,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1893,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 2172,
"s": 1954,
"text": "offsetHeight: It returns the height of an HTML element including padding, border and scrollbar in pixels but does not include margin height. If the element does not have any associated layout box then it returns zero."
},
{
"code": null,
"e": 2180,
"s": 2172,
"text": "Syntax:"
},
{
"code": null,
"e": 2201,
"s": 2180,
"text": "element.offsetHeight"
},
{
"code": null,
"e": 2342,
"s": 2201,
"text": "clientHeight: It returns the height of an HTML element including padding in pixels but does not include margin, border and scrollbar height."
},
{
"code": null,
"e": 2350,
"s": 2342,
"text": "Syntax:"
},
{
"code": null,
"e": 2371,
"s": 2350,
"text": "element.clientHeight"
},
{
"code": null,
"e": 2507,
"s": 2371,
"text": "scrollHeight: It returns the height of the content enclosed in an html element including padding but not margin, border and scroll bar."
},
{
"code": null,
"e": 2515,
"s": 2507,
"text": "Syntax:"
},
{
"code": null,
"e": 2536,
"s": 2515,
"text": "element.scrollHeight"
},
{
"code": null,
"e": 2635,
"s": 2536,
"text": "Example: This example illustrates the use of offsetHeight, clientHeight and scrollHeight property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Use of offsetHeight, ClientHeight and scrollHeight property </title> <style> #box { height: 100px; width: 150px; border: 5px black; padding: 10px; margin: 5px; overflow: scroll; background-color: aqua; } </style></head> <body> <div id=\"box\"> It is an example of offsetHeight, ClientHeight and scrollHeight property </div> <p>Click on button to get result</p> <button onClick=\"display()\"> Click Here! </button> <div id=\"result\"></div> <script> function display() { var ele = document.getElementById(\"box\"); var osw = ele.offsetHeight; var sw = ele.scrollHeight; var cw = ele.clientHeight; document.getElementById(\"result\").innerHTML = \"offsetHeight: \" + osw + \"px<br>clientHeight: \" + cw + \"px<br>scrollHeight: \" + sw + \"px\" ; } </script></body> </html> ",
"e": 3749,
"s": 2635,
"text": null
},
{
"code": null,
"e": 3810,
"s": 3749,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 3819,
"s": 3810,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3826,
"s": 3819,
"text": "Picked"
},
{
"code": null,
"e": 3830,
"s": 3826,
"text": "CSS"
},
{
"code": null,
"e": 3847,
"s": 3830,
"text": "Web Technologies"
},
{
"code": null,
"e": 3874,
"s": 3847,
"text": "Web technologies Questions"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.