title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Explain BLOB object and tree object in Git.
|
Git uses a series of BLOBs and trees to store content of the working directory of a project. Whenever we perform a commit operation, Git internally creates a series of trees and BLOBs, which is the binary representation of the project folder structure at that point in time of commit.
BLOB stands for Binary Large Object. Each version of a file in Git is represented as a BLOB. A BLOB holds a file’s data but doesn’t contain any metadata about the file or even its name.
To understand a BLOB let us see an example.
Create 3 files “file1.txt”, “file2.txt” and “file3.txt” text files. The first two files will contain the same contents and the second file will have different content.
Create 3 files “file1.txt”, “file2.txt” and “file3.txt” text files. The first two files will contain the same contents and the second file will have different content.
$ git init // initialize a repo
$ echo hello>file1.txt // create a file and enter some content
$ echo hello>file2.txt // create a file and enter the same content
$ echo hello world>file3.txt // create a file and enter some content
Let us add each of these files to the staging area. Staging these files will create BLOBs under the “.git\objects” folder. In this example, we will list the contents in the “.git\objects” folder each time a file is staged.
Let us add each of these files to the staging area. Staging these files will create BLOBs under the “.git\objects” folder. In this example, we will list the contents in the “.git\objects” folder each time a file is staged.
$ git add file1.txt // stage the file
$ ls .git/objects/ // list contents
$ git add file2.txt
$ ls .git/objects/
$ git add file3.txt
$ ls .git/objects/
The output of the ls commands is shown below.
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add filel.txt
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ Is .git/objects/
ce/ info/ pack/
dell@DESKTOP-N96LNR5 MINGW64 /e/tut_repo (master)
$ git add file2.txt
dell@DESKTOP-N961NR5 MINGw64 /e/tut_repo (master)
$ Is .git/objects/
ce/ info/ pack/
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add file3.txt
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ Is .git/objects/
3b/ ce/ info/ pack/
Folders with the name ‘ce’ and ‘3b’ are created when “file1.txt” and “file3.txt” are staged. However, no new folder is created when “file2.txt” is staged. This is because “file1.txt” and “file2.txt” have the same content.
Let us now see the contents of the folder ‘ce’ and ‘3b’.
Let us now see the contents of the folder ‘ce’ and ‘3b’.
$ ls .git/objects/ce
$ ls .git/objects/3b
The output shows that the folders contain BLOB objects represented as SHA1 hash.
dell@DESKTOP-N961NRS MINGW64 /e/tut_repo (master)
$ Is .git/objects/ce
013625030ba8dba906f756967f9e9ca394464a
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ Is .git/objects/3b
18e512dba79e4c8300dd08aeb37f8e728b8dad
Let us now verify the type of the files and its contents.
$ git cat−file −t ce01
$ git cat−file −p ce01
$ git cat−file −t 3b18
$ git cat−file −p 3b18
From the output it is clear that Git created 2 BLOBs though we added 3 files. This is because the content in the first two files is the same. It is clear from the output that a BLOB stores only a file’s contents and doesn’t store file names.
//output of cat−file −t ce01
blob
//output of cat−file −p ce01
hello
//output of cat−file −t 3b18
blob
//output of cat−file −p 3b18
hello world
A tree is like a directory. Each commit in Git points to a tree object, which in turn references the BLOBs. A tree object records the following.
BLOB identifiers
BLOB identifiers
Path names
Path names
Metadata of all files in that directory
Metadata of all files in that directory
A tree can recursively reference other tree objects or subtrees. Thus, a tree builds a complete hierarchy of files and subdirectories. Just like BLOBs, trees can be viewed under the “.git/objects” folder.
Let us understand a tree through our previous example. We had created three files and added all of them to the staging area. Let us verify this by using the git status command. Let us also commit all changes to the repository.
$ git status -s // verify status
$ git commit -m 'initial commit' // commit to the repo
The status indicates that 3 files have been staged. On issuing the git commit command a commit with the hash “84a00db” is created
dell@0ESKTop-N961NR5 MINGW64 /e/tut_repo (master)
$ git status -s
A fiIe1.txt
A file2.txt
A file3.txt
dell@DESKTOP-N961NR5 MINGW64 /e/tut—repo (master)
$ git commit -m 'initial commit'
[master (root-commit) 84aOOdb) initial commit
3 files changed, 3 insertions(+)
create mode 100644 file1. txt
create mode 100644 file2. txt
create mode 100644 file3.txt
The internal structure of our example can be represented as given below −
The above diagram shows the commit “84a0” points to a tree which is the root folder of the project. The root folder has 3 files that are stored as BLOBs. The first 2 files point to the same BLOB as their contents are the same. The tree object holds reference to all BLOBs. If we create new folders within the current project, then the folders will be created as a subtree of the root project tree “e115”.
Let us verify the objects folder to see if any commit object or tree object is created. This can be viewed using the ls command.
$ ls .git/objects
$ ls .git/objects/84
$ ls .git/objects/e1
Output shows that the folder “84” represents a commit and “e1” will be the tree associated with it. These folders have a pointer file represented by a SHA1 hash.
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ Is .git/0bjects/84
aOOdb87bb5c69926b3343a564db1b3a96a389d
dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ Is .git/objects/el
1588b4a639bb90b18268b7e26f243ba31706fd
Let us now verify the content in these pointer files using the cat-filecommand.
$ git cat−file −p 84a0
$ git cat−file −p e115
From the output, it is clear that the commit (84a0) points to a tree which is the root folder of the project.
tree e11588b4a639bb90b18268b7e26f243ba31706fd
author Kiran 1612777422+0530
committer Kiran 1612777422+0530
initial commit
The root folder of the project holds three files that are stored as BLOBs.
dell@DESKTop-N961NR5 MINGW64 /e/tut_repo (master)
$ git cat
−file −p e115
100644 blob ce013625030ba8dba906f756967f9e9ca394464a file1.txt
100644 blob ce013625030ba8dba906f756967f9e9ca394464a file2.txt
100644 blob 3b18e5L2dba79e4c8300dd08aeb37f8e728b8dad file3.txt
|
[
{
"code": null,
"e": 1347,
"s": 1062,
"text": "Git uses a series of BLOBs and trees to store content of the working directory of a project. Whenever we perform a commit operation, Git internally creates a series of trees and BLOBs, which is the binary representation of the project folder structure at that point in time of commit."
},
{
"code": null,
"e": 1533,
"s": 1347,
"text": "BLOB stands for Binary Large Object. Each version of a file in Git is represented as a BLOB. A BLOB holds a file’s data but doesn’t contain any metadata about the file or even its name."
},
{
"code": null,
"e": 1577,
"s": 1533,
"text": "To understand a BLOB let us see an example."
},
{
"code": null,
"e": 1745,
"s": 1577,
"text": "Create 3 files “file1.txt”, “file2.txt” and “file3.txt” text files. The first two files will contain the same contents and the second file will have different content."
},
{
"code": null,
"e": 1913,
"s": 1745,
"text": "Create 3 files “file1.txt”, “file2.txt” and “file3.txt” text files. The first two files will contain the same contents and the second file will have different content."
},
{
"code": null,
"e": 2178,
"s": 1913,
"text": "$ git init // initialize a repo\n$ echo hello>file1.txt // create a file and enter some content\n$ echo hello>file2.txt // create a file and enter the same content\n$ echo hello world>file3.txt // create a file and enter some content"
},
{
"code": null,
"e": 2401,
"s": 2178,
"text": "Let us add each of these files to the staging area. Staging these files will create BLOBs under the “.git\\objects” folder. In this example, we will list the contents in the “.git\\objects” folder each time a file is staged."
},
{
"code": null,
"e": 2624,
"s": 2401,
"text": "Let us add each of these files to the staging area. Staging these files will create BLOBs under the “.git\\objects” folder. In this example, we will list the contents in the “.git\\objects” folder each time a file is staged."
},
{
"code": null,
"e": 2783,
"s": 2624,
"text": "$ git add file1.txt // stage the file\n$ ls .git/objects/ // list contents\n$ git add file2.txt\n$ ls .git/objects/\n$ git add file3.txt\n$ ls .git/objects/"
},
{
"code": null,
"e": 2829,
"s": 2783,
"text": "The output of the ls commands is shown below."
},
{
"code": null,
"e": 3303,
"s": 2829,
"text": "dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add filel.txt\n\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ Is .git/objects/\nce/ info/ pack/\n\ndell@DESKTOP-N96LNR5 MINGW64 /e/tut_repo (master)\n$ git add file2.txt\n\ndell@DESKTOP-N961NR5 MINGw64 /e/tut_repo (master)\n$ Is .git/objects/\nce/ info/ pack/\n\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add file3.txt\n\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ Is .git/objects/\n3b/ ce/ info/ pack/"
},
{
"code": null,
"e": 3525,
"s": 3303,
"text": "Folders with the name ‘ce’ and ‘3b’ are created when “file1.txt” and “file3.txt” are staged. However, no new folder is created when “file2.txt” is staged. This is because “file1.txt” and “file2.txt” have the same content."
},
{
"code": null,
"e": 3582,
"s": 3525,
"text": "Let us now see the contents of the folder ‘ce’ and ‘3b’."
},
{
"code": null,
"e": 3639,
"s": 3582,
"text": "Let us now see the contents of the folder ‘ce’ and ‘3b’."
},
{
"code": null,
"e": 3681,
"s": 3639,
"text": "$ ls .git/objects/ce\n$ ls .git/objects/3b"
},
{
"code": null,
"e": 3762,
"s": 3681,
"text": "The output shows that the folders contain BLOB objects represented as SHA1 hash."
},
{
"code": null,
"e": 3983,
"s": 3762,
"text": "dell@DESKTOP-N961NRS MINGW64 /e/tut_repo (master)\n$ Is .git/objects/ce\n013625030ba8dba906f756967f9e9ca394464a\n\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ Is .git/objects/3b\n18e512dba79e4c8300dd08aeb37f8e728b8dad"
},
{
"code": null,
"e": 4041,
"s": 3983,
"text": "Let us now verify the type of the files and its contents."
},
{
"code": null,
"e": 4133,
"s": 4041,
"text": "$ git cat−file −t ce01\n$ git cat−file −p ce01\n$ git cat−file −t 3b18\n$ git cat−file −p 3b18"
},
{
"code": null,
"e": 4375,
"s": 4133,
"text": "From the output it is clear that Git created 2 BLOBs though we added 3 files. This is because the content in the first two files is the same. It is clear from the output that a BLOB stores only a file’s contents and doesn’t store file names."
},
{
"code": null,
"e": 4519,
"s": 4375,
"text": "//output of cat−file −t ce01\nblob\n//output of cat−file −p ce01\nhello\n//output of cat−file −t 3b18\nblob\n//output of cat−file −p 3b18\nhello world"
},
{
"code": null,
"e": 4664,
"s": 4519,
"text": "A tree is like a directory. Each commit in Git points to a tree object, which in turn references the BLOBs. A tree object records the following."
},
{
"code": null,
"e": 4681,
"s": 4664,
"text": "BLOB identifiers"
},
{
"code": null,
"e": 4698,
"s": 4681,
"text": "BLOB identifiers"
},
{
"code": null,
"e": 4709,
"s": 4698,
"text": "Path names"
},
{
"code": null,
"e": 4720,
"s": 4709,
"text": "Path names"
},
{
"code": null,
"e": 4760,
"s": 4720,
"text": "Metadata of all files in that directory"
},
{
"code": null,
"e": 4800,
"s": 4760,
"text": "Metadata of all files in that directory"
},
{
"code": null,
"e": 5005,
"s": 4800,
"text": "A tree can recursively reference other tree objects or subtrees. Thus, a tree builds a complete hierarchy of files and subdirectories. Just like BLOBs, trees can be viewed under the “.git/objects” folder."
},
{
"code": null,
"e": 5232,
"s": 5005,
"text": "Let us understand a tree through our previous example. We had created three files and added all of them to the staging area. Let us verify this by using the git status command. Let us also commit all changes to the repository."
},
{
"code": null,
"e": 5320,
"s": 5232,
"text": "$ git status -s // verify status\n$ git commit -m 'initial commit' // commit to the repo"
},
{
"code": null,
"e": 5450,
"s": 5320,
"text": "The status indicates that 3 files have been staged. On issuing the git commit command a commit with the hash “84a00db” is created"
},
{
"code": null,
"e": 5803,
"s": 5450,
"text": "dell@0ESKTop-N961NR5 MINGW64 /e/tut_repo (master)\n$ git status -s\nA fiIe1.txt\nA file2.txt\nA file3.txt\ndell@DESKTOP-N961NR5 MINGW64 /e/tut—repo (master)\n$ git commit -m 'initial commit'\n[master (root-commit) 84aOOdb) initial commit\n3 files changed, 3 insertions(+)\ncreate mode 100644 file1. txt\ncreate mode 100644 file2. txt\ncreate mode 100644 file3.txt"
},
{
"code": null,
"e": 5877,
"s": 5803,
"text": "The internal structure of our example can be represented as given below −"
},
{
"code": null,
"e": 6282,
"s": 5877,
"text": "The above diagram shows the commit “84a0” points to a tree which is the root folder of the project. The root folder has 3 files that are stored as BLOBs. The first 2 files point to the same BLOB as their contents are the same. The tree object holds reference to all BLOBs. If we create new folders within the current project, then the folders will be created as a subtree of the root project tree “e115”."
},
{
"code": null,
"e": 6411,
"s": 6282,
"text": "Let us verify the objects folder to see if any commit object or tree object is created. This can be viewed using the ls command."
},
{
"code": null,
"e": 6471,
"s": 6411,
"text": "$ ls .git/objects\n$ ls .git/objects/84\n$ ls .git/objects/e1"
},
{
"code": null,
"e": 6633,
"s": 6471,
"text": "Output shows that the folder “84” represents a commit and “e1” will be the tree associated with it. These folders have a pointer file represented by a SHA1 hash."
},
{
"code": null,
"e": 6853,
"s": 6633,
"text": "dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ Is .git/0bjects/84\naOOdb87bb5c69926b3343a564db1b3a96a389d\ndell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ Is .git/objects/el\n1588b4a639bb90b18268b7e26f243ba31706fd"
},
{
"code": null,
"e": 6933,
"s": 6853,
"text": "Let us now verify the content in these pointer files using the cat-filecommand."
},
{
"code": null,
"e": 6979,
"s": 6933,
"text": "$ git cat−file −p 84a0\n$ git cat−file −p e115"
},
{
"code": null,
"e": 7089,
"s": 6979,
"text": "From the output, it is clear that the commit (84a0) points to a tree which is the root folder of the project."
},
{
"code": null,
"e": 7211,
"s": 7089,
"text": "tree e11588b4a639bb90b18268b7e26f243ba31706fd\nauthor Kiran 1612777422+0530\ncommitter Kiran 1612777422+0530\ninitial commit"
},
{
"code": null,
"e": 7286,
"s": 7211,
"text": "The root folder of the project holds three files that are stored as BLOBs."
},
{
"code": null,
"e": 7549,
"s": 7286,
"text": "dell@DESKTop-N961NR5 MINGW64 /e/tut_repo (master)\n$ git cat\n−file −p e115\n100644 blob ce013625030ba8dba906f756967f9e9ca394464a file1.txt\n100644 blob ce013625030ba8dba906f756967f9e9ca394464a file2.txt\n100644 blob 3b18e5L2dba79e4c8300dd08aeb37f8e728b8dad file3.txt"
}
] |
The return Statement in Python
|
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
Live Demo
#!/usr/bin/python
Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None."
},
{
"code": null,
"e": 1336,
"s": 1232,
"text": "All the above examples are not returning any value. You can return a value from a function as follows −"
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": " Live Demo"
},
{
"code": null,
"e": 1638,
"s": 1347,
"text": "#!/usr/bin/python\nFunction definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2\n print \"Inside the function : \", total\n return total;\n# Now you can call sum function\ntotal = sum( 10, 20 );\nprint \"Outside the function : \", total"
},
{
"code": null,
"e": 1706,
"s": 1638,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1757,
"s": 1706,
"text": "Inside the function : 30\nOutside the function : 30"
}
] |
Automatically run SAP transactions out of Excel | by Jesko Rehberg | Towards Data Science
|
Do you frequently have to execute SAP transactions with specific filter parameters and export the result as an Excel file? If so, and if you want to automate these steps using Excel VBA and SAP scripts, this is your story. Out of an Excel file we will automatically run SAP transactions with defined filters/settings, export the results out of SAP and save the result as an Excel file without further manual input. This is very helpful when we have to run specific SAP transactions frequently, always using the same filter/parameter settings. Let’s now start automating this boring repetitive manual work building an Excel-SAP GUI.
In SAP you can record your inputs using the “Script Recording and playback” functionality. This is very similar to e.g. Excel’s macro recorder. To do this in SAP you must press ALT+F12 and then click “Script Recording and playback”:
After you have clicked the red “record” button, everything you will do in SAP will be recorded until you stop the recording via “Stop” button.
In our example we will run the transaction “IW29”, set some filters, and execute the transaction to see the results. We will also export the results out of SAP as an Excel file. After that we will stop the recording and have a look upon the just recorded SAP script file. In our example it looks like this:
We now simply copy and paste this script into our Excel file’s VBA module. Therefore we open our Excel Macro file (e.g. .xlsm) and add below code (Sub Routine) into our module:
Sub SapExport()If Not IsObject(SAPapplication) ThenSet SapGuiAuto = GetObject(“SAPGUI”)Set SAPapplication = SapGuiAuto.GetScriptingEngineEnd IfIf Not IsObject(SAPconnection) ThenSet SAPconnection = SAPapplication.Children(0)End IfIf Not IsObject(SAPsession) ThenSet SAPsession = SAPconnection.Children(0)End IfIf IsObject(WScript) ThenWScript.ConnectObject SAPsession, “on”WScript.ConnectObject Application, “on”End If
This piece of VBA code will set the connection between our Excel file and SAP. Each time we run this code, SAP will show us this message, which needs to be confirmed first before the script can go on:
In case you want to get rid off this “A script is trying to attach to SAP GUI, please confirm via Okay button” message, you have to customize your local layout in SAP as below:
Press (ALT+F12) in SAP to be able to “Customize local layout”. Then click on “Options”, click “Accessibility&Scripting”, and finally choose “Scripting”. Now untick the box ‘Notify when a script attaches to SAP GUI’ and ‘Notify when a script opens a connection’. So in the end the SAP scripting setting should look like this:
Back in your Excel VBA module, you now paste in the recorded session tasks (the transaction’s filters). The only modification you have to do is to replace session with SAPsession, so finally it looks something like this in your Excel module:
SAPsession.findById(“wnd[0]”).maximizeSAPsession.findById(“wnd[0]/tbar[0]/okcd”).Text = “iw29”SAPsession.findById(“wnd[0]”).sendVKey 0SAPsession.findById(“wnd[0]/usr/chkDY_MAB”).Selected = FalseSAPsession.findById(“wnd[0]/usr/ctxtQMART-LOW”).Text = “z2”SAPsession.findById(“wnd[0]/usr/ctxtDATUV”).Text = “10012021”SAPsession.findById(“wnd[0]/usr/ctxtDATUB”).Text = “26012021”SAPsession.findById(“wnd[0]/usr/ctxtDATUB”).SetFocusSAPsession.findById(“wnd[0]/usr/ctxtDATUB”).caretPosition = 8SAPsession.findById(“wnd[0]”).sendVKey 0SAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[0]/tbar[1]/btn[16]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).press
Until now we have run the SAP transactions with defined filters and exported the results as an Excel file. Finally, we also want to save this file to a defined path. Below you will find an easy solution for this, which is already sufficient enough for our task:
‘Disable the Application Alert before saving the fileApplication.DisplayAlerts = FalseWindows(“FileName”).ActivateActiveWorkbook.SaveAs FileName:=”C:\FileName.xlsx”, FileFormat _:=xlOpenXMLWorkbook, CreateBackup:=False‘Enabling the Application Alerts after saving the fileApplication.DisplayAlerts = True'to “clean up” SAP we return back to SAP’s Easy Access:SAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[0]/tbar[0]/btn[3]”).pressSAPsession.findById(“wnd[0]/tbar[0]/btn[3]”).pressEnd sub()
If you added all this VBA code into one Sub Routine in Excel you’re done. So in the future you can just start calling your SAP transaction with defined filters out of Excel.
Note: for this VBA code to work properly you must have one instance of SAP open (in other words, you must already be logged in). Please ensure only one SAP mode is active and this one instance must be in start mode:
Big up yourself, you are now able to export result lists out of SAP in an automated way using Excel! You can find the complete Excel Macro on my Github. Many thanks for reading, hope this was supportive! Any questions, please let me know. You can connect with me on LinkedIn or Twitter.
Originally published on my website DAR-Analytics.
|
[
{
"code": null,
"e": 804,
"s": 172,
"text": "Do you frequently have to execute SAP transactions with specific filter parameters and export the result as an Excel file? If so, and if you want to automate these steps using Excel VBA and SAP scripts, this is your story. Out of an Excel file we will automatically run SAP transactions with defined filters/settings, export the results out of SAP and save the result as an Excel file without further manual input. This is very helpful when we have to run specific SAP transactions frequently, always using the same filter/parameter settings. Let’s now start automating this boring repetitive manual work building an Excel-SAP GUI."
},
{
"code": null,
"e": 1037,
"s": 804,
"text": "In SAP you can record your inputs using the “Script Recording and playback” functionality. This is very similar to e.g. Excel’s macro recorder. To do this in SAP you must press ALT+F12 and then click “Script Recording and playback”:"
},
{
"code": null,
"e": 1180,
"s": 1037,
"text": "After you have clicked the red “record” button, everything you will do in SAP will be recorded until you stop the recording via “Stop” button."
},
{
"code": null,
"e": 1487,
"s": 1180,
"text": "In our example we will run the transaction “IW29”, set some filters, and execute the transaction to see the results. We will also export the results out of SAP as an Excel file. After that we will stop the recording and have a look upon the just recorded SAP script file. In our example it looks like this:"
},
{
"code": null,
"e": 1664,
"s": 1487,
"text": "We now simply copy and paste this script into our Excel file’s VBA module. Therefore we open our Excel Macro file (e.g. .xlsm) and add below code (Sub Routine) into our module:"
},
{
"code": null,
"e": 2083,
"s": 1664,
"text": "Sub SapExport()If Not IsObject(SAPapplication) ThenSet SapGuiAuto = GetObject(“SAPGUI”)Set SAPapplication = SapGuiAuto.GetScriptingEngineEnd IfIf Not IsObject(SAPconnection) ThenSet SAPconnection = SAPapplication.Children(0)End IfIf Not IsObject(SAPsession) ThenSet SAPsession = SAPconnection.Children(0)End IfIf IsObject(WScript) ThenWScript.ConnectObject SAPsession, “on”WScript.ConnectObject Application, “on”End If"
},
{
"code": null,
"e": 2284,
"s": 2083,
"text": "This piece of VBA code will set the connection between our Excel file and SAP. Each time we run this code, SAP will show us this message, which needs to be confirmed first before the script can go on:"
},
{
"code": null,
"e": 2461,
"s": 2284,
"text": "In case you want to get rid off this “A script is trying to attach to SAP GUI, please confirm via Okay button” message, you have to customize your local layout in SAP as below:"
},
{
"code": null,
"e": 2786,
"s": 2461,
"text": "Press (ALT+F12) in SAP to be able to “Customize local layout”. Then click on “Options”, click “Accessibility&Scripting”, and finally choose “Scripting”. Now untick the box ‘Notify when a script attaches to SAP GUI’ and ‘Notify when a script opens a connection’. So in the end the SAP scripting setting should look like this:"
},
{
"code": null,
"e": 3028,
"s": 2786,
"text": "Back in your Excel VBA module, you now paste in the recorded session tasks (the transaction’s filters). The only modification you have to do is to replace session with SAPsession, so finally it looks something like this in your Excel module:"
},
{
"code": null,
"e": 3808,
"s": 3028,
"text": "SAPsession.findById(“wnd[0]”).maximizeSAPsession.findById(“wnd[0]/tbar[0]/okcd”).Text = “iw29”SAPsession.findById(“wnd[0]”).sendVKey 0SAPsession.findById(“wnd[0]/usr/chkDY_MAB”).Selected = FalseSAPsession.findById(“wnd[0]/usr/ctxtQMART-LOW”).Text = “z2”SAPsession.findById(“wnd[0]/usr/ctxtDATUV”).Text = “10012021”SAPsession.findById(“wnd[0]/usr/ctxtDATUB”).Text = “26012021”SAPsession.findById(“wnd[0]/usr/ctxtDATUB”).SetFocusSAPsession.findById(“wnd[0]/usr/ctxtDATUB”).caretPosition = 8SAPsession.findById(“wnd[0]”).sendVKey 0SAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[0]/tbar[1]/btn[16]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).press"
},
{
"code": null,
"e": 4070,
"s": 3808,
"text": "Until now we have run the SAP transactions with defined filters and exported the results as an Excel file. Finally, we also want to save this file to a defined path. Below you will find an easy solution for this, which is already sufficient enough for our task:"
},
{
"code": null,
"e": 4589,
"s": 4070,
"text": "‘Disable the Application Alert before saving the fileApplication.DisplayAlerts = FalseWindows(“FileName”).ActivateActiveWorkbook.SaveAs FileName:=”C:\\FileName.xlsx”, FileFormat _:=xlOpenXMLWorkbook, CreateBackup:=False‘Enabling the Application Alerts after saving the fileApplication.DisplayAlerts = True'to “clean up” SAP we return back to SAP’s Easy Access:SAPsession.findById(“wnd[1]/tbar[0]/btn[0]”).pressSAPsession.findById(“wnd[0]/tbar[0]/btn[3]”).pressSAPsession.findById(“wnd[0]/tbar[0]/btn[3]”).pressEnd sub()"
},
{
"code": null,
"e": 4763,
"s": 4589,
"text": "If you added all this VBA code into one Sub Routine in Excel you’re done. So in the future you can just start calling your SAP transaction with defined filters out of Excel."
},
{
"code": null,
"e": 4979,
"s": 4763,
"text": "Note: for this VBA code to work properly you must have one instance of SAP open (in other words, you must already be logged in). Please ensure only one SAP mode is active and this one instance must be in start mode:"
},
{
"code": null,
"e": 5266,
"s": 4979,
"text": "Big up yourself, you are now able to export result lists out of SAP in an automated way using Excel! You can find the complete Excel Macro on my Github. Many thanks for reading, hope this was supportive! Any questions, please let me know. You can connect with me on LinkedIn or Twitter."
}
] |
ASP.NET WP - View Engines
|
The View Engine in ASP.NET is used to translate our views to HTML and then render them to the browser. By default, ASP.Net supports ASPX and the Razor View Engine. The view engine templates have a different syntax than the implementation. In this chapter, we will discuss the two most important view engines which are −
ASPX View Engine also known as Web Form View Engine and
ASPX View Engine also known as Web Form View Engine and
Razor View Engine
Razor View Engine
There are many more third-party view engines, like Spark, Nhaml, etc.
ASPX or Web Form Engine is the default view engine for ASP.NET that is included with ASP.NET MVC from the beginning itself.
The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms.
The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms.
The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master).
The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master).
ASPX uses "<% = %>" or "<% : %>" to render server-side content.
ASPX uses "<% = %>" or "<% : %>" to render server-side content.
The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.
The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.
ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default.
ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default.
ASPX View Engine is comparatively faster than Razor View Engine.
ASPX View Engine is comparatively faster than Razor View Engine.
Razor Engine is an advanced view engine that was introduced with MVC3. It is not a new language, but it is a new markup syntax.
The Razor syntax is based on the C# programming language.
The Razor syntax is based on the C# programming language.
The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well.
The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well.
The namespace for Razor Engine is System.Web.Razor.
The namespace for Razor Engine is System.Web.Razor.
Razor uses the "@" character instead of "<% %>" as used by the ASPX View Engine.
Razor uses the "@" character instead of "<% %>" as used by the ASPX View Engine.
The Razor file extension is "cshtml" for the C# language.
The Razor file extension is "cshtml" for the C# language.
By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks.
By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks.
Razor View Engine is slow as compared to ASPX View Engine.
Razor View Engine is slow as compared to ASPX View Engine.
To understand the syntax difference, let’s have a look into a simple example that is written in both ASPX and Razor view engines. Following is the code snippet for ASPX view engine.
<%foreach (var student in Students){ %>
<% if (student.IsPassed){ %>
<% = student.FirstName%> is going to next grade.
<% } else{ %>
<% = student. FirstName %> is not going to next grade.
<% } %>
<% } %>
Following is the same example code written in Razor View engine.
@foreach (var student in Students){
@if(student.IsPassed){
@student. FirstName is going to next grade.
} else {
@student. FirstName is not going to next grade.
}
}
If you look at both the above code snippets written in ASPX and Razor syntax, then you can see quite clearly that Razor syntax is clean and simpler as compared to the ASPX syntax. One of the disadvantages of Razor is, it is not supported by visual editors like Dream Viewer.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2605,
"s": 2285,
"text": "The View Engine in ASP.NET is used to translate our views to HTML and then render them to the browser. By default, ASP.Net supports ASPX and the Razor View Engine. The view engine templates have a different syntax than the implementation. In this chapter, we will discuss the two most important view engines which are −"
},
{
"code": null,
"e": 2661,
"s": 2605,
"text": "ASPX View Engine also known as Web Form View Engine and"
},
{
"code": null,
"e": 2717,
"s": 2661,
"text": "ASPX View Engine also known as Web Form View Engine and"
},
{
"code": null,
"e": 2735,
"s": 2717,
"text": "Razor View Engine"
},
{
"code": null,
"e": 2753,
"s": 2735,
"text": "Razor View Engine"
},
{
"code": null,
"e": 2823,
"s": 2753,
"text": "There are many more third-party view engines, like Spark, Nhaml, etc."
},
{
"code": null,
"e": 2947,
"s": 2823,
"text": "ASPX or Web Form Engine is the default view engine for ASP.NET that is included with ASP.NET MVC from the beginning itself."
},
{
"code": null,
"e": 3065,
"s": 2947,
"text": "The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms."
},
{
"code": null,
"e": 3183,
"s": 3065,
"text": "The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms."
},
{
"code": null,
"e": 3276,
"s": 3183,
"text": "The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master)."
},
{
"code": null,
"e": 3369,
"s": 3276,
"text": "The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master)."
},
{
"code": null,
"e": 3433,
"s": 3369,
"text": "ASPX uses \"<% = %>\" or \"<% : %>\" to render server-side content."
},
{
"code": null,
"e": 3497,
"s": 3433,
"text": "ASPX uses \"<% = %>\" or \"<% : %>\" to render server-side content."
},
{
"code": null,
"e": 3567,
"s": 3497,
"text": "The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine."
},
{
"code": null,
"e": 3637,
"s": 3567,
"text": "The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine."
},
{
"code": null,
"e": 3717,
"s": 3637,
"text": "ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default."
},
{
"code": null,
"e": 3797,
"s": 3717,
"text": "ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default."
},
{
"code": null,
"e": 3862,
"s": 3797,
"text": "ASPX View Engine is comparatively faster than Razor View Engine."
},
{
"code": null,
"e": 3927,
"s": 3862,
"text": "ASPX View Engine is comparatively faster than Razor View Engine."
},
{
"code": null,
"e": 4055,
"s": 3927,
"text": "Razor Engine is an advanced view engine that was introduced with MVC3. It is not a new language, but it is a new markup syntax."
},
{
"code": null,
"e": 4113,
"s": 4055,
"text": "The Razor syntax is based on the C# programming language."
},
{
"code": null,
"e": 4171,
"s": 4113,
"text": "The Razor syntax is based on the C# programming language."
},
{
"code": null,
"e": 4318,
"s": 4171,
"text": "The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well."
},
{
"code": null,
"e": 4465,
"s": 4318,
"text": "The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well."
},
{
"code": null,
"e": 4517,
"s": 4465,
"text": "The namespace for Razor Engine is System.Web.Razor."
},
{
"code": null,
"e": 4569,
"s": 4517,
"text": "The namespace for Razor Engine is System.Web.Razor."
},
{
"code": null,
"e": 4650,
"s": 4569,
"text": "Razor uses the \"@\" character instead of \"<% %>\" as used by the ASPX View Engine."
},
{
"code": null,
"e": 4731,
"s": 4650,
"text": "Razor uses the \"@\" character instead of \"<% %>\" as used by the ASPX View Engine."
},
{
"code": null,
"e": 4789,
"s": 4731,
"text": "The Razor file extension is \"cshtml\" for the C# language."
},
{
"code": null,
"e": 4847,
"s": 4789,
"text": "The Razor file extension is \"cshtml\" for the C# language."
},
{
"code": null,
"e": 4983,
"s": 4847,
"text": "By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks."
},
{
"code": null,
"e": 5119,
"s": 4983,
"text": "By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks."
},
{
"code": null,
"e": 5178,
"s": 5119,
"text": "Razor View Engine is slow as compared to ASPX View Engine."
},
{
"code": null,
"e": 5237,
"s": 5178,
"text": "Razor View Engine is slow as compared to ASPX View Engine."
},
{
"code": null,
"e": 5419,
"s": 5237,
"text": "To understand the syntax difference, let’s have a look into a simple example that is written in both ASPX and Razor view engines. Following is the code snippet for ASPX view engine."
},
{
"code": null,
"e": 5648,
"s": 5419,
"text": "<%foreach (var student in Students){ %>\n \n <% if (student.IsPassed){ %>\n <% = student.FirstName%> is going to next grade.\n <% } else{ %>\n <% = student. FirstName %> is not going to next grade.\n <% } %>\n\n<% } %>"
},
{
"code": null,
"e": 5713,
"s": 5648,
"text": "Following is the same example code written in Razor View engine."
},
{
"code": null,
"e": 5898,
"s": 5713,
"text": "@foreach (var student in Students){\n @if(student.IsPassed){\n @student. FirstName is going to next grade.\n } else {\n @student. FirstName is not going to next grade.\n }\n}"
},
{
"code": null,
"e": 6173,
"s": 5898,
"text": "If you look at both the above code snippets written in ASPX and Razor syntax, then you can see quite clearly that Razor syntax is clean and simpler as compared to the ASPX syntax. One of the disadvantages of Razor is, it is not supported by visual editors like Dream Viewer."
},
{
"code": null,
"e": 6208,
"s": 6173,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6222,
"s": 6208,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6257,
"s": 6222,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6280,
"s": 6257,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6314,
"s": 6280,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6334,
"s": 6314,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6369,
"s": 6334,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6386,
"s": 6369,
"text": " University Code"
},
{
"code": null,
"e": 6421,
"s": 6386,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6438,
"s": 6421,
"text": " University Code"
},
{
"code": null,
"e": 6472,
"s": 6438,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6487,
"s": 6472,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6494,
"s": 6487,
"text": " Print"
},
{
"code": null,
"e": 6505,
"s": 6494,
"text": " Add Notes"
}
] |
5 Most Difficult Programming Languages of the World - GeeksforGeeks
|
22 Sep, 2019
You might have written your first code in programming languages such as C/C++ or Java and might have faced difficulty learning these languages. Well, these languages are at least readable or understandable but what if we say to write a program printing ‘Hello World!‘ using spaces, tabs, and linefeeds only. We are not joking and actually there are some programming languages in the world where you need to write your code using some commands or syntax which is neither readable nor understandable. They are also considered as the most difficult programming languages in the world and maybe you will get to know about these languages for the first time so let’s discuss these languages one by one.
As the name suggests, this language is really complicated and coding in this language is really difficult. It was created in 1993 by Urban Muller and the main purpose to create this language was to write minimal lines of code. This language operates in an array of memory cells and there are only 8 commands defined in this language to write any program.
Example: Hello World! Program
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
Check the output of this code from here.
We know that the name of this language sounds a funny name for you but it is actually a programming language and it was created by Sean Heber in 2003. This language consists of 12 instructions and the funniest thing about this language is the keyword ‘moo’ (sound of a cow) or it’s variations used in this language. Writing any other character or word considered as a comment in this language. It was based on the language used in Turing Machine.
Example: Hello World! Program
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO Moo Moo MoO MoO MoO Moo OOO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOoMOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo Moo MoO MoO MoO Moo MOo MOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo MooOOO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo
Check the output of this code from here.
This language was created in 1972 by Don Woods and James M. Lyon and they both were students at Princeton University. This language doesn’t have any pronounceable acronym. Creators of this programming language included keywords like Read out, Ignore, Please, Forget, and likewise to make this language user-friendly. The funny thing about this language is that it expects 4 Please keyword in code to check programmers politeness. If it will be less the code won’t execute because it will consider the programmer is insufficiently polite. If it will be 5 or more than 5 then also it won’t execute because it will consider the programmer is overly polite.
Example: Hello World! Program
DO ,1 <- #13PLEASE DO ,1 SUB #1 <- #238DO ,1 SUB #2 <- #108DO ,1 SUB #3 <- #112DO ,1 SUB #4 <- #0DO ,1 SUB #5 <- #64DO ,1 SUB #6 <- #194DO ,1 SUB #7 <- #48PLEASE DO ,1 SUB #8 <- #22DO ,1 SUB #9 <- #248DO ,1 SUB #10 <- #168DO ,1 SUB #11 <- #24DO ,1 SUB #12 <- #16DO ,1 SUB #13 <- #162PLEASE READ OUT ,1PLEASE GIVE UP
Check the output of this code from here.
This language was introduced by Ben Olmstead in 1998 and the amazing fact is that it took almost two years to write the first program so you can imagine the complexity of this language. Coding in this language looks like garbage or malfunction and it is said to be that Ben Olmstead has never written a single program in this language. Malbolge is a public domain esoteric programming language and considered as one of the hardest programming languages in the world.
Example: Hello World! Program
('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ
Check the output of this code from here.
This language was introduced by Edwin Brady and Chris Morris on 1st April 2003 (April fools day). The day it was introduced people thought it was a joke but it wasn’t actually. You are allowed to use only spaces, tabs, and linefeeds to write your code in this language. Any other character will be ignored by the interpreter.
Example: Hello World! Program. Don’t confuse as the source code only contains the whitespace and tabs. Check the output of this code from here.
Other Difficult Programming Languages:
Chef
Shakespeare
ArnoldC
GBlog
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Top 10 Projects For Beginners To Practice HTML and CSS Skills
GET and POST requests using Python
Top 10 Angular Libraries For Web Developers
Working with csv files in Python
Modulo Operator (%) in C/C++ with Examples
Arrow operator -> in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n22 Sep, 2019"
},
{
"code": null,
"e": 25229,
"s": 24531,
"text": "You might have written your first code in programming languages such as C/C++ or Java and might have faced difficulty learning these languages. Well, these languages are at least readable or understandable but what if we say to write a program printing ‘Hello World!‘ using spaces, tabs, and linefeeds only. We are not joking and actually there are some programming languages in the world where you need to write your code using some commands or syntax which is neither readable nor understandable. They are also considered as the most difficult programming languages in the world and maybe you will get to know about these languages for the first time so let’s discuss these languages one by one."
},
{
"code": null,
"e": 25584,
"s": 25229,
"text": "As the name suggests, this language is really complicated and coding in this language is really difficult. It was created in 1993 by Urban Muller and the main purpose to create this language was to write minimal lines of code. This language operates in an array of memory cells and there are only 8 commands defined in this language to write any program."
},
{
"code": null,
"e": 25614,
"s": 25584,
"text": "Example: Hello World! Program"
},
{
"code": null,
"e": 25726,
"s": 25614,
"text": "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
},
{
"code": null,
"e": 25767,
"s": 25726,
"text": "Check the output of this code from here."
},
{
"code": null,
"e": 26214,
"s": 25767,
"text": "We know that the name of this language sounds a funny name for you but it is actually a programming language and it was created by Sean Heber in 2003. This language consists of 12 instructions and the funniest thing about this language is the keyword ‘moo’ (sound of a cow) or it’s variations used in this language. Writing any other character or word considered as a comment in this language. It was based on the language used in Turing Machine."
},
{
"code": null,
"e": 26244,
"s": 26214,
"text": "Example: Hello World! Program"
},
{
"code": null,
"e": 27782,
"s": 26244,
"text": "MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO Moo Moo MoO MoO MoO Moo OOO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOoMOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo Moo MoO MoO MoO Moo MOo MOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo MooOOO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo"
},
{
"code": null,
"e": 27823,
"s": 27782,
"text": "Check the output of this code from here."
},
{
"code": null,
"e": 28477,
"s": 27823,
"text": "This language was created in 1972 by Don Woods and James M. Lyon and they both were students at Princeton University. This language doesn’t have any pronounceable acronym. Creators of this programming language included keywords like Read out, Ignore, Please, Forget, and likewise to make this language user-friendly. The funny thing about this language is that it expects 4 Please keyword in code to check programmers politeness. If it will be less the code won’t execute because it will consider the programmer is insufficiently polite. If it will be 5 or more than 5 then also it won’t execute because it will consider the programmer is overly polite."
},
{
"code": null,
"e": 28507,
"s": 28477,
"text": "Example: Hello World! Program"
},
{
"code": null,
"e": 28823,
"s": 28507,
"text": "DO ,1 <- #13PLEASE DO ,1 SUB #1 <- #238DO ,1 SUB #2 <- #108DO ,1 SUB #3 <- #112DO ,1 SUB #4 <- #0DO ,1 SUB #5 <- #64DO ,1 SUB #6 <- #194DO ,1 SUB #7 <- #48PLEASE DO ,1 SUB #8 <- #22DO ,1 SUB #9 <- #248DO ,1 SUB #10 <- #168DO ,1 SUB #11 <- #24DO ,1 SUB #12 <- #16DO ,1 SUB #13 <- #162PLEASE READ OUT ,1PLEASE GIVE UP"
},
{
"code": null,
"e": 28864,
"s": 28823,
"text": "Check the output of this code from here."
},
{
"code": null,
"e": 29331,
"s": 28864,
"text": "This language was introduced by Ben Olmstead in 1998 and the amazing fact is that it took almost two years to write the first program so you can imagine the complexity of this language. Coding in this language looks like garbage or malfunction and it is said to be that Ben Olmstead has never written a single program in this language. Malbolge is a public domain esoteric programming language and considered as one of the hardest programming languages in the world."
},
{
"code": null,
"e": 29361,
"s": 29331,
"text": "Example: Hello World! Program"
},
{
"code": null,
"e": 29475,
"s": 29361,
"text": "('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#\"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\\}}|z2VxSSQ\n"
},
{
"code": null,
"e": 29516,
"s": 29475,
"text": "Check the output of this code from here."
},
{
"code": null,
"e": 29842,
"s": 29516,
"text": "This language was introduced by Edwin Brady and Chris Morris on 1st April 2003 (April fools day). The day it was introduced people thought it was a joke but it wasn’t actually. You are allowed to use only spaces, tabs, and linefeeds to write your code in this language. Any other character will be ignored by the interpreter."
},
{
"code": null,
"e": 29986,
"s": 29842,
"text": "Example: Hello World! Program. Don’t confuse as the source code only contains the whitespace and tabs. Check the output of this code from here."
},
{
"code": null,
"e": 30025,
"s": 29986,
"text": "Other Difficult Programming Languages:"
},
{
"code": null,
"e": 30030,
"s": 30025,
"text": "Chef"
},
{
"code": null,
"e": 30042,
"s": 30030,
"text": "Shakespeare"
},
{
"code": null,
"e": 30050,
"s": 30042,
"text": "ArnoldC"
},
{
"code": null,
"e": 30056,
"s": 30050,
"text": "GBlog"
},
{
"code": null,
"e": 30077,
"s": 30056,
"text": "Programming Language"
},
{
"code": null,
"e": 30175,
"s": 30077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30184,
"s": 30175,
"text": "Comments"
},
{
"code": null,
"e": 30197,
"s": 30184,
"text": "Old Comments"
},
{
"code": null,
"e": 30222,
"s": 30197,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30284,
"s": 30222,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30319,
"s": 30284,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 30363,
"s": 30319,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 30396,
"s": 30363,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 30439,
"s": 30396,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30480,
"s": 30439,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30543,
"s": 30480,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 30561,
"s": 30543,
"text": "Structures in C++"
}
] |
How to check Android Phone Model programmatically?
|
This example demonstrate about How to check Android Phone Model programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :layout_margin= "16dp"
tools :context= ".MainActivity" >
<TextView
android :gravity= "center"
android :id= "@+id/textView"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :layout_centerInParent= "true"
android :textSize= "18sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Build ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity {
TextView textView ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
textView = findViewById(R.id. textView ) ;
textView .setText(getPhoneModel()) ;
}
private String getPhoneModel () {
return Build. MODEL ;
}
}
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.tutorialspoint.com.sample" >
<uses-permission android :name= "android.permission.CALL_PHONE" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@string/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "true"
android :theme= "@style/AppTheme" >
<activity android :name= ".MainActivity" >
<intent-filter>
<action android :name= "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrate about How to check Android Phone Model programmatically."
},
{
"code": null,
"e": 1273,
"s": 1144,
"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": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1934,
"s": 1338,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <TextView\n android :gravity= \"center\"\n android :id= \"@+id/textView\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :layout_centerInParent= \"true\"\n android :textSize= \"18sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1991,
"s": 1934,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2576,
"s": 1991,
"text": "package app.tutorialspoint.com.sample ;\nimport android.os.Build ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity {\n TextView textView ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n textView = findViewById(R.id. textView ) ;\n textView .setText(getPhoneModel()) ;\n }\n private String getPhoneModel () {\n return Build. MODEL ;\n }\n}"
},
{
"code": null,
"e": 2631,
"s": 2576,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3418,
"s": 2631,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\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": 3765,
"s": 3418,
"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 –"
}
] |
Scala - Logical Operators
|
Try the following example program to understand all the logical operators available in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var a = true;
var b = false;
println("a && b = " + (a&&b) );
println("a || b = " + (a||b) );
println("!(a && b) = " + !(a && b) );
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
a && b = false
a || b = true
!(a && b) = true
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2113,
"s": 1998,
"text": "Try the following example program to understand all the logical operators available in Scala Programming Language."
},
{
"code": null,
"e": 2346,
"s": 2113,
"text": "object Demo {\n def main(args: Array[String]) {\n var a = true;\n var b = false;\n\n println(\"a && b = \" + (a&&b) );\n \n println(\"a || b = \" + (a||b) );\n \n println(\"!(a && b) = \" + !(a && b) );\n }\n} "
},
{
"code": null,
"e": 2453,
"s": 2346,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 2487,
"s": 2453,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 2534,
"s": 2487,
"text": "a && b = false\na || b = true\n!(a && b) = true\n"
},
{
"code": null,
"e": 2567,
"s": 2534,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2586,
"s": 2567,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2621,
"s": 2586,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2642,
"s": 2621,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 2677,
"s": 2642,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2695,
"s": 2677,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2730,
"s": 2695,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2748,
"s": 2730,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2783,
"s": 2748,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 2801,
"s": 2783,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2836,
"s": 2801,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2859,
"s": 2836,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 2866,
"s": 2859,
"text": " Print"
},
{
"code": null,
"e": 2877,
"s": 2866,
"text": " Add Notes"
}
] |
Apache POI - Cells
|
Any data that you enter into a spreadsheet is always stored in a cell. We use the labels of rows and columns to identify a cell. This chapter describes how to manipulate data in cells in a spreadsheet using Java programming.
You need to create a row before creating a cell. A row is nothing but a collection of cells.
The following code snippet is used for creating a cell.
//create new workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//create spreadsheet with a name
XSSFSheet spreadsheet = workbook.createSheet("new sheet");
//create first row on a created spreadsheet
XSSFRow row = spreadsheet.createRow(0);
//create first cell on created row
XSSFCell cell = row.createCell(0);
The cell type specifies whether a cell can contain strings, numeric value, or formulas. A string cell cannot hold numeric values and a numeric cell cannot hold strings.
The following code is used to create different types of cells in a spreadsheet.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TypesofCells {
public static void main(String[] args)throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cell types");
XSSFRow row = spreadsheet.createRow((short) 2);
row.createCell(0).setCellValue("Type of Cell");
row.createCell(1).setCellValue("cell value");
row = spreadsheet.createRow((short) 3);
row.createCell(0).setCellValue("set cell type BLANK");
row.createCell(1);
row = spreadsheet.createRow((short) 4);
row.createCell(0).setCellValue("set cell type BOOLEAN");
row.createCell(1).setCellValue(true);
row = spreadsheet.createRow((short) 5);
row.createCell(0).setCellValue("set cell type date");
row.createCell(1).setCellValue(new Date());
row = spreadsheet.createRow((short) 6);
row.createCell(0).setCellValue("set cell type numeric");
row.createCell(1).setCellValue(20 );
row = spreadsheet.createRow((short) 7);
row.createCell(0).setCellValue("set cell type string");
row.createCell(1).setCellValue("A String");
FileOutputStream out = new FileOutputStream(new File("typesofcells.xlsx"));
workbook.write(out);
out.close();
System.out.println("typesofcells.xlsx written successfully");
}
}
Save the above code in a file named TypesofCells.java, compile and execute it from the command prompt as follows −
$javac TypesofCells.java
$java TypesofCells
If your system is configured with the POI library, then it will compile and execute to generate an Excel file named typesofcells.xlsx in your current directory and display the following output.
typesofcells.xlsx written successfully
The typesofcells.xlsx file looks as follows −
Here you can learn how to do cell formatting and apply different styles such as merging adjacent cells, adding borders, setting cell alignment and filling with colors.
The following code is used to apply different styles to cells using Java programming.
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.FillPatternType;
public class CellStyle {
public static void main(String[] args)throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cellstyle");
XSSFRow row = spreadsheet.createRow((short) 1);
row.setHeight((short) 800);
XSSFCell cell = (XSSFCell) row.createCell((short) 1);
cell.setCellValue("test of merging");
//MEARGING CELLS
//this statement for merging cells
spreadsheet.addMergedRegion(
new CellRangeAddress(
1, //first row (0-based)
1, //last row (0-based)
1, //first column (0-based)
4 //last column (0-based)
)
);
//CELL Alignment
row = spreadsheet.createRow(5);
cell = (XSSFCell) row.createCell(0);
row.setHeight((short) 800);
// Top Left alignment
XSSFCellStyle style1 = workbook.createCellStyle();
spreadsheet.setColumnWidth(0, 8000);
style1.setAlignment(HorizontalAlignment.LEFT);
style1.setVerticalAlignment(VerticalAlignment.TOP);
cell.setCellValue("Top Left");
cell.setCellStyle(style1);
row = spreadsheet.createRow(6);
cell = (XSSFCell) row.createCell(1);
row.setHeight((short) 800);
// Center Align Cell Contents
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellValue("Center Aligned");
cell.setCellStyle(style2);
row = spreadsheet.createRow(7);
cell = (XSSFCell) row.createCell(2);
row.setHeight((short) 800);
// Bottom Right alignment
XSSFCellStyle style3 = workbook.createCellStyle();
style3.setAlignment(HorizontalAlignment.RIGHT);
style3.setVerticalAlignment(VerticalAlignment.BOTTOM);
cell.setCellValue("Bottom Right");
cell.setCellStyle(style3);
row = spreadsheet.createRow(8);
cell = (XSSFCell) row.createCell(3);
// Justified Alignment
XSSFCellStyle style4 = workbook.createCellStyle();
style4.setAlignment(HorizontalAlignment.JUSTIFY);
style4.setVerticalAlignment(VerticalAlignment.JUSTIFY);
cell.setCellValue("Contents are Justified in Alignment");
cell.setCellStyle(style4);
//CELL BORDER
row = spreadsheet.createRow((short) 10);
row.setHeight((short) 800);
cell = (XSSFCell) row.createCell((short) 1);
cell.setCellValue("BORDER");
XSSFCellStyle style5 = workbook.createCellStyle();
style5.setBorderBottom(BorderStyle.THICK);
style5.setBottomBorderColor(IndexedColors.BLUE.getIndex());
style5.setBorderLeft(BorderStyle.DOUBLE);
style5.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style5.setBorderRight(BorderStyle.HAIR);
style5.setRightBorderColor(IndexedColors.RED.getIndex());
style5.setBorderTop(BorderStyle.DOTTED);
style5.setTopBorderColor(IndexedColors.CORAL.getIndex());
cell.setCellStyle(style5);
//Fill Colors
//background color
row = spreadsheet.createRow((short) 10 );
cell = (XSSFCell) row.createCell((short) 1);
XSSFCellStyle style6 = workbook.createCellStyle();
style6.setFillBackgroundColor(IndexedColors.LIME.index);
style6.setFillPattern(FillPatternType.LESS_DOTS);
style6.setAlignment(HorizontalAlignment.FILL);
spreadsheet.setColumnWidth(1,8000);
cell.setCellValue("FILL BACKGROUNG/FILL PATTERN");
cell.setCellStyle(style6);
//Foreground color
row = spreadsheet.createRow((short) 12);
cell = (XSSFCell) row.createCell((short) 1);
XSSFCellStyle style7 = workbook.createCellStyle();
style7.setFillForegroundColor(IndexedColors.BLUE.index);
style7.setFillPattern( FillPatternType.LESS_DOTS);
style7.setAlignment(HorizontalAlignment.FILL);
cell.setCellValue("FILL FOREGROUND/FILL PATTERN");
cell.setCellStyle(style7);
FileOutputStream out = new FileOutputStream(new File("cellstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("cellstyle.xlsx written successfully");
}
}
Save the above code in a file named CellStyle.java, compile and execute it from the command prompt as follows −
$javac CellStyle.java
$java CellStyle
It will generate an Excel file named cellstyle.xlsx in your current directory and display the following output.
cellstyle.xlsx written successfully
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": 2129,
"s": 1904,
"text": "Any data that you enter into a spreadsheet is always stored in a cell. We use the labels of rows and columns to identify a cell. This chapter describes how to manipulate data in cells in a spreadsheet using Java programming."
},
{
"code": null,
"e": 2222,
"s": 2129,
"text": "You need to create a row before creating a cell. A row is nothing but a collection of cells."
},
{
"code": null,
"e": 2278,
"s": 2222,
"text": "The following code snippet is used for creating a cell."
},
{
"code": null,
"e": 2594,
"s": 2278,
"text": "//create new workbook\nXSSFWorkbook workbook = new XSSFWorkbook(); \n\n//create spreadsheet with a name\nXSSFSheet spreadsheet = workbook.createSheet(\"new sheet\");\n\n//create first row on a created spreadsheet\nXSSFRow row = spreadsheet.createRow(0);\n\n//create first cell on created row\nXSSFCell cell = row.createCell(0);"
},
{
"code": null,
"e": 2763,
"s": 2594,
"text": "The cell type specifies whether a cell can contain strings, numeric value, or formulas. A string cell cannot hold numeric values and a numeric cell cannot hold strings."
},
{
"code": null,
"e": 2843,
"s": 2763,
"text": "The following code is used to create different types of cells in a spreadsheet."
},
{
"code": null,
"e": 4481,
"s": 2843,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport java.util.Date;\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class TypesofCells {\n public static void main(String[] args)throws Exception {\n XSSFWorkbook workbook = new XSSFWorkbook(); \n XSSFSheet spreadsheet = workbook.createSheet(\"cell types\");\n \n XSSFRow row = spreadsheet.createRow((short) 2);\n row.createCell(0).setCellValue(\"Type of Cell\");\n row.createCell(1).setCellValue(\"cell value\");\n \n row = spreadsheet.createRow((short) 3);\n row.createCell(0).setCellValue(\"set cell type BLANK\");\n row.createCell(1);\n \n row = spreadsheet.createRow((short) 4);\n row.createCell(0).setCellValue(\"set cell type BOOLEAN\");\n row.createCell(1).setCellValue(true);\n \n row = spreadsheet.createRow((short) 5);\n row.createCell(0).setCellValue(\"set cell type date\");\n row.createCell(1).setCellValue(new Date());\n \n row = spreadsheet.createRow((short) 6);\n row.createCell(0).setCellValue(\"set cell type numeric\");\n row.createCell(1).setCellValue(20 );\n \n row = spreadsheet.createRow((short) 7);\n row.createCell(0).setCellValue(\"set cell type string\");\n row.createCell(1).setCellValue(\"A String\");\n \n FileOutputStream out = new FileOutputStream(new File(\"typesofcells.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"typesofcells.xlsx written successfully\");\n }\n}"
},
{
"code": null,
"e": 4596,
"s": 4481,
"text": "Save the above code in a file named TypesofCells.java, compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 4641,
"s": 4596,
"text": "$javac TypesofCells.java\n$java TypesofCells\n"
},
{
"code": null,
"e": 4835,
"s": 4641,
"text": "If your system is configured with the POI library, then it will compile and execute to generate an Excel file named typesofcells.xlsx in your current directory and display the following output."
},
{
"code": null,
"e": 4875,
"s": 4835,
"text": "typesofcells.xlsx written successfully\n"
},
{
"code": null,
"e": 4921,
"s": 4875,
"text": "The typesofcells.xlsx file looks as follows −"
},
{
"code": null,
"e": 5089,
"s": 4921,
"text": "Here you can learn how to do cell formatting and apply different styles such as merging adjacent cells, adding borders, setting cell alignment and filling with colors."
},
{
"code": null,
"e": 5175,
"s": 5089,
"text": "The following code is used to apply different styles to cells using Java programming."
},
{
"code": null,
"e": 10194,
"s": 5175,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\n\nimport org.apache.poi.hssf.util.HSSFColor;\nimport org.apache.poi.ss.usermodel.BorderStyle;\nimport org.apache.poi.ss.usermodel.HorizontalAlignment;\nimport org.apache.poi.ss.usermodel.IndexedColors;\nimport org.apache.poi.ss.usermodel.VerticalAlignment;\nimport org.apache.poi.ss.util.CellRangeAddress;\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFCellStyle;\nimport org.apache.poi.xssf.usermodel.XSSFColor;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\nimport org.apache.poi.ss.usermodel.Color;\nimport org.apache.poi.ss.usermodel.FillPatternType;\n\npublic class CellStyle {\n public static void main(String[] args)throws Exception {\n XSSFWorkbook workbook = new XSSFWorkbook(); \n XSSFSheet spreadsheet = workbook.createSheet(\"cellstyle\");\n XSSFRow row = spreadsheet.createRow((short) 1);\n row.setHeight((short) 800);\n XSSFCell cell = (XSSFCell) row.createCell((short) 1);\n cell.setCellValue(\"test of merging\");\n\n //MEARGING CELLS \n //this statement for merging cells\n\n spreadsheet.addMergedRegion(\n new CellRangeAddress(\n 1, //first row (0-based)\n 1, //last row (0-based)\n 1, //first column (0-based)\n 4 //last column (0-based)\n )\n );\n \n //CELL Alignment\n row = spreadsheet.createRow(5); \n cell = (XSSFCell) row.createCell(0);\n row.setHeight((short) 800);\n \n // Top Left alignment \n XSSFCellStyle style1 = workbook.createCellStyle();\n spreadsheet.setColumnWidth(0, 8000);\n style1.setAlignment(HorizontalAlignment.LEFT);\n style1.setVerticalAlignment(VerticalAlignment.TOP);\n cell.setCellValue(\"Top Left\");\n cell.setCellStyle(style1);\n row = spreadsheet.createRow(6); \n cell = (XSSFCell) row.createCell(1);\n row.setHeight((short) 800);\n \n // Center Align Cell Contents \n XSSFCellStyle style2 = workbook.createCellStyle();\n style2.setAlignment(HorizontalAlignment.CENTER);\n style2.setVerticalAlignment(VerticalAlignment.CENTER);\n cell.setCellValue(\"Center Aligned\"); \n cell.setCellStyle(style2);\n row = spreadsheet.createRow(7); \n cell = (XSSFCell) row.createCell(2);\n row.setHeight((short) 800);\n \n // Bottom Right alignment \n XSSFCellStyle style3 = workbook.createCellStyle();\n style3.setAlignment(HorizontalAlignment.RIGHT);\n style3.setVerticalAlignment(VerticalAlignment.BOTTOM);\n cell.setCellValue(\"Bottom Right\");\n cell.setCellStyle(style3);\n row = spreadsheet.createRow(8);\n cell = (XSSFCell) row.createCell(3);\n \n // Justified Alignment \n XSSFCellStyle style4 = workbook.createCellStyle();\n style4.setAlignment(HorizontalAlignment.JUSTIFY);\n style4.setVerticalAlignment(VerticalAlignment.JUSTIFY);\n cell.setCellValue(\"Contents are Justified in Alignment\"); \n cell.setCellStyle(style4);\n \n //CELL BORDER\n row = spreadsheet.createRow((short) 10);\n row.setHeight((short) 800);\n cell = (XSSFCell) row.createCell((short) 1);\n cell.setCellValue(\"BORDER\");\n \n XSSFCellStyle style5 = workbook.createCellStyle();\n style5.setBorderBottom(BorderStyle.THICK);\n style5.setBottomBorderColor(IndexedColors.BLUE.getIndex());\n style5.setBorderLeft(BorderStyle.DOUBLE);\n style5.setLeftBorderColor(IndexedColors.GREEN.getIndex());\n style5.setBorderRight(BorderStyle.HAIR);\n style5.setRightBorderColor(IndexedColors.RED.getIndex());\n style5.setBorderTop(BorderStyle.DOTTED);\n style5.setTopBorderColor(IndexedColors.CORAL.getIndex());\n cell.setCellStyle(style5);\n \n //Fill Colors\n //background color\n row = spreadsheet.createRow((short) 10 );\n cell = (XSSFCell) row.createCell((short) 1);\n \n XSSFCellStyle style6 = workbook.createCellStyle();\n style6.setFillBackgroundColor(IndexedColors.LIME.index);\n style6.setFillPattern(FillPatternType.LESS_DOTS);\n style6.setAlignment(HorizontalAlignment.FILL);\n spreadsheet.setColumnWidth(1,8000);\n cell.setCellValue(\"FILL BACKGROUNG/FILL PATTERN\");\n cell.setCellStyle(style6);\n \n //Foreground color\n row = spreadsheet.createRow((short) 12);\n cell = (XSSFCell) row.createCell((short) 1);\n \n XSSFCellStyle style7 = workbook.createCellStyle();\n style7.setFillForegroundColor(IndexedColors.BLUE.index);\n style7.setFillPattern( FillPatternType.LESS_DOTS);\n style7.setAlignment(HorizontalAlignment.FILL);\n cell.setCellValue(\"FILL FOREGROUND/FILL PATTERN\");\n cell.setCellStyle(style7);\n\n FileOutputStream out = new FileOutputStream(new File(\"cellstyle.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"cellstyle.xlsx written successfully\");\n }\n}"
},
{
"code": null,
"e": 10306,
"s": 10194,
"text": "Save the above code in a file named CellStyle.java, compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 10345,
"s": 10306,
"text": "$javac CellStyle.java\n$java CellStyle\n"
},
{
"code": null,
"e": 10457,
"s": 10345,
"text": "It will generate an Excel file named cellstyle.xlsx in your current directory and display the following output."
},
{
"code": null,
"e": 10494,
"s": 10457,
"text": "cellstyle.xlsx written successfully\n"
},
{
"code": null,
"e": 10529,
"s": 10494,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10548,
"s": 10529,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10583,
"s": 10548,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10604,
"s": 10583,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 10637,
"s": 10604,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10650,
"s": 10637,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 10685,
"s": 10650,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10703,
"s": 10685,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10736,
"s": 10703,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10754,
"s": 10736,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10787,
"s": 10754,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10805,
"s": 10787,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 10812,
"s": 10805,
"text": " Print"
},
{
"code": null,
"e": 10823,
"s": 10812,
"text": " Add Notes"
}
] |
C - Memory Management
|
This chapter explains dynamic memory management in C. The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.
void *calloc(int num, int size);
This function allocates an array of num elements each of which size in bytes will be size.
void free(void *address);
This function releases a block of memory block specified by address.
void *malloc(size_t size);
This function allocates an array of num bytes and leave them uninitialized.
void *realloc(void *address, int newsize);
This function re-allocates memory extending it upto newsize.
While programming, if you are aware of the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go up to a maximum of 100 characters, so you can define something as follows −
char name[100];
But now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory as shown in the below example −
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 200 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
}
When the above code is compiled and executed, it produces the following result.
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Same program can be written using calloc(); only thing is you need to replace malloc with calloc as follows −
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while allocating memory, unlike arrays where once the size defined, you cannot change it.
When your program comes out, operating system automatically release all the memory allocated by your program but as a good practice when you are not in need of memory anymore then you should release that memory by calling the function free().
Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc(). Let us check the above program once again and make use of realloc() and free() functions −
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcpy( description, "Zara ali a DPS student.");
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* release memory using free() function */
free(description);
}
When the above code is compiled and executed, it produces the following result.
Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th
You can try the above example without re-allocating extra memory, and strcat() function will give an error due to lack of available memory in description.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2290,
"s": 2084,
"text": "This chapter explains dynamic memory management in C. The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file."
},
{
"code": null,
"e": 2323,
"s": 2290,
"text": "void *calloc(int num, int size);"
},
{
"code": null,
"e": 2414,
"s": 2323,
"text": "This function allocates an array of num elements each of which size in bytes will be size."
},
{
"code": null,
"e": 2440,
"s": 2414,
"text": "void free(void *address);"
},
{
"code": null,
"e": 2509,
"s": 2440,
"text": "This function releases a block of memory block specified by address."
},
{
"code": null,
"e": 2536,
"s": 2509,
"text": "void *malloc(size_t size);"
},
{
"code": null,
"e": 2612,
"s": 2536,
"text": "This function allocates an array of num bytes and leave them uninitialized."
},
{
"code": null,
"e": 2655,
"s": 2612,
"text": "void *realloc(void *address, int newsize);"
},
{
"code": null,
"e": 2716,
"s": 2655,
"text": "This function re-allocates memory extending it upto newsize."
},
{
"code": null,
"e": 2958,
"s": 2716,
"text": "While programming, if you are aware of the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go up to a maximum of 100 characters, so you can define something as follows −"
},
{
"code": null,
"e": 2975,
"s": 2958,
"text": "char name[100];\n"
},
{
"code": null,
"e": 3330,
"s": 2975,
"text": "But now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory as shown in the below example −"
},
{
"code": null,
"e": 3834,
"s": 3330,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n\n char name[100];\n char *description;\n\n strcpy(name, \"Zara Ali\");\n\n /* allocate memory dynamically */\n description = malloc( 200 * sizeof(char) );\n\t\n if( description == NULL ) {\n fprintf(stderr, \"Error - unable to allocate required memory\\n\");\n } else {\n strcpy( description, \"Zara ali a DPS student in class 10th\");\n }\n \n printf(\"Name = %s\\n\", name );\n printf(\"Description: %s\\n\", description );\n}"
},
{
"code": null,
"e": 3914,
"s": 3834,
"text": "When the above code is compiled and executed, it produces the following result."
},
{
"code": null,
"e": 3981,
"s": 3914,
"text": "Name = Zara Ali\nDescription: Zara ali a DPS student in class 10th\n"
},
{
"code": null,
"e": 4091,
"s": 3981,
"text": "Same program can be written using calloc(); only thing is you need to replace malloc with calloc as follows −"
},
{
"code": null,
"e": 4118,
"s": 4091,
"text": "calloc(200, sizeof(char));"
},
{
"code": null,
"e": 4269,
"s": 4118,
"text": "So you have complete control and you can pass any size value while allocating memory, unlike arrays where once the size defined, you cannot change it."
},
{
"code": null,
"e": 4512,
"s": 4269,
"text": "When your program comes out, operating system automatically release all the memory allocated by your program but as a good practice when you are not in need of memory anymore then you should release that memory by calling the function free()."
},
{
"code": null,
"e": 4720,
"s": 4512,
"text": "Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc(). Let us check the above program once again and make use of realloc() and free() functions −"
},
{
"code": null,
"e": 5569,
"s": 4720,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n\n char name[100];\n char *description;\n\n strcpy(name, \"Zara Ali\");\n\n /* allocate memory dynamically */\n description = malloc( 30 * sizeof(char) );\n\t\n if( description == NULL ) {\n fprintf(stderr, \"Error - unable to allocate required memory\\n\");\n } else {\n strcpy( description, \"Zara ali a DPS student.\");\n }\n\t\n /* suppose you want to store bigger description */\n description = realloc( description, 100 * sizeof(char) );\n\t\n if( description == NULL ) {\n fprintf(stderr, \"Error - unable to allocate required memory\\n\");\n } else {\n strcat( description, \"She is in class 10th\");\n }\n \n printf(\"Name = %s\\n\", name );\n printf(\"Description: %s\\n\", description );\n\n /* release memory using free() function */\n free(description);\n}"
},
{
"code": null,
"e": 5649,
"s": 5569,
"text": "When the above code is compiled and executed, it produces the following result."
},
{
"code": null,
"e": 5723,
"s": 5649,
"text": "Name = Zara Ali\nDescription: Zara ali a DPS student.She is in class 10th\n"
},
{
"code": null,
"e": 5878,
"s": 5723,
"text": "You can try the above example without re-allocating extra memory, and strcat() function will give an error due to lack of available memory in description."
},
{
"code": null,
"e": 5885,
"s": 5878,
"text": " Print"
},
{
"code": null,
"e": 5896,
"s": 5885,
"text": " Add Notes"
}
] |
How to connect SQL Server database from JavaScript in the browser ? - GeeksforGeeks
|
16 Nov, 2021
There is no common way to connect to SQL Server database from JavaScript client, every browser has it’s own API and packages to connect to SQL Server. For example, in Windows operating system, Internet Explorer has a class name called ActiveXObject which is used to create instances of OLE Automation objects, and these objects help us to create an environment for SQL Driver connection. It is not recommended to use JavaScript clients to access databases for several reasons. For example, it is not good practice, there are some security issues and it offers vulnerabilities issues. Node.js provides us an environment to run JavaScript code outside the browser and also it offers useful benefits like security, scalability, robustness, and may more. SQL Server: Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network. Node.Js: Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser.
Here, We are representing the connection of the MS SQL Server database using JavaScript in Node.js environment. To get started we need to install certain packages and MS SQL Server Node.js must be installed in the local system.
It’s strongly recommended to use any command-line tool(CLI) like terminal, cmd to run following queries and commands.
Before getting started MS SQL Server should be installed in the local system.
Hit listed command to get connect with SQL Server.
sqlcmd -S localhost -U SA -P "<password>"
Issue listed queries to create a database name called ‘geek’.
> CREATE DATABASE geek;
> GO
To use created data issue listed queries.
> Use <your database name>;
> GO
Issue listed queries to create a table name called ‘student’ with three fields id, firstname and lastname.
> CREATE TABLE student (id INT,
firstname NVARCHAR(30), lastname NVARCHAR(30));
> GO
Issue listed queries to insert some values into table ‘student’.
> INSERT INTO student VALUES (1, 'Stephen', 'Hawking');
> INSERT INTO student VALUES (2, 'Isaac', 'Newton');
> INSERT INTO student VALUES (3, 'Chandrasekhara Venkata', 'Raman');
> GO
To check entries of table issue listed queries.
> SELECT * from student;
> GO
Before getting started Node.js should be installed in the local system.
To create Node.js environment issue following command.
npm init
Express allows us to set up middlewares to respond to HTTP Requests.
npm install express --save
Microsoft SQL Server client give us functionality to connect with SQL server.
npm install mssql --save
To begin with Node.js part, we need to create our server file server.js in our local system.
javascript
// Requiring modulesconst express = require('express');const app = express();const mssql = require("mysql"); // Get requestapp.get('/', function (req, res) { // Config your database credential const config = { user: 'SA', password: 'Your_Password', server: 'localhost', database: 'geek' }; // Connect to your database mssql.connect(config, function (err) { // Create Request object to perform // query operation var request = new mssql.Request(); // Query to the database and get the records request.query('select * from student', function (err, records) { if (err) console.log(err) // Send records as a response // to browser res.send(records); }); });}); var server = app.listen(5000, function () { console.log('Server is listening at port 5000...');});
Run server.js file using the following command:
node server.js
After executing the above command, you will see the following output on your console:
Server is listening at port 5000...
Now hit the url http://localhost:5000/ in the local browser.
Output:
adnanirshad158
samuelliebert
JavaScript-Misc
Node.js
JavaScript
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
|
[
{
"code": null,
"e": 25195,
"s": 25167,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 26414,
"s": 25195,
"text": "There is no common way to connect to SQL Server database from JavaScript client, every browser has it’s own API and packages to connect to SQL Server. For example, in Windows operating system, Internet Explorer has a class name called ActiveXObject which is used to create instances of OLE Automation objects, and these objects help us to create an environment for SQL Driver connection. It is not recommended to use JavaScript clients to access databases for several reasons. For example, it is not good practice, there are some security issues and it offers vulnerabilities issues. Node.js provides us an environment to run JavaScript code outside the browser and also it offers useful benefits like security, scalability, robustness, and may more. SQL Server: Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network. Node.Js: Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser. "
},
{
"code": null,
"e": 26642,
"s": 26414,
"text": "Here, We are representing the connection of the MS SQL Server database using JavaScript in Node.js environment. To get started we need to install certain packages and MS SQL Server Node.js must be installed in the local system."
},
{
"code": null,
"e": 26762,
"s": 26644,
"text": "It’s strongly recommended to use any command-line tool(CLI) like terminal, cmd to run following queries and commands."
},
{
"code": null,
"e": 26841,
"s": 26762,
"text": "Before getting started MS SQL Server should be installed in the local system. "
},
{
"code": null,
"e": 26892,
"s": 26841,
"text": "Hit listed command to get connect with SQL Server."
},
{
"code": null,
"e": 26934,
"s": 26892,
"text": "sqlcmd -S localhost -U SA -P \"<password>\""
},
{
"code": null,
"e": 26996,
"s": 26934,
"text": "Issue listed queries to create a database name called ‘geek’."
},
{
"code": null,
"e": 27025,
"s": 26996,
"text": "> CREATE DATABASE geek;\n> GO"
},
{
"code": null,
"e": 27067,
"s": 27025,
"text": "To use created data issue listed queries."
},
{
"code": null,
"e": 27100,
"s": 27067,
"text": "> Use <your database name>;\n> GO"
},
{
"code": null,
"e": 27207,
"s": 27100,
"text": "Issue listed queries to create a table name called ‘student’ with three fields id, firstname and lastname."
},
{
"code": null,
"e": 27297,
"s": 27207,
"text": "> CREATE TABLE student (id INT, \n firstname NVARCHAR(30), lastname NVARCHAR(30));\n> GO"
},
{
"code": null,
"e": 27362,
"s": 27297,
"text": "Issue listed queries to insert some values into table ‘student’."
},
{
"code": null,
"e": 27545,
"s": 27362,
"text": "> INSERT INTO student VALUES (1, 'Stephen', 'Hawking');\n> INSERT INTO student VALUES (2, 'Isaac', 'Newton');\n> INSERT INTO student VALUES (3, 'Chandrasekhara Venkata', 'Raman');\n> GO"
},
{
"code": null,
"e": 27593,
"s": 27545,
"text": "To check entries of table issue listed queries."
},
{
"code": null,
"e": 27623,
"s": 27593,
"text": "> SELECT * from student;\n> GO"
},
{
"code": null,
"e": 27696,
"s": 27623,
"text": "Before getting started Node.js should be installed in the local system. "
},
{
"code": null,
"e": 27751,
"s": 27696,
"text": "To create Node.js environment issue following command."
},
{
"code": null,
"e": 27760,
"s": 27751,
"text": "npm init"
},
{
"code": null,
"e": 27829,
"s": 27760,
"text": "Express allows us to set up middlewares to respond to HTTP Requests."
},
{
"code": null,
"e": 27856,
"s": 27829,
"text": "npm install express --save"
},
{
"code": null,
"e": 27934,
"s": 27856,
"text": "Microsoft SQL Server client give us functionality to connect with SQL server."
},
{
"code": null,
"e": 27959,
"s": 27934,
"text": "npm install mssql --save"
},
{
"code": null,
"e": 28052,
"s": 27959,
"text": "To begin with Node.js part, we need to create our server file server.js in our local system."
},
{
"code": null,
"e": 28063,
"s": 28052,
"text": "javascript"
},
{
"code": "// Requiring modulesconst express = require('express');const app = express();const mssql = require(\"mysql\"); // Get requestapp.get('/', function (req, res) { // Config your database credential const config = { user: 'SA', password: 'Your_Password', server: 'localhost', database: 'geek' }; // Connect to your database mssql.connect(config, function (err) { // Create Request object to perform // query operation var request = new mssql.Request(); // Query to the database and get the records request.query('select * from student', function (err, records) { if (err) console.log(err) // Send records as a response // to browser res.send(records); }); });}); var server = app.listen(5000, function () { console.log('Server is listening at port 5000...');});",
"e": 28992,
"s": 28063,
"text": null
},
{
"code": null,
"e": 29042,
"s": 28992,
"text": "Run server.js file using the following command: "
},
{
"code": null,
"e": 29057,
"s": 29042,
"text": "node server.js"
},
{
"code": null,
"e": 29145,
"s": 29057,
"text": "After executing the above command, you will see the following output on your console: "
},
{
"code": null,
"e": 29181,
"s": 29145,
"text": "Server is listening at port 5000..."
},
{
"code": null,
"e": 29242,
"s": 29181,
"text": "Now hit the url http://localhost:5000/ in the local browser."
},
{
"code": null,
"e": 29250,
"s": 29242,
"text": "Output:"
},
{
"code": null,
"e": 29265,
"s": 29250,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29279,
"s": 29265,
"text": "samuelliebert"
},
{
"code": null,
"e": 29295,
"s": 29279,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29303,
"s": 29295,
"text": "Node.js"
},
{
"code": null,
"e": 29314,
"s": 29303,
"text": "JavaScript"
},
{
"code": null,
"e": 29322,
"s": 29314,
"text": "Node.js"
},
{
"code": null,
"e": 29339,
"s": 29322,
"text": "Web Technologies"
},
{
"code": null,
"e": 29366,
"s": 29339,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29464,
"s": 29366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29473,
"s": 29464,
"text": "Comments"
},
{
"code": null,
"e": 29486,
"s": 29473,
"text": "Old Comments"
},
{
"code": null,
"e": 29547,
"s": 29486,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29588,
"s": 29547,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29642,
"s": 29588,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29682,
"s": 29642,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29744,
"s": 29682,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 29777,
"s": 29744,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29825,
"s": 29777,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29858,
"s": 29825,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 29887,
"s": 29858,
"text": "Node.js fs.readFile() Method"
}
] |
Find the nth term of the series 0, 8, 64, 216, 512, . . . - GeeksforGeeks
|
06 Apr, 2021
Given an integer N, the task is to find the Nth term of the following series:
0, 8, 64, 216, 512, 1000, 1728, . . .
Examples:
Input: N = 6 Output: 1000Input: N = 5 Output: 512
Approach:
Given series 0, 8, 64, 216, 512, 1000, 1728, ... can also be written as 0 * (02), 2 * (22), 4 * (42), 6 * (62), 8 * (82), 10 * (102), ...
Observe that 0, 2, 4, 6, 10, ... is in AP and the nth term of this series can be found using the formula term = a1 + (n – 1) * d where a1 is the first term, n is the term position and d is the common difference.
To get the term in the original series, term = term * (term2) i.e. term3.
Finally print the term.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the nth term of the given serieslong term(int n){ // Common difference int d = 2; // First term int a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series An = pow(An, 3); return An;} // Driver codeint main(){ int n = 5; cout << term(n); return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; public class GFG { // Function to return the nth term of the given series static int nthTerm(int n) { // Common difference and first term int d = 2, a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series return (int)Math.pow(An, 3); } // Driver code public static void main(String[] args) { int n = 5; System.out.println(nthTerm(n)); }}
# Python3 implementation of the approach # Function to return the nth term of the given seriesdef term(n): # Common difference d = 2 # First term a1 = 0 # nth term An = a1 +(n-1)*d # nth term of the given series An = An**3 return An; # Driver coden = 5print(term(n))
// C# implementation of the approachusing System;public class GFG { // Function to return the nth term of the given series static int nthTerm(int n) { // Common difference and first term int d = 2, a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series return (int)Math.Pow(An, 3); } // Driver code public static void Main() { int n = 5; Console. WriteLine(nthTerm(n)); }}// This code is contributed by Mutual singh.
<?php// PHP implementation of the approach // Function to return the nth term of the given seriesfunction term($n) { // Common difference $d = 2; // First term $a1 = 0; // nth term $An=$a1+($n-1)*$d; // nth term of the given series return pow($An, 3); } // Driver code $n = 5;echo term($n); ?>
<script> // javascript implementation of the approach // Function to return the nth term of the given seriesfunction term(n) { // Common difference let d = 2; // First term let a1 = 0; // nth term An=a1+(n-1)*d; // nth term of the given series return Math.pow(An, 3); } // Driver code let n = 5;document.write( term(n)); // This code is contributed by sravan kumar </script>
512
Code_Mech
sravankumar8128
arithmetic progression
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Operators in C / C++
|
[
{
"code": null,
"e": 24493,
"s": 24465,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 24573,
"s": 24493,
"text": "Given an integer N, the task is to find the Nth term of the following series: "
},
{
"code": null,
"e": 24613,
"s": 24573,
"text": "0, 8, 64, 216, 512, 1000, 1728, . . . "
},
{
"code": null,
"e": 24625,
"s": 24613,
"text": "Examples: "
},
{
"code": null,
"e": 24677,
"s": 24625,
"text": "Input: N = 6 Output: 1000Input: N = 5 Output: 512 "
},
{
"code": null,
"e": 24691,
"s": 24679,
"text": "Approach: "
},
{
"code": null,
"e": 24829,
"s": 24691,
"text": "Given series 0, 8, 64, 216, 512, 1000, 1728, ... can also be written as 0 * (02), 2 * (22), 4 * (42), 6 * (62), 8 * (82), 10 * (102), ..."
},
{
"code": null,
"e": 25041,
"s": 24829,
"text": "Observe that 0, 2, 4, 6, 10, ... is in AP and the nth term of this series can be found using the formula term = a1 + (n – 1) * d where a1 is the first term, n is the term position and d is the common difference."
},
{
"code": null,
"e": 25115,
"s": 25041,
"text": "To get the term in the original series, term = term * (term2) i.e. term3."
},
{
"code": null,
"e": 25139,
"s": 25115,
"text": "Finally print the term."
},
{
"code": null,
"e": 25191,
"s": 25139,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25195,
"s": 25191,
"text": "C++"
},
{
"code": null,
"e": 25200,
"s": 25195,
"text": "Java"
},
{
"code": null,
"e": 25208,
"s": 25200,
"text": "Python3"
},
{
"code": null,
"e": 25211,
"s": 25208,
"text": "C#"
},
{
"code": null,
"e": 25215,
"s": 25211,
"text": "PHP"
},
{
"code": null,
"e": 25226,
"s": 25215,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the nth term of the given serieslong term(int n){ // Common difference int d = 2; // First term int a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series An = pow(An, 3); return An;} // Driver codeint main(){ int n = 5; cout << term(n); return 0;}",
"e": 25644,
"s": 25226,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; public class GFG { // Function to return the nth term of the given series static int nthTerm(int n) { // Common difference and first term int d = 2, a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series return (int)Math.pow(An, 3); } // Driver code public static void main(String[] args) { int n = 5; System.out.println(nthTerm(n)); }}",
"e": 26184,
"s": 25644,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the nth term of the given seriesdef term(n): # Common difference d = 2 # First term a1 = 0 # nth term An = a1 +(n-1)*d # nth term of the given series An = An**3 return An; # Driver coden = 5print(term(n))",
"e": 26503,
"s": 26184,
"text": null
},
{
"code": "// C# implementation of the approachusing System;public class GFG { // Function to return the nth term of the given series static int nthTerm(int n) { // Common difference and first term int d = 2, a1 = 0; // nth term int An = a1 + (n - 1) * d; // nth term of the given series return (int)Math.Pow(An, 3); } // Driver code public static void Main() { int n = 5; Console. WriteLine(nthTerm(n)); }}// This code is contributed by Mutual singh.",
"e": 27029,
"s": 26503,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the nth term of the given seriesfunction term($n) { // Common difference $d = 2; // First term $a1 = 0; // nth term $An=$a1+($n-1)*$d; // nth term of the given series return pow($An, 3); } // Driver code $n = 5;echo term($n); ?>",
"e": 27376,
"s": 27029,
"text": null
},
{
"code": "<script> // javascript implementation of the approach // Function to return the nth term of the given seriesfunction term(n) { // Common difference let d = 2; // First term let a1 = 0; // nth term An=a1+(n-1)*d; // nth term of the given series return Math.pow(An, 3); } // Driver code let n = 5;document.write( term(n)); // This code is contributed by sravan kumar </script>",
"e": 27805,
"s": 27376,
"text": null
},
{
"code": null,
"e": 27809,
"s": 27805,
"text": "512"
},
{
"code": null,
"e": 27821,
"s": 27811,
"text": "Code_Mech"
},
{
"code": null,
"e": 27837,
"s": 27821,
"text": "sravankumar8128"
},
{
"code": null,
"e": 27860,
"s": 27837,
"text": "arithmetic progression"
},
{
"code": null,
"e": 27867,
"s": 27860,
"text": "series"
},
{
"code": null,
"e": 27880,
"s": 27867,
"text": "Mathematical"
},
{
"code": null,
"e": 27893,
"s": 27880,
"text": "Mathematical"
},
{
"code": null,
"e": 27900,
"s": 27893,
"text": "series"
},
{
"code": null,
"e": 27998,
"s": 27900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28007,
"s": 27998,
"text": "Comments"
},
{
"code": null,
"e": 28020,
"s": 28007,
"text": "Old Comments"
},
{
"code": null,
"e": 28044,
"s": 28020,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28058,
"s": 28044,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28101,
"s": 28058,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28142,
"s": 28101,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 28187,
"s": 28142,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28236,
"s": 28187,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28263,
"s": 28236,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 28306,
"s": 28263,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 28340,
"s": 28306,
"text": "Program for factorial of a number"
}
] |
Environments, Conda, Pip, aaaaah! | by Dennis Bakhuis | Towards Data Science
|
There are many ways to install Python and unfortunately, it is very easy to create a mess. In this blog post I describe a method that works pretty well. I am aware of other great solutions, but this is generally the way I recommend, especially to beginners.
👉 This is part of my Python-10-minutes-a-day course!
While there is not much to code along, this document is still available as a Jupyter Notebook on my Github. You can also find my previous tutorials there.
A short overview of the topics we will be discussing:
Python is great, but...A way that worksA typical workflowRound up
Python is great, but...
A way that works
A typical workflow
Round up
As many others, I ❤️ Python! You can very rapidly translate your ideas into readable code solutions. One big reason Python is such a success is the very active community in which amazing people share their awesome solutions. This is why you do not have to write Data structures from scratch, but you simply import Pandas. Write the data to an hdf5 file format? Import h5py! Plot some figure, xkcd style? Import matplotlib! Even better, there are multiple flavors so if you prefer to plot your data in a different way, import one of the various other plotting system, e.g. Plotly, Bokeh, ggplot, to name a few. All this sharing goodness makes that Python is quite popular in many rapid evolving fields, such as Machine Learning.
Unfortunately, all effort from the large community comes at a price. The packages you used get updated, restructured, improved, or just rewritten, just because the authors came up with a better way to solve their problem. These changes can be breaking changes for the code you have written. Popular packages, such as Numpy or Matplotlib are very reliable, and chances that you get breaking changes are slim. However, using packages that are not as popular, breaking changing can happen, especially when upgrading the package or Python itself.
A way, the Python community solved this problem is with the use of virtual environments. These create isolated Python installations with their own set of packages. It is good practice to have a unique environment for each project or task. This ensures that dependencies of one project will not create breaking changes for another. This solution works great, but also creates some bookkeeping as you have different Python installations, for which each might come with their own package manager Pip. All of these references pointing Python and/or Pip can create a mess quite quickly and we end up in the famous diagram van XKCD below:
While all XKCDs are funny as they generally contain some truth and indeed, if you do not have some sort of system to do the bookkeeping, your Python installations can become a mess. As with all things in Python, there are many different ways to organize this, including some great tools such as Poetry, Pipenv, and many more. In the next section I will describe the system I am using. This works for me and this might also work for you. These are just my two cents, and you should of course choose whatever suits you best.
While there are many ways to organize your Python versions, virtual environments, and packages I do the following:
conda for Python and virtual environmentspip for package management inside the virtual environments
conda for Python and virtual environments
pip for package management inside the virtual environments
There are probably very nice and flexible graphical user interfaces (GUIs) out there, however I prefer the command line interace (CLI) over them. They give me the impression that I am more in control. I am not sure if that is true, but at least I get confirmation over each step that I am doing. There are many different shells to choose from and it really does not matter that much. Use the one you have available is generally the easiest. When you spend more time in the CLI, you might get pickier one day and choose a different flavor.
Windows has two different CLIs installed by default, the Command Line Prompt (CMD) and Windows Powershell. Both are fine, but the power shell gives more of an shell feeling. If you have never used a CLI, it can be useful to watch a tutorial of the power shell on Youtube. While I have not used Windows for a while, there are other options including running the famous Linux Bash shell on windows.
MacOs has by default Bash (MacOs Catalina has Zsh) which is great. You can access the shell using the Terminal application which is a way to interact with bash or zsh. I personally prefer Zsh as a shell and iTerm2 to interact with it. Both can be installed using home-brew. If you are not familiar with Bash, I highly advice to watch a tutorial on it, as it is incredibly useful.
Linux users are probably already familiar with a shell. Which shell and terminal application is installed, depends on the distribution you have installed. Generally all are fine, use what you have available.
While your shell will most likely look quite different, here is an image of my shell:
Now that we are familiar with a shell, lets get the next requirement: a conda distribution. Conda is a popular package manager for Python (and many other languages) and gives you access practically all Python versions and packages. It includes a easy system to manage virtual environments. While conda can be used to install packages, I only use it for virtual environments and Python versions. Conda has a feature called dependency checking, which works quite well, but sometimes can be a bit slow. Also, some packages are more up-to-date using Pip and therefore I choose to only use pip. Mixing both will probably work but it is probably better to use a single tool.
Often, conda is installed using Anaconda, which is a full-fledged distribution, including many packages, tools and a GUI. It installs many packages you will probably never use and I find the GUI slow to work with. The other option to install conda is to use Miniconda, another distribution which is much smaller as the name suggests. Miniconda is a base installation with a Python system, Pip, Conda, and some other tools. While it is straight forward to install, here are some simple guide lines:
Install in your home directory if and only if you do not have spaces in the full path. For example, if you have a username using a space, e.g. "dennis bakhuis", your home directory path will also contain a space (/home/dennis bakhuis/). This can cause problems with some packages as not all imports use quotes around paths, which is required for spaces folder names. If you happen to have a space in the folder, install miniconda in a different location. For example in Windows, just use the root directory: 'C:/miniconda3'
After installing miniconda, you should have the conda command available in your shell. To test this, open your shell and type "conda --version". If the command is not found, the path to miniconda has to be added to the global path variable.
For powershell users, there is an additional step which should be entered in the powershell: "conda init powershell"
This is all there is in installing the tools required to work with Python en virtual environments. In the next section I will explain a typical workflow.
Miniconda comes without any GUIs and therefore, your starting point is always the shell.
If you now open a shell, you have your new Python, Conda, and Pip ready for your bidding. You could install packages straight into your ‘base’ environment, however I highly advice against this. If you, for what ever reason make a mess of you ‘base’ environment, there is not way to delete it. Options are a reinstall (which actually is not all that bad) or removing packages by hand. Maybe there are tricks, but much easier is to just create virtual environments.
I would create an environment for each project or task, just to keep things separate. As mentioned before, I create an environment using conda:
conda create --name tutorial python=3.7
This will create a new environment with the name ‘tutorial’ and Python version 3.7.x. Because we used a single ‘=’, we tell conda to use the latest version in the Python 3.7 tree. At the moment this is version 3.7.7. If we would have used two equal signs ‘==’ we would tell conda to give exactly version 3.7, so there is a subtle difference.
After the environment is created, we have to switch to the newly created environment. For this conda has the activate command:
conda activate tutorial
Now you are in the isolated python environment called ‘tutorial’, which has its own version of Python, Conda, and pip. It is possible that you are not completely sure how a previously created environment was called. To check the available environments, you can always use:
conda env list
The previous figure shows all my available environments. These are just subdirectories in your miniconda folder. The currently active environment is shown with an asterix. Let’s now install some packages in our fleshly created environment in the next section.
In your activated environment, it is dead easy to install packages using the command ‘pip install’. For this example we will install the packages numpy, pandas, jupyterlab, matplotlib. While the dependency checking of pip is not as sophisticated as conda, it does however know that Pandas depends on numpy, and will install the dependecy if it is missing. To install the packages type:
pip install pandas matplotlib jupyterlab
After the install, the packages are ready to go. For example to start Jupyter Lab type:
jupyter lab
Sometimes it happens when you work in a notebook, bot forgot to install that one package. For example, want to use tqdm to have some progress bars. To install that package, open another shell next to the one you are already using, activate the environment, and use pip to install tqdm. The package is immediately ready for use in the notebook you are working in. Or install it directly in you notebook using:
The ‘!’ is used to execute shell commands. For example to do an *list directory* (ls) we do:
So using ‘!pip install tqdm’ we can directly install the package in the current environment. The shell method is in my opinion a bit more explicit as you are absolutely sure in which environment you are installing the package, but both are great!.
Another great way of installing packages is using the requirements.txt file. This is a list generated using the ‘pip freeze’ command and gives exact versions of packages used and is a great way to reproduce environments from previous projects. To create a requirements.txt yourself, type the following in a shell:
pip freeze > requirements.txt
Of course you can also invoke this command from jupyter:
If you open the file, or run it without the ‘> requirements.txt’ you will see a list of all packages in your environment and the exact version behind the double equal sign. If you provide this file in the root folder of your project or git-repo, others can install all required packages with a single command:
pip install -r requirements.txt
As you can see, requirements.txt is a great way to share and reproduce environments.
After a while, you will be collecting quite some environments, which can introduce some clutter to your system. To remove environments that are not needed anymore, we can simply delete them. If you would require it again, using the requirements.txt it is dead easy to recreate the environment. Before we can remove an environment, we have to deactivate it. To do that type:
conda deactivate
Now we can delete an environment by typing:
conda env remove --name tutorial
To verify, the environment is indeed gone:
conda env list
Some commands that might be useful:Clone an existing environment:
conda create --clone tutorial --name tutorial2
Search for available packages:
pip search tensorflow
This was it for managing Pythons, ENVs, PIPs, and all the snakes. As I mentioned before, this is one way to do it and there are many others. The other ways might work better, but this works for me. Feel free to comment on how this process can be done better or what works for you.
Please let me know if you have any questions or suggestions.
|
[
{
"code": null,
"e": 429,
"s": 171,
"text": "There are many ways to install Python and unfortunately, it is very easy to create a mess. In this blog post I describe a method that works pretty well. I am aware of other great solutions, but this is generally the way I recommend, especially to beginners."
},
{
"code": null,
"e": 482,
"s": 429,
"text": "👉 This is part of my Python-10-minutes-a-day course!"
},
{
"code": null,
"e": 637,
"s": 482,
"text": "While there is not much to code along, this document is still available as a Jupyter Notebook on my Github. You can also find my previous tutorials there."
},
{
"code": null,
"e": 691,
"s": 637,
"text": "A short overview of the topics we will be discussing:"
},
{
"code": null,
"e": 757,
"s": 691,
"text": "Python is great, but...A way that worksA typical workflowRound up"
},
{
"code": null,
"e": 781,
"s": 757,
"text": "Python is great, but..."
},
{
"code": null,
"e": 798,
"s": 781,
"text": "A way that works"
},
{
"code": null,
"e": 817,
"s": 798,
"text": "A typical workflow"
},
{
"code": null,
"e": 826,
"s": 817,
"text": "Round up"
},
{
"code": null,
"e": 1554,
"s": 826,
"text": "As many others, I ❤️ Python! You can very rapidly translate your ideas into readable code solutions. One big reason Python is such a success is the very active community in which amazing people share their awesome solutions. This is why you do not have to write Data structures from scratch, but you simply import Pandas. Write the data to an hdf5 file format? Import h5py! Plot some figure, xkcd style? Import matplotlib! Even better, there are multiple flavors so if you prefer to plot your data in a different way, import one of the various other plotting system, e.g. Plotly, Bokeh, ggplot, to name a few. All this sharing goodness makes that Python is quite popular in many rapid evolving fields, such as Machine Learning."
},
{
"code": null,
"e": 2097,
"s": 1554,
"text": "Unfortunately, all effort from the large community comes at a price. The packages you used get updated, restructured, improved, or just rewritten, just because the authors came up with a better way to solve their problem. These changes can be breaking changes for the code you have written. Popular packages, such as Numpy or Matplotlib are very reliable, and chances that you get breaking changes are slim. However, using packages that are not as popular, breaking changing can happen, especially when upgrading the package or Python itself."
},
{
"code": null,
"e": 2730,
"s": 2097,
"text": "A way, the Python community solved this problem is with the use of virtual environments. These create isolated Python installations with their own set of packages. It is good practice to have a unique environment for each project or task. This ensures that dependencies of one project will not create breaking changes for another. This solution works great, but also creates some bookkeeping as you have different Python installations, for which each might come with their own package manager Pip. All of these references pointing Python and/or Pip can create a mess quite quickly and we end up in the famous diagram van XKCD below:"
},
{
"code": null,
"e": 3253,
"s": 2730,
"text": "While all XKCDs are funny as they generally contain some truth and indeed, if you do not have some sort of system to do the bookkeeping, your Python installations can become a mess. As with all things in Python, there are many different ways to organize this, including some great tools such as Poetry, Pipenv, and many more. In the next section I will describe the system I am using. This works for me and this might also work for you. These are just my two cents, and you should of course choose whatever suits you best."
},
{
"code": null,
"e": 3368,
"s": 3253,
"text": "While there are many ways to organize your Python versions, virtual environments, and packages I do the following:"
},
{
"code": null,
"e": 3468,
"s": 3368,
"text": "conda for Python and virtual environmentspip for package management inside the virtual environments"
},
{
"code": null,
"e": 3510,
"s": 3468,
"text": "conda for Python and virtual environments"
},
{
"code": null,
"e": 3569,
"s": 3510,
"text": "pip for package management inside the virtual environments"
},
{
"code": null,
"e": 4108,
"s": 3569,
"text": "There are probably very nice and flexible graphical user interfaces (GUIs) out there, however I prefer the command line interace (CLI) over them. They give me the impression that I am more in control. I am not sure if that is true, but at least I get confirmation over each step that I am doing. There are many different shells to choose from and it really does not matter that much. Use the one you have available is generally the easiest. When you spend more time in the CLI, you might get pickier one day and choose a different flavor."
},
{
"code": null,
"e": 4505,
"s": 4108,
"text": "Windows has two different CLIs installed by default, the Command Line Prompt (CMD) and Windows Powershell. Both are fine, but the power shell gives more of an shell feeling. If you have never used a CLI, it can be useful to watch a tutorial of the power shell on Youtube. While I have not used Windows for a while, there are other options including running the famous Linux Bash shell on windows."
},
{
"code": null,
"e": 4885,
"s": 4505,
"text": "MacOs has by default Bash (MacOs Catalina has Zsh) which is great. You can access the shell using the Terminal application which is a way to interact with bash or zsh. I personally prefer Zsh as a shell and iTerm2 to interact with it. Both can be installed using home-brew. If you are not familiar with Bash, I highly advice to watch a tutorial on it, as it is incredibly useful."
},
{
"code": null,
"e": 5093,
"s": 4885,
"text": "Linux users are probably already familiar with a shell. Which shell and terminal application is installed, depends on the distribution you have installed. Generally all are fine, use what you have available."
},
{
"code": null,
"e": 5179,
"s": 5093,
"text": "While your shell will most likely look quite different, here is an image of my shell:"
},
{
"code": null,
"e": 5848,
"s": 5179,
"text": "Now that we are familiar with a shell, lets get the next requirement: a conda distribution. Conda is a popular package manager for Python (and many other languages) and gives you access practically all Python versions and packages. It includes a easy system to manage virtual environments. While conda can be used to install packages, I only use it for virtual environments and Python versions. Conda has a feature called dependency checking, which works quite well, but sometimes can be a bit slow. Also, some packages are more up-to-date using Pip and therefore I choose to only use pip. Mixing both will probably work but it is probably better to use a single tool."
},
{
"code": null,
"e": 6346,
"s": 5848,
"text": "Often, conda is installed using Anaconda, which is a full-fledged distribution, including many packages, tools and a GUI. It installs many packages you will probably never use and I find the GUI slow to work with. The other option to install conda is to use Miniconda, another distribution which is much smaller as the name suggests. Miniconda is a base installation with a Python system, Pip, Conda, and some other tools. While it is straight forward to install, here are some simple guide lines:"
},
{
"code": null,
"e": 6870,
"s": 6346,
"text": "Install in your home directory if and only if you do not have spaces in the full path. For example, if you have a username using a space, e.g. \"dennis bakhuis\", your home directory path will also contain a space (/home/dennis bakhuis/). This can cause problems with some packages as not all imports use quotes around paths, which is required for spaces folder names. If you happen to have a space in the folder, install miniconda in a different location. For example in Windows, just use the root directory: 'C:/miniconda3'"
},
{
"code": null,
"e": 7111,
"s": 6870,
"text": "After installing miniconda, you should have the conda command available in your shell. To test this, open your shell and type \"conda --version\". If the command is not found, the path to miniconda has to be added to the global path variable."
},
{
"code": null,
"e": 7228,
"s": 7111,
"text": "For powershell users, there is an additional step which should be entered in the powershell: \"conda init powershell\""
},
{
"code": null,
"e": 7382,
"s": 7228,
"text": "This is all there is in installing the tools required to work with Python en virtual environments. In the next section I will explain a typical workflow."
},
{
"code": null,
"e": 7471,
"s": 7382,
"text": "Miniconda comes without any GUIs and therefore, your starting point is always the shell."
},
{
"code": null,
"e": 7935,
"s": 7471,
"text": "If you now open a shell, you have your new Python, Conda, and Pip ready for your bidding. You could install packages straight into your ‘base’ environment, however I highly advice against this. If you, for what ever reason make a mess of you ‘base’ environment, there is not way to delete it. Options are a reinstall (which actually is not all that bad) or removing packages by hand. Maybe there are tricks, but much easier is to just create virtual environments."
},
{
"code": null,
"e": 8079,
"s": 7935,
"text": "I would create an environment for each project or task, just to keep things separate. As mentioned before, I create an environment using conda:"
},
{
"code": null,
"e": 8119,
"s": 8079,
"text": "conda create --name tutorial python=3.7"
},
{
"code": null,
"e": 8461,
"s": 8119,
"text": "This will create a new environment with the name ‘tutorial’ and Python version 3.7.x. Because we used a single ‘=’, we tell conda to use the latest version in the Python 3.7 tree. At the moment this is version 3.7.7. If we would have used two equal signs ‘==’ we would tell conda to give exactly version 3.7, so there is a subtle difference."
},
{
"code": null,
"e": 8588,
"s": 8461,
"text": "After the environment is created, we have to switch to the newly created environment. For this conda has the activate command:"
},
{
"code": null,
"e": 8612,
"s": 8588,
"text": "conda activate tutorial"
},
{
"code": null,
"e": 8885,
"s": 8612,
"text": "Now you are in the isolated python environment called ‘tutorial’, which has its own version of Python, Conda, and pip. It is possible that you are not completely sure how a previously created environment was called. To check the available environments, you can always use:"
},
{
"code": null,
"e": 8900,
"s": 8885,
"text": "conda env list"
},
{
"code": null,
"e": 9160,
"s": 8900,
"text": "The previous figure shows all my available environments. These are just subdirectories in your miniconda folder. The currently active environment is shown with an asterix. Let’s now install some packages in our fleshly created environment in the next section."
},
{
"code": null,
"e": 9546,
"s": 9160,
"text": "In your activated environment, it is dead easy to install packages using the command ‘pip install’. For this example we will install the packages numpy, pandas, jupyterlab, matplotlib. While the dependency checking of pip is not as sophisticated as conda, it does however know that Pandas depends on numpy, and will install the dependecy if it is missing. To install the packages type:"
},
{
"code": null,
"e": 9588,
"s": 9546,
"text": " pip install pandas matplotlib jupyterlab"
},
{
"code": null,
"e": 9676,
"s": 9588,
"text": "After the install, the packages are ready to go. For example to start Jupyter Lab type:"
},
{
"code": null,
"e": 9688,
"s": 9676,
"text": "jupyter lab"
},
{
"code": null,
"e": 10097,
"s": 9688,
"text": "Sometimes it happens when you work in a notebook, bot forgot to install that one package. For example, want to use tqdm to have some progress bars. To install that package, open another shell next to the one you are already using, activate the environment, and use pip to install tqdm. The package is immediately ready for use in the notebook you are working in. Or install it directly in you notebook using:"
},
{
"code": null,
"e": 10190,
"s": 10097,
"text": "The ‘!’ is used to execute shell commands. For example to do an *list directory* (ls) we do:"
},
{
"code": null,
"e": 10438,
"s": 10190,
"text": "So using ‘!pip install tqdm’ we can directly install the package in the current environment. The shell method is in my opinion a bit more explicit as you are absolutely sure in which environment you are installing the package, but both are great!."
},
{
"code": null,
"e": 10752,
"s": 10438,
"text": "Another great way of installing packages is using the requirements.txt file. This is a list generated using the ‘pip freeze’ command and gives exact versions of packages used and is a great way to reproduce environments from previous projects. To create a requirements.txt yourself, type the following in a shell:"
},
{
"code": null,
"e": 10782,
"s": 10752,
"text": "pip freeze > requirements.txt"
},
{
"code": null,
"e": 10839,
"s": 10782,
"text": "Of course you can also invoke this command from jupyter:"
},
{
"code": null,
"e": 11149,
"s": 10839,
"text": "If you open the file, or run it without the ‘> requirements.txt’ you will see a list of all packages in your environment and the exact version behind the double equal sign. If you provide this file in the root folder of your project or git-repo, others can install all required packages with a single command:"
},
{
"code": null,
"e": 11181,
"s": 11149,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 11266,
"s": 11181,
"text": "As you can see, requirements.txt is a great way to share and reproduce environments."
},
{
"code": null,
"e": 11640,
"s": 11266,
"text": "After a while, you will be collecting quite some environments, which can introduce some clutter to your system. To remove environments that are not needed anymore, we can simply delete them. If you would require it again, using the requirements.txt it is dead easy to recreate the environment. Before we can remove an environment, we have to deactivate it. To do that type:"
},
{
"code": null,
"e": 11657,
"s": 11640,
"text": "conda deactivate"
},
{
"code": null,
"e": 11701,
"s": 11657,
"text": "Now we can delete an environment by typing:"
},
{
"code": null,
"e": 11734,
"s": 11701,
"text": "conda env remove --name tutorial"
},
{
"code": null,
"e": 11777,
"s": 11734,
"text": "To verify, the environment is indeed gone:"
},
{
"code": null,
"e": 11792,
"s": 11777,
"text": "conda env list"
},
{
"code": null,
"e": 11858,
"s": 11792,
"text": "Some commands that might be useful:Clone an existing environment:"
},
{
"code": null,
"e": 11905,
"s": 11858,
"text": "conda create --clone tutorial --name tutorial2"
},
{
"code": null,
"e": 11936,
"s": 11905,
"text": "Search for available packages:"
},
{
"code": null,
"e": 11958,
"s": 11936,
"text": "pip search tensorflow"
},
{
"code": null,
"e": 12239,
"s": 11958,
"text": "This was it for managing Pythons, ENVs, PIPs, and all the snakes. As I mentioned before, this is one way to do it and there are many others. The other ways might work better, but this works for me. Feel free to comment on how this process can be done better or what works for you."
}
] |
Swift - Tuples
|
Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value.
The values in a tuple can be of any type, and do not need to be of same type.
For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.
let ImplementationError = (501, "Not implemented") is an error when something on the server is not implemented, It returns two values. Error Code, and Description.
You can create tuples from as many values as you want and from any number of different data types.
Here’s the syntax of Tuple declaration −
var TupleName = (Value1, value2,... any number of values)
Here’s a Tuple declaration −
var error501 = (501, “Not implemented”)
You can access the values of tuple using the index numbers that start from 0.
Here’s an example of accessing tuple Values −
print(“The code is\(error501.0)”)
print(“The definition of error is\(error501.1)”)
You can name the variables of a tuple while declaring , and you can call them using their names
var error501 = (errorCode: 501, description: “Not Implemented”)
print(error501.errorCode) // prints 501.
Tuples are helpful in returning multiple values from a function. Like, a web application might return a tuple of type ("String", Int) to show whether the loading was successful or failed.
By returning different values in a tuple we can make decisions depending on different tuple types.
Note − Tuples are useful for temporary values and are not suited for complex data.
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2358,
"s": 2253,
"text": "Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value."
},
{
"code": null,
"e": 2436,
"s": 2358,
"text": "The values in a tuple can be of any type, and do not need to be of same type."
},
{
"code": null,
"e": 2572,
"s": 2436,
"text": "For example, (\"Tutorials Point\", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command."
},
{
"code": null,
"e": 2736,
"s": 2572,
"text": "let ImplementationError = (501, \"Not implemented\") is an error when something on the server is not implemented, It returns two values. Error Code, and Description."
},
{
"code": null,
"e": 2835,
"s": 2736,
"text": "You can create tuples from as many values as you want and from any number of different data types."
},
{
"code": null,
"e": 2876,
"s": 2835,
"text": "Here’s the syntax of Tuple declaration −"
},
{
"code": null,
"e": 2935,
"s": 2876,
"text": "var TupleName = (Value1, value2,... any number of values)\n"
},
{
"code": null,
"e": 2964,
"s": 2935,
"text": "Here’s a Tuple declaration −"
},
{
"code": null,
"e": 3005,
"s": 2964,
"text": "var error501 = (501, “Not implemented”)\n"
},
{
"code": null,
"e": 3083,
"s": 3005,
"text": "You can access the values of tuple using the index numbers that start from 0."
},
{
"code": null,
"e": 3129,
"s": 3083,
"text": "Here’s an example of accessing tuple Values −"
},
{
"code": null,
"e": 3213,
"s": 3129,
"text": "print(“The code is\\(error501.0)”)\nprint(“The definition of error is\\(error501.1)”)\n"
},
{
"code": null,
"e": 3309,
"s": 3213,
"text": "You can name the variables of a tuple while declaring , and you can call them using their names"
},
{
"code": null,
"e": 3417,
"s": 3309,
"text": "var error501 = (errorCode: 501, description: “Not Implemented”)\nprint(error501.errorCode) // prints 501.\n"
},
{
"code": null,
"e": 3605,
"s": 3417,
"text": "Tuples are helpful in returning multiple values from a function. Like, a web application might return a tuple of type (\"String\", Int) to show whether the loading was successful or failed."
},
{
"code": null,
"e": 3704,
"s": 3605,
"text": "By returning different values in a tuple we can make decisions depending on different tuple types."
},
{
"code": null,
"e": 3787,
"s": 3704,
"text": "Note − Tuples are useful for temporary values and are not suited for complex data."
},
{
"code": null,
"e": 3820,
"s": 3787,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3835,
"s": 3820,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3868,
"s": 3835,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3887,
"s": 3868,
"text": " Three Millennials"
},
{
"code": null,
"e": 3919,
"s": 3887,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3938,
"s": 3919,
"text": " Three Millennials"
},
{
"code": null,
"e": 3971,
"s": 3938,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3988,
"s": 3971,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4020,
"s": 3988,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 4040,
"s": 4020,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 4075,
"s": 4040,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4092,
"s": 4075,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 4099,
"s": 4092,
"text": " Print"
},
{
"code": null,
"e": 4110,
"s": 4099,
"text": " Add Notes"
}
] |
Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++
|
We are given an array; we need to arrange this array in an order that the first element should be a minimum element, the second element should be a maximum element, the third element should be 2nd minimum element, the fourth element should be the 2nd maximum element and so on for example −
Input : arr[ ] = { 13, 34, 30, 56, 78, 3 }
Output : { 3, 78, 13, 56, 34, 30 }
Explanation : array is rearranged in the order { 1st min, 1st max, 2nd min, 2nd max, 3rd min, 3rd max }
Input : arr [ ] = { 2, 4, 6, 8, 11, 13, 15 }
Output : { 2, 15, 4, 13, 6, 11, 8 }
This problem can be solved using two variables, 'x's and 'y' where they will point to the maximum and minimum element, But for that array should be sorted, so we need to sort the array first, Then create a new empty array of the same size to store the reordered array. Now iterate over the array and if the iterative element is at even index, then add arr[ x ] element to the empty array and increment x by 1. if the element is at an odd index, then add arr[ y ] element to the empty array and decrement y by 1. Do this until y becomes smaller than x.
#include <bits/stdc++.h>
using namespace std;
int main () {
int arr[] = { 2, 4, 6, 8, 11, 13, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
// creating a new array to store the rearranged array.
int reordered_array[n];
// sorting the original array
sort(arr, arr + n);
// pointing variables to minimum and maximum element index.
int x = 0, y = n - 1;
int i = 0;
// iterating over the array until max is less than or equals to max.
while (x <= y) {
// if i is even then store max index element
if (i % 2 == 0) {
reordered_array[i] = arr[x];
x++;
}
// store min index element
else {
reordered_array[i] = arr[y];
y--;
}
i++;
}
// printing the reordered array.
for (int i = 0; i < n; i++)
cout << reordered_array[i] << " ";
// or we can update the original array
// for (int i = 0; i < n; i++)
// arr[i] = reordered_array[i];
return 0;
}
2 15 4 13 6 11 8
Variables are initialised as x=0 and y = array_length(n) - 1.
while( x<=y) traverse the array until x becomes greater than y.
If the count is even (x), the element is added to the final array, and variable x is incremented by 1.
If i is odd, then (y)the element is added in the final array, and variable y is decremented by 1.
Finally, the Reordered array is stored in the reordered_array[ ].
In this article, we discussed the solution to rearrange the given array in the smallest, largest form. We also write a C++ program for the same. Similarly, we can write this program in any other language like C, Java, Python, etc. We hope you find this article helpful.
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "We are given an array; we need to arrange this array in an order that the first element should be a minimum element, the second element should be a maximum element, the third element should be 2nd minimum element, the fourth element should be the 2nd maximum element and so on for example −"
},
{
"code": null,
"e": 1617,
"s": 1353,
"text": "Input : arr[ ] = { 13, 34, 30, 56, 78, 3 }\nOutput : { 3, 78, 13, 56, 34, 30 }\nExplanation : array is rearranged in the order { 1st min, 1st max, 2nd min, 2nd max, 3rd min, 3rd max }\n\nInput : arr [ ] = { 2, 4, 6, 8, 11, 13, 15 }\nOutput : { 2, 15, 4, 13, 6, 11, 8 }"
},
{
"code": null,
"e": 2169,
"s": 1617,
"text": "This problem can be solved using two variables, 'x's and 'y' where they will point to the maximum and minimum element, But for that array should be sorted, so we need to sort the array first, Then create a new empty array of the same size to store the reordered array. Now iterate over the array and if the iterative element is at even index, then add arr[ x ] element to the empty array and increment x by 1. if the element is at an odd index, then add arr[ y ] element to the empty array and decrement y by 1. Do this until y becomes smaller than x."
},
{
"code": null,
"e": 3144,
"s": 2169,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main () {\n int arr[] = { 2, 4, 6, 8, 11, 13, 15 };\n int n = sizeof (arr) / sizeof (arr[0]);\n\n // creating a new array to store the rearranged array.\n int reordered_array[n];\n\n // sorting the original array\n sort(arr, arr + n);\n\n // pointing variables to minimum and maximum element index.\n int x = 0, y = n - 1;\n int i = 0;\n\n // iterating over the array until max is less than or equals to max.\n while (x <= y) {\n // if i is even then store max index element\n\n if (i % 2 == 0) {\n reordered_array[i] = arr[x];\n x++;\n }\n // store min index element\n else {\n reordered_array[i] = arr[y];\n y--;\n }\n i++;\n }\n // printing the reordered array.\n for (int i = 0; i < n; i++)\n cout << reordered_array[i] << \" \";\n\n // or we can update the original array\n // for (int i = 0; i < n; i++)\n // arr[i] = reordered_array[i];\n return 0;\n}"
},
{
"code": null,
"e": 3161,
"s": 3144,
"text": "2 15 4 13 6 11 8"
},
{
"code": null,
"e": 3223,
"s": 3161,
"text": "Variables are initialised as x=0 and y = array_length(n) - 1."
},
{
"code": null,
"e": 3287,
"s": 3223,
"text": "while( x<=y) traverse the array until x becomes greater than y."
},
{
"code": null,
"e": 3390,
"s": 3287,
"text": "If the count is even (x), the element is added to the final array, and variable x is incremented by 1."
},
{
"code": null,
"e": 3488,
"s": 3390,
"text": "If i is odd, then (y)the element is added in the final array, and variable y is decremented by 1."
},
{
"code": null,
"e": 3554,
"s": 3488,
"text": "Finally, the Reordered array is stored in the reordered_array[ ]."
},
{
"code": null,
"e": 3824,
"s": 3554,
"text": "In this article, we discussed the solution to rearrange the given array in the smallest, largest form. We also write a C++ program for the same. Similarly, we can write this program in any other language like C, Java, Python, etc. We hope you find this article helpful."
}
] |
C# | ToUpper() Method - GeeksforGeeks
|
31 Jan, 2019
In C#, ToUpper() is a string method. It converts every characters to uppercase (if there an an uppercase version). If a character does not have an uppercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing different type of arguments to it.
String.ToUpper() Method
String.ToUpper(CultureInfo) Method
This method is used to returns a copy of the current string converted to uppercase.
Syntax:
public string ToUpper();
Return Type: Its return the string value, which is the uppercase equivalent of the given string. The return type of this method is System.String.
Example:
Input : str = "GeeksForGeeks"
str.ToUpper()
Output: GEEKSFORGEEKS
Input : str = "This is C# Program xsdd_$#%"
str.ToUpper()
Output: THIS IS C# PROGRAM XSDD_$#%
Below example programs illustrate the ToUpper() Method
Example 1:// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str1 = "GeeksForGeeks"; // string converted to Upper case string upperstr1 = str1.ToUpper(); Console.WriteLine(upperstr1); }}Output:GEEKSFORGEEKS
// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str1 = "GeeksForGeeks"; // string converted to Upper case string upperstr1 = str1.ToUpper(); Console.WriteLine(upperstr1); }}
Output:
GEEKSFORGEEKS
Example 2:// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str2 = "This is C# Program xsdd_$#%"; // string converted to Upper case string upperstr2 = str2.ToUpper(); Console.WriteLine(upperstr2); }}Output:THIS IS C# PROGRAM XSDD_$#%
// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str2 = "This is C# Program xsdd_$#%"; // string converted to Upper case string upperstr2 = str2.ToUpper(); Console.WriteLine(upperstr2); }}
Output:
THIS IS C# PROGRAM XSDD_$#%
This method is used to return a copy of the current string converted to uppercase, using the casing rules of the specified culture.
Syntax:
public string ToUpper (System.Globalization.CultureInfo culture);
Parameter:
culture: It is the required object which supplies culture-specific casing rules.
Return Type: This method returns the uppercase equivalent of the current string of type System.String.
Exception: This method can give ArgumentNullException if the value of culture is null.
Example:
// C# program to desmonstrate the // use of ToUpper(CultureInfo) method using System;using System.Globalization; class Program { // Main Method public static void Main() { // original string string str2 = "This is C# Program xsdd_$#%"; // string converted to Uppercase by // using English-United States culture string upperstr2 = str2.ToUpper(new CultureInfo("en-US", false)); Console.WriteLine(upperstr2); }}
Output:
THIS IS C# PROGRAM XSDD_$#%
Note: These methods will not modify the value of the current instance. Instead, these return a new string in which all characters in the current instance will convert to uppercase.
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.toupper?view=netframework-4.7.2
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
|
[
{
"code": null,
"e": 24436,
"s": 24408,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24750,
"s": 24436,
"text": "In C#, ToUpper() is a string method. It converts every characters to uppercase (if there an an uppercase version). If a character does not have an uppercase equivalent, it remains unchanged. For example, special symbols remain unchanged. This method can be overloaded by passing different type of arguments to it."
},
{
"code": null,
"e": 24774,
"s": 24750,
"text": "String.ToUpper() Method"
},
{
"code": null,
"e": 24809,
"s": 24774,
"text": "String.ToUpper(CultureInfo) Method"
},
{
"code": null,
"e": 24893,
"s": 24809,
"text": "This method is used to returns a copy of the current string converted to uppercase."
},
{
"code": null,
"e": 24901,
"s": 24893,
"text": "Syntax:"
},
{
"code": null,
"e": 24927,
"s": 24901,
"text": "public string ToUpper();\n"
},
{
"code": null,
"e": 25073,
"s": 24927,
"text": "Return Type: Its return the string value, which is the uppercase equivalent of the given string. The return type of this method is System.String."
},
{
"code": null,
"e": 25082,
"s": 25073,
"text": "Example:"
},
{
"code": null,
"e": 25262,
"s": 25082,
"text": "Input : str = \"GeeksForGeeks\"\n str.ToUpper()\nOutput: GEEKSFORGEEKS\n\nInput : str = \"This is C# Program xsdd_$#%\"\n str.ToUpper()\nOutput: THIS IS C# PROGRAM XSDD_$#%\n"
},
{
"code": null,
"e": 25317,
"s": 25262,
"text": "Below example programs illustrate the ToUpper() Method"
},
{
"code": null,
"e": 25690,
"s": 25317,
"text": "Example 1:// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str1 = \"GeeksForGeeks\"; // string converted to Upper case string upperstr1 = str1.ToUpper(); Console.WriteLine(upperstr1); }}Output:GEEKSFORGEEKS\n"
},
{
"code": "// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str1 = \"GeeksForGeeks\"; // string converted to Upper case string upperstr1 = str1.ToUpper(); Console.WriteLine(upperstr1); }}",
"e": 26032,
"s": 25690,
"text": null
},
{
"code": null,
"e": 26040,
"s": 26032,
"text": "Output:"
},
{
"code": null,
"e": 26055,
"s": 26040,
"text": "GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 26454,
"s": 26055,
"text": "Example 2:// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str2 = \"This is C# Program xsdd_$#%\"; // string converted to Upper case string upperstr2 = str2.ToUpper(); Console.WriteLine(upperstr2); }}Output:THIS IS C# PROGRAM XSDD_$#%\n"
},
{
"code": "// C# program to desmonstrate the // use of ToUpper() method using System; class Program { // Main Method public static void Main() { // original string string str2 = \"This is C# Program xsdd_$#%\"; // string converted to Upper case string upperstr2 = str2.ToUpper(); Console.WriteLine(upperstr2); }}",
"e": 26808,
"s": 26454,
"text": null
},
{
"code": null,
"e": 26816,
"s": 26808,
"text": "Output:"
},
{
"code": null,
"e": 26845,
"s": 26816,
"text": "THIS IS C# PROGRAM XSDD_$#%\n"
},
{
"code": null,
"e": 26977,
"s": 26845,
"text": "This method is used to return a copy of the current string converted to uppercase, using the casing rules of the specified culture."
},
{
"code": null,
"e": 26985,
"s": 26977,
"text": "Syntax:"
},
{
"code": null,
"e": 27052,
"s": 26985,
"text": "public string ToUpper (System.Globalization.CultureInfo culture);\n"
},
{
"code": null,
"e": 27063,
"s": 27052,
"text": "Parameter:"
},
{
"code": null,
"e": 27144,
"s": 27063,
"text": "culture: It is the required object which supplies culture-specific casing rules."
},
{
"code": null,
"e": 27247,
"s": 27144,
"text": "Return Type: This method returns the uppercase equivalent of the current string of type System.String."
},
{
"code": null,
"e": 27334,
"s": 27247,
"text": "Exception: This method can give ArgumentNullException if the value of culture is null."
},
{
"code": null,
"e": 27343,
"s": 27334,
"text": "Example:"
},
{
"code": "// C# program to desmonstrate the // use of ToUpper(CultureInfo) method using System;using System.Globalization; class Program { // Main Method public static void Main() { // original string string str2 = \"This is C# Program xsdd_$#%\"; // string converted to Uppercase by // using English-United States culture string upperstr2 = str2.ToUpper(new CultureInfo(\"en-US\", false)); Console.WriteLine(upperstr2); }}",
"e": 27814,
"s": 27343,
"text": null
},
{
"code": null,
"e": 27822,
"s": 27814,
"text": "Output:"
},
{
"code": null,
"e": 27851,
"s": 27822,
"text": "THIS IS C# PROGRAM XSDD_$#%\n"
},
{
"code": null,
"e": 28032,
"s": 27851,
"text": "Note: These methods will not modify the value of the current instance. Instead, these return a new string in which all characters in the current instance will convert to uppercase."
},
{
"code": null,
"e": 28133,
"s": 28032,
"text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.toupper?view=netframework-4.7.2"
},
{
"code": null,
"e": 28147,
"s": 28133,
"text": "CSharp-method"
},
{
"code": null,
"e": 28161,
"s": 28147,
"text": "CSharp-string"
},
{
"code": null,
"e": 28164,
"s": 28161,
"text": "C#"
},
{
"code": null,
"e": 28262,
"s": 28164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28285,
"s": 28262,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28313,
"s": 28285,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28328,
"s": 28313,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28374,
"s": 28328,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28392,
"s": 28374,
"text": "Destructors in C#"
},
{
"code": null,
"e": 28415,
"s": 28392,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28433,
"s": 28415,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28464,
"s": 28433,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28486,
"s": 28464,
"text": "C# | Abstract Classes"
}
] |
Finding intersection of multiple arrays - JavaScript
|
We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array.
Let’s say the following are our arrays −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
Following is the code −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
const intersection = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
if(!arr2.includes(arr1[i])){
continue;
};
res.push(arr1[i]);
};
return res;
};
const intersectMany = (...arrs) => {
let res = arrs[0].slice();
for(let i = 1; i < arrs.length; i++){
res = intersection(res, arrs[i]);
};
return res;
};
console.log(intersectMany(arr1, arr2, arr3));
This will produce the following output in console −
[2, 1, 3]
|
[
{
"code": null,
"e": 1289,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array."
},
{
"code": null,
"e": 1330,
"s": 1289,
"text": "Let’s say the following are our arrays −"
},
{
"code": null,
"e": 1451,
"s": 1330,
"text": "const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];\nconst arr2 = [5, ,7, 2, 2, 1, 3];\nconst arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];"
},
{
"code": null,
"e": 1475,
"s": 1451,
"text": "Following is the code −"
},
{
"code": null,
"e": 2025,
"s": 1475,
"text": "const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];\nconst arr2 = [5, ,7, 2, 2, 1, 3];\nconst arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];\nconst intersection = (arr1, arr2) => {\n const res = [];\n for(let i = 0; i < arr1.length; i++){\n if(!arr2.includes(arr1[i])){\n continue;\n };\n res.push(arr1[i]);\n };\n return res;\n};\nconst intersectMany = (...arrs) => {\n let res = arrs[0].slice();\n for(let i = 1; i < arrs.length; i++){\n res = intersection(res, arrs[i]);\n };\n return res;\n};\nconsole.log(intersectMany(arr1, arr2, arr3));"
},
{
"code": null,
"e": 2077,
"s": 2025,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 2087,
"s": 2077,
"text": "[2, 1, 3]"
}
] |
ALTER table by adding AUTOINCREMENT in MySQL?
|
To add AUTOINCREMENT in MySQL, you can use the ALTER command.
ALTER TABLE yourTableName change yourColumName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;
To understand the above concept, create a table with a column. Let us create a table −
mysql> create table AlterTableToAddAutoIncrement
-> (
-> StudentId int
-> );
Query OK, 0 rows affected (0.57 sec)
Implement the above syntax to change “StudentId” with AUTOINCREMENT. The query is as follows −
mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary key;
Query OK, 0 rows affected (1.93 sec)
Records: 0 Duplicates: 0 Warnings: 0
We have added AUTO_INCREMENT to column name ‘StudentId’. Now you can verify whether autoincrement is working or not by inserting records without giving any value.
The query is as follows −
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.33 sec)
Now you can display all records which will be displayed in sequence of 1, 2, 3, 4, etc. The query is as follows −
mysql> select *from AlterTableToAddAutoIncrement;
The following is the output −
+-----------+
| StudentId |
+-----------+
| 1 |
| 2 |
| 3 |
+-----------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "To add AUTOINCREMENT in MySQL, you can use the ALTER command."
},
{
"code": null,
"e": 1223,
"s": 1124,
"text": "ALTER TABLE yourTableName change yourColumName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;"
},
{
"code": null,
"e": 1310,
"s": 1223,
"text": "To understand the above concept, create a table with a column. Let us create a table −"
},
{
"code": null,
"e": 1433,
"s": 1310,
"text": "mysql> create table AlterTableToAddAutoIncrement\n -> (\n -> StudentId int\n -> );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1528,
"s": 1433,
"text": "Implement the above syntax to change “StudentId” with AUTOINCREMENT. The query is as follows −"
},
{
"code": null,
"e": 1710,
"s": 1528,
"text": "mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary key;\nQuery OK, 0 rows affected (1.93 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1873,
"s": 1710,
"text": "We have added AUTO_INCREMENT to column name ‘StudentId’. Now you can verify whether autoincrement is working or not by inserting records without giving any value."
},
{
"code": null,
"e": 1899,
"s": 1873,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2181,
"s": 1899,
"text": "mysql> insert into AlterTableToAddAutoIncrement values();\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AlterTableToAddAutoIncrement values();\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AlterTableToAddAutoIncrement values();\nQuery OK, 1 row affected (0.33 sec)"
},
{
"code": null,
"e": 2295,
"s": 2181,
"text": "Now you can display all records which will be displayed in sequence of 1, 2, 3, 4, etc. The query is as follows −"
},
{
"code": null,
"e": 2345,
"s": 2295,
"text": "mysql> select *from AlterTableToAddAutoIncrement;"
},
{
"code": null,
"e": 2375,
"s": 2345,
"text": "The following is the output −"
},
{
"code": null,
"e": 2498,
"s": 2375,
"text": "+-----------+\n| StudentId |\n+-----------+\n| 1 |\n| 2 |\n| 3 |\n+-----------+\n3 rows in set (0.00 sec)"
}
] |
Linked List Cycle II in C++
|
Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list
To solve this, we will follow these steps −
slow := head and fast := head
while slow, fast and next of fast is available, thenslow := next of slowfast := next of (next of fast)if slow = fast, then break
slow := next of slow
fast := next of (next of fast)
if slow = fast, then break
if fast is not empty or next of first is not empty, then return null
if slow = fast, thenslow := headwhile slow is not same as fastslow := next of slow and fast := next of fast
slow := head
while slow is not same as fastslow := next of slow and fast := next of fast
slow := next of slow and fast := next of fast
return slow
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
ListNode *get_node(ListNode *head, int pos){
ListNode *ptr = head;
if(pos != -1){
int p = 0;
while(p < pos){
ptr = ptr->next;
p++;
}
return ptr;
}
return NULL;
}
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)break;
}
if(!fast || !fast->next)return NULL;
if(slow == fast){
slow = head;
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
}
return slow;
}
};
main(){
Solution ob;
vector<int> v = {5,3,2,0,-4,7};
ListNode *head = make_list(v);
int pos = 1;
ListNode *lastNode = get_node(head, v.size() - 1);
lastNode->next = get_node(head, pos);
cout << "Tail is connected to the node with value:" <<ob.detectCycle(head)->val;
}
[5,3,2,0,-4,7]
1
Tail is connected to the node with value:3
|
[
{
"code": null,
"e": 1569,
"s": 1062,
"text": "Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list"
},
{
"code": null,
"e": 1613,
"s": 1569,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1643,
"s": 1613,
"text": "slow := head and fast := head"
},
{
"code": null,
"e": 1772,
"s": 1643,
"text": "while slow, fast and next of fast is available, thenslow := next of slowfast := next of (next of fast)if slow = fast, then break"
},
{
"code": null,
"e": 1793,
"s": 1772,
"text": "slow := next of slow"
},
{
"code": null,
"e": 1824,
"s": 1793,
"text": "fast := next of (next of fast)"
},
{
"code": null,
"e": 1851,
"s": 1824,
"text": "if slow = fast, then break"
},
{
"code": null,
"e": 1920,
"s": 1851,
"text": "if fast is not empty or next of first is not empty, then return null"
},
{
"code": null,
"e": 2028,
"s": 1920,
"text": "if slow = fast, thenslow := headwhile slow is not same as fastslow := next of slow and fast := next of fast"
},
{
"code": null,
"e": 2041,
"s": 2028,
"text": "slow := head"
},
{
"code": null,
"e": 2117,
"s": 2041,
"text": "while slow is not same as fastslow := next of slow and fast := next of fast"
},
{
"code": null,
"e": 2163,
"s": 2117,
"text": "slow := next of slow and fast := next of fast"
},
{
"code": null,
"e": 2175,
"s": 2163,
"text": "return slow"
},
{
"code": null,
"e": 2245,
"s": 2175,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2256,
"s": 2245,
"text": " Live Demo"
},
{
"code": null,
"e": 3719,
"s": 2256,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass ListNode{\n public:\n int val;\n ListNode *next;\n ListNode(int data){\n val = data;\n next = NULL;\n }\n};\nListNode *make_list(vector<int> v){\n ListNode *head = new ListNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n ListNode *ptr = head;\n while(ptr->next != NULL){\n ptr = ptr->next;\n }\n ptr->next = new ListNode(v[i]);\n }\n return head;\n}\nListNode *get_node(ListNode *head, int pos){\n ListNode *ptr = head;\n if(pos != -1){\n int p = 0;\n while(p < pos){\n ptr = ptr->next;\n p++;\n }\n return ptr;\n }\n return NULL;\n}\nclass Solution {\n public:\n ListNode *detectCycle(ListNode *head) {\n ListNode* slow = head;\n ListNode* fast = head;\n while(slow && fast && fast->next){\n slow = slow->next;\n fast = fast->next->next;\n if(slow == fast)break;\n }\n if(!fast || !fast->next)return NULL;\n if(slow == fast){\n slow = head;\n while(slow!=fast){\n slow = slow->next;\n fast = fast->next;\n }\n }\n return slow;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {5,3,2,0,-4,7};\n ListNode *head = make_list(v);\n int pos = 1;\n ListNode *lastNode = get_node(head, v.size() - 1);\n lastNode->next = get_node(head, pos);\n cout << \"Tail is connected to the node with value:\" <<ob.detectCycle(head)->val;\n}"
},
{
"code": null,
"e": 3736,
"s": 3719,
"text": "[5,3,2,0,-4,7]\n1"
},
{
"code": null,
"e": 3779,
"s": 3736,
"text": "Tail is connected to the node with value:3"
}
] |
Getting Started With Network Datasets | by ASHISH RANA | Towards Data Science
|
Have you ever wondered what might be reason behind videos, memes and posts going viral in this social age. What makes them propagate throughout the world and make them popular. Let’s analyze this phenomenon with underlying structures behind the internet i.e. the network of people. And try to understand this phenomenon based on one property only “connectedness” for simplicity.
In this article we will learn how to use network datasets for extracting information and resources from where we can get them. Which libraries can be used to analyze them. Also later on, we will try to understand connectedness property in graphs and implications of it. Main aim of this article is to lay foundation of concepts of network datasets and show some interesting properties related to it..
Real World Networks developed with human related data often exhibit social properties i.e. patterns in graph from which human behavioral patterns can be analyzed and mined for valuable information. The Power of which is being used by all the companies to maximize their throughput. Well to start with, all of us use different social media networks either to find jobs, express our views, make friends, stay connected, gaming, dating and many more things. Also, the domain is not restricted to these social sites instead business decisions for marketing & sales, supply-chain management and advertisements gets influenced by knowledge of analyzing networks.
Now, these networks are not random networks where a node gets added randomly, they exhibit special properties. What special properties to consider? Let’s take one property for example connectedness. By connectedness we mean that there is no isolated vertices in the existing graph.
Are these large scale real world social graphs connected ? Yes, if not definitely the probability of them being not connected is very less. Consider a case, in a class there are 50 students each making only three friends (quite an unsocial class 😉). What is the probability of this being disconnected at a given instance?
This was the case for small class imagine it for very large scale networks where ‘m’ & ‘n’ goes to very large values, event of graph being disconnected is highly improbable for real life networks. This connectedness property can be analyzed with following stated problem statement.
Given ‘n’ nodes, what is the minimum number of edges that needed to be added in a completely disconnected graph, So that, graph becomes connected in nature? It can also be stated as when will a graph have no isolated vertex, provided edges are inserted uniformly at random?
If we solve this problem using probabilistic analysis, the results will be as follows : if we put n*log(n) edges than probability of this graph being disconnected is (1/n)2. Since, this n being very large on real world networks, it is an improbable event to occur. Well, what are implication of such a property ? Take one such case where all facebook friends are connected each containing their respective information.
Consider the case of Cambridge Analytica (excluding political conversation). Since, based on our assumption that the network of friends in US is connected on facebook, with a loophole in Facebook API they were able to access raw data of 87 million people by analyzing data about friends of facebook users who took the quiz. Just to talk about the scale of impact here 270,000 users took the quiz using which they were able to access 322 times more data from that. Property of accessing information about friends of friends and chain goes on. Also, which is 27% of entire population of USA, just from a simple quiz. That data then being used for malicious reasons to influence democracy. Imagine data handled by big tech Giants and the power that they hold now from analytics of data from these social networks. So, let’s get a glimpse onto this topic and its analysis.
In what shape or form this data exists? This thing is quite intuitive that it will store information about graphs with many nodes and edges. Also, each of which will exhibit some special properties that can be stored as attributes and weights. Now, let’s take a look at different forms this data is represented.
Let’s see different format of datasets that are available to us for analyzing.
CSV Format: Data being presented in either Edgelist format or Adjacency List format. Edge List format contains two/three values in each line (To, From, [Weight]) node giving an idea about edges that exist in graph with any weight if attached. In Adjacency List first value in a row is source node and succeeding nodes are the ones to which edge is present. For example: [Source, Node1, Node2, ...].GML Format: One of the most common formats as provide huge flexibility for graphs to store information. It is modeling language to store information about node, edges, labels, attributes etc.
CSV Format: Data being presented in either Edgelist format or Adjacency List format. Edge List format contains two/three values in each line (To, From, [Weight]) node giving an idea about edges that exist in graph with any weight if attached. In Adjacency List first value in a row is source node and succeeding nodes are the ones to which edge is present. For example: [Source, Node1, Node2, ...].
GML Format: One of the most common formats as provide huge flexibility for graphs to store information. It is modeling language to store information about node, edges, labels, attributes etc.
3. Pajek Net Format: Uses .NET extensions. There are two columns present in this format one vertices which specifies label of nodes another specifies edges between nodes. If nodes don’t have any labels then row entries below vertices column can be skipped. Also, an attribute value can be added if needed.
4. GraphML Format: Uses xml tag structures to store information about a graph ends with .graphml extension. Here, graphml tag store metadata about the graph, graph tag for attributes about graph. Node tag, which specifies all the properties about nodes and than edge tags are there to give edge specifications. Also, an optional key tag can be used to assign weight to edges and attributes to nodes.
5. GEXF Format: Graph Exchange XML Format, developed by Gephi organization. Much similar to graphXML format. It is a language for describing complex networks structures, their associated data and dynamics. Gelphi tool is also used for easy visualization of network graphs.
We can download these datasets from repositories like SNAP, Konect, UCI etc. Also, you can search them Google’s dataset search. For analyzing these datasets using popular python libraries networkx and visualizing MatplotLib is a very good option. Click on specified links for basic tutorials to get started with, otherwise you can also follow along with coding examples in this article. Here, is an example to get started with.
# Draws circular plot of the networkimport matplotlib.pyplot as pltimport networkx as nxG = nx.karate_club_graph() # data can be read from specified stored social graph in networkx library.print("Node Degree")for v in G: print (v, G.degree(v))nx.draw_circular(G, with_labels=True) # different plot layouts possibleplt.show()
Consider case of a popular karate club known as Zachary karate club where two teachers had a conflict and tried recruiting members in each others group. It is clear that there will be two groups formed at the end. Can we predict what those groups are? Which person is on whose side, by properties of graph?
Now, inter-community edges have high betweenness i.e. number of shortest path between any two nodes are high. An intuition for this is let’s consider two cities connected by a bridge, in order to connect any two points b/w two cities we must pass from that bridge. Resulting in that bridge being used always to connect two communities like in above case of two groups getting formed after fight.
These edges keeping the graph connected and acting as bridges. What we can do is remove these edges upto a safe limit and observe the communities that exist, if the graph becomes disconnected at that point. Like, if we remove that bridge b/w towns they will be disconnected. Similarly here, consider two groups in Zachary karate clubs are connected by few bridges which might be result of earlier friendship existing b/w those two people.
import networkx as nx # Python 2.x, NetworkX 2.0import networkx as nxdef edge_to_remove(G): # high betweenness edges are removed first dic1 = nx.edge_betweenness_centrality(G) list_tuples = dic1.items() list_tuples.sort(key =lambda x:x[1], reverse = True) return list_tuples[0][0] #(a,b)def girvan(G): # returns number of connected components c = nx.connected_component_subgraphs(G) i=0 while(i<11): # you can experiment with different values G.remove_edge(*edge_to_remove(G)) return cG = nx.karate_club_graph() # imports popular zachary karate clubc = girvan(G) # After enough edge removal, groups printedfor i in c: print 'Group Nodes: ', i.nodes() print 'Number Of Nodes: ', i.number_of_nodes()Output :Group Nodes: [0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]Number Of Nodes: 15Group Nodes: [32, 33, 2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]Number Of Nodes: 19
Let’s analyze the connectedness property in more detail and see what interesting information can be derived from it when social constructs are applied on it. What more can we leverage? Take this case of Daman, who is from Delhi and wants to connect to Lana from L.A. in 1970 with post or mailing service but only with the help of friends or friends of friends. Now, it might be reasonable to assume all the communities at that time were connected, is the friendship graph of world connected? Based on our argument above it is reasonable to assume world is connected. In order to deliver a message how many hops is required on an average i.e. how many intermediate people are required on an average to deliver his letter?
Only six hops on an average is required for such a message transfer. Meaning only six people on an average can deliver his message, such small number of friends required to deliver a far out message is incredible. But, why such less hops ?
The answer is homophily(similar nodes connect and form communities with high clustering co-efficient) and weak ties(generally bridges between two such cluster). Meaning the people in neighborhood are very well connected but at the same time they have connections to far out node which are less probable but still feasible. Like one of your friend can know someone in California, other one knows people in Europe and so on.
Both these are discussed in above example of Zachary club with two communities resulted because of homophily two similar nodes getting connected and high betweenness edges as weak ties as some friends might be there even in opposite groups.
In real world networks, it can be understood with a stochastic explanation like there is less probability forming long ties as compared to a smaller one. Reason can be geographic like in above case resulting in less neighborhood overlap i.e. with more distance less probable links of friendship are extended.
How to detect it in a network dataset? Analyze only the average shortest path length which will be closer to 6 or will be drastically small compared to network size. That would mean that graph/network exhibit small world phenomenon.
First read any desired graph in any format you are comfortable in, refer documentation. Then use the following function in code snippet.
# Networkx ExamplesG =nx.karate_club_graph() # Can be applied on different graphsprint(nx.average_shortest_path_length(G))G = nx.florentine_families_graph()print(nx.average_shortest_path_length(G))G = nx.davis_southern_women_graph()print(nx.average_shortest_path_length(G))
After this let’s apply it onto some real dataset lets say facebook_combined dataset from SNAP containing data in edgelist format from all ego-nets. And try to simulate Cambridge-analytica’s case study, how users were connected to each other, will also recommend to visualize this with matplotlib.
G = nx.read_edgelist('Desktop/facebook_combined.txt')print(nx.average_shortest_path_length(G)) # Takes 4 mins approx.[Output]: 3.6925068497 # Confirms our statement above.
This reduced distance from 6 can be attributed to the fact it much easier to connect due to globalization that has happened with world being more connected than ever as compared to when Milgram conducted his experiment.
Now, what’s the interpretation of this result? A very large scale graph with very less average shortest path property. It would mean that we can search relation between any two nodes in O(k) constant time. This is also known as decentralized search. Or myopic search as we can see only upto a certain extent from our connections. This will allow us extract information b/w any two nodes at any distance with a constant time lookup.
Imagine the implications of such phenomenon, this will result in very fast rapid exchange of information b/w the nodes independent of vicinity. This can clearly be seen with Vines, Memes getting viral throughout the internet and probably as a result of this phenomenon ‘Break the Internet’ term was coined.
Analyzing properties of real world large networks specific to a domain gives advantages in data mining capabilities when we are aware of such special properties that these graphs will exhibit. Like connectedness there are many more important properties to explore like Power Law, Cascading Effect, Link Prediction, Pseudo cores, Spatial and Community arrangements, Evolutionary networks each one deserving separate discussion. Knowledge of these does help in reducing the effort working with these large network datasets. Few important ones I’ll definitely discuss in upcoming articles on more real use-cases. Also, will definitely encourage you to read books like Mining The Social Web & Network, Crowd and Markets Reasoning about a Highly Connected World. Thanks to SRS Iyengar for wonderful course on Social Networks!!
|
[
{
"code": null,
"e": 551,
"s": 172,
"text": "Have you ever wondered what might be reason behind videos, memes and posts going viral in this social age. What makes them propagate throughout the world and make them popular. Let’s analyze this phenomenon with underlying structures behind the internet i.e. the network of people. And try to understand this phenomenon based on one property only “connectedness” for simplicity."
},
{
"code": null,
"e": 952,
"s": 551,
"text": "In this article we will learn how to use network datasets for extracting information and resources from where we can get them. Which libraries can be used to analyze them. Also later on, we will try to understand connectedness property in graphs and implications of it. Main aim of this article is to lay foundation of concepts of network datasets and show some interesting properties related to it.."
},
{
"code": null,
"e": 1609,
"s": 952,
"text": "Real World Networks developed with human related data often exhibit social properties i.e. patterns in graph from which human behavioral patterns can be analyzed and mined for valuable information. The Power of which is being used by all the companies to maximize their throughput. Well to start with, all of us use different social media networks either to find jobs, express our views, make friends, stay connected, gaming, dating and many more things. Also, the domain is not restricted to these social sites instead business decisions for marketing & sales, supply-chain management and advertisements gets influenced by knowledge of analyzing networks."
},
{
"code": null,
"e": 1891,
"s": 1609,
"text": "Now, these networks are not random networks where a node gets added randomly, they exhibit special properties. What special properties to consider? Let’s take one property for example connectedness. By connectedness we mean that there is no isolated vertices in the existing graph."
},
{
"code": null,
"e": 2213,
"s": 1891,
"text": "Are these large scale real world social graphs connected ? Yes, if not definitely the probability of them being not connected is very less. Consider a case, in a class there are 50 students each making only three friends (quite an unsocial class 😉). What is the probability of this being disconnected at a given instance?"
},
{
"code": null,
"e": 2495,
"s": 2213,
"text": "This was the case for small class imagine it for very large scale networks where ‘m’ & ‘n’ goes to very large values, event of graph being disconnected is highly improbable for real life networks. This connectedness property can be analyzed with following stated problem statement."
},
{
"code": null,
"e": 2769,
"s": 2495,
"text": "Given ‘n’ nodes, what is the minimum number of edges that needed to be added in a completely disconnected graph, So that, graph becomes connected in nature? It can also be stated as when will a graph have no isolated vertex, provided edges are inserted uniformly at random?"
},
{
"code": null,
"e": 3188,
"s": 2769,
"text": "If we solve this problem using probabilistic analysis, the results will be as follows : if we put n*log(n) edges than probability of this graph being disconnected is (1/n)2. Since, this n being very large on real world networks, it is an improbable event to occur. Well, what are implication of such a property ? Take one such case where all facebook friends are connected each containing their respective information."
},
{
"code": null,
"e": 4057,
"s": 3188,
"text": "Consider the case of Cambridge Analytica (excluding political conversation). Since, based on our assumption that the network of friends in US is connected on facebook, with a loophole in Facebook API they were able to access raw data of 87 million people by analyzing data about friends of facebook users who took the quiz. Just to talk about the scale of impact here 270,000 users took the quiz using which they were able to access 322 times more data from that. Property of accessing information about friends of friends and chain goes on. Also, which is 27% of entire population of USA, just from a simple quiz. That data then being used for malicious reasons to influence democracy. Imagine data handled by big tech Giants and the power that they hold now from analytics of data from these social networks. So, let’s get a glimpse onto this topic and its analysis."
},
{
"code": null,
"e": 4369,
"s": 4057,
"text": "In what shape or form this data exists? This thing is quite intuitive that it will store information about graphs with many nodes and edges. Also, each of which will exhibit some special properties that can be stored as attributes and weights. Now, let’s take a look at different forms this data is represented."
},
{
"code": null,
"e": 4448,
"s": 4369,
"text": "Let’s see different format of datasets that are available to us for analyzing."
},
{
"code": null,
"e": 5038,
"s": 4448,
"text": "CSV Format: Data being presented in either Edgelist format or Adjacency List format. Edge List format contains two/three values in each line (To, From, [Weight]) node giving an idea about edges that exist in graph with any weight if attached. In Adjacency List first value in a row is source node and succeeding nodes are the ones to which edge is present. For example: [Source, Node1, Node2, ...].GML Format: One of the most common formats as provide huge flexibility for graphs to store information. It is modeling language to store information about node, edges, labels, attributes etc."
},
{
"code": null,
"e": 5437,
"s": 5038,
"text": "CSV Format: Data being presented in either Edgelist format or Adjacency List format. Edge List format contains two/three values in each line (To, From, [Weight]) node giving an idea about edges that exist in graph with any weight if attached. In Adjacency List first value in a row is source node and succeeding nodes are the ones to which edge is present. For example: [Source, Node1, Node2, ...]."
},
{
"code": null,
"e": 5629,
"s": 5437,
"text": "GML Format: One of the most common formats as provide huge flexibility for graphs to store information. It is modeling language to store information about node, edges, labels, attributes etc."
},
{
"code": null,
"e": 5935,
"s": 5629,
"text": "3. Pajek Net Format: Uses .NET extensions. There are two columns present in this format one vertices which specifies label of nodes another specifies edges between nodes. If nodes don’t have any labels then row entries below vertices column can be skipped. Also, an attribute value can be added if needed."
},
{
"code": null,
"e": 6335,
"s": 5935,
"text": "4. GraphML Format: Uses xml tag structures to store information about a graph ends with .graphml extension. Here, graphml tag store metadata about the graph, graph tag for attributes about graph. Node tag, which specifies all the properties about nodes and than edge tags are there to give edge specifications. Also, an optional key tag can be used to assign weight to edges and attributes to nodes."
},
{
"code": null,
"e": 6608,
"s": 6335,
"text": "5. GEXF Format: Graph Exchange XML Format, developed by Gephi organization. Much similar to graphXML format. It is a language for describing complex networks structures, their associated data and dynamics. Gelphi tool is also used for easy visualization of network graphs."
},
{
"code": null,
"e": 7036,
"s": 6608,
"text": "We can download these datasets from repositories like SNAP, Konect, UCI etc. Also, you can search them Google’s dataset search. For analyzing these datasets using popular python libraries networkx and visualizing MatplotLib is a very good option. Click on specified links for basic tutorials to get started with, otherwise you can also follow along with coding examples in this article. Here, is an example to get started with."
},
{
"code": null,
"e": 7364,
"s": 7036,
"text": "# Draws circular plot of the networkimport matplotlib.pyplot as pltimport networkx as nxG = nx.karate_club_graph() # data can be read from specified stored social graph in networkx library.print(\"Node Degree\")for v in G: print (v, G.degree(v))nx.draw_circular(G, with_labels=True) # different plot layouts possibleplt.show()"
},
{
"code": null,
"e": 7671,
"s": 7364,
"text": "Consider case of a popular karate club known as Zachary karate club where two teachers had a conflict and tried recruiting members in each others group. It is clear that there will be two groups formed at the end. Can we predict what those groups are? Which person is on whose side, by properties of graph?"
},
{
"code": null,
"e": 8067,
"s": 7671,
"text": "Now, inter-community edges have high betweenness i.e. number of shortest path between any two nodes are high. An intuition for this is let’s consider two cities connected by a bridge, in order to connect any two points b/w two cities we must pass from that bridge. Resulting in that bridge being used always to connect two communities like in above case of two groups getting formed after fight."
},
{
"code": null,
"e": 8506,
"s": 8067,
"text": "These edges keeping the graph connected and acting as bridges. What we can do is remove these edges upto a safe limit and observe the communities that exist, if the graph becomes disconnected at that point. Like, if we remove that bridge b/w towns they will be disconnected. Similarly here, consider two groups in Zachary karate clubs are connected by few bridges which might be result of earlier friendship existing b/w those two people."
},
{
"code": null,
"e": 9410,
"s": 8506,
"text": "import networkx as nx # Python 2.x, NetworkX 2.0import networkx as nxdef edge_to_remove(G): # high betweenness edges are removed first dic1 = nx.edge_betweenness_centrality(G) list_tuples = dic1.items() list_tuples.sort(key =lambda x:x[1], reverse = True) return list_tuples[0][0] #(a,b)def girvan(G): # returns number of connected components c = nx.connected_component_subgraphs(G) i=0 while(i<11): # you can experiment with different values G.remove_edge(*edge_to_remove(G)) return cG = nx.karate_club_graph() # imports popular zachary karate clubc = girvan(G) # After enough edge removal, groups printedfor i in c: print 'Group Nodes: ', i.nodes() print 'Number Of Nodes: ', i.number_of_nodes()Output :Group Nodes: [0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]Number Of Nodes: 15Group Nodes: [32, 33, 2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]Number Of Nodes: 19"
},
{
"code": null,
"e": 10131,
"s": 9410,
"text": "Let’s analyze the connectedness property in more detail and see what interesting information can be derived from it when social constructs are applied on it. What more can we leverage? Take this case of Daman, who is from Delhi and wants to connect to Lana from L.A. in 1970 with post or mailing service but only with the help of friends or friends of friends. Now, it might be reasonable to assume all the communities at that time were connected, is the friendship graph of world connected? Based on our argument above it is reasonable to assume world is connected. In order to deliver a message how many hops is required on an average i.e. how many intermediate people are required on an average to deliver his letter?"
},
{
"code": null,
"e": 10371,
"s": 10131,
"text": "Only six hops on an average is required for such a message transfer. Meaning only six people on an average can deliver his message, such small number of friends required to deliver a far out message is incredible. But, why such less hops ?"
},
{
"code": null,
"e": 10794,
"s": 10371,
"text": "The answer is homophily(similar nodes connect and form communities with high clustering co-efficient) and weak ties(generally bridges between two such cluster). Meaning the people in neighborhood are very well connected but at the same time they have connections to far out node which are less probable but still feasible. Like one of your friend can know someone in California, other one knows people in Europe and so on."
},
{
"code": null,
"e": 11035,
"s": 10794,
"text": "Both these are discussed in above example of Zachary club with two communities resulted because of homophily two similar nodes getting connected and high betweenness edges as weak ties as some friends might be there even in opposite groups."
},
{
"code": null,
"e": 11344,
"s": 11035,
"text": "In real world networks, it can be understood with a stochastic explanation like there is less probability forming long ties as compared to a smaller one. Reason can be geographic like in above case resulting in less neighborhood overlap i.e. with more distance less probable links of friendship are extended."
},
{
"code": null,
"e": 11577,
"s": 11344,
"text": "How to detect it in a network dataset? Analyze only the average shortest path length which will be closer to 6 or will be drastically small compared to network size. That would mean that graph/network exhibit small world phenomenon."
},
{
"code": null,
"e": 11714,
"s": 11577,
"text": "First read any desired graph in any format you are comfortable in, refer documentation. Then use the following function in code snippet."
},
{
"code": null,
"e": 11988,
"s": 11714,
"text": "# Networkx ExamplesG =nx.karate_club_graph() # Can be applied on different graphsprint(nx.average_shortest_path_length(G))G = nx.florentine_families_graph()print(nx.average_shortest_path_length(G))G = nx.davis_southern_women_graph()print(nx.average_shortest_path_length(G))"
},
{
"code": null,
"e": 12285,
"s": 11988,
"text": "After this let’s apply it onto some real dataset lets say facebook_combined dataset from SNAP containing data in edgelist format from all ego-nets. And try to simulate Cambridge-analytica’s case study, how users were connected to each other, will also recommend to visualize this with matplotlib."
},
{
"code": null,
"e": 12457,
"s": 12285,
"text": "G = nx.read_edgelist('Desktop/facebook_combined.txt')print(nx.average_shortest_path_length(G)) # Takes 4 mins approx.[Output]: 3.6925068497 # Confirms our statement above."
},
{
"code": null,
"e": 12677,
"s": 12457,
"text": "This reduced distance from 6 can be attributed to the fact it much easier to connect due to globalization that has happened with world being more connected than ever as compared to when Milgram conducted his experiment."
},
{
"code": null,
"e": 13109,
"s": 12677,
"text": "Now, what’s the interpretation of this result? A very large scale graph with very less average shortest path property. It would mean that we can search relation between any two nodes in O(k) constant time. This is also known as decentralized search. Or myopic search as we can see only upto a certain extent from our connections. This will allow us extract information b/w any two nodes at any distance with a constant time lookup."
},
{
"code": null,
"e": 13416,
"s": 13109,
"text": "Imagine the implications of such phenomenon, this will result in very fast rapid exchange of information b/w the nodes independent of vicinity. This can clearly be seen with Vines, Memes getting viral throughout the internet and probably as a result of this phenomenon ‘Break the Internet’ term was coined."
}
] |
Machine learning for anomaly detection: Elliptic Envelope | by Mahbubul Alam | Towards Data Science
|
Welcome back to anomaly detection; this is 6th in a series of “bite-sized” data science focusing on outlier detection. Today I am writing about a machine learning algorithm called EllipticEnvelope , which is yet another tool in data scientists’ toolbox for fraud/anomaly/outlier detection.
In case you have missed my previous articles or you are interested in learning more about the topic, find the links below:
Local Outlier Factor (LOF)
Z-score
Boxplot
Statistical techniques
Time series anomaly detection
So what is elliptic envelope and what’s the intuition behind the algorithm?
If you have taken geometry classes you are probably familiar with ellipse — a geometric configuration that takes an oval shape on a two-dimensional plane.
The green area in the above diagram is an ellipse. So the algorithm — Elliptical Envelope— creates an imaginary elliptical area around a given dataset. Values that fall inside the envelope are considered normal data and anything outside the envelope is returned as outliers. So, naturally, the red data points in the above diagram should be identified as outliers by this algorithm. As evident from this figure, the algorithm works best if data has a Gaussian distribution.
sklearn is the Swiss army knife of machine learning algorithms. So not surprisingly it has a module for anomaly detection using the elliptical envelope as well. Below I am demonstrating an implementation using imaginary data points in 5 simple steps.
# import librariesimport pandas as pdimport numpy as npfrom sklearn.covariance import EllipticEnvelopeimport matplotlib.pyplot as plt
# create a dataframedf = pd.DataFrame(np.array([[0,1], [1,1], [1,2], [2,2], [5,6]]), columns = ["x", "y"], index = [0,1,2,3,4])# show data in a scatterplotplt.scatter(df["x"], df["y"], color = "r")plt.grid()
# convert dataframe to arraysdata = df[['x', 'y']].values
The most important parameter in defining the model is to set the “contamination” parameter, which basically defines the proportion of values that will be identified as outliers. The parameter value ranges between 0 and 0.5
# instantiate modelmodel1 = EllipticEnvelope(contamination = 0.1) # fit modelmodel1.fit(data)
# new data for prediction (data needs to be in arrays)new_data = np.array([[10,10], [1,1], [1,1], [1,1]])# predict on new data pred1 = model1.predict(new_data)print(pred1)
The purpose of this article was to introduce Elliptic Envelope — a machine learning algorithm for anomaly detection — and implementing the algorithm using the Scikit-Learn library. If you now have the key concepts clear, go ahead and try implementing it on a real dataset, for example, the Iris dataset available online. You should be able to use the same 5 steps above on this dataset, just need to make sure that you’ve selected the right columns for the algorithm to work.
|
[
{
"code": null,
"e": 461,
"s": 171,
"text": "Welcome back to anomaly detection; this is 6th in a series of “bite-sized” data science focusing on outlier detection. Today I am writing about a machine learning algorithm called EllipticEnvelope , which is yet another tool in data scientists’ toolbox for fraud/anomaly/outlier detection."
},
{
"code": null,
"e": 584,
"s": 461,
"text": "In case you have missed my previous articles or you are interested in learning more about the topic, find the links below:"
},
{
"code": null,
"e": 611,
"s": 584,
"text": "Local Outlier Factor (LOF)"
},
{
"code": null,
"e": 619,
"s": 611,
"text": "Z-score"
},
{
"code": null,
"e": 627,
"s": 619,
"text": "Boxplot"
},
{
"code": null,
"e": 650,
"s": 627,
"text": "Statistical techniques"
},
{
"code": null,
"e": 680,
"s": 650,
"text": "Time series anomaly detection"
},
{
"code": null,
"e": 756,
"s": 680,
"text": "So what is elliptic envelope and what’s the intuition behind the algorithm?"
},
{
"code": null,
"e": 911,
"s": 756,
"text": "If you have taken geometry classes you are probably familiar with ellipse — a geometric configuration that takes an oval shape on a two-dimensional plane."
},
{
"code": null,
"e": 1385,
"s": 911,
"text": "The green area in the above diagram is an ellipse. So the algorithm — Elliptical Envelope— creates an imaginary elliptical area around a given dataset. Values that fall inside the envelope are considered normal data and anything outside the envelope is returned as outliers. So, naturally, the red data points in the above diagram should be identified as outliers by this algorithm. As evident from this figure, the algorithm works best if data has a Gaussian distribution."
},
{
"code": null,
"e": 1636,
"s": 1385,
"text": "sklearn is the Swiss army knife of machine learning algorithms. So not surprisingly it has a module for anomaly detection using the elliptical envelope as well. Below I am demonstrating an implementation using imaginary data points in 5 simple steps."
},
{
"code": null,
"e": 1770,
"s": 1636,
"text": "# import librariesimport pandas as pdimport numpy as npfrom sklearn.covariance import EllipticEnvelopeimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1978,
"s": 1770,
"text": "# create a dataframedf = pd.DataFrame(np.array([[0,1], [1,1], [1,2], [2,2], [5,6]]), columns = [\"x\", \"y\"], index = [0,1,2,3,4])# show data in a scatterplotplt.scatter(df[\"x\"], df[\"y\"], color = \"r\")plt.grid()"
},
{
"code": null,
"e": 2036,
"s": 1978,
"text": "# convert dataframe to arraysdata = df[['x', 'y']].values"
},
{
"code": null,
"e": 2259,
"s": 2036,
"text": "The most important parameter in defining the model is to set the “contamination” parameter, which basically defines the proportion of values that will be identified as outliers. The parameter value ranges between 0 and 0.5"
},
{
"code": null,
"e": 2353,
"s": 2259,
"text": "# instantiate modelmodel1 = EllipticEnvelope(contamination = 0.1) # fit modelmodel1.fit(data)"
},
{
"code": null,
"e": 2525,
"s": 2353,
"text": "# new data for prediction (data needs to be in arrays)new_data = np.array([[10,10], [1,1], [1,1], [1,1]])# predict on new data pred1 = model1.predict(new_data)print(pred1)"
}
] |
C++ STL | Set 2 (pair) | Practice | GeeksforGeeks
|
Implement different operations on pairs.
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .
A query can be of five types
1. a s x y (Adds a pair with string s and values x,y to the vector A at the end )
2. b (returns the size of the vector A)
3. c (prints space separated values of each element of the vector of pairs A)
4. d (sorts the pair's array with respect to the values x,y in ascending order)
Output:
The output for each test case will be space separated integers denoting the results of each query .
Constraints:
1<=T<=100
1<=Q<=100
Example:
Input
2
5
a ga 4 5 a ra 1 2 a sh 1 1 d c
4
a geeks 10 12 a code 11 11 b c
Output
sh 1 1 ra 1 2 ga 4 5
2 geeks 10 12 code 11 11
Explanation :
For the first test case
There are five queries. Queries are performed in this order
1. a ga 4 5 --> vector contents {ga,4,5}
2. a ra 1 2 --> vector contents {ga,4,5}, {ra,1,2}
3. a sh 1 1 --> vector contents are {ga,4,5}, {ra,1,2}, {sh,1,1}
4. d --> vector get sorted as {sh,1,1}, {ra,1,2}, {ga,4,5}
5. c --> vector values printed as 'sh 1 1 ra 1 2 ga 4 5 ' without quotes
For the sec test case
There are four queries. Queries are performed in this order
1. a geeks 10 12 --> vector A has {geeks,10,12}
2. a code 11 11 --> vector A has {geeks,10,12}, {code,11,11}
3. b --> prints the size of the vector A ie 2
4. c --> prints the elements of the pair of vectors as 'geeks 10 12 code 11 11' without quotes.
Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
-5
kashibalti556 months ago
jkfheio
0
Kiranjeet Kaur
This comment was deleted.
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.01
/* Inserts a pair <string, pair<x,="" y=""> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ A.push_back({str, {x, y}});}/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ return A.size();}/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ for(auto x: A) { cout << x.first << " " << x.second.first << " " << x.second.second << " "; }}/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ sort( A.begin(), A.end(), [](pair<string,pair<int,int>> &p1, pair<string,pair<int,int>> &p2) { return p1.second < p2.second; } );}
0
sagar dhankar2 years ago
sagar dhankar
/* Inserts a pair <string, pair<x,="" y=""> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ A.push_back(make_pair(str, make_pair(x, y))); // Your code here}
/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ return A.size(); // Your code here}
/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ for(int i=0; i<a.size(); ++i)="" cout="" <<="" a[i].first="" <<"="" "<<="" a[i].second.first="" <<"="" "<<="" a[i].second.second="" <<"="" ";="" your="" code="" here="" }="" <b="">bool myCmp(pair<string, pair<int,="" int="">> p1, pair<string, pair<int,="" int="">> p2){ return (p1.second < p2.second);}
/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ sort(A.begin(), A.end(), myCmp); // Your code here}
0
underrated2 years ago
underrated
Sorting through loop:https://ide.geeksforgeeks.o...
0
Yash Parmar2 years ago
Yash Parmar
/* Inserts a pair <string, pair<x,="" y=""> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ // Your code here A.push_back(make_pair(str,make_pair(x,y)));
}/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ // Your code here return A.size();}/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ // Your code here int i; for(i=0;i<a.size();i++) {="" cout<<a[i].first="" <<"="" "<<a[i].second.first<<"="" "<<a[i].second.second<<"="" ";="" }="" cout<<endl;="" }="" bool="" sortbysec(const="" pair<string,pair<int,int=""> > &A,const pair<string,pair<int,int> > &B) { return (A.second < B.second); }/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ // Your code here sort(A.begin(),A.end(),sortbysec);}
0
Aman Birla3 years ago
Aman Birla
i didnt get it..how to sort with respect to both x and y?do we need to take x and y as one single digit and then sort?
0
Muskan Agarwal3 years ago
Muskan Agarwal
AC answer:https://practice.geeksforge...
0
Raghav Goyal3 years ago
Raghav Goyal
Why do my code gives runtime error ?
https://practice.geeksforge...
0
Sammas3 years ago
Sammas
whats wrong with this https://ide.geeksforgeeks.o...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 986,
"s": 238,
"text": "Implement different operations on pairs.\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of five types \n1. a s x y (Adds a pair with string s and values x,y to the vector A at the end )\n2. b (returns the size of the vector A)\n3. c (prints space separated values of each element of the vector of pairs A)\n4. d (sorts the pair's array with respect to the values x,y in ascending order)\n\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:"
},
{
"code": null,
"e": 1116,
"s": 986,
"text": "Input\n2\n5\na ga 4 5 a ra 1 2 a sh 1 1 d c\n4\na geeks 10 12 a code 11 11 b c\n\nOutput\nsh 1 1 ra 1 2 ga 4 5 \n2 geeks 10 12 code 11 11"
},
{
"code": null,
"e": 2205,
"s": 1116,
"text": "\nExplanation :\nFor the first test case\nThere are five queries. Queries are performed in this order\n1. a ga 4 5 --> vector contents {ga,4,5} \n2. a ra 1 2 --> vector contents {ga,4,5}, {ra,1,2}\n3. a sh 1 1 --> vector contents are {ga,4,5}, {ra,1,2}, {sh,1,1}\n4. d --> vector get sorted as {sh,1,1}, {ra,1,2}, {ga,4,5}\n5. c --> vector values printed as 'sh 1 1 ra 1 2 ga 4 5 ' without quotes \n\nFor the sec test case \nThere are four queries. Queries are performed in this order\n1. a geeks 10 12 --> vector A has {geeks,10,12} \n2. a code 11 11 --> vector A has {geeks,10,12}, {code,11,11}\n3. b --> prints the size of the vector A ie 2\n4. c --> prints the elements of the pair of vectors as 'geeks 10 12 code 11 11' without quotes.\n\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 2208,
"s": 2205,
"text": "-5"
},
{
"code": null,
"e": 2233,
"s": 2208,
"text": "kashibalti556 months ago"
},
{
"code": null,
"e": 2241,
"s": 2233,
"text": "jkfheio"
},
{
"code": null,
"e": 2243,
"s": 2241,
"text": "0"
},
{
"code": null,
"e": 2258,
"s": 2243,
"text": "Kiranjeet Kaur"
},
{
"code": null,
"e": 2284,
"s": 2258,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2286,
"s": 2284,
"text": "0"
},
{
"code": null,
"e": 2312,
"s": 2286,
"text": "Debojyoti Sinha1 year ago"
},
{
"code": null,
"e": 2328,
"s": 2312,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 2377,
"s": 2328,
"text": "Correct Answer.Correct AnswerExecution Time:0.01"
},
{
"code": null,
"e": 3208,
"s": 2377,
"text": "/* Inserts a pair <string, pair<x,=\"\" y=\"\"> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ A.push_back({str, {x, y}});}/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ return A.size();}/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ for(auto x: A) { cout << x.first << \" \" << x.second.first << \" \" << x.second.second << \" \"; }}/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ sort( A.begin(), A.end(), [](pair<string,pair<int,int>> &p1, pair<string,pair<int,int>> &p2) { return p1.second < p2.second; } );}"
},
{
"code": null,
"e": 3210,
"s": 3208,
"text": "0"
},
{
"code": null,
"e": 3235,
"s": 3210,
"text": "sagar dhankar2 years ago"
},
{
"code": null,
"e": 3249,
"s": 3235,
"text": "sagar dhankar"
},
{
"code": null,
"e": 3475,
"s": 3249,
"text": "/* Inserts a pair <string, pair<x,=\"\" y=\"\"> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ A.push_back(make_pair(str, make_pair(x, y))); // Your code here}"
},
{
"code": null,
"e": 3611,
"s": 3475,
"text": "/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ return A.size(); // Your code here}"
},
{
"code": null,
"e": 4027,
"s": 3611,
"text": "/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ for(int i=0; i<a.size(); ++i)=\"\" cout=\"\" <<=\"\" a[i].first=\"\" <<\"=\"\" \"<<=\"\" a[i].second.first=\"\" <<\"=\"\" \"<<=\"\" a[i].second.second=\"\" <<\"=\"\" \";=\"\" your=\"\" code=\"\" here=\"\" }=\"\" <b=\"\">bool myCmp(pair<string, pair<int,=\"\" int=\"\">> p1, pair<string, pair<int,=\"\" int=\"\">> p2){ return (p1.second < p2.second);}"
},
{
"code": null,
"e": 4189,
"s": 4027,
"text": "/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ sort(A.begin(), A.end(), myCmp); // Your code here}"
},
{
"code": null,
"e": 4191,
"s": 4189,
"text": "0"
},
{
"code": null,
"e": 4213,
"s": 4191,
"text": "underrated2 years ago"
},
{
"code": null,
"e": 4224,
"s": 4213,
"text": "underrated"
},
{
"code": null,
"e": 4276,
"s": 4224,
"text": "Sorting through loop:https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4278,
"s": 4276,
"text": "0"
},
{
"code": null,
"e": 4301,
"s": 4278,
"text": "Yash Parmar2 years ago"
},
{
"code": null,
"e": 4313,
"s": 4301,
"text": "Yash Parmar"
},
{
"code": null,
"e": 4537,
"s": 4313,
"text": "/* Inserts a pair <string, pair<x,=\"\" y=\"\"> > > into the vector A */void add_pair(vector<pair<string,pair<int,int> > > &A, string str, int x, int y){ // Your code here A.push_back(make_pair(str,make_pair(x,y)));"
},
{
"code": null,
"e": 5262,
"s": 4537,
"text": "}/* Returns the size of the vector A */int get_size(vector<pair<string,pair<int,int> > > &A){ // Your code here return A.size();}/* Prints space separated values of vector A */void print_values(vector<pair<string,pair<int,int> > > &A){ // Your code here int i; for(i=0;i<a.size();i++) {=\"\" cout<<a[i].first=\"\" <<\"=\"\" \"<<a[i].second.first<<\"=\"\" \"<<a[i].second.second<<\"=\"\" \";=\"\" }=\"\" cout<<endl;=\"\" }=\"\" bool=\"\" sortbysec(const=\"\" pair<string,pair<int,int=\"\"> > &A,const pair<string,pair<int,int> > &B) { return (A.second < B.second); }/* Sorts the vector A based on value x and y*/void sort_pair(vector<pair<string,pair<int,int> > > &A){ // Your code here sort(A.begin(),A.end(),sortbysec);}"
},
{
"code": null,
"e": 5264,
"s": 5262,
"text": "0"
},
{
"code": null,
"e": 5286,
"s": 5264,
"text": "Aman Birla3 years ago"
},
{
"code": null,
"e": 5297,
"s": 5286,
"text": "Aman Birla"
},
{
"code": null,
"e": 5417,
"s": 5297,
"text": "i didnt get it..how to sort with respect to both x and y?do we need to take x and y as one single digit and then sort?"
},
{
"code": null,
"e": 5419,
"s": 5417,
"text": "0"
},
{
"code": null,
"e": 5445,
"s": 5419,
"text": "Muskan Agarwal3 years ago"
},
{
"code": null,
"e": 5460,
"s": 5445,
"text": "Muskan Agarwal"
},
{
"code": null,
"e": 5501,
"s": 5460,
"text": "AC answer:https://practice.geeksforge..."
},
{
"code": null,
"e": 5503,
"s": 5501,
"text": "0"
},
{
"code": null,
"e": 5527,
"s": 5503,
"text": "Raghav Goyal3 years ago"
},
{
"code": null,
"e": 5540,
"s": 5527,
"text": "Raghav Goyal"
},
{
"code": null,
"e": 5577,
"s": 5540,
"text": "Why do my code gives runtime error ?"
},
{
"code": null,
"e": 5608,
"s": 5577,
"text": "https://practice.geeksforge..."
},
{
"code": null,
"e": 5610,
"s": 5608,
"text": "0"
},
{
"code": null,
"e": 5628,
"s": 5610,
"text": "Sammas3 years ago"
},
{
"code": null,
"e": 5635,
"s": 5628,
"text": "Sammas"
},
{
"code": null,
"e": 5688,
"s": 5635,
"text": "whats wrong with this https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5834,
"s": 5688,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5870,
"s": 5834,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5880,
"s": 5870,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5890,
"s": 5880,
"text": "\nContest\n"
},
{
"code": null,
"e": 5953,
"s": 5890,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6101,
"s": 5953,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6309,
"s": 6101,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6415,
"s": 6309,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Complex Numbers in Python | Set 3 (Trigonometric and Hyperbolic Functions) - GeeksforGeeks
|
04 Feb, 2020
Some of the Important Complex number functions are discussed in the articles below
Complex Numbers in Python | Set 1 (Introduction)Complex Numbers in Python | Set 2 (Important Functions and constants)
Trigonometric and Hyperbolic Functions are discussed in this article.
Trigonometric Functions
1. sin() : This function returns the sine of the complex number passed in argument.
2. cos() : This function returns the cosine of the complex number passed in argument.
3. tan() : This function returns the tangent of the complex number passed in argument.
# Python code to demonstrate the working of # sin(), cos(), tan() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing sine of the complex numberprint ("The sine value of complex number is : ",end="")print (cmath.sin(z)) # printing cosine of the complex numberprint ("The cosine value of complex number is : ",end="")print (cmath.cos(z)) # printing tangent of the complex numberprint ("The tangent value of complex number is : ",end="")print (cmath.tan(z))
Output:
The sine value of complex number is : (1.2984575814159773+0.6349639147847361j)
The cosine value of complex number is : (0.8337300251311491-0.9888977057628651j)
The tangent value of complex number is : (0.2717525853195118+1.0839233273386946j)
4. asin() : This function returns the arc sine of the complex number passed in argument.
5. acos() : This function returns the arc cosine of the complex number passed in argument.
6. atan() : This function returns the arc tangent of the complex number passed in argument.
# Python code to demonstrate the working of # asin(), acos(), atan() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing arc sine of the complex numberprint ("The arc sine value of complex number is : ",end="")print (cmath.asin(z)) # printing arc cosine of the complex numberprint ("The arc cosine value of complex number is : ",end="")print (cmath.acos(z)) # printing arc tangent of the complex numberprint ("The arc tangent value of complex number is : ",end="")print (cmath.atan(z))
Output:
The arc sine value of complex number is : (0.6662394324925153+1.0612750619050357j)
The arc cosine value of complex number is : (0.9045568943023814-1.0612750619050357j)
The arc tangent value of complex number is : (1.0172219678978514+0.40235947810852507j)
Hyperbolic Functions
1. sinh() : This function returns the hyperbolic sine of the complex number passed in argument.
2. cosh() : This function returns the hyperbolic cosine of the complex number passed in argument.
3. tanh() : This function returns the hyperbolic tangent of the complex number passed in argument.
# Python code to demonstrate the working of # sinh(), cosh(), tanh() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing hyperbolic sine of the complex numberprint ("The hyperbolic sine value of complex number is : ",end="")print (cmath.sinh(z)) # printing hyperbolic cosine of the complex numberprint ("The hyperbolic cosine value of complex number is : ",end="")print (cmath.cosh(z)) # printing hyperbolic tangent of the complex numberprint ("The hyperbolic tangent value of complex number is : ",end="")print (cmath.tanh(z))
Output:
The hyperbolic sine value of complex number is : (0.6349639147847361+1.2984575814159773j)
The hyperbolic cosine value of complex number is : (0.8337300251311491+0.9888977057628651j)
The hyperbolic tangent value of complex number is : (1.0839233273386946+0.2717525853195117j)
4. asinh() : This function returns the inverse hyperbolic sine of the complex number passed in argument.
5. acosh() : This function returns the inverse hyperbolic cosine of the complex number passed in argument.
6. atanh() : This function returns the inverse hyperbolic tangent of the complex number passed in argument.
# Python code to demonstrate the working of # asinh(), acosh(), atanh() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing inverse hyperbolic sine of the complex numberprint ("The inverse hyperbolic sine value of complex number is : ",end="")print (cmath.asinh(z)) # printing inverse hyperbolic cosine of the complex numberprint ("The inverse hyperbolic cosine value of complex number is : ",end="")print (cmath.acosh(z)) # printing inverse hyperbolic tangent of the complex numberprint ("The inverse hyperbolic tangent value of complex number is : ",end="")print (cmath.atanh(z))
Output:
The inverse hyperbolic sine value of complex number is : (1.0612750619050357+0.6662394324925153j)
The inverse hyperbolic cosine value of complex number is : (1.0612750619050357+0.9045568943023813j)
The inverse hyperbolic tangent value of complex number is : (0.40235947810852507+1.0172219678978514j)
YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Complex Numbers - Part 3 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oC9hmlSgwsw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to 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.
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25176,
"s": 25148,
"text": "\n04 Feb, 2020"
},
{
"code": null,
"e": 25259,
"s": 25176,
"text": "Some of the Important Complex number functions are discussed in the articles below"
},
{
"code": null,
"e": 25377,
"s": 25259,
"text": "Complex Numbers in Python | Set 1 (Introduction)Complex Numbers in Python | Set 2 (Important Functions and constants)"
},
{
"code": null,
"e": 25447,
"s": 25377,
"text": "Trigonometric and Hyperbolic Functions are discussed in this article."
},
{
"code": null,
"e": 25471,
"s": 25447,
"text": "Trigonometric Functions"
},
{
"code": null,
"e": 25555,
"s": 25471,
"text": "1. sin() : This function returns the sine of the complex number passed in argument."
},
{
"code": null,
"e": 25641,
"s": 25555,
"text": "2. cos() : This function returns the cosine of the complex number passed in argument."
},
{
"code": null,
"e": 25728,
"s": 25641,
"text": "3. tan() : This function returns the tangent of the complex number passed in argument."
},
{
"code": "# Python code to demonstrate the working of # sin(), cos(), tan() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing sine of the complex numberprint (\"The sine value of complex number is : \",end=\"\")print (cmath.sin(z)) # printing cosine of the complex numberprint (\"The cosine value of complex number is : \",end=\"\")print (cmath.cos(z)) # printing tangent of the complex numberprint (\"The tangent value of complex number is : \",end=\"\")print (cmath.tan(z))",
"e": 26318,
"s": 25728,
"text": null
},
{
"code": null,
"e": 26326,
"s": 26318,
"text": "Output:"
},
{
"code": null,
"e": 26569,
"s": 26326,
"text": "The sine value of complex number is : (1.2984575814159773+0.6349639147847361j)\nThe cosine value of complex number is : (0.8337300251311491-0.9888977057628651j)\nThe tangent value of complex number is : (0.2717525853195118+1.0839233273386946j)\n"
},
{
"code": null,
"e": 26658,
"s": 26569,
"text": "4. asin() : This function returns the arc sine of the complex number passed in argument."
},
{
"code": null,
"e": 26749,
"s": 26658,
"text": "5. acos() : This function returns the arc cosine of the complex number passed in argument."
},
{
"code": null,
"e": 26841,
"s": 26749,
"text": "6. atan() : This function returns the arc tangent of the complex number passed in argument."
},
{
"code": "# Python code to demonstrate the working of # asin(), acos(), atan() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing arc sine of the complex numberprint (\"The arc sine value of complex number is : \",end=\"\")print (cmath.asin(z)) # printing arc cosine of the complex numberprint (\"The arc cosine value of complex number is : \",end=\"\")print (cmath.acos(z)) # printing arc tangent of the complex numberprint (\"The arc tangent value of complex number is : \",end=\"\")print (cmath.atan(z))",
"e": 27461,
"s": 26841,
"text": null
},
{
"code": null,
"e": 27469,
"s": 27461,
"text": "Output:"
},
{
"code": null,
"e": 27725,
"s": 27469,
"text": "The arc sine value of complex number is : (0.6662394324925153+1.0612750619050357j)\nThe arc cosine value of complex number is : (0.9045568943023814-1.0612750619050357j)\nThe arc tangent value of complex number is : (1.0172219678978514+0.40235947810852507j)\n"
},
{
"code": null,
"e": 27746,
"s": 27725,
"text": "Hyperbolic Functions"
},
{
"code": null,
"e": 27842,
"s": 27746,
"text": "1. sinh() : This function returns the hyperbolic sine of the complex number passed in argument."
},
{
"code": null,
"e": 27940,
"s": 27842,
"text": "2. cosh() : This function returns the hyperbolic cosine of the complex number passed in argument."
},
{
"code": null,
"e": 28039,
"s": 27940,
"text": "3. tanh() : This function returns the hyperbolic tangent of the complex number passed in argument."
},
{
"code": "# Python code to demonstrate the working of # sinh(), cosh(), tanh() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing hyperbolic sine of the complex numberprint (\"The hyperbolic sine value of complex number is : \",end=\"\")print (cmath.sinh(z)) # printing hyperbolic cosine of the complex numberprint (\"The hyperbolic cosine value of complex number is : \",end=\"\")print (cmath.cosh(z)) # printing hyperbolic tangent of the complex numberprint (\"The hyperbolic tangent value of complex number is : \",end=\"\")print (cmath.tanh(z))",
"e": 28701,
"s": 28039,
"text": null
},
{
"code": null,
"e": 28709,
"s": 28701,
"text": "Output:"
},
{
"code": null,
"e": 28985,
"s": 28709,
"text": "The hyperbolic sine value of complex number is : (0.6349639147847361+1.2984575814159773j)\nThe hyperbolic cosine value of complex number is : (0.8337300251311491+0.9888977057628651j)\nThe hyperbolic tangent value of complex number is : (1.0839233273386946+0.2717525853195117j)\n"
},
{
"code": null,
"e": 29090,
"s": 28985,
"text": "4. asinh() : This function returns the inverse hyperbolic sine of the complex number passed in argument."
},
{
"code": null,
"e": 29197,
"s": 29090,
"text": "5. acosh() : This function returns the inverse hyperbolic cosine of the complex number passed in argument."
},
{
"code": null,
"e": 29305,
"s": 29197,
"text": "6. atanh() : This function returns the inverse hyperbolic tangent of the complex number passed in argument."
},
{
"code": "# Python code to demonstrate the working of # asinh(), acosh(), atanh() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = 1.0 y = 1.0 # converting x and y into complex number zz = complex(x,y); # printing inverse hyperbolic sine of the complex numberprint (\"The inverse hyperbolic sine value of complex number is : \",end=\"\")print (cmath.asinh(z)) # printing inverse hyperbolic cosine of the complex numberprint (\"The inverse hyperbolic cosine value of complex number is : \",end=\"\")print (cmath.acosh(z)) # printing inverse hyperbolic tangent of the complex numberprint (\"The inverse hyperbolic tangent value of complex number is : \",end=\"\")print (cmath.atanh(z))",
"e": 30021,
"s": 29305,
"text": null
},
{
"code": null,
"e": 30029,
"s": 30021,
"text": "Output:"
},
{
"code": null,
"e": 30330,
"s": 30029,
"text": "The inverse hyperbolic sine value of complex number is : (1.0612750619050357+0.6662394324925153j)\nThe inverse hyperbolic cosine value of complex number is : (1.0612750619050357+0.9045568943023813j)\nThe inverse hyperbolic tangent value of complex number is : (0.40235947810852507+1.0172219678978514j)\n"
},
{
"code": null,
"e": 31183,
"s": 30330,
"text": "YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Complex Numbers - Part 3 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oC9hmlSgwsw\" 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": 31484,
"s": 31183,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31609,
"s": 31484,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31616,
"s": 31609,
"text": "Python"
},
{
"code": null,
"e": 31714,
"s": 31616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31732,
"s": 31714,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31767,
"s": 31732,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31789,
"s": 31767,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31821,
"s": 31789,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31851,
"s": 31821,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31893,
"s": 31851,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31919,
"s": 31893,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31956,
"s": 31919,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31999,
"s": 31956,
"text": "Python program to convert a list to string"
}
] |
Python - tensorflow.math.confusion_matrix() - GeeksforGeeks
|
08 Dec, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. confusion_matrix() is used to find the confusion matrix from predictions and labels.
Syntax: tensorflow.math.confusion_matrix( labels, predictions, num_classes, weights, dtype,name)
Parameters:
labels: It’s a 1-D Tensor which contains real labels for the classification task.
predictions: It’s also a 1-D Tensor of same shape as labels. It’s value represents the predicted class.
num_classes(optional): It is the possible number of labels/class classification task might have. If it’s not provided then num_classes will be one more than the maximum value in either predictions or labels.
weight(optional): It’s a Tensor of same shape as predictions whose values define the corresponding weight for each prediction.
dtype(optional): It defines the dtype of returned confusion matrix. Default if tensorflow.dtypes.int32.
name(optional): Defines the name for the operation.
Returns:It returns a confusion matrix of shape [n,n] where n is the possible number of labels.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensorlabels = tf.constant([1,3,4],dtype = tf.int32)predictions = tf.constant([1,2,3],dtype = tf.int32) # Printing the input tensorprint('labels: ',labels)print('Predictions: ',predictions) # Evaluating confusion matrixres = tf.math.confusion_matrix(labels,predictions) # Printing the resultprint('Confusion_matrix: ',res)
Output:
labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)
Predictions: tf.Tensor([1 2 3], shape=(3,), dtype=int32)
Confusion_matrix: tf.Tensor(
[[0 0 0 0 0]
[0 1 0 0 0]
[0 0 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]], shape=(5, 5), dtype=int32)
Example2: This example provide the weights to all predictions.
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensorlabels = tf.constant([1,3,4],dtype = tf.int32)predictions = tf.constant([1,2,4],dtype = tf.int32)weights = tf.constant([1,2,2], dtype = tf.int32) # Printing the input tensorprint('labels: ',labels)print('Predictions: ',predictions)print('Weights: ',weights) # Evaluating confusion matrixres = tf.math.confusion_matrix(labels, predictions, weights=weights) # Printing the resultprint('Confusion_matrix: ',res)
Output:
labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)
Predictions: tf.Tensor([1 2 4], shape=(3,), dtype=int32)
Weights: tf.Tensor([1 2 2], shape=(3,), dtype=int32)
Confusion_matrix: tf.Tensor(
[[0 0 0 0 0]
[0 1 0 0 0]
[0 0 0 0 0]
[0 0 2 0 0]
[0 0 0 0 2]], shape=(5, 5), dtype=int32)
surindertarika1234
sumitgumber28
sagartomar9927
nnr223442
Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 24118,
"s": 23901,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. confusion_matrix() is used to find the confusion matrix from predictions and labels."
},
{
"code": null,
"e": 24216,
"s": 24118,
"text": "Syntax: tensorflow.math.confusion_matrix( labels, predictions, num_classes, weights, dtype,name) "
},
{
"code": null,
"e": 24228,
"s": 24216,
"text": "Parameters:"
},
{
"code": null,
"e": 24310,
"s": 24228,
"text": "labels: It’s a 1-D Tensor which contains real labels for the classification task."
},
{
"code": null,
"e": 24414,
"s": 24310,
"text": "predictions: It’s also a 1-D Tensor of same shape as labels. It’s value represents the predicted class."
},
{
"code": null,
"e": 24622,
"s": 24414,
"text": "num_classes(optional): It is the possible number of labels/class classification task might have. If it’s not provided then num_classes will be one more than the maximum value in either predictions or labels."
},
{
"code": null,
"e": 24749,
"s": 24622,
"text": "weight(optional): It’s a Tensor of same shape as predictions whose values define the corresponding weight for each prediction."
},
{
"code": null,
"e": 24853,
"s": 24749,
"text": "dtype(optional): It defines the dtype of returned confusion matrix. Default if tensorflow.dtypes.int32."
},
{
"code": null,
"e": 24906,
"s": 24853,
"text": "name(optional): Defines the name for the operation. "
},
{
"code": null,
"e": 25002,
"s": 24906,
"text": "Returns:It returns a confusion matrix of shape [n,n] where n is the possible number of labels. "
},
{
"code": null,
"e": 25013,
"s": 25002,
"text": "Example 1:"
},
{
"code": null,
"e": 25021,
"s": 25013,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensorlabels = tf.constant([1,3,4],dtype = tf.int32)predictions = tf.constant([1,2,3],dtype = tf.int32) # Printing the input tensorprint('labels: ',labels)print('Predictions: ',predictions) # Evaluating confusion matrixres = tf.math.confusion_matrix(labels,predictions) # Printing the resultprint('Confusion_matrix: ',res)",
"e": 25416,
"s": 25021,
"text": null
},
{
"code": null,
"e": 25424,
"s": 25416,
"text": "Output:"
},
{
"code": null,
"e": 25659,
"s": 25424,
"text": "labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)\nPredictions: tf.Tensor([1 2 3], shape=(3,), dtype=int32)\nConfusion_matrix: tf.Tensor(\n[[0 0 0 0 0]\n [0 1 0 0 0]\n [0 0 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]], shape=(5, 5), dtype=int32)"
},
{
"code": null,
"e": 25722,
"s": 25659,
"text": "Example2: This example provide the weights to all predictions."
},
{
"code": null,
"e": 25730,
"s": 25722,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensorlabels = tf.constant([1,3,4],dtype = tf.int32)predictions = tf.constant([1,2,4],dtype = tf.int32)weights = tf.constant([1,2,2], dtype = tf.int32) # Printing the input tensorprint('labels: ',labels)print('Predictions: ',predictions)print('Weights: ',weights) # Evaluating confusion matrixres = tf.math.confusion_matrix(labels, predictions, weights=weights) # Printing the resultprint('Confusion_matrix: ',res)",
"e": 26217,
"s": 25730,
"text": null
},
{
"code": null,
"e": 26225,
"s": 26217,
"text": "Output:"
},
{
"code": null,
"e": 26514,
"s": 26225,
"text": "labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)\nPredictions: tf.Tensor([1 2 4], shape=(3,), dtype=int32)\nWeights: tf.Tensor([1 2 2], shape=(3,), dtype=int32)\nConfusion_matrix: tf.Tensor(\n[[0 0 0 0 0]\n [0 1 0 0 0]\n [0 0 0 0 0]\n [0 0 2 0 0]\n [0 0 0 0 2]], shape=(5, 5), dtype=int32)"
},
{
"code": null,
"e": 26533,
"s": 26514,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26547,
"s": 26533,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26562,
"s": 26547,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26572,
"s": 26562,
"text": "nnr223442"
},
{
"code": null,
"e": 26605,
"s": 26572,
"text": "Python Tensorflow-math-functions"
},
{
"code": null,
"e": 26623,
"s": 26605,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 26630,
"s": 26623,
"text": "Python"
},
{
"code": null,
"e": 26728,
"s": 26630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26737,
"s": 26728,
"text": "Comments"
},
{
"code": null,
"e": 26750,
"s": 26737,
"text": "Old Comments"
},
{
"code": null,
"e": 26782,
"s": 26750,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26838,
"s": 26782,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26880,
"s": 26838,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26922,
"s": 26880,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26958,
"s": 26922,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26980,
"s": 26958,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27019,
"s": 26980,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27046,
"s": 27019,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27077,
"s": 27046,
"text": "Python | os.path.join() method"
}
] |
Difference between body.onload() and document.ready() function - GeeksforGeeks
|
01 Jul, 2021
The body.onload() event will be called once the DOM and all associated resources like images got loaded. Basically, onload() will be called when the page has been fully loaded with entire images, iframes and stylesheets, etc.
For example, if our page contains a larger size image, so onload() event will wait till the image is fully loaded.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body onload="loadBody()"> <h2>GeeksForGeeks</h2> <script> function loadBody(){ alert("page loaded"); } </script></body> </html>
Output:
body onload
The document.ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.
We can have multiple document.ready() function in our code but only one body.onload() is allowed.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Using jquery library --> <script src="https://code.jquery.com/jquery-git.js"></script> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body onload="loadBody()"> <h2>GeeksForGeeks</h2> <script> $(document).ready(function(){ alert("ready - page loaded") }) </script></body> </html>
Output:
DOM is ready
Difference between body.onload and document.ready:
JavaScript-Events
JavaScript-Questions
Picked
Difference Between
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 24921,
"s": 24893,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 25147,
"s": 24921,
"text": "The body.onload() event will be called once the DOM and all associated resources like images got loaded. Basically, onload() will be called when the page has been fully loaded with entire images, iframes and stylesheets, etc."
},
{
"code": null,
"e": 25263,
"s": 25147,
"text": "For example, if our page contains a larger size image, so onload() event will wait till the image is fully loaded. "
},
{
"code": null,
"e": 25272,
"s": 25263,
"text": "Example:"
},
{
"code": null,
"e": 25277,
"s": 25272,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> </head> <body onload=\"loadBody()\"> <h2>GeeksForGeeks</h2> <script> function loadBody(){ alert(\"page loaded\"); } </script></body> </html>",
"e": 25769,
"s": 25277,
"text": null
},
{
"code": null,
"e": 25777,
"s": 25769,
"text": "Output:"
},
{
"code": null,
"e": 25789,
"s": 25777,
"text": "body onload"
},
{
"code": null,
"e": 25962,
"s": 25791,
"text": "The document.ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded."
},
{
"code": null,
"e": 26060,
"s": 25962,
"text": "We can have multiple document.ready() function in our code but only one body.onload() is allowed."
},
{
"code": null,
"e": 26069,
"s": 26060,
"text": "Example:"
},
{
"code": null,
"e": 26074,
"s": 26069,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"></script> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> </head> <body onload=\"loadBody()\"> <h2>GeeksForGeeks</h2> <script> $(document).ready(function(){ alert(\"ready - page loaded\") }) </script></body> </html>",
"e": 26572,
"s": 26074,
"text": null
},
{
"code": null,
"e": 26580,
"s": 26572,
"text": "Output:"
},
{
"code": null,
"e": 26593,
"s": 26580,
"text": "DOM is ready"
},
{
"code": null,
"e": 26644,
"s": 26593,
"text": "Difference between body.onload and document.ready:"
},
{
"code": null,
"e": 26662,
"s": 26644,
"text": "JavaScript-Events"
},
{
"code": null,
"e": 26683,
"s": 26662,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 26690,
"s": 26683,
"text": "Picked"
},
{
"code": null,
"e": 26709,
"s": 26690,
"text": "Difference Between"
},
{
"code": null,
"e": 26716,
"s": 26709,
"text": "JQuery"
},
{
"code": null,
"e": 26733,
"s": 26716,
"text": "Web Technologies"
},
{
"code": null,
"e": 26831,
"s": 26733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26892,
"s": 26831,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26960,
"s": 26892,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27018,
"s": 26960,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27073,
"s": 27018,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27147,
"s": 27073,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 27193,
"s": 27147,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 27256,
"s": 27193,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 27285,
"s": 27256,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27362,
"s": 27285,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Generate Fibonacci Series
|
The Fibonacci sequence is like this,
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......
In this sequence, the nth term is the sum of (n-1)'th and (n-2)'th terms.
To generate we can use the recursive approach, but in dynamic programming, the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence.
Input:
Take the term number as an input. Say it is 10
Output:
Enter number of terms: 10
10th fibinacci Terms: 55
genFiboSeries(n)
Input: max number of terms.
Output − The nth Fibonacci term.
Begin
define array named fibo of size n+2
fibo[0] := 0
fibo[1] := 1
for i := 2 to n, do
fibo[i] := fibo[i-1] + fibo[i-2]
done
return fibo[n]
End
#include<iostream>
using namespace std;
int genFibonacci(int n) {
int fibo[n+2]; //array to store fibonacci values
// 0th and 1st number of the series are 0 and 1
fibo[0] = 0;
fibo[1] = 1;
for (int i = 2; i <= n; i++) {
fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous two terms
}
return fibo[n];
}
int main () {
int n;
cout << "Enter number of terms: "; cin >>n;
cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
}
Enter number of terms: 10
10th Fibonacci Terms: 55
|
[
{
"code": null,
"e": 1099,
"s": 1062,
"text": "The Fibonacci sequence is like this,"
},
{
"code": null,
"e": 1142,
"s": 1099,
"text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......"
},
{
"code": null,
"e": 1216,
"s": 1142,
"text": "In this sequence, the nth term is the sum of (n-1)'th and (n-2)'th terms."
},
{
"code": null,
"e": 1440,
"s": 1216,
"text": "To generate we can use the recursive approach, but in dynamic programming, the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence."
},
{
"code": null,
"e": 1553,
"s": 1440,
"text": "Input:\nTake the term number as an input. Say it is 10\nOutput:\nEnter number of terms: 10\n10th fibinacci Terms: 55"
},
{
"code": null,
"e": 1570,
"s": 1553,
"text": "genFiboSeries(n)"
},
{
"code": null,
"e": 1598,
"s": 1570,
"text": "Input: max number of terms."
},
{
"code": null,
"e": 1631,
"s": 1598,
"text": "Output − The nth Fibonacci term."
},
{
"code": null,
"e": 1801,
"s": 1631,
"text": "Begin\n define array named fibo of size n+2\n fibo[0] := 0\n fibo[1] := 1\n\n for i := 2 to n, do\n fibo[i] := fibo[i-1] + fibo[i-2]\n done\n return fibo[n]\nEnd"
},
{
"code": null,
"e": 2297,
"s": 1801,
"text": "#include<iostream>\nusing namespace std;\n\nint genFibonacci(int n) {\n int fibo[n+2]; //array to store fibonacci values\n\n // 0th and 1st number of the series are 0 and 1\n fibo[0] = 0;\n fibo[1] = 1;\n\n for (int i = 2; i <= n; i++) {\n fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous two terms\n }\n return fibo[n];\n}\n\nint main () {\n int n;\n cout << \"Enter number of terms: \"; cin >>n;\n cout << n<<\" th Fibonacci Terms: \"<<genFibonacci(n)<<endl;\n}"
},
{
"code": null,
"e": 2348,
"s": 2297,
"text": "Enter number of terms: 10\n10th Fibonacci Terms: 55"
}
] |
Minimum Swaps required to group all 1s together | Practice | GeeksforGeeks
|
Given an array of 0’s and 1’s, we need to write a program to find the minimum number of swaps required to group all 1’s present in the array together.
Example 1:
​Input : arr[ ] = {1, 0, 1, 0, 1}
Output : 1
Explanation:
Only 1 swap is required to group all 1's together.
Swapping index 1 and 4 will give arr[] = {1, 1, 1, 0, 0}.
​Example 2:
Input : arr[ ] = {1, 0, 1, 0, 1, 1}
Output : 1
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwaps() that takes an array (arr), sizeOfArray (n) and return the minimum number of swaps required and if no 1's are present print -1. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 105
0 ≤ Arri ≤ 1
+1
sknwd88643 months ago
int minSwaps(int arr[], int n) {
int k = 0;
for(int i = 0; i < n; i++)
{
if(arr[i])
k++;
}
if(k == 0)
return -1;
int maxi = INT_MIN;
int curr = 0;
for(int i = 0; i < n; i++)
{
if(i < k)
{
if(arr[i])
{
curr++;
}
}
else
{
maxi = max(maxi, curr);
if(arr[i])
{
curr++;
}
if(arr[i - k])
{
curr--;
}
}
}
maxi = max(maxi, curr);
return k - maxi ;
}
0
shikharsrivastava20023 months ago
int minSwaps(int arr[], int n) {
// Complete the function
int ones=0;
for(int i=0;i<n;i++)
{
if(arr[i])
ones+=1;
}
if(!ones)
return -1;
int left=0;
int right=0;
int oc=0;
int zeros=0;
int minzeros=0;
for(right=0;right<n;right++)
{
if(arr[right]==0)
{
zeros+=1;
}
oc+=1;
if(oc==ones)
{
break;
}
}
minzeros=zeros;
while(right<n)
{
if(arr[left]==0)
{
zeros-=1;
}
left+=1;
right+=1;
if(arr[right]==0)
{
zeros+=1;
}
if(right<n)
minzeros=min(minzeros,zeros);
}
return minzeros;
}
+1
defendersatya53 months ago
not a easy question though.
0
chessnoobdj4 months ago
C++
int minSwaps(int arr[], int n) {
int cnt_one = 0;
for(int i=0; i<n; i++){
if(arr[i])
cnt_one += 1;
}
if(!cnt_one)
return -1;
int cnt = 0;
for(int i=0; i<cnt_one; i++){
if(arr[i])
cnt += 1;
}
int ans = cnt_one-cnt, l=0, r=cnt_one;
for(int i=0; i+cnt_one<n; i++){
//cout << cnt << " " << l << " " << r << " " << i << "\n";
if(arr[l++])
cnt -= 1;
if(arr[r++])
cnt += 1;
ans = min(ans, cnt_one-cnt);
//cout << cnt << " " << ans << "\n";
}
return ans;
}
+1
imranwahid5 months ago
Easy C++ solution
0
tonyapstark
This comment was deleted.
0
VickySam19017 months ago
VickySam1901
Time Complexity: O(N).Auxiliary Space: O(1).Sliding Window Approach https://uploads.disquscdn.c...
-1
aditya anand10 months ago
aditya anand
Elegant Python3 Solutiondef minSwaps (arr, n) : total_ones=arr.count(1) temp_ones,max_ones=arr[:total_ones].count(1),0 max_ones=temp_ones for i in range(total_ones,n): if arr[i]==1: temp_ones+=1 if arr[i-total_ones]==1: temp_ones-=1 max_ones=max(max_ones,temp_ones) return total_ones-max_ones if total_ones>0 else -1
0
PK11 months ago
PK
int minSwaps(int a[], int n) {
int tcount_one=0; for(int i=0;i<n;i++) {="" tcount_one+="a[i];" }="" if(tcount_one="=0)" {="" return="" -1;="" }="" int="" count="0,max_count=0,i=0,j=0;" while(j<n)="" {="" count+="a[j];" if((j-i+1)="=" tcount_one)="" {="" max_count="max(max_count,count);" if(a[i]="=1)" {="" count--;="" }="" i++;="" }="" j++;="" }="" return="" tcount_one-max_count;="" }="">
0
prerna singh2 years ago
prerna singh
It gives incorrect output for this:
291 0 0 1 0 1 1 0 0 1 0 0 0 0 1 0 1 0 0 0 0 1 1 1 1 0 1 1 1
I do it in my ide it gives 6 which is correct. But while submitting code here, it gives 3 as output
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 389,
"s": 238,
"text": "Given an array of 0’s and 1’s, we need to write a program to find the minimum number of swaps required to group all 1’s present in the array together."
},
{
"code": null,
"e": 400,
"s": 389,
"text": "Example 1:"
},
{
"code": null,
"e": 572,
"s": 400,
"text": "​Input : arr[ ] = {1, 0, 1, 0, 1}\nOutput : 1\nExplanation:\nOnly 1 swap is required to group all 1's together. \nSwapping index 1 and 4 will give arr[] = {1, 1, 1, 0, 0}.\n"
},
{
"code": null,
"e": 588,
"s": 572,
"text": "\n​Example 2:"
},
{
"code": null,
"e": 637,
"s": 588,
"text": "Input : arr[ ] = {1, 0, 1, 0, 1, 1} \nOutput : 1"
},
{
"code": null,
"e": 954,
"s": 639,
"text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwaps() that takes an array (arr), sizeOfArray (n) and return the minimum number of swaps required and if no 1's are present print -1. The driver code takes care of the printing."
},
{
"code": null,
"e": 1018,
"s": 954,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1059,
"s": 1020,
"text": "Constraints:\n1 ≤ N ≤ 105\n0 ≤ Arri ≤ 1"
},
{
"code": null,
"e": 1062,
"s": 1059,
"text": "+1"
},
{
"code": null,
"e": 1084,
"s": 1062,
"text": "sknwd88643 months ago"
},
{
"code": null,
"e": 1785,
"s": 1084,
"text": "int minSwaps(int arr[], int n) {\n \n int k = 0;\n \n for(int i = 0; i < n; i++)\n {\n if(arr[i])\n k++;\n }\n \n if(k == 0)\n return -1;\n \n int maxi = INT_MIN;\n \n int curr = 0;\n \n for(int i = 0; i < n; i++)\n {\n if(i < k)\n {\n if(arr[i])\n {\n curr++;\n }\n }\n \n else\n {\n maxi = max(maxi, curr);\n \n if(arr[i])\n {\n curr++;\n }\n \n if(arr[i - k])\n {\n curr--;\n }\n }\n }\n \n maxi = max(maxi, curr);\n \n return k - maxi ;\n}"
},
{
"code": null,
"e": 1787,
"s": 1785,
"text": "0"
},
{
"code": null,
"e": 1821,
"s": 1787,
"text": "shikharsrivastava20023 months ago"
},
{
"code": null,
"e": 2592,
"s": 1821,
"text": "int minSwaps(int arr[], int n) {\n \n // Complete the function\n int ones=0;\n for(int i=0;i<n;i++)\n {\n if(arr[i])\n ones+=1;\n }\n if(!ones)\n return -1;\n int left=0;\n int right=0;\n \n int oc=0;\n int zeros=0;\n int minzeros=0;\n for(right=0;right<n;right++)\n {\n if(arr[right]==0)\n {\n zeros+=1;\n }\n oc+=1;\n if(oc==ones)\n {\n break;\n }\n \n }\n minzeros=zeros;\n \n while(right<n)\n {\n if(arr[left]==0)\n {\n zeros-=1;\n }\n left+=1;\n right+=1;\n if(arr[right]==0)\n {\n zeros+=1;\n }\n if(right<n)\n minzeros=min(minzeros,zeros);\n }\nreturn minzeros;\n\n}"
},
{
"code": null,
"e": 2595,
"s": 2592,
"text": "+1"
},
{
"code": null,
"e": 2622,
"s": 2595,
"text": "defendersatya53 months ago"
},
{
"code": null,
"e": 2650,
"s": 2622,
"text": "not a easy question though."
},
{
"code": null,
"e": 2652,
"s": 2650,
"text": "0"
},
{
"code": null,
"e": 2676,
"s": 2652,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 2680,
"s": 2676,
"text": "C++"
},
{
"code": null,
"e": 3286,
"s": 2680,
"text": "int minSwaps(int arr[], int n) {\n int cnt_one = 0;\n for(int i=0; i<n; i++){\n if(arr[i])\n cnt_one += 1;\n }\n if(!cnt_one)\n return -1;\n int cnt = 0;\n for(int i=0; i<cnt_one; i++){\n if(arr[i])\n cnt += 1;\n }\n int ans = cnt_one-cnt, l=0, r=cnt_one;\n for(int i=0; i+cnt_one<n; i++){\n //cout << cnt << \" \" << l << \" \" << r << \" \" << i << \"\\n\"; \n if(arr[l++])\n cnt -= 1;\n if(arr[r++])\n cnt += 1;\n ans = min(ans, cnt_one-cnt);\n //cout << cnt << \" \" << ans << \"\\n\";\n }\n return ans;\n}"
},
{
"code": null,
"e": 3289,
"s": 3286,
"text": "+1"
},
{
"code": null,
"e": 3312,
"s": 3289,
"text": "imranwahid5 months ago"
},
{
"code": null,
"e": 3330,
"s": 3312,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 3332,
"s": 3330,
"text": "0"
},
{
"code": null,
"e": 3344,
"s": 3332,
"text": "tonyapstark"
},
{
"code": null,
"e": 3370,
"s": 3344,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3372,
"s": 3370,
"text": "0"
},
{
"code": null,
"e": 3397,
"s": 3372,
"text": "VickySam19017 months ago"
},
{
"code": null,
"e": 3410,
"s": 3397,
"text": "VickySam1901"
},
{
"code": null,
"e": 3509,
"s": 3410,
"text": "Time Complexity: O(N).Auxiliary Space: O(1).Sliding Window Approach https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 3512,
"s": 3509,
"text": "-1"
},
{
"code": null,
"e": 3538,
"s": 3512,
"text": "aditya anand10 months ago"
},
{
"code": null,
"e": 3551,
"s": 3538,
"text": "aditya anand"
},
{
"code": null,
"e": 3909,
"s": 3551,
"text": "Elegant Python3 Solutiondef minSwaps (arr, n) : total_ones=arr.count(1) temp_ones,max_ones=arr[:total_ones].count(1),0 max_ones=temp_ones for i in range(total_ones,n): if arr[i]==1: temp_ones+=1 if arr[i-total_ones]==1: temp_ones-=1 max_ones=max(max_ones,temp_ones) return total_ones-max_ones if total_ones>0 else -1 "
},
{
"code": null,
"e": 3911,
"s": 3909,
"text": "0"
},
{
"code": null,
"e": 3927,
"s": 3911,
"text": "PK11 months ago"
},
{
"code": null,
"e": 3930,
"s": 3927,
"text": "PK"
},
{
"code": null,
"e": 3961,
"s": 3930,
"text": "int minSwaps(int a[], int n) {"
},
{
"code": null,
"e": 4328,
"s": 3961,
"text": " int tcount_one=0; for(int i=0;i<n;i++) {=\"\" tcount_one+=\"a[i];\" }=\"\" if(tcount_one=\"=0)\" {=\"\" return=\"\" -1;=\"\" }=\"\" int=\"\" count=\"0,max_count=0,i=0,j=0;\" while(j<n)=\"\" {=\"\" count+=\"a[j];\" if((j-i+1)=\"=\" tcount_one)=\"\" {=\"\" max_count=\"max(max_count,count);\" if(a[i]=\"=1)\" {=\"\" count--;=\"\" }=\"\" i++;=\"\" }=\"\" j++;=\"\" }=\"\" return=\"\" tcount_one-max_count;=\"\" }=\"\">"
},
{
"code": null,
"e": 4330,
"s": 4328,
"text": "0"
},
{
"code": null,
"e": 4354,
"s": 4330,
"text": "prerna singh2 years ago"
},
{
"code": null,
"e": 4367,
"s": 4354,
"text": "prerna singh"
},
{
"code": null,
"e": 4403,
"s": 4367,
"text": "It gives incorrect output for this:"
},
{
"code": null,
"e": 4463,
"s": 4403,
"text": "291 0 0 1 0 1 1 0 0 1 0 0 0 0 1 0 1 0 0 0 0 1 1 1 1 0 1 1 1"
},
{
"code": null,
"e": 4563,
"s": 4463,
"text": "I do it in my ide it gives 6 which is correct. But while submitting code here, it gives 3 as output"
},
{
"code": null,
"e": 4709,
"s": 4563,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4745,
"s": 4709,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4755,
"s": 4745,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4765,
"s": 4755,
"text": "\nContest\n"
},
{
"code": null,
"e": 4828,
"s": 4765,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4976,
"s": 4828,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5184,
"s": 4976,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5290,
"s": 5184,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How can I get the output of a Matplotlib plot as an SVG?
|
Just using the savefig method of the pyplot package and mentioning the file format, we can save the output as a SVG format.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create xpoints and ypoints using np.array(0, 5).
Create xpoints and ypoints using np.array(0, 5).
Plot lines using xpoints and ypoints.
Plot lines using xpoints and ypoints.
Set the X-axis label using plt.xlabel() method.
Set the X-axis label using plt.xlabel() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format="svg".
To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format="svg".
To show the image, use plt.show() method.
To show the image, use plt.show() method.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
xpoints = np.array([0, 5])
ypoints = np.array([0, 5])
plt.plot(xpoints, ypoints)
plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")
image_format = 'svg' # e.g .png, .svg, etc.
image_name = 'myimage.svg'
fig.savefig(image_name, format=image_format, dpi=1200)
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Just using the savefig method of the pyplot package and mentioning the file format, we can save the output as a SVG format."
},
{
"code": null,
"e": 1274,
"s": 1186,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1362,
"s": 1274,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1411,
"s": 1362,
"text": "Create xpoints and ypoints using np.array(0, 5)."
},
{
"code": null,
"e": 1460,
"s": 1411,
"text": "Create xpoints and ypoints using np.array(0, 5)."
},
{
"code": null,
"e": 1498,
"s": 1460,
"text": "Plot lines using xpoints and ypoints."
},
{
"code": null,
"e": 1536,
"s": 1498,
"text": "Plot lines using xpoints and ypoints."
},
{
"code": null,
"e": 1584,
"s": 1536,
"text": "Set the X-axis label using plt.xlabel() method."
},
{
"code": null,
"e": 1632,
"s": 1584,
"text": "Set the X-axis label using plt.xlabel() method."
},
{
"code": null,
"e": 1680,
"s": 1632,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 1728,
"s": 1680,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 1831,
"s": 1728,
"text": "To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format=\"svg\"."
},
{
"code": null,
"e": 1934,
"s": 1831,
"text": "To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format=\"svg\"."
},
{
"code": null,
"e": 1976,
"s": 1934,
"text": "To show the image, use plt.show() method."
},
{
"code": null,
"e": 2018,
"s": 1976,
"text": "To show the image, use plt.show() method."
},
{
"code": null,
"e": 2349,
"s": 2018,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nfig, ax = plt.subplots()\nxpoints = np.array([0, 5])\nypoints = np.array([0, 5])\nplt.plot(xpoints, ypoints)\n\nplt.ylabel(\"Y-axis \")\nplt.xlabel(\"X-axis \")\n\nimage_format = 'svg' # e.g .png, .svg, etc.\nimage_name = 'myimage.svg'\n\nfig.savefig(image_name, format=image_format, dpi=1200)"
}
] |
“roc_auc_score” Can Be Calculated Also for Regression Models | by Samuele Mazzanti | Towards Data Science
|
You work as a data scientist for an auction company, and your boss asks you to build a model to predict the hammer price (i.e. the final selling price) of the items on sale. Such a model will serve two purposes:
setting a meaningful opening bid for each item;placing the most expensive items at periodic intervals during the auction. In this way, you will keep up the attention of the audience.
setting a meaningful opening bid for each item;
placing the most expensive items at periodic intervals during the auction. In this way, you will keep up the attention of the audience.
Since you want to predict a point value (in $), you decide to use a regression model (for instance, XGBRegressor()). Now, how do you evaluate the performance of your model?
Let’s see Scikit’s metric toolbox for regression models:
All these metrics seek to quantify how far model predictions are from the actual values. In fact, if you take a look at their formulas, you will always find this quantity:
In other words, these metrics are great for evaluating the ability to get close to the true prices (1st objective). But they are useless for assessing the 2nd objective, which is the ability to rank the items from the most to the least expensive.
Want an example? Let’s say that the first version of your model delivers these results:
y_true = [1000.0, 2000.0, 3000.0, 4000.0, 5000.0]y_pred = [1100.0, 1300.0, 4000.0, 4800.0, 5200.0]
Graphically,
If we take mean_absolute_error(y_true, y_pred), we get 560$, which is probably not so good. However, the ranking is perfect! This means that the model is perfectly capable to discern which items will be auctioned at higher prices.
This is a very important information about our model, that we wouldn’t sense from the other regression metrics. But how could we measure the ability to rank of a regression model?
The most popular metric for assessing the ability to rank of a predictive model is roc_auc_score. So, let’s try to compute it with our data...
We get an error!
This happens because roc_auc_score works only with classification models, either one class versus rest (“ovr”) or one versus one (“ovo”). Scikit-learn expects to find discrete classes into y_true and y_pred, while we are passing continuous values.
For this reason, we need to extend the concept of roc_auc_score to regression problems. We will call such a metric regression_roc_auc_score. In the next paragraph, we will understand how to compute it.
Intuitively, regression_roc_auc_score shall have the following properties:
Exactly like roc_auc_score, it should be bounded between 0 (worst possible ranking) and 1 (best possible ranking), with 0.5 indicating random ranking.
When the target variable is binary, regression_roc_auc_score must give the same outcome of roc_auc_score (in this way, this metric will be a generalization of roc_auc_score).
Now, how to obtain the metric we are looking for?
roc_auc_score is defined as the area under the ROC curve, which is the curve having False Positive Rate on the x-axis and True Positive Rate on the y-axis at all classification thresholds. But it’s impossible to calculate FPR and TPR for regression methods, so we cannot take this road.
Luckily for us, there is an alternative definition. In fact, according to Wikipedia, roc_auc_score coincides with “the probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one”.
In other words, if we take any two observations a and b such that a > b, then roc_auc_score is equal to the probability that our model actually ranks a higher than b.
This definition is much more useful for us, because it makes sense also for regression (in fact a and b may not be restricted to be 0 or 1, they could assume any continuous value);
Moreover, calculating roc_auc_score is far easier now. In fact, it boils down to consider each possible pair of items a and b, such that a > b, and count how many times the value predicted by our model for a is actually higher than the value predicted for b (eventual ties will be counted half). Then, roc_auc_score is simply the number of successes divided by the total number of pairs.
In Python, this would be:
In order to make sure that the definition provided by Wikipedia is reliable, let’s compare our function naive_roc_auc_score with the outcome of Scikit-learn.
Great!
As said above— unlike Scikit-learn’s roc_auc_score— this version works also with continuous target variables. Let’s give it a try:
The output is exactly what we expected. The ranking is perfect and therefore roc_auc_score equals 1.
Everything looks great, but the implementation above is a bit naive. In fact, naive_roc_auc_score evaluates every possible pair of observations. Thus, it requires O(n2) iterations (where n is the number of samples), and it becomes unusable as soon as n becomes a little bigger.
However, if we do not require the “exact” answer, we can obtain a good approximation through bootstrapping. Rather than evaluating every single possible pair (which would mean not less than n*(n+1)/2 pairs), we can use a number of randomly chosen pairs.
This would translate to the following Python code:
regression_roc_auc_score has 3 parameters: y_true, y_pred and num_rounds. If num_rounds is an integer, it is used as the number of random pairs to consider (approximate solution). However, you can also compute the “exact” score (i.e. all possible pairs), by passing the string "exact" to num_rounds.
Are you curious to see the outcome of the function regression_roc_auc_score on a real dataset? I am too, so let’s use it on a classical dataset for regression problems: California Housing from StatLib (the data can be imported directly from Scikit-learn, which is under BSD License).
The target variable is the median house value for California districts. The dataset is made of 20,640 samples and 8 observed features.
from sklearn.datasets import fetch_california_housingfrom sklearn.model_selection import train_test_splitX, y = fetch_california_housing(return_X_y = True, as_frame = True)y *= 100000X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 4321)
Now, let’s try out many different models on the training set and then compute some metrics (including regression_roc_auc_score, defined in the previous paragraph) on the test set.
from sklearn.dummy import DummyRegressorfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.svm import SVRfrom sklearn.neural_network import MLPRegressorfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.ensemble import GradientBoostingRegressorfrom xgboost import XGBRegressorfrom catboost import CatBoostRegressorfrom sklearn.metrics import mean_absolute_error, median_absolute_error, roc_auc_score, r2_score, explained_variance_scoremodelnames = [ ‘DummyRegressor()’, ‘KNeighborsRegressor()’, ‘LinearRegression()’, ‘SVR()’, ‘MLPRegressor(hidden_layer_sizes = (16, 16))’, ‘DecisionTreeRegressor()’, ‘GradientBoostingRegressor()’, ‘XGBRegressor()’, ‘CatBoostRegressor()’]metricnames = [ ‘mean_absolute_error’, ‘median_absolute_error’, ‘r2_score’, ‘explained_variance_score’, ‘regression_roc_auc_score’]metrics = pd.DataFrame(index = modelnames, columns = metricnames)for modelname in modelnames: model = eval(modelname) pred_test = model.fit(X_train, y_train).predict(X_test) for metricname in metricnames: metrics.loc[modelname, metricname] = eval(f'{metricname}(y_test, pred_test)')
The following plot compares regression_roc_auc_score to mean_absolute_error for all the trained models:
As we could have been expected, the two metrics are inversely correlated. Of course, a lower mean_absolute_error tends to be associated with a higher regression_roc_auc_score .
The latter metric provides additional knowledge about the model performance: after calculating regression_roc_auc_score we can say that the probability that Catboost estimates a higher value for a compared to b, given that a > b, is close to 90%.
Thank you for reading! I hope you enjoyed this article.
I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact.
|
[
{
"code": null,
"e": 384,
"s": 172,
"text": "You work as a data scientist for an auction company, and your boss asks you to build a model to predict the hammer price (i.e. the final selling price) of the items on sale. Such a model will serve two purposes:"
},
{
"code": null,
"e": 567,
"s": 384,
"text": "setting a meaningful opening bid for each item;placing the most expensive items at periodic intervals during the auction. In this way, you will keep up the attention of the audience."
},
{
"code": null,
"e": 615,
"s": 567,
"text": "setting a meaningful opening bid for each item;"
},
{
"code": null,
"e": 751,
"s": 615,
"text": "placing the most expensive items at periodic intervals during the auction. In this way, you will keep up the attention of the audience."
},
{
"code": null,
"e": 924,
"s": 751,
"text": "Since you want to predict a point value (in $), you decide to use a regression model (for instance, XGBRegressor()). Now, how do you evaluate the performance of your model?"
},
{
"code": null,
"e": 981,
"s": 924,
"text": "Let’s see Scikit’s metric toolbox for regression models:"
},
{
"code": null,
"e": 1153,
"s": 981,
"text": "All these metrics seek to quantify how far model predictions are from the actual values. In fact, if you take a look at their formulas, you will always find this quantity:"
},
{
"code": null,
"e": 1400,
"s": 1153,
"text": "In other words, these metrics are great for evaluating the ability to get close to the true prices (1st objective). But they are useless for assessing the 2nd objective, which is the ability to rank the items from the most to the least expensive."
},
{
"code": null,
"e": 1488,
"s": 1400,
"text": "Want an example? Let’s say that the first version of your model delivers these results:"
},
{
"code": null,
"e": 1587,
"s": 1488,
"text": "y_true = [1000.0, 2000.0, 3000.0, 4000.0, 5000.0]y_pred = [1100.0, 1300.0, 4000.0, 4800.0, 5200.0]"
},
{
"code": null,
"e": 1600,
"s": 1587,
"text": "Graphically,"
},
{
"code": null,
"e": 1831,
"s": 1600,
"text": "If we take mean_absolute_error(y_true, y_pred), we get 560$, which is probably not so good. However, the ranking is perfect! This means that the model is perfectly capable to discern which items will be auctioned at higher prices."
},
{
"code": null,
"e": 2011,
"s": 1831,
"text": "This is a very important information about our model, that we wouldn’t sense from the other regression metrics. But how could we measure the ability to rank of a regression model?"
},
{
"code": null,
"e": 2154,
"s": 2011,
"text": "The most popular metric for assessing the ability to rank of a predictive model is roc_auc_score. So, let’s try to compute it with our data..."
},
{
"code": null,
"e": 2171,
"s": 2154,
"text": "We get an error!"
},
{
"code": null,
"e": 2419,
"s": 2171,
"text": "This happens because roc_auc_score works only with classification models, either one class versus rest (“ovr”) or one versus one (“ovo”). Scikit-learn expects to find discrete classes into y_true and y_pred, while we are passing continuous values."
},
{
"code": null,
"e": 2621,
"s": 2419,
"text": "For this reason, we need to extend the concept of roc_auc_score to regression problems. We will call such a metric regression_roc_auc_score. In the next paragraph, we will understand how to compute it."
},
{
"code": null,
"e": 2696,
"s": 2621,
"text": "Intuitively, regression_roc_auc_score shall have the following properties:"
},
{
"code": null,
"e": 2847,
"s": 2696,
"text": "Exactly like roc_auc_score, it should be bounded between 0 (worst possible ranking) and 1 (best possible ranking), with 0.5 indicating random ranking."
},
{
"code": null,
"e": 3022,
"s": 2847,
"text": "When the target variable is binary, regression_roc_auc_score must give the same outcome of roc_auc_score (in this way, this metric will be a generalization of roc_auc_score)."
},
{
"code": null,
"e": 3072,
"s": 3022,
"text": "Now, how to obtain the metric we are looking for?"
},
{
"code": null,
"e": 3359,
"s": 3072,
"text": "roc_auc_score is defined as the area under the ROC curve, which is the curve having False Positive Rate on the x-axis and True Positive Rate on the y-axis at all classification thresholds. But it’s impossible to calculate FPR and TPR for regression methods, so we cannot take this road."
},
{
"code": null,
"e": 3599,
"s": 3359,
"text": "Luckily for us, there is an alternative definition. In fact, according to Wikipedia, roc_auc_score coincides with “the probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one”."
},
{
"code": null,
"e": 3766,
"s": 3599,
"text": "In other words, if we take any two observations a and b such that a > b, then roc_auc_score is equal to the probability that our model actually ranks a higher than b."
},
{
"code": null,
"e": 3947,
"s": 3766,
"text": "This definition is much more useful for us, because it makes sense also for regression (in fact a and b may not be restricted to be 0 or 1, they could assume any continuous value);"
},
{
"code": null,
"e": 4335,
"s": 3947,
"text": "Moreover, calculating roc_auc_score is far easier now. In fact, it boils down to consider each possible pair of items a and b, such that a > b, and count how many times the value predicted by our model for a is actually higher than the value predicted for b (eventual ties will be counted half). Then, roc_auc_score is simply the number of successes divided by the total number of pairs."
},
{
"code": null,
"e": 4361,
"s": 4335,
"text": "In Python, this would be:"
},
{
"code": null,
"e": 4519,
"s": 4361,
"text": "In order to make sure that the definition provided by Wikipedia is reliable, let’s compare our function naive_roc_auc_score with the outcome of Scikit-learn."
},
{
"code": null,
"e": 4526,
"s": 4519,
"text": "Great!"
},
{
"code": null,
"e": 4657,
"s": 4526,
"text": "As said above— unlike Scikit-learn’s roc_auc_score— this version works also with continuous target variables. Let’s give it a try:"
},
{
"code": null,
"e": 4758,
"s": 4657,
"text": "The output is exactly what we expected. The ranking is perfect and therefore roc_auc_score equals 1."
},
{
"code": null,
"e": 5036,
"s": 4758,
"text": "Everything looks great, but the implementation above is a bit naive. In fact, naive_roc_auc_score evaluates every possible pair of observations. Thus, it requires O(n2) iterations (where n is the number of samples), and it becomes unusable as soon as n becomes a little bigger."
},
{
"code": null,
"e": 5290,
"s": 5036,
"text": "However, if we do not require the “exact” answer, we can obtain a good approximation through bootstrapping. Rather than evaluating every single possible pair (which would mean not less than n*(n+1)/2 pairs), we can use a number of randomly chosen pairs."
},
{
"code": null,
"e": 5341,
"s": 5290,
"text": "This would translate to the following Python code:"
},
{
"code": null,
"e": 5641,
"s": 5341,
"text": "regression_roc_auc_score has 3 parameters: y_true, y_pred and num_rounds. If num_rounds is an integer, it is used as the number of random pairs to consider (approximate solution). However, you can also compute the “exact” score (i.e. all possible pairs), by passing the string \"exact\" to num_rounds."
},
{
"code": null,
"e": 5925,
"s": 5641,
"text": "Are you curious to see the outcome of the function regression_roc_auc_score on a real dataset? I am too, so let’s use it on a classical dataset for regression problems: California Housing from StatLib (the data can be imported directly from Scikit-learn, which is under BSD License)."
},
{
"code": null,
"e": 6060,
"s": 5925,
"text": "The target variable is the median house value for California districts. The dataset is made of 20,640 samples and 8 observed features."
},
{
"code": null,
"e": 6340,
"s": 6060,
"text": "from sklearn.datasets import fetch_california_housingfrom sklearn.model_selection import train_test_splitX, y = fetch_california_housing(return_X_y = True, as_frame = True)y *= 100000X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 4321)"
},
{
"code": null,
"e": 6520,
"s": 6340,
"text": "Now, let’s try out many different models on the training set and then compute some metrics (including regression_roc_auc_score, defined in the previous paragraph) on the test set."
},
{
"code": null,
"e": 7683,
"s": 6520,
"text": "from sklearn.dummy import DummyRegressorfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.svm import SVRfrom sklearn.neural_network import MLPRegressorfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.ensemble import GradientBoostingRegressorfrom xgboost import XGBRegressorfrom catboost import CatBoostRegressorfrom sklearn.metrics import mean_absolute_error, median_absolute_error, roc_auc_score, r2_score, explained_variance_scoremodelnames = [ ‘DummyRegressor()’, ‘KNeighborsRegressor()’, ‘LinearRegression()’, ‘SVR()’, ‘MLPRegressor(hidden_layer_sizes = (16, 16))’, ‘DecisionTreeRegressor()’, ‘GradientBoostingRegressor()’, ‘XGBRegressor()’, ‘CatBoostRegressor()’]metricnames = [ ‘mean_absolute_error’, ‘median_absolute_error’, ‘r2_score’, ‘explained_variance_score’, ‘regression_roc_auc_score’]metrics = pd.DataFrame(index = modelnames, columns = metricnames)for modelname in modelnames: model = eval(modelname) pred_test = model.fit(X_train, y_train).predict(X_test) for metricname in metricnames: metrics.loc[modelname, metricname] = eval(f'{metricname}(y_test, pred_test)')"
},
{
"code": null,
"e": 7787,
"s": 7683,
"text": "The following plot compares regression_roc_auc_score to mean_absolute_error for all the trained models:"
},
{
"code": null,
"e": 7964,
"s": 7787,
"text": "As we could have been expected, the two metrics are inversely correlated. Of course, a lower mean_absolute_error tends to be associated with a higher regression_roc_auc_score ."
},
{
"code": null,
"e": 8211,
"s": 7964,
"text": "The latter metric provides additional knowledge about the model performance: after calculating regression_roc_auc_score we can say that the probability that Catboost estimates a higher value for a compared to b, given that a > b, is close to 90%."
},
{
"code": null,
"e": 8267,
"s": 8211,
"text": "Thank you for reading! I hope you enjoyed this article."
}
] |
Program to find smallest intersecting element of each row in a matrix in Python
|
Suppose we have a 2D matrix where each row is sorted in ascending order. We have to find the smallest number that exists in every row. If there's no such result, then return −1.
So, if the input is like
then the output will be 5
To solve this, we will follow these steps −
if matrix is empty, thenreturn −1
if matrix is empty, then
return −1
return −1
first := a new set from first row of matrix
first := a new set from first row of matrix
for each row in matrix, dofirst := Intersect first a set of elements of rowif first is empty, thenreturn −1
for each row in matrix, do
first := Intersect first a set of elements of row
first := Intersect first a set of elements of row
if first is empty, thenreturn −1
if first is empty, then
return −1
return −1
return minimum of first
return minimum of first
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, matrix):
if not matrix:
return -1
first = set(matrix[0])
for row in matrix:
first &= set(row)
if not first:
return -1
return min(first)
ob1 = Solution()
matrix = [
[2, 3, 5],
[5, 10, 10],
[1, 3, 5]
]
print(ob1.solve(matrix))
matrix = [
[2, 3, 5],
[5, 10, 10],
[1, 3, 5] ]
5
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "Suppose we have a 2D matrix where each row is sorted in ascending order. We have to find the smallest number that exists in every row. If there's no such result, then return −1."
},
{
"code": null,
"e": 1265,
"s": 1240,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1291,
"s": 1265,
"text": "then the output will be 5"
},
{
"code": null,
"e": 1335,
"s": 1291,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1369,
"s": 1335,
"text": "if matrix is empty, thenreturn −1"
},
{
"code": null,
"e": 1394,
"s": 1369,
"text": "if matrix is empty, then"
},
{
"code": null,
"e": 1404,
"s": 1394,
"text": "return −1"
},
{
"code": null,
"e": 1414,
"s": 1404,
"text": "return −1"
},
{
"code": null,
"e": 1458,
"s": 1414,
"text": "first := a new set from first row of matrix"
},
{
"code": null,
"e": 1502,
"s": 1458,
"text": "first := a new set from first row of matrix"
},
{
"code": null,
"e": 1610,
"s": 1502,
"text": "for each row in matrix, dofirst := Intersect first a set of elements of rowif first is empty, thenreturn −1"
},
{
"code": null,
"e": 1637,
"s": 1610,
"text": "for each row in matrix, do"
},
{
"code": null,
"e": 1687,
"s": 1637,
"text": "first := Intersect first a set of elements of row"
},
{
"code": null,
"e": 1737,
"s": 1687,
"text": "first := Intersect first a set of elements of row"
},
{
"code": null,
"e": 1770,
"s": 1737,
"text": "if first is empty, thenreturn −1"
},
{
"code": null,
"e": 1794,
"s": 1770,
"text": "if first is empty, then"
},
{
"code": null,
"e": 1804,
"s": 1794,
"text": "return −1"
},
{
"code": null,
"e": 1814,
"s": 1804,
"text": "return −1"
},
{
"code": null,
"e": 1838,
"s": 1814,
"text": "return minimum of first"
},
{
"code": null,
"e": 1862,
"s": 1838,
"text": "return minimum of first"
},
{
"code": null,
"e": 1932,
"s": 1862,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1943,
"s": 1932,
"text": " Live Demo"
},
{
"code": null,
"e": 2275,
"s": 1943,
"text": "class Solution:\n def solve(self, matrix):\n if not matrix:\n return -1\n first = set(matrix[0])\n for row in matrix:\n first &= set(row)\n if not first:\n return -1\n return min(first)\nob1 = Solution()\nmatrix = [\n [2, 3, 5],\n [5, 10, 10],\n [1, 3, 5]\n]\nprint(ob1.solve(matrix))"
},
{
"code": null,
"e": 2322,
"s": 2275,
"text": "matrix = [\n[2, 3, 5],\n[5, 10, 10],\n[1, 3, 5] ]"
},
{
"code": null,
"e": 2324,
"s": 2322,
"text": "5"
}
] |
Time Series - Walk Forward Validation
|
In time series modelling, the predictions over time become less and less accurate and hence it is a more realistic approach to re-train the model with actual data as it gets available for further predictions. Since training of statistical models are not time consuming, walk-forward validation is the most preferred solution to get most accurate results.
Let us apply one step walk forward validation on our data and compare it with the results we got earlier.
In [333]:
prediction = []
data = train.values
for t In test.values:
model = (ExponentialSmoothing(data).fit())
y = model.predict()
prediction.append(y[0])
data = numpy.append(data, t)
In [335]:
test_ = pandas.DataFrame(test)
test_['predictionswf'] = prediction
In [341]:
plt.plot(test_['T'])
plt.plot(test_.predictionswf, '--')
plt.show()
In [340]:
error = sqrt(metrics.mean_squared_error(test.values,prediction))
print ('Test RMSE for Triple Exponential Smoothing with Walk-Forward Validation: ', error)
Test RMSE for Triple Exponential Smoothing with Walk-Forward Validation: 11.787532205759442
We can see that our model performs significantly better now. In fact, the trend is followed so closely that on the plot predictions are overlapping with the actual values. You can try applying walk-forward validation on ARIMA models too.
16 Lectures
2 hours
Malhar Lathkar
21 Lectures
2.5 hours
Sasha Miller
19 Lectures
1 hours
Sasha Miller
94 Lectures
13 hours
Abhishek And Pukhraj
12 Lectures
2 hours
Prof. Paul Cline, Ed.D
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2496,
"s": 2141,
"text": "In time series modelling, the predictions over time become less and less accurate and hence it is a more realistic approach to re-train the model with actual data as it gets available for further predictions. Since training of statistical models are not time consuming, walk-forward validation is the most preferred solution to get most accurate results."
},
{
"code": null,
"e": 2602,
"s": 2496,
"text": "Let us apply one step walk forward validation on our data and compare it with the results we got earlier."
},
{
"code": null,
"e": 2612,
"s": 2602,
"text": "In [333]:"
},
{
"code": null,
"e": 2799,
"s": 2612,
"text": "prediction = []\ndata = train.values\nfor t In test.values:\n model = (ExponentialSmoothing(data).fit())\n y = model.predict()\n prediction.append(y[0])\n data = numpy.append(data, t)\n"
},
{
"code": null,
"e": 2809,
"s": 2799,
"text": "In [335]:"
},
{
"code": null,
"e": 2877,
"s": 2809,
"text": "test_ = pandas.DataFrame(test)\ntest_['predictionswf'] = prediction\n"
},
{
"code": null,
"e": 2887,
"s": 2877,
"text": "In [341]:"
},
{
"code": null,
"e": 2956,
"s": 2887,
"text": "plt.plot(test_['T'])\nplt.plot(test_.predictionswf, '--')\nplt.show()\n"
},
{
"code": null,
"e": 2966,
"s": 2956,
"text": "In [340]:"
},
{
"code": null,
"e": 3216,
"s": 2966,
"text": "error = sqrt(metrics.mean_squared_error(test.values,prediction))\nprint ('Test RMSE for Triple Exponential Smoothing with Walk-Forward Validation: ', error)\nTest RMSE for Triple Exponential Smoothing with Walk-Forward Validation: 11.787532205759442\n"
},
{
"code": null,
"e": 3454,
"s": 3216,
"text": "We can see that our model performs significantly better now. In fact, the trend is followed so closely that on the plot predictions are overlapping with the actual values. You can try applying walk-forward validation on ARIMA models too."
},
{
"code": null,
"e": 3487,
"s": 3454,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3503,
"s": 3487,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3538,
"s": 3503,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3552,
"s": 3538,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3585,
"s": 3552,
"text": "\n 19 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3599,
"s": 3585,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3633,
"s": 3599,
"text": "\n 94 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3655,
"s": 3633,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3688,
"s": 3655,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3712,
"s": 3688,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3745,
"s": 3712,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3769,
"s": 3745,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3776,
"s": 3769,
"text": " Print"
},
{
"code": null,
"e": 3787,
"s": 3776,
"text": " Add Notes"
}
] |
Does HTML5 Canvas support Double Buffering?
|
For double buffering on the canvas, create a 2nd canvas element and draw to it. After that draw the image to the first canvas using the drawImage() method,
// canvas element
var canvas1 = document.getElementById('canvas');
var context1 = canvas1.getContext('2d');
// buffer canvas
var canvas2 = document.createElement('canvas');
canvas2.width = 250;
canvas2.height =250;
var context2 = canvas2.getContext('2d');
// create on the canvas
context2.beginPath();
context2.moveTo(10,10);
context2.lineTo(10,30);
context2.stroke();
//render the buffered canvas
context1.drawImage(canvas2, 0, 0);
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "For double buffering on the canvas, create a 2nd canvas element and draw to it. After that draw the image to the first canvas using the drawImage() method,"
},
{
"code": null,
"e": 1654,
"s": 1218,
"text": "// canvas element\nvar canvas1 = document.getElementById('canvas');\nvar context1 = canvas1.getContext('2d');\n\n// buffer canvas\nvar canvas2 = document.createElement('canvas');\ncanvas2.width = 250;\ncanvas2.height =250;\nvar context2 = canvas2.getContext('2d');\n\n// create on the canvas\ncontext2.beginPath();\ncontext2.moveTo(10,10);\ncontext2.lineTo(10,30);\ncontext2.stroke();\n\n//render the buffered canvas\ncontext1.drawImage(canvas2, 0, 0);"
}
] |
How to change the size of a bootstrap pill badge? - GeeksforGeeks
|
27 Nov, 2020
Given an HTML document having pill badges (In case if you don’t know what a pill badge then refer to this ) and the task is to increase the size of the badge. There can be three approaches to do that. The approaches are discussed below:-
Approach 1: Using Inline styling: You can simply add a style attribute to the span tag which has badge-pill as a class and change the font-size according to your wish.
Example:
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"></head> <body> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class="badge badge-pill badge-primary"> </span> <h3> Size of Pill badge after using Approach 1st </h3> <span class="badge badge-pill badge-primary" style="font-size:2rem;"> </span></body> </html>
Output:
Approach 2: Embedding the badge inside the heading tag: We can also wrap the span tag of the badge in a different heading tags to achieve the desired result.
Example:
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"></head> <body> <div class="example"> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class="badge badge-pill badge-primary"> </span> <h3> Different Sizes of Pill badge after using Approach 2nd </h3> <h4>h1 tag</h4> <h1><span class="badge badge-pill badge-primary"> </span> </h1> <h4>h2 tag</h4> <h2><span class="badge badge-pill badge-primary"> </span> </h2> <h4>h3 tag</h4> <h3><span class="badge badge-pill badge-primary"> </span> </h3> <h4>h4 tag</h4> <h4><span class="badge badge-pill badge-primary"> </span> </h4> <h4>h5 tag</h4> <h5><span class="badge badge-pill badge-primary"> </span> </h5> <h4>h6 tag</h4> <h6><span class="badge badge-pill badge-primary"> </span> </h6> </div></body> </html>
Output:
Approach 3: By overriding the class using Internal/External CSS: We can also add our own custom class name for the badge and in the CSS file, we can update the font-size property to achieve the desired result.
Example:
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css"> <style> .increase-size { font-size: 2rem; } </style></head> <body> <div class="example"> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class="badge badge-pill badge-primary"> </span> <h3> Size of Pill badge after using Approach 3nd </h3> <span class="badge badge-pill badge-primary increase-size"> </span> </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.
Bootstrap-Misc
HTML-Misc
Picked
Technical Scripter 2020
Bootstrap
HTML
Technical Scripter
Web Technologies
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 set Bootstrap Timepicker using datetimepicker library ?
How to change the background color of the active nav-item?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 24496,
"s": 24468,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 24734,
"s": 24496,
"text": "Given an HTML document having pill badges (In case if you don’t know what a pill badge then refer to this ) and the task is to increase the size of the badge. There can be three approaches to do that. The approaches are discussed below:-"
},
{
"code": null,
"e": 24902,
"s": 24734,
"text": "Approach 1: Using Inline styling: You can simply add a style attribute to the span tag which has badge-pill as a class and change the font-size according to your wish."
},
{
"code": null,
"e": 24911,
"s": 24902,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css\"></head> <body> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class=\"badge badge-pill badge-primary\"> </span> <h3> Size of Pill badge after using Approach 1st </h3> <span class=\"badge badge-pill badge-primary\" style=\"font-size:2rem;\"> </span></body> </html>",
"e": 25429,
"s": 24911,
"text": null
},
{
"code": null,
"e": 25437,
"s": 25429,
"text": "Output:"
},
{
"code": null,
"e": 25595,
"s": 25437,
"text": "Approach 2: Embedding the badge inside the heading tag: We can also wrap the span tag of the badge in a different heading tags to achieve the desired result."
},
{
"code": null,
"e": 25604,
"s": 25595,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css\"></head> <body> <div class=\"example\"> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class=\"badge badge-pill badge-primary\"> </span> <h3> Different Sizes of Pill badge after using Approach 2nd </h3> <h4>h1 tag</h4> <h1><span class=\"badge badge-pill badge-primary\"> </span> </h1> <h4>h2 tag</h4> <h2><span class=\"badge badge-pill badge-primary\"> </span> </h2> <h4>h3 tag</h4> <h3><span class=\"badge badge-pill badge-primary\"> </span> </h3> <h4>h4 tag</h4> <h4><span class=\"badge badge-pill badge-primary\"> </span> </h4> <h4>h5 tag</h4> <h5><span class=\"badge badge-pill badge-primary\"> </span> </h5> <h4>h6 tag</h4> <h6><span class=\"badge badge-pill badge-primary\"> </span> </h6> </div></body> </html>",
"e": 26847,
"s": 25604,
"text": null
},
{
"code": null,
"e": 26855,
"s": 26847,
"text": "Output:"
},
{
"code": null,
"e": 27065,
"s": 26855,
"text": "Approach 3: By overriding the class using Internal/External CSS: We can also add our own custom class name for the badge and in the CSS file, we can update the font-size property to achieve the desired result."
},
{
"code": null,
"e": 27074,
"s": 27065,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css\"> <style> .increase-size { font-size: 2rem; } </style></head> <body> <div class=\"example\"> <h3> Size of Pill badge Simple Bootstrap Code </h3> <span class=\"badge badge-pill badge-primary\"> </span> <h3> Size of Pill badge after using Approach 3nd </h3> <span class=\"badge badge-pill badge-primary increase-size\"> </span> </div></body> </html>",
"e": 27772,
"s": 27074,
"text": null
},
{
"code": null,
"e": 27780,
"s": 27772,
"text": "Output:"
},
{
"code": null,
"e": 27917,
"s": 27780,
"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": 27932,
"s": 27917,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 27942,
"s": 27932,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27949,
"s": 27942,
"text": "Picked"
},
{
"code": null,
"e": 27973,
"s": 27949,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27983,
"s": 27973,
"text": "Bootstrap"
},
{
"code": null,
"e": 27988,
"s": 27983,
"text": "HTML"
},
{
"code": null,
"e": 28007,
"s": 27988,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28024,
"s": 28007,
"text": "Web Technologies"
},
{
"code": null,
"e": 28029,
"s": 28024,
"text": "HTML"
},
{
"code": null,
"e": 28127,
"s": 28029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28168,
"s": 28127,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 28231,
"s": 28168,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 28290,
"s": 28231,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 28323,
"s": 28290,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 28370,
"s": 28323,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 28420,
"s": 28370,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28482,
"s": 28420,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28542,
"s": 28482,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28590,
"s": 28542,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Elo Rating Algorithm in C++
|
Elo Rating Algorithm is a rating algorithm used to rank players in competitive games. The ranking of player of the competition is based on ranting which changes based on the performance of the player as follows,
For a game between two players of different ratings. Let’s say there are two players competing against each other−
Rating of player1 is greater than player2.
If player1 wins the game some player will be transferred from player1 to player2 and vice versa if player2 wins.
But the amount of rating to be transferred for victory is not constant. Instead it is dependent on the person winning the game,
If player1 wins the game, points transferred is less.If player2 wins the game, points transferred is more.
The amount of points transferred is dependent on the formula,
For player1,
New rating = old Rating + ratingConstant * (successProb - P1)
For player2,
New rating = old Rating + ratingConstant * (successProb - P2)
Here,
ratingConstant is a constant, it is decided by the gaming community.
P1, probability of player1 winning.P2, probability of player2 winning.
Rating1 is the rating of player1.Rating2 is the rating of player2.
If a player wins the successProb is 1 otherwise its 0.
Input: rating1 = 782, rating2 = 1432,ratingConstant = 100, player1 wins the game.
Output: rating1 = 780, rating2 = 1434
Explanation −
Player1 wins,
For player1,
successProb = 1
New rating = 782 + 100*(1 - 0.98) = 782 + 100*(0.02) = 782 + 2 = 784
For player2,
successProb = 0
New rating = 1432 + 100*(0 - 0.02) = 1432 - 2 = 1430
Live Demo
#include <bits/stdc++.h>
using namespace std;
void updateRatingUsingELoRating(float rating1, float rating2, int ratingConstant, bool player1SuccessProb) {
float P1, P2;
if(rating1 > rating2){
P1 = (1.0 / (1.0 + pow(10.0, ((rating1 - rating2) / 400.0)) ) );
P2 = 1 - P1;
}
else {
P2 = (1.0 / (1.0 + pow(10.0, ((rating2 - rating1) / 400.0)) ) );
P1 = 1 - P2;
}
if (player1SuccessProb == 1) {
rating1 = rating1 + ratingConstant * (1 - P1);
rating2 = rating2 + ratingConstant * (0 - P2);
}
else {
rating1 = rating1 + ratingConstant * (0 - P1);
rating1 = rating1 + ratingConstant * (1 - P2);
}
cout<<"Ratings After the game\n";
cout<<"Player 1 : "<<rating1<<"\t Player 2 : "<<rating2;
}
int main()
{
float rating1 = 782, rating2 = 1432;
int ratingConstant = 100;
bool player1SuccessProb = 1;
cout<<"Ratings before the game: \n";
cout<<"Player 1 : "<<rating1<<"\t Player 2 : "<<rating2<<endl;
if(player1SuccessProb)
cout<<"Player 1 wins the game!\n";
else
cout<<"Player 2 wins the game!\n";
updateRatingUsingELoRating(rating1, rating2, ratingConstant, player1SuccessProb);
return 0;
}
Ratings before the game:
Player 1 : 782 Player 2 : 1432
Player 1 wins the game!
Ratings After the game
Player 1 : 784.316 Player 2 : 1429.68
|
[
{
"code": null,
"e": 1274,
"s": 1062,
"text": "Elo Rating Algorithm is a rating algorithm used to rank players in competitive games. The ranking of player of the competition is based on ranting which changes based on the performance of the player as follows,"
},
{
"code": null,
"e": 1389,
"s": 1274,
"text": "For a game between two players of different ratings. Let’s say there are two players competing against each other−"
},
{
"code": null,
"e": 1432,
"s": 1389,
"text": "Rating of player1 is greater than player2."
},
{
"code": null,
"e": 1545,
"s": 1432,
"text": "If player1 wins the game some player will be transferred from player1 to player2 and vice versa if player2 wins."
},
{
"code": null,
"e": 1673,
"s": 1545,
"text": "But the amount of rating to be transferred for victory is not constant. Instead it is dependent on the person winning the game,"
},
{
"code": null,
"e": 1781,
"s": 1673,
"text": "If player1 wins the game, points transferred is less.If player2 wins the game, points transferred is more. "
},
{
"code": null,
"e": 1843,
"s": 1781,
"text": "The amount of points transferred is dependent on the formula,"
},
{
"code": null,
"e": 1856,
"s": 1843,
"text": "For player1,"
},
{
"code": null,
"e": 1918,
"s": 1856,
"text": "New rating = old Rating + ratingConstant * (successProb - P1)"
},
{
"code": null,
"e": 1931,
"s": 1918,
"text": "For player2,"
},
{
"code": null,
"e": 1993,
"s": 1931,
"text": "New rating = old Rating + ratingConstant * (successProb - P2)"
},
{
"code": null,
"e": 1999,
"s": 1993,
"text": "Here,"
},
{
"code": null,
"e": 2068,
"s": 1999,
"text": "ratingConstant is a constant, it is decided by the gaming community."
},
{
"code": null,
"e": 2139,
"s": 2068,
"text": "P1, probability of player1 winning.P2, probability of player2 winning."
},
{
"code": null,
"e": 2206,
"s": 2139,
"text": "Rating1 is the rating of player1.Rating2 is the rating of player2."
},
{
"code": null,
"e": 2261,
"s": 2206,
"text": "If a player wins the successProb is 1 otherwise its 0."
},
{
"code": null,
"e": 2343,
"s": 2261,
"text": "Input: rating1 = 782, rating2 = 1432,ratingConstant = 100, player1 wins the game."
},
{
"code": null,
"e": 2381,
"s": 2343,
"text": "Output: rating1 = 780, rating2 = 1434"
},
{
"code": null,
"e": 2395,
"s": 2381,
"text": "Explanation −"
},
{
"code": null,
"e": 2409,
"s": 2395,
"text": "Player1 wins,"
},
{
"code": null,
"e": 2422,
"s": 2409,
"text": "For player1,"
},
{
"code": null,
"e": 2438,
"s": 2422,
"text": "successProb = 1"
},
{
"code": null,
"e": 2507,
"s": 2438,
"text": "New rating = 782 + 100*(1 - 0.98) = 782 + 100*(0.02) = 782 + 2 = 784"
},
{
"code": null,
"e": 2520,
"s": 2507,
"text": "For player2,"
},
{
"code": null,
"e": 2536,
"s": 2520,
"text": "successProb = 0"
},
{
"code": null,
"e": 2589,
"s": 2536,
"text": "New rating = 1432 + 100*(0 - 0.02) = 1432 - 2 = 1430"
},
{
"code": null,
"e": 2599,
"s": 2589,
"text": "Live Demo"
},
{
"code": null,
"e": 3804,
"s": 2599,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid updateRatingUsingELoRating(float rating1, float rating2, int ratingConstant, bool player1SuccessProb) {\n\n float P1, P2;\n if(rating1 > rating2){\n P1 = (1.0 / (1.0 + pow(10.0, ((rating1 - rating2) / 400.0)) ) );\n P2 = 1 - P1;\n }\n else {\n P2 = (1.0 / (1.0 + pow(10.0, ((rating2 - rating1) / 400.0)) ) );\n P1 = 1 - P2;\n }\n\n if (player1SuccessProb == 1) {\n rating1 = rating1 + ratingConstant * (1 - P1);\n rating2 = rating2 + ratingConstant * (0 - P2);\n }\n else {\n rating1 = rating1 + ratingConstant * (0 - P1);\n rating1 = rating1 + ratingConstant * (1 - P2);\n }\n\n cout<<\"Ratings After the game\\n\";\n cout<<\"Player 1 : \"<<rating1<<\"\\t Player 2 : \"<<rating2;\n}\n\nint main()\n{\n float rating1 = 782, rating2 = 1432;\n int ratingConstant = 100;\n bool player1SuccessProb = 1;\n cout<<\"Ratings before the game: \\n\";\n cout<<\"Player 1 : \"<<rating1<<\"\\t Player 2 : \"<<rating2<<endl;\n if(player1SuccessProb)\n cout<<\"Player 1 wins the game!\\n\";\n else\n cout<<\"Player 2 wins the game!\\n\";\n updateRatingUsingELoRating(rating1, rating2, ratingConstant, player1SuccessProb);\n\n return 0;\n}"
},
{
"code": null,
"e": 3951,
"s": 3804,
"text": "Ratings before the game:\nPlayer 1 : 782 Player 2 : 1432\nPlayer 1 wins the game!\nRatings After the game\nPlayer 1 : 784.316 Player 2 : 1429.68"
}
] |
string.whitespace in Python
|
In this tutorial, we are going to learn about the string.whitespace.
The string whitespace is pre-defined in the string module of Python3. If contains space, tab,
linefeed, return, formfeed, and vertical tab.
Live Demo
# importing the string module
import string
# printing a string
print("Hello")
# whitespace printing
print(string.whitespace)
# printing a string
print('tutorialspoint')
If you run the above code, then you will get the following result.
Hello
tutorialspoint
If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "In this tutorial, we are going to learn about the string.whitespace."
},
{
"code": null,
"e": 1271,
"s": 1131,
"text": "The string whitespace is pre-defined in the string module of Python3. If contains space, tab,\nlinefeed, return, formfeed, and vertical tab."
},
{
"code": null,
"e": 1282,
"s": 1271,
"text": " Live Demo"
},
{
"code": null,
"e": 1452,
"s": 1282,
"text": "# importing the string module\nimport string\n# printing a string\nprint(\"Hello\")\n# whitespace printing\nprint(string.whitespace)\n# printing a string\nprint('tutorialspoint')"
},
{
"code": null,
"e": 1519,
"s": 1452,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 1541,
"s": 1519,
"text": "Hello\n\ntutorialspoint"
},
{
"code": null,
"e": 1618,
"s": 1541,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
How to avoid a new line with tag? - GeeksforGeeks
|
25 Jun, 2021
The p tag in HTML represents a paragraph. It is a block-level element which means that the text which is present inside the paragraph tag is considered as a block and it takes up the full width available. By default, the browser applies a line break before and after the p tag to separate the paragraphs. We can achieve this by adding the following style definition:
p {
display:inline;
}
Example 1: In this code, we have used the display attribute and set it to inline which will change the default behavior of paragraph tag and make it behave like an inline element. By using the inline property we can avoid the new line.
html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> p { padding:5px; border:1px solid black; color:green; font-size:24px; } #p2{ display:inline; } </style></head><body> Random Text1 <p id="p1">Geeks for Geeks</p> Random Text2 <p id="p2">Geeks for Geeks </p> Random Text3 </body><script> </script></html>
Output:
Example 2: In this code, we have used the inline styling to avoid the new line with paragraphs. The approach is the same as above
html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> p { padding:5px; border:1px solid black; color:green; font-size:24px; } </style></head><body> Random Text1 <p id="p2" style="display:inline">Text without new line </p> Random Text3 </body><script> </script></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ysachin2314
HTML-Misc
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24894,
"s": 24866,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 25263,
"s": 24894,
"text": "The p tag in HTML represents a paragraph. It is a block-level element which means that the text which is present inside the paragraph tag is considered as a block and it takes up the full width available. By default, the browser applies a line break before and after the p tag to separate the paragraphs. We can achieve this by adding the following style definition: "
},
{
"code": null,
"e": 25288,
"s": 25263,
"text": "p {\n display:inline;\n}"
},
{
"code": null,
"e": 25526,
"s": 25288,
"text": "Example 1: In this code, we have used the display attribute and set it to inline which will change the default behavior of paragraph tag and make it behave like an inline element. By using the inline property we can avoid the new line. "
},
{
"code": null,
"e": 25531,
"s": 25526,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Document</title> <style> p { padding:5px; border:1px solid black; color:green; font-size:24px; } #p2{ display:inline; } </style></head><body> Random Text1 <p id=\"p1\">Geeks for Geeks</p> Random Text2 <p id=\"p2\">Geeks for Geeks </p> Random Text3 </body><script> </script></html>",
"e": 26135,
"s": 25531,
"text": null
},
{
"code": null,
"e": 26145,
"s": 26135,
"text": "Output: "
},
{
"code": null,
"e": 26277,
"s": 26145,
"text": "Example 2: In this code, we have used the inline styling to avoid the new line with paragraphs. The approach is the same as above "
},
{
"code": null,
"e": 26282,
"s": 26277,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Document</title> <style> p { padding:5px; border:1px solid black; color:green; font-size:24px; } </style></head><body> Random Text1 <p id=\"p2\" style=\"display:inline\">Text without new line </p> Random Text3 </body><script> </script></html>",
"e": 26812,
"s": 26282,
"text": null
},
{
"code": null,
"e": 26822,
"s": 26812,
"text": "Output: "
},
{
"code": null,
"e": 26842,
"s": 26822,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 26856,
"s": 26842,
"text": "Google Chrome"
},
{
"code": null,
"e": 26874,
"s": 26856,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26882,
"s": 26874,
"text": "Firefox"
},
{
"code": null,
"e": 26888,
"s": 26882,
"text": "Opera"
},
{
"code": null,
"e": 26895,
"s": 26888,
"text": "Safari"
},
{
"code": null,
"e": 27032,
"s": 26895,
"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": 27044,
"s": 27032,
"text": "ysachin2314"
},
{
"code": null,
"e": 27054,
"s": 27044,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27064,
"s": 27054,
"text": "HTML-Tags"
},
{
"code": null,
"e": 27071,
"s": 27064,
"text": "Picked"
},
{
"code": null,
"e": 27076,
"s": 27071,
"text": "HTML"
},
{
"code": null,
"e": 27093,
"s": 27076,
"text": "Web Technologies"
},
{
"code": null,
"e": 27098,
"s": 27093,
"text": "HTML"
},
{
"code": null,
"e": 27196,
"s": 27098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27220,
"s": 27196,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27257,
"s": 27220,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27277,
"s": 27257,
"text": "Angular File Upload"
},
{
"code": null,
"e": 27306,
"s": 27277,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27334,
"s": 27306,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 27376,
"s": 27334,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27409,
"s": 27376,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27452,
"s": 27409,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27497,
"s": 27452,
"text": "Convert a string to an integer in JavaScript"
}
] |
How to search a word by capital or small letter in MySQL?
|
You can use BINARY along with the LIKE operator. Let us first create a table −
mysql> create table DemoTable
(
Header text
);
Query OK, 0 rows affected (1.09 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('Programming tutorials on MySQL');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('programming in Java language');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Program in C language');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('pRograMMing in Python language');
Query OK, 1 row affected (0.41 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------------------------------+
| Header |
+--------------------------------+
| Programming tutorials on MySQL |
| programming in Java language |
| Program in C language |
| pRograMMing in Python language |
+--------------------------------+
4 rows in set (0.00 sec)
Following is the query to search a word by the small letter −
mysql> select * from DemoTable where binary Header like '%programming%';
This will produce the following output −
+------------------------------+
| Header |
+------------------------------+
| programming in Java language |
+------------------------------+
1 row in set (0.05 sec)
NOTE: If you want to search a word by a capital letter, you need to put the word in LIKE operator.
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "You can use BINARY along with the LIKE operator. Let us first create a table −"
},
{
"code": null,
"e": 1234,
"s": 1141,
"text": "mysql> create table DemoTable\n (\n Header text\n );\nQuery OK, 0 rows affected (1.09 sec)"
},
{
"code": null,
"e": 1285,
"s": 1234,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1702,
"s": 1285,
"text": "mysql> insert into DemoTable values('Programming tutorials on MySQL');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('programming in Java language');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Program in C language');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('pRograMMing in Python language');\nQuery OK, 1 row affected (0.41 sec)"
},
{
"code": null,
"e": 1762,
"s": 1702,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1794,
"s": 1762,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1835,
"s": 1794,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2140,
"s": 1835,
"text": "+--------------------------------+\n| Header |\n+--------------------------------+\n| Programming tutorials on MySQL |\n| programming in Java language |\n| Program in C language |\n| pRograMMing in Python language |\n+--------------------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2202,
"s": 2140,
"text": "Following is the query to search a word by the small letter −"
},
{
"code": null,
"e": 2275,
"s": 2202,
"text": "mysql> select * from DemoTable where binary Header like '%programming%';"
},
{
"code": null,
"e": 2316,
"s": 2275,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2505,
"s": 2316,
"text": "+------------------------------+\n| Header |\n+------------------------------+\n| programming in Java language |\n+------------------------------+\n1 row in set (0.05 sec)"
},
{
"code": null,
"e": 2604,
"s": 2505,
"text": "NOTE: If you want to search a word by a capital letter, you need to put the word in LIKE operator."
}
] |
How to convert a string in uppercase in Golang? - GeeksforGeeks
|
26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you are allowed to convert a string in the uppercase using the following functions. All these functions are defined under strings package, so you have to import strings package in your program to access these functions:
1. ToUpper: This function is used to convert the given string elements to uppercase. Or in other words, this function returns a copy of the given string in which all the Unicode characters are mapped into uppercase.
Syntax:
func ToUpper(str string) string
Here, str represents the string which you want to convert to uppercase. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to convert// the given string into uppercasepackage main import ( "fmt" "strings") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := "WelcomE, GeeksforGeeks**" str2 := "$$This is the, tuTorial oF Golang##" str3 := "HELLO! GOLANG" str4 := "uppercase conversion" // Displaying strings fmt.Println("Strings (before):") fmt.Println("String 1: ", str1) fmt.Println("String 2:", str2) fmt.Println("String 3:", str3) fmt.Println("String 4:", str4) // Converting all the string into uppercase // Using ToUpper() function res1 := strings.ToUpper(str1) res2 := strings.ToUpper(str2) res3 := strings.ToUpper(str3) res4 := strings.ToUpper(str4) // Displaying the results fmt.Println("\nStrings (after):") fmt.Println("Result 1: ", res1) fmt.Println("Result 2:", res2) fmt.Println("Result 3:", res3) fmt.Println("Result 4:", res4)}
Output:
Strings (before):
String 1: WelcomE, GeeksforGeeks**
String 2: $$This is the, tuTorial oF Golang##
String 3: HELLO! GOLANG
String 4: uppercase conversion
Strings (after):
Result 1: WELCOME, GEEKSFORGEEKS**
Result 2: $$THIS IS THE, TUTORIAL OF GOLANG##
Result 3: HELLO! GOLANG
Result 4: UPPERCASE CONVERSION
2. ToTitle: This function is used to convert the string elements to title case. Or in other words, this function returns a copy of the given string in which all the Unicode characters are mapped into title case.
Syntax:
func ToTitle(str string) string
Here, str represents the string which you want to convert to title case. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to convert// the given string into title casepackage main import ( "fmt" "strings") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := "WelcomE, GeeksforGeeks**" str2 := "$$This is the, tuTorial oF Golang##" str3 := "HELLO! GOLANG" str4 := "uppercase conversion" // Displaying strings fmt.Println("Strings (before):") fmt.Println("String 1: ", str1) fmt.Println("String 2:", str2) fmt.Println("String 3:", str3) fmt.Println("String 4:", str4) // Converting all the string into title case // Using ToTitle() function res1 := strings.ToTitle(str1) res2 := strings.ToTitle(str2) res3 := strings.ToTitle(str3) res4 := strings.ToTitle(str4) // Displaying the results fmt.Println("\nStrings (after):") fmt.Println("Result 1: ", res1) fmt.Println("Result 2:", res2) fmt.Println("Result 3:", res3) fmt.Println("Result 4:", res4)}
Output:
Strings (before):
String 1: WelcomE, GeeksforGeeks**
String 2: $$This is the, tuTorial oF Golang##
String 3: HELLO! GOLANG
String 4: uppercase conversion
Strings (after):
Result 1: WELCOME, GEEKSFORGEEKS**
Result 2: $$THIS IS THE, TUTORIAL OF GOLANG##
Result 3: HELLO! GOLANG
Result 4: UPPERCASE CONVERSION
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Interfaces in Golang
How to Trim a String in Golang?
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 24047,
"s": 24019,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 24503,
"s": 24047,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you are allowed to convert a string in the uppercase using the following functions. All these functions are defined under strings package, so you have to import strings package in your program to access these functions:"
},
{
"code": null,
"e": 24719,
"s": 24503,
"text": "1. ToUpper: This function is used to convert the given string elements to uppercase. Or in other words, this function returns a copy of the given string in which all the Unicode characters are mapped into uppercase."
},
{
"code": null,
"e": 24727,
"s": 24719,
"text": "Syntax:"
},
{
"code": null,
"e": 24759,
"s": 24727,
"text": "func ToUpper(str string) string"
},
{
"code": null,
"e": 24888,
"s": 24759,
"text": "Here, str represents the string which you want to convert to uppercase. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 24897,
"s": 24888,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to convert// the given string into uppercasepackage main import ( \"fmt\" \"strings\") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := \"WelcomE, GeeksforGeeks**\" str2 := \"$$This is the, tuTorial oF Golang##\" str3 := \"HELLO! GOLANG\" str4 := \"uppercase conversion\" // Displaying strings fmt.Println(\"Strings (before):\") fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2:\", str2) fmt.Println(\"String 3:\", str3) fmt.Println(\"String 4:\", str4) // Converting all the string into uppercase // Using ToUpper() function res1 := strings.ToUpper(str1) res2 := strings.ToUpper(str2) res3 := strings.ToUpper(str3) res4 := strings.ToUpper(str4) // Displaying the results fmt.Println(\"\\nStrings (after):\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2:\", res2) fmt.Println(\"Result 3:\", res3) fmt.Println(\"Result 4:\", res4)}",
"e": 25889,
"s": 24897,
"text": null
},
{
"code": null,
"e": 25897,
"s": 25889,
"text": "Output:"
},
{
"code": null,
"e": 26208,
"s": 25897,
"text": "Strings (before):\nString 1: WelcomE, GeeksforGeeks**\nString 2: $$This is the, tuTorial oF Golang##\nString 3: HELLO! GOLANG\nString 4: uppercase conversion\n\nStrings (after):\nResult 1: WELCOME, GEEKSFORGEEKS**\nResult 2: $$THIS IS THE, TUTORIAL OF GOLANG##\nResult 3: HELLO! GOLANG\nResult 4: UPPERCASE CONVERSION\n"
},
{
"code": null,
"e": 26422,
"s": 26210,
"text": "2. ToTitle: This function is used to convert the string elements to title case. Or in other words, this function returns a copy of the given string in which all the Unicode characters are mapped into title case."
},
{
"code": null,
"e": 26430,
"s": 26422,
"text": "Syntax:"
},
{
"code": null,
"e": 26462,
"s": 26430,
"text": "func ToTitle(str string) string"
},
{
"code": null,
"e": 26592,
"s": 26462,
"text": "Here, str represents the string which you want to convert to title case. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 26601,
"s": 26592,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to convert// the given string into title casepackage main import ( \"fmt\" \"strings\") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := \"WelcomE, GeeksforGeeks**\" str2 := \"$$This is the, tuTorial oF Golang##\" str3 := \"HELLO! GOLANG\" str4 := \"uppercase conversion\" // Displaying strings fmt.Println(\"Strings (before):\") fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2:\", str2) fmt.Println(\"String 3:\", str3) fmt.Println(\"String 4:\", str4) // Converting all the string into title case // Using ToTitle() function res1 := strings.ToTitle(str1) res2 := strings.ToTitle(str2) res3 := strings.ToTitle(str3) res4 := strings.ToTitle(str4) // Displaying the results fmt.Println(\"\\nStrings (after):\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2:\", res2) fmt.Println(\"Result 3:\", res3) fmt.Println(\"Result 4:\", res4)}",
"e": 27595,
"s": 26601,
"text": null
},
{
"code": null,
"e": 27603,
"s": 27595,
"text": "Output:"
},
{
"code": null,
"e": 27914,
"s": 27603,
"text": "Strings (before):\nString 1: WelcomE, GeeksforGeeks**\nString 2: $$This is the, tuTorial oF Golang##\nString 3: HELLO! GOLANG\nString 4: uppercase conversion\n\nStrings (after):\nResult 1: WELCOME, GEEKSFORGEEKS**\nResult 2: $$THIS IS THE, TUTORIAL OF GOLANG##\nResult 3: HELLO! GOLANG\nResult 4: UPPERCASE CONVERSION\n"
},
{
"code": null,
"e": 27921,
"s": 27914,
"text": "Golang"
},
{
"code": null,
"e": 27935,
"s": 27921,
"text": "Golang-String"
},
{
"code": null,
"e": 27947,
"s": 27935,
"text": "Go Language"
},
{
"code": null,
"e": 28045,
"s": 27947,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28054,
"s": 28045,
"text": "Comments"
},
{
"code": null,
"e": 28067,
"s": 28054,
"text": "Old Comments"
},
{
"code": null,
"e": 28080,
"s": 28067,
"text": "Arrays in Go"
},
{
"code": null,
"e": 28113,
"s": 28080,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 28130,
"s": 28113,
"text": "Slices in Golang"
},
{
"code": null,
"e": 28142,
"s": 28130,
"text": "Golang Maps"
},
{
"code": null,
"e": 28196,
"s": 28142,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 28218,
"s": 28196,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 28250,
"s": 28218,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 28271,
"s": 28250,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 28303,
"s": 28271,
"text": "How to Trim a String in Golang?"
}
] |
Introduction to Datapane: A Python Library to Build Interactive Reports | by Khuyen Tran | Towards Data Science
|
For many Python data analyses, sometimes you want to share your findings with others. Showing your work will help your team and manager keep up-to-date with your progress and build your reputation as a data scientist in your network. I mentioned about how sharing my work has leveraged my career in this article:
towardsdatascience.com
But sharing alone is not enough. Let’s say after cleaning your data and creating some charts for analyzing, you want to share with others your findings. The last thing you want to do is to share with non-technical people (such as your stakeholders) the whole code or notebook and ask them to install Jupyter Notebook and environments required to see your findings like the below:
“This is the .ipynb file. To view this file, you need to pip installthese packages. Then type on the command line Jupyter Notebook. Once you see the notebook, run all the cells and you should be able to see the data and visualization”.
As an alternative, you could take the picture of the visualization and put it in a deck, but viewers will not have much control over the visualization — they wouldn’t be able to use it interactively, explore any data, or change the input parameters. Additionally, every time they want a change, you’ll have to create another report manually.
The optimal strategy is to share a specific user-facing part without setting up the environments. Wouldn’t it be great if you can send them a link like this to your teammates or stakeholders
to view all of your findings in one place?
That is when you need a Python framework like Datapane.
Datapane is an API for people who analyze data in Python and need a way to share their results. It provides a way to create reports programmatically from components that wrap around the common objects in analyses, such as:
Pandas DataFrames
Plots from Python visualization libraries such as Plotly, Bokeh, Altair, and Folium
Markdown
Once created, reports can be published on the web, dynamically generated in the cloud, or embedded into your own application, where data can be explored, and visualizations can be used interactively
Datapane also allows you to deploy your Python scripts and notebooks, so that other people can run them to generate reports from their browser without worrying about code, notebooks, or setting up a Python environment.
Let’s say you have a script like this with Pandas Dataframe and Altair chart
To create a report, simply follow these steps
Install Datapane with
pip3 install datapane
Sign up on Datapane to get your own token and use that token to login in datapane in your terminal
datapane login --server=https://datapane.com/ --token=yourtoken
Then simply add a few more lines of code to your existing analysis!
Run the scripts and voila! A report is automatically created for you on Datapane.com!
https://datapane.com/khuyen/reports/stock_report_9eddadcd/
That’s it! Now all you need to do now is to share this link to your teammates or manager
Or share on social media
Not only do you like the viewers to look at your report but you might also want to give them the ability to interact with the plots and plug in different parameters like this
With Datapane, others can generate your reports without worrying about code, notebooks, or setting up a Python environment. They could enter which parameters they would like to specify as input and will receive a dynamic report each time.
To deploy a script called stock_report.py, create a script like above then use Datapane’s CLI:
datapane script deploy --script=stock_report.py --name=stock_report
See further instructions on how to deploy a script here.
If you are a Medium writer or a blogger like me, you might want to embed a table or a plot like below:
With Datapane, you could embed your chart in Medium by simply copying and pasting the url published on Datapane on Medium. You can also embed them into Reddit, Confluence, Notion, or your own website.
Datapane provides a Blob API which allows you to upload files from any Python or CLI environment, and access them inside your scripts or through the CLI.
Let’s say you can use dp.Blob to save a dataframe, a file, or an object in blob.py, use
Then if you want to load them in another script, use
If your viewers want to download your table or chart, they could easily do that with Download button in the report.
Congratulations! You have just learned a new tool to add to your data science workflow along with your other favorite Python libraries.
I hope this article gives you a good headstart to try out Datapane. You could learn more about Datapane here. Comment below or send me a message on LinkedIn if you have any question about this tool.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 485,
"s": 172,
"text": "For many Python data analyses, sometimes you want to share your findings with others. Showing your work will help your team and manager keep up-to-date with your progress and build your reputation as a data scientist in your network. I mentioned about how sharing my work has leveraged my career in this article:"
},
{
"code": null,
"e": 508,
"s": 485,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 888,
"s": 508,
"text": "But sharing alone is not enough. Let’s say after cleaning your data and creating some charts for analyzing, you want to share with others your findings. The last thing you want to do is to share with non-technical people (such as your stakeholders) the whole code or notebook and ask them to install Jupyter Notebook and environments required to see your findings like the below:"
},
{
"code": null,
"e": 1124,
"s": 888,
"text": "“This is the .ipynb file. To view this file, you need to pip installthese packages. Then type on the command line Jupyter Notebook. Once you see the notebook, run all the cells and you should be able to see the data and visualization”."
},
{
"code": null,
"e": 1466,
"s": 1124,
"text": "As an alternative, you could take the picture of the visualization and put it in a deck, but viewers will not have much control over the visualization — they wouldn’t be able to use it interactively, explore any data, or change the input parameters. Additionally, every time they want a change, you’ll have to create another report manually."
},
{
"code": null,
"e": 1657,
"s": 1466,
"text": "The optimal strategy is to share a specific user-facing part without setting up the environments. Wouldn’t it be great if you can send them a link like this to your teammates or stakeholders"
},
{
"code": null,
"e": 1700,
"s": 1657,
"text": "to view all of your findings in one place?"
},
{
"code": null,
"e": 1756,
"s": 1700,
"text": "That is when you need a Python framework like Datapane."
},
{
"code": null,
"e": 1979,
"s": 1756,
"text": "Datapane is an API for people who analyze data in Python and need a way to share their results. It provides a way to create reports programmatically from components that wrap around the common objects in analyses, such as:"
},
{
"code": null,
"e": 1997,
"s": 1979,
"text": "Pandas DataFrames"
},
{
"code": null,
"e": 2081,
"s": 1997,
"text": "Plots from Python visualization libraries such as Plotly, Bokeh, Altair, and Folium"
},
{
"code": null,
"e": 2090,
"s": 2081,
"text": "Markdown"
},
{
"code": null,
"e": 2289,
"s": 2090,
"text": "Once created, reports can be published on the web, dynamically generated in the cloud, or embedded into your own application, where data can be explored, and visualizations can be used interactively"
},
{
"code": null,
"e": 2508,
"s": 2289,
"text": "Datapane also allows you to deploy your Python scripts and notebooks, so that other people can run them to generate reports from their browser without worrying about code, notebooks, or setting up a Python environment."
},
{
"code": null,
"e": 2585,
"s": 2508,
"text": "Let’s say you have a script like this with Pandas Dataframe and Altair chart"
},
{
"code": null,
"e": 2631,
"s": 2585,
"text": "To create a report, simply follow these steps"
},
{
"code": null,
"e": 2653,
"s": 2631,
"text": "Install Datapane with"
},
{
"code": null,
"e": 2675,
"s": 2653,
"text": "pip3 install datapane"
},
{
"code": null,
"e": 2774,
"s": 2675,
"text": "Sign up on Datapane to get your own token and use that token to login in datapane in your terminal"
},
{
"code": null,
"e": 2838,
"s": 2774,
"text": "datapane login --server=https://datapane.com/ --token=yourtoken"
},
{
"code": null,
"e": 2906,
"s": 2838,
"text": "Then simply add a few more lines of code to your existing analysis!"
},
{
"code": null,
"e": 2992,
"s": 2906,
"text": "Run the scripts and voila! A report is automatically created for you on Datapane.com!"
},
{
"code": null,
"e": 3051,
"s": 2992,
"text": "https://datapane.com/khuyen/reports/stock_report_9eddadcd/"
},
{
"code": null,
"e": 3140,
"s": 3051,
"text": "That’s it! Now all you need to do now is to share this link to your teammates or manager"
},
{
"code": null,
"e": 3165,
"s": 3140,
"text": "Or share on social media"
},
{
"code": null,
"e": 3340,
"s": 3165,
"text": "Not only do you like the viewers to look at your report but you might also want to give them the ability to interact with the plots and plug in different parameters like this"
},
{
"code": null,
"e": 3579,
"s": 3340,
"text": "With Datapane, others can generate your reports without worrying about code, notebooks, or setting up a Python environment. They could enter which parameters they would like to specify as input and will receive a dynamic report each time."
},
{
"code": null,
"e": 3674,
"s": 3579,
"text": "To deploy a script called stock_report.py, create a script like above then use Datapane’s CLI:"
},
{
"code": null,
"e": 3742,
"s": 3674,
"text": "datapane script deploy --script=stock_report.py --name=stock_report"
},
{
"code": null,
"e": 3799,
"s": 3742,
"text": "See further instructions on how to deploy a script here."
},
{
"code": null,
"e": 3902,
"s": 3799,
"text": "If you are a Medium writer or a blogger like me, you might want to embed a table or a plot like below:"
},
{
"code": null,
"e": 4103,
"s": 3902,
"text": "With Datapane, you could embed your chart in Medium by simply copying and pasting the url published on Datapane on Medium. You can also embed them into Reddit, Confluence, Notion, or your own website."
},
{
"code": null,
"e": 4257,
"s": 4103,
"text": "Datapane provides a Blob API which allows you to upload files from any Python or CLI environment, and access them inside your scripts or through the CLI."
},
{
"code": null,
"e": 4345,
"s": 4257,
"text": "Let’s say you can use dp.Blob to save a dataframe, a file, or an object in blob.py, use"
},
{
"code": null,
"e": 4398,
"s": 4345,
"text": "Then if you want to load them in another script, use"
},
{
"code": null,
"e": 4514,
"s": 4398,
"text": "If your viewers want to download your table or chart, they could easily do that with Download button in the report."
},
{
"code": null,
"e": 4650,
"s": 4514,
"text": "Congratulations! You have just learned a new tool to add to your data science workflow along with your other favorite Python libraries."
},
{
"code": null,
"e": 4849,
"s": 4650,
"text": "I hope this article gives you a good headstart to try out Datapane. You could learn more about Datapane here. Comment below or send me a message on LinkedIn if you have any question about this tool."
},
{
"code": null,
"e": 5009,
"s": 4849,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
C# Variables
|
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
string - stores text, such as "Hello World".
String values are surrounded by double quotes
bool - stores values with two states:
true or false
To create a variable, you must specify the type and assign it a value:
type variableName = value;
Where type is a C# type (such as int or string), and
variableName is the name of the variable (such as x or
name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Create a variable called name of type string and assign it the value "John":
string name = "John";
Console.WriteLine(name);
Try it Yourself »
To create a variable that should store a number, look at the following example:
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
Console.WriteLine(myNum);
Try it Yourself »
You can also declare a variable without assigning the value, and assign the value later:
int myNum;
myNum = 15;
Console.WriteLine(myNum);
Try it Yourself »
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Change the value of myNum to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
Console.WriteLine(myNum);
Try it Yourself »
However, you can add the const keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "constant", which means unchangeable and read-only):
const int myNum = 15;
myNum = 20; // error
Try it Yourself »
The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An example that is often referred to as a constant, is PI (3.14159...).
Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.
A demonstration of how to declare variables of other types:
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";
You will learn more about data types in the next chapter.
The WriteLine() method is often used to
display variable values to the console window.
To combine both text and a variable, use the + character:
string name = "John";
Console.WriteLine("Hello " + name);
Try it Yourself »
You can also use the + character to add a variable to another variable:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
Try it Yourself »
For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):
int x = 5;
int y = 6;
Console.WriteLine(x + y); // Print the value of x + y
Try it Yourself »
From the example above, you can expect:
x stores the value 5
y stores the value 6
Then we use the WriteLine() method to display the value of x + y,
which is 11
To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
Try it Yourself »
You can also assign the same value to multiple variables in one line:
int x, y, z;
x = y = z = 50;
Console.WriteLine(x + y + z);
Try it Yourself »
All C# variables must be
identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to
create understandable and maintainable code:
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
Try it Yourself »
The general rules for naming variables are:
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or
double) cannot be used as names
Create a variable named myNum and assign the value 50 to it.
= ;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 51,
"s": 0,
"text": "Variables are containers for storing data values. "
},
{
"code": null,
"e": 145,
"s": 51,
"text": "In C#, there are different types of variables (defined with different keywords), for example:"
},
{
"code": null,
"e": 222,
"s": 145,
"text": "int - stores integers (whole numbers), without decimals, such as 123 or -123"
},
{
"code": null,
"e": 301,
"s": 222,
"text": "double - stores floating point numbers, with decimals, such as 19.99 or -19.99"
},
{
"code": null,
"e": 400,
"s": 301,
"text": "char - stores single characters, such as 'a' or 'B'. \n Char values are surrounded by single quotes"
},
{
"code": null,
"e": 493,
"s": 400,
"text": "string - stores text, such as \"Hello World\". \n String values are surrounded by double quotes"
},
{
"code": null,
"e": 547,
"s": 493,
"text": "bool - stores values with two states: \n true or false"
},
{
"code": null,
"e": 618,
"s": 547,
"text": "To create a variable, you must specify the type and assign it a value:"
},
{
"code": null,
"e": 646,
"s": 618,
"text": "type variableName = value;\n"
},
{
"code": null,
"e": 819,
"s": 646,
"text": "Where type is a C# type (such as int or string), and \nvariableName is the name of the variable (such as x or\nname). The equal sign is used to assign values to the variable."
},
{
"code": null,
"e": 895,
"s": 819,
"text": "To create a variable that should store text, look at the following example:"
},
{
"code": null,
"e": 972,
"s": 895,
"text": "Create a variable called name of type string and assign it the value \"John\":"
},
{
"code": null,
"e": 1020,
"s": 972,
"text": "string name = \"John\";\nConsole.WriteLine(name);\n"
},
{
"code": null,
"e": 1040,
"s": 1020,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1120,
"s": 1040,
"text": "To create a variable that should store a number, look at the following example:"
},
{
"code": null,
"e": 1191,
"s": 1120,
"text": "Create a variable called myNum of type int and assign it the value 15:"
},
{
"code": null,
"e": 1234,
"s": 1191,
"text": "int myNum = 15;\nConsole.WriteLine(myNum);\n"
},
{
"code": null,
"e": 1254,
"s": 1234,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1343,
"s": 1254,
"text": "You can also declare a variable without assigning the value, and assign the value later:"
},
{
"code": null,
"e": 1393,
"s": 1343,
"text": "int myNum;\nmyNum = 15;\nConsole.WriteLine(myNum);\n"
},
{
"code": null,
"e": 1413,
"s": 1393,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1512,
"s": 1413,
"text": "Note that if you assign a new value to an existing variable, it will overwrite the previous value:"
},
{
"code": null,
"e": 1545,
"s": 1512,
"text": "Change the value of myNum to 20:"
},
{
"code": null,
"e": 1618,
"s": 1545,
"text": "int myNum = 15;\nmyNum = 20; // myNum is now 20\nConsole.WriteLine(myNum);"
},
{
"code": null,
"e": 1638,
"s": 1618,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1833,
"s": 1638,
"text": "However, you can add the const keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as \"constant\", which means unchangeable and read-only):"
},
{
"code": null,
"e": 1877,
"s": 1833,
"text": "const int myNum = 15;\nmyNum = 20; // error\n"
},
{
"code": null,
"e": 1897,
"s": 1877,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2108,
"s": 1897,
"text": "The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An example that is often referred to as a constant, is PI (3.14159...)."
},
{
"code": null,
"e": 2261,
"s": 2108,
"text": "Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided."
},
{
"code": null,
"e": 2321,
"s": 2261,
"text": "A demonstration of how to declare variables of other types:"
},
{
"code": null,
"e": 2431,
"s": 2321,
"text": "int myNum = 5;\ndouble myDoubleNum = 5.99D;\nchar myLetter = 'D';\nbool myBool = true;\nstring myText = \"Hello\";\n"
},
{
"code": null,
"e": 2489,
"s": 2431,
"text": "You will learn more about data types in the next chapter."
},
{
"code": null,
"e": 2577,
"s": 2489,
"text": "The WriteLine() method is often used to \ndisplay variable values to the console window."
},
{
"code": null,
"e": 2635,
"s": 2577,
"text": "To combine both text and a variable, use the + character:"
},
{
"code": null,
"e": 2694,
"s": 2635,
"text": "string name = \"John\";\nConsole.WriteLine(\"Hello \" + name);\n"
},
{
"code": null,
"e": 2714,
"s": 2694,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2786,
"s": 2714,
"text": "You can also use the + character to add a variable to another variable:"
},
{
"code": null,
"e": 2909,
"s": 2786,
"text": "string firstName = \"John \";\nstring lastName = \"Doe\";\nstring fullName = firstName + lastName;\nConsole.WriteLine(fullName);\n"
},
{
"code": null,
"e": 2929,
"s": 2909,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 3049,
"s": 2929,
"text": "For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):"
},
{
"code": null,
"e": 3126,
"s": 3049,
"text": "int x = 5;\nint y = 6;\nConsole.WriteLine(x + y); // Print the value of x + y\n"
},
{
"code": null,
"e": 3146,
"s": 3126,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 3186,
"s": 3146,
"text": "From the example above, you can expect:"
},
{
"code": null,
"e": 3207,
"s": 3186,
"text": "x stores the value 5"
},
{
"code": null,
"e": 3228,
"s": 3207,
"text": "y stores the value 6"
},
{
"code": null,
"e": 3308,
"s": 3228,
"text": "Then we use the WriteLine() method to display the value of x + y, \n which is 11"
},
{
"code": null,
"e": 3388,
"s": 3308,
"text": "To declare more than one variable of the same type, use a comma-separated list:"
},
{
"code": null,
"e": 3445,
"s": 3388,
"text": "int x = 5, y = 6, z = 50;\nConsole.WriteLine(x + y + z);\n"
},
{
"code": null,
"e": 3465,
"s": 3445,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 3535,
"s": 3465,
"text": "You can also assign the same value to multiple variables in one line:"
},
{
"code": null,
"e": 3594,
"s": 3535,
"text": "int x, y, z;\nx = y = z = 50;\nConsole.WriteLine(x + y + z);"
},
{
"code": null,
"e": 3614,
"s": 3594,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 3669,
"s": 3614,
"text": "All C# variables must be\nidentified with unique names."
},
{
"code": null,
"e": 3712,
"s": 3669,
"text": "These unique names are called identifiers."
},
{
"code": null,
"e": 3809,
"s": 3712,
"text": "Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume)."
},
{
"code": null,
"e": 3916,
"s": 3809,
"text": "Note: It is recommended to use descriptive names in order to \ncreate understandable and maintainable code:"
},
{
"code": null,
"e": 4019,
"s": 3916,
"text": "// Good\nint minutesPerHour = 60;\n\n// OK, but not so easy to understand what m actually is\nint m = 60;\n"
},
{
"code": null,
"e": 4039,
"s": 4019,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 4083,
"s": 4039,
"text": "The general rules for naming variables are:"
},
{
"code": null,
"e": 4150,
"s": 4083,
"text": "Names can contain letters, digits and the underscore character (_)"
},
{
"code": null,
"e": 4181,
"s": 4150,
"text": "Names must begin with a letter"
},
{
"code": null,
"e": 4257,
"s": 4181,
"text": "Names should start with a lowercase letter and it cannot contain whitespace"
},
{
"code": null,
"e": 4328,
"s": 4257,
"text": "Names are case sensitive (\"myVar\" and \"myvar\" are different variables)"
},
{
"code": null,
"e": 4412,
"s": 4328,
"text": "Reserved words (like C# keywords, such as int or \n double) cannot be used as names"
},
{
"code": null,
"e": 4473,
"s": 4412,
"text": "Create a variable named myNum and assign the value 50 to it."
},
{
"code": null,
"e": 4480,
"s": 4473,
"text": " = ;\n"
},
{
"code": null,
"e": 4499,
"s": 4480,
"text": "Start the Exercise"
},
{
"code": null,
"e": 4532,
"s": 4499,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4574,
"s": 4532,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4681,
"s": 4574,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 4700,
"s": 4681,
"text": "help@w3schools.com"
}
] |
Generate all rotations of a given string - GeeksforGeeks
|
02 Nov, 2021
Given a string S. The task is to print all the possible rotated strings of the given string.
Examples:
Input : S = "geeks"
Output : geeks
eeksg
eksge
ksgee
sgeek
Input : S = "abc"
Output : abc
bca
cab
Method 1 (Simple) The idea is to run a loop from i = 0 to n – 1 ( n = length of string) i.e for each point of rotation, copy the second part of the string in the temporary string and then copy the first part of the original string to the temporary string.
Below implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to generate all rotations// of a given string#include<bits/stdc++.h>using namespace std; // Print all the rotated string.void printRotatedString(char str[]){ int len = strlen(str); // Generate all rotations one by one and print char temp[len]; for (int i = 0; i < len; i++) { int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. while (str[j] != '\0') { temp[k] = str[j]; k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { temp[k] = str[j]; j++; k++; } printf("%s\n", temp); }} // Driven Programint main(){ char str[] = "geeks"; printRotatedString(str); return 0;}
// A simple Java program to generate all rotations// of a given string class Test{ // Print all the rotated string. static void printRotatedString(String str) { int len = str.length(); // Generate all rotations one by one and print StringBuffer sb; for (int i = 0; i < len; i++) { sb = new StringBuffer(); int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. for (int k2 = j; k2 < str.length(); k2++) { sb.insert(k, str.charAt(j)); k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { sb.insert(k, str.charAt(j)); j++; k++; } System.out.println(sb); } } // Driver method public static void main(String[] args) { String str = new String("geeks"); printRotatedString(str); }}
# A simple Python3 program to generate# all rotations of a given string # Print all the rotated strings.def printRotatedString(str): lenn = len(str) # Generate all rotations # one by one and print temp = [0] * (lenn) for i in range(lenn): j = i # Current index in str k = 0 # Current index in temp # Copying the second part from # the point of rotation. while (j < len(str)): temp[k] = str[j] k += 1 j += 1 # Copying the first part from # the point of rotation. j = 0 while (j < i) : temp[k] = str[j] j += 1 k += 1 print(*temp, sep = "") # Driver Codeif __name__ == '__main__': str = "geeks" printRotatedString(str) # This code is contributed# by SHUBHAMSINGH10
// A simple C# program to generate// all rotations of a given string using System;using System.Text; class GFG{// Print all the rotated string.public static void printRotatedString(string str){ int len = str.Length; // Generate all rotations one // by one and print StringBuilder sb; for (int i = 0; i < len; i++) { sb = new StringBuilder(); int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from // the point of rotation. for (int k2 = j; k2 < str.Length; k2++) { sb.Insert(k, str[j]); k++; j++; } // Copying the first part from // the point of rotation. j = 0; while (j < i) { sb.Insert(k, str[j]); j++; k++; } Console.WriteLine(sb); }} // Driver Codepublic static void Main(string[] args){ string str = "geeks"; printRotatedString(str);}} // This code is contributed// by Shrikant13
<?php// A simple PHP program to generate// all rotations of a given string // Print all the rotated string.function printRotatedString($str){ $len = strlen($str); // Generate all rotations one // by one and print $temp = " "; for ($i = 0; $i < $len; $i++) { $j = $i; // Current index in str $k = 0; // Current index in temp // Copying the second part from // the point of rotation. while ($j < $len) { $temp[$k] = $str[$j]; $k++; $j++; } // Copying the first part from // the point of rotation. $j = 0; while ($j < $i) { $temp[$k] = $str[$j]; $j++; $k++; } echo $temp . "\n"; }} // Driver Code$str = "geeks";printRotatedString($str); // This code is contributed// by Akanksha Rai?>
<script> // A simple javascript program to generate// all rotations of a given string // Print all the rotated string.function printRotatedString(str){ var len = str.length; // Generate all rotations one // by one and print var sb; for(i = 0; i < len; i++) { sb = []; // Current index in str var j = i; // Current index in temp var k = 0; // Copying the second part from the point // of rotation. for(k2 = j; k2 < str.length; k2++) { sb.push(str.charAt(j)); k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { sb.push(str.charAt(j)); j++; k++; } document.write(sb.join("") + "<br>"); }} // Driver codevar str = "geeks";printRotatedString(str); // This code is contributed by Amit Katiyar </script>
Output:
geeks
eeksg
eksge
ksgee
sgeek
Method 2 (Tricky and Efficient) The idea is based on the efficient method to check if strings are rotations of each other or not. We concatenate str with itself, i.e., we do str.str where . is concatenation operator. Now we traverse the concatenated string from 0 to n – 1 and print all substrings of size n.
Below is implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to print all// rotations of a string.#include<bits/stdc++.h>using namespace std; // Print all the rotated string.void printRotatedString(char str[]){ int n = strlen(str); // Concatenate str with itself char temp[2*n + 1]; strcpy(temp, str); strcat(temp, str); // Print all substrings of size n. // Note that size of temp is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) printf("%c",temp[i + j]); printf("\n"); }} // Driven Programint main(){ char str[] = "geeks"; printRotatedString(str); return 0;}
// A simple Java program to generate all rotations// of a given string class Test{ // Print all the rotated string. static void printRotatedString(String str) { int n = str.length(); StringBuffer sb = new StringBuffer(str); // Concatenate str with itself sb.append(str); // Print all substrings of size n. // Note that size of sb is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) System.out.print(sb.charAt(i + j)); System.out.println(); } } // Driver method public static void main(String[] args) { String str = new String("geeks"); printRotatedString(str); }}
# An efficient Python3 program to print # all rotations of a string. # Print all the rotated string.def printRotatedString(string) : n = len(string) # Concatenate str with itself temp = string + string # Print all substrings of size n. # Note that size of temp is 2n for i in range(n) : for j in range(n) : print(temp[i + j], end = "") print() # Driver Codeif __name__ == "__main__" : string = "geeks" printRotatedString(string) # This code is contributed by Ryuga
// A simple C# program to generate all rotations// of a given stringusing System;using System.Text; class Test{ // Print all the rotated string. static void printRotatedString(String str) { int n = str.Length; StringBuilder sb = new StringBuilder(str); // Concatenate str with itself sb.Append(str); // Print all substrings of size n. // Note that size of sb is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) Console.Write(sb[i + j]); Console.WriteLine(); } } // Driver method public static void Main(String[] args) { String str = "geeks"; printRotatedString(str); }}
<?php// An efficient PHP program to print all// rotations of a string. // Print all the rotated string.function printRotatedString($str){ $n = strlen($str); // Concatenate str with itself $temp=$str.$str; // Print all substrings of size n. // Note that size of temp is 2n for ($i = 0; $i < $n; $i++) { for ($j = 0; $j != $n; $j++) print($temp[$i + $j]); print("\n"); }} // Driver code $str = "geeks"; printRotatedString($str); // This code is contributed by mits?>
<script>// A simple javascript program to generate all rotations// of a given string // Print all the rotated string. function printRotatedString(str) { var n = str.length; var sb = str; // Concatenate str with itself sb += (str); // Print all substrings of size n. // Note that size of sb is 2n for (var i = 0; i < n; i++) { for (var j = 0; j != n; j++) document.write(sb.charAt(i + j)); document.write('<br>'); } } // Driver method var str = "geeks"; printRotatedString(str); // This code is contributed by 29AjayKumar</script>
Output:
geeks
eeksg
eksge
ksgee
sgeek
This article is contributed by Anuj Chauhan. 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.
shrikanth13
Kirti_Mangal
ankthon
Akanksha_Rai
SHUBHAMSINGH10
Mithun Kumar
amit143katiyar
29AjayKumar
ankita_saini
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
|
[
{
"code": null,
"e": 25236,
"s": 25208,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 25329,
"s": 25236,
"text": "Given a string S. The task is to print all the possible rotated strings of the given string."
},
{
"code": null,
"e": 25340,
"s": 25329,
"text": "Examples: "
},
{
"code": null,
"e": 25494,
"s": 25340,
"text": "Input : S = \"geeks\"\nOutput : geeks\n eeksg\n eksge\n ksgee\n sgeek\n\nInput : S = \"abc\" \nOutput : abc\n bca\n cab"
},
{
"code": null,
"e": 25750,
"s": 25494,
"text": "Method 1 (Simple) The idea is to run a loop from i = 0 to n – 1 ( n = length of string) i.e for each point of rotation, copy the second part of the string in the temporary string and then copy the first part of the original string to the temporary string."
},
{
"code": null,
"e": 25791,
"s": 25750,
"text": "Below implementation of this approach: "
},
{
"code": null,
"e": 25795,
"s": 25791,
"text": "C++"
},
{
"code": null,
"e": 25800,
"s": 25795,
"text": "Java"
},
{
"code": null,
"e": 25808,
"s": 25800,
"text": "Python3"
},
{
"code": null,
"e": 25811,
"s": 25808,
"text": "C#"
},
{
"code": null,
"e": 25815,
"s": 25811,
"text": "PHP"
},
{
"code": null,
"e": 25826,
"s": 25815,
"text": "Javascript"
},
{
"code": "// A simple C++ program to generate all rotations// of a given string#include<bits/stdc++.h>using namespace std; // Print all the rotated string.void printRotatedString(char str[]){ int len = strlen(str); // Generate all rotations one by one and print char temp[len]; for (int i = 0; i < len; i++) { int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. while (str[j] != '\\0') { temp[k] = str[j]; k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { temp[k] = str[j]; j++; k++; } printf(\"%s\\n\", temp); }} // Driven Programint main(){ char str[] = \"geeks\"; printRotatedString(str); return 0;}",
"e": 26729,
"s": 25826,
"text": null
},
{
"code": "// A simple Java program to generate all rotations// of a given string class Test{ // Print all the rotated string. static void printRotatedString(String str) { int len = str.length(); // Generate all rotations one by one and print StringBuffer sb; for (int i = 0; i < len; i++) { sb = new StringBuffer(); int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. for (int k2 = j; k2 < str.length(); k2++) { sb.insert(k, str.charAt(j)); k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { sb.insert(k, str.charAt(j)); j++; k++; } System.out.println(sb); } } // Driver method public static void main(String[] args) { String str = new String(\"geeks\"); printRotatedString(str); }}",
"e": 27899,
"s": 26729,
"text": null
},
{
"code": "# A simple Python3 program to generate# all rotations of a given string # Print all the rotated strings.def printRotatedString(str): lenn = len(str) # Generate all rotations # one by one and print temp = [0] * (lenn) for i in range(lenn): j = i # Current index in str k = 0 # Current index in temp # Copying the second part from # the point of rotation. while (j < len(str)): temp[k] = str[j] k += 1 j += 1 # Copying the first part from # the point of rotation. j = 0 while (j < i) : temp[k] = str[j] j += 1 k += 1 print(*temp, sep = \"\") # Driver Codeif __name__ == '__main__': str = \"geeks\" printRotatedString(str) # This code is contributed# by SHUBHAMSINGH10",
"e": 28771,
"s": 27899,
"text": null
},
{
"code": "// A simple C# program to generate// all rotations of a given string using System;using System.Text; class GFG{// Print all the rotated string.public static void printRotatedString(string str){ int len = str.Length; // Generate all rotations one // by one and print StringBuilder sb; for (int i = 0; i < len; i++) { sb = new StringBuilder(); int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from // the point of rotation. for (int k2 = j; k2 < str.Length; k2++) { sb.Insert(k, str[j]); k++; j++; } // Copying the first part from // the point of rotation. j = 0; while (j < i) { sb.Insert(k, str[j]); j++; k++; } Console.WriteLine(sb); }} // Driver Codepublic static void Main(string[] args){ string str = \"geeks\"; printRotatedString(str);}} // This code is contributed// by Shrikant13",
"e": 29812,
"s": 28771,
"text": null
},
{
"code": "<?php// A simple PHP program to generate// all rotations of a given string // Print all the rotated string.function printRotatedString($str){ $len = strlen($str); // Generate all rotations one // by one and print $temp = \" \"; for ($i = 0; $i < $len; $i++) { $j = $i; // Current index in str $k = 0; // Current index in temp // Copying the second part from // the point of rotation. while ($j < $len) { $temp[$k] = $str[$j]; $k++; $j++; } // Copying the first part from // the point of rotation. $j = 0; while ($j < $i) { $temp[$k] = $str[$j]; $j++; $k++; } echo $temp . \"\\n\"; }} // Driver Code$str = \"geeks\";printRotatedString($str); // This code is contributed// by Akanksha Rai?>",
"e": 30684,
"s": 29812,
"text": null
},
{
"code": "<script> // A simple javascript program to generate// all rotations of a given string // Print all the rotated string.function printRotatedString(str){ var len = str.length; // Generate all rotations one // by one and print var sb; for(i = 0; i < len; i++) { sb = []; // Current index in str var j = i; // Current index in temp var k = 0; // Copying the second part from the point // of rotation. for(k2 = j; k2 < str.length; k2++) { sb.push(str.charAt(j)); k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { sb.push(str.charAt(j)); j++; k++; } document.write(sb.join(\"\") + \"<br>\"); }} // Driver codevar str = \"geeks\";printRotatedString(str); // This code is contributed by Amit Katiyar </script>",
"e": 31671,
"s": 30684,
"text": null
},
{
"code": null,
"e": 31680,
"s": 31671,
"text": "Output: "
},
{
"code": null,
"e": 31710,
"s": 31680,
"text": "geeks\neeksg\neksge\nksgee\nsgeek"
},
{
"code": null,
"e": 32021,
"s": 31710,
"text": " Method 2 (Tricky and Efficient) The idea is based on the efficient method to check if strings are rotations of each other or not. We concatenate str with itself, i.e., we do str.str where . is concatenation operator. Now we traverse the concatenated string from 0 to n – 1 and print all substrings of size n."
},
{
"code": null,
"e": 32065,
"s": 32021,
"text": "Below is implementation of this approach: "
},
{
"code": null,
"e": 32069,
"s": 32065,
"text": "C++"
},
{
"code": null,
"e": 32074,
"s": 32069,
"text": "Java"
},
{
"code": null,
"e": 32082,
"s": 32074,
"text": "Python3"
},
{
"code": null,
"e": 32085,
"s": 32082,
"text": "C#"
},
{
"code": null,
"e": 32089,
"s": 32085,
"text": "PHP"
},
{
"code": null,
"e": 32100,
"s": 32089,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to print all// rotations of a string.#include<bits/stdc++.h>using namespace std; // Print all the rotated string.void printRotatedString(char str[]){ int n = strlen(str); // Concatenate str with itself char temp[2*n + 1]; strcpy(temp, str); strcat(temp, str); // Print all substrings of size n. // Note that size of temp is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) printf(\"%c\",temp[i + j]); printf(\"\\n\"); }} // Driven Programint main(){ char str[] = \"geeks\"; printRotatedString(str); return 0;}",
"e": 32708,
"s": 32100,
"text": null
},
{
"code": "// A simple Java program to generate all rotations// of a given string class Test{ // Print all the rotated string. static void printRotatedString(String str) { int n = str.length(); StringBuffer sb = new StringBuffer(str); // Concatenate str with itself sb.append(str); // Print all substrings of size n. // Note that size of sb is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) System.out.print(sb.charAt(i + j)); System.out.println(); } } // Driver method public static void main(String[] args) { String str = new String(\"geeks\"); printRotatedString(str); }}",
"e": 33443,
"s": 32708,
"text": null
},
{
"code": "# An efficient Python3 program to print # all rotations of a string. # Print all the rotated string.def printRotatedString(string) : n = len(string) # Concatenate str with itself temp = string + string # Print all substrings of size n. # Note that size of temp is 2n for i in range(n) : for j in range(n) : print(temp[i + j], end = \"\") print() # Driver Codeif __name__ == \"__main__\" : string = \"geeks\" printRotatedString(string) # This code is contributed by Ryuga",
"e": 33987,
"s": 33443,
"text": null
},
{
"code": "// A simple C# program to generate all rotations// of a given stringusing System;using System.Text; class Test{ // Print all the rotated string. static void printRotatedString(String str) { int n = str.Length; StringBuilder sb = new StringBuilder(str); // Concatenate str with itself sb.Append(str); // Print all substrings of size n. // Note that size of sb is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) Console.Write(sb[i + j]); Console.WriteLine(); } } // Driver method public static void Main(String[] args) { String str = \"geeks\"; printRotatedString(str); }}",
"e": 34726,
"s": 33987,
"text": null
},
{
"code": "<?php// An efficient PHP program to print all// rotations of a string. // Print all the rotated string.function printRotatedString($str){ $n = strlen($str); // Concatenate str with itself $temp=$str.$str; // Print all substrings of size n. // Note that size of temp is 2n for ($i = 0; $i < $n; $i++) { for ($j = 0; $j != $n; $j++) print($temp[$i + $j]); print(\"\\n\"); }} // Driver code $str = \"geeks\"; printRotatedString($str); // This code is contributed by mits?>",
"e": 35256,
"s": 34726,
"text": null
},
{
"code": "<script>// A simple javascript program to generate all rotations// of a given string // Print all the rotated string. function printRotatedString(str) { var n = str.length; var sb = str; // Concatenate str with itself sb += (str); // Print all substrings of size n. // Note that size of sb is 2n for (var i = 0; i < n; i++) { for (var j = 0; j != n; j++) document.write(sb.charAt(i + j)); document.write('<br>'); } } // Driver method var str = \"geeks\"; printRotatedString(str); // This code is contributed by 29AjayKumar</script>",
"e": 35941,
"s": 35256,
"text": null
},
{
"code": null,
"e": 35950,
"s": 35941,
"text": "Output: "
},
{
"code": null,
"e": 35980,
"s": 35950,
"text": "geeks\neeksg\neksge\nksgee\nsgeek"
},
{
"code": null,
"e": 36401,
"s": 35980,
"text": "This article is contributed by Anuj Chauhan. 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": 36413,
"s": 36401,
"text": "shrikanth13"
},
{
"code": null,
"e": 36426,
"s": 36413,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 36434,
"s": 36426,
"text": "ankthon"
},
{
"code": null,
"e": 36447,
"s": 36434,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 36462,
"s": 36447,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 36475,
"s": 36462,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 36490,
"s": 36475,
"text": "amit143katiyar"
},
{
"code": null,
"e": 36502,
"s": 36490,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36515,
"s": 36502,
"text": "ankita_saini"
},
{
"code": null,
"e": 36523,
"s": 36515,
"text": "Strings"
},
{
"code": null,
"e": 36531,
"s": 36523,
"text": "Strings"
},
{
"code": null,
"e": 36629,
"s": 36531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36686,
"s": 36629,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 36761,
"s": 36686,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 36797,
"s": 36761,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 36844,
"s": 36797,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 36880,
"s": 36844,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 36918,
"s": 36880,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 36971,
"s": 36918,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 37001,
"s": 36971,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 37033,
"s": 37001,
"text": "Reverse words in a given string"
}
] |
Distinct adjacent elements in an array - GeeksforGeeks
|
23 Jun, 2021
Given an array, find whether it is possible to obtain an array having distinct neighbouring elements by swapping two neighbouring array elements.Examples:
Input : 1 1 2
Output : YES
swap 1 (second last element) and 2 (last element),
to obtain 1 2 1, which has distinct neighbouring
elements .
Input : 7 7 7 7
Output : NO
We can't swap to obtain distinct elements in
neighbor .
To obtain an array having distinct neighbouring elements is possible only, when the frequency of most occurring element is less than or equal to half of size of array i.e ( <= (n+1)/2 ). To make it more clear consider different examples 1st Example : a[] = {1, 1, 2, 3, 1} We can obtain array {1, 2, 1, 3, 1} by swapping (2nd and 3rd) element from array a. Here 1 occurs most and its frequency is 3 . So that 3 <= ((5+1)/2) .Hence, it is possible. Below is the implementation of this approach.
C++
Python3
C#
Java
Javascript
// C++ program to check if we can make// neighbors distinct.#include <bits/stdc++.h>using namespace std; void distinctAdjacentElement(int a[], int n){ // map used to count the frequency // of each element occurring in the // array map<int, int> m; // In this loop we count the frequency // of element through map m . for (int i = 0; i < n; ++i) m[a[i]]++; // mx store the frequency of element which // occurs most in array . int mx = 0; // In this loop we calculate the maximum // frequency and store it in variable mx. for (int i = 0; i < n; ++i) if (mx < m[a[i]]) mx = m[a[i]]; // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > (n + 1) / 2) cout << "NO" << endl; else cout << "YES" << endl;} // Driver program to test the above functionint main(){ int a[] = { 7, 7, 7, 7 }; int n = sizeof(a) / sizeof(a[0]); distinctAdjacentElement(a, n); return 0;}
# Python program to check if we can make# neighbors distinct.def distantAdjacentElement(a, n): # dict used to count the frequency # of each element occurring in the # array m = dict() # In this loop we count the frequency # of element through map m for i in range(n): if a[i] in m: m[a[i]] += 1 else: m[a[i]] = 1 # mx store the frequency of element which # occurs most in array . mx = 0 # In this loop we calculate the maximum # frequency and store it in variable mx. for i in range(n): if mx < m[a[i]]: mx = m[a[i]] # By swapping we can adjust array only # when the frequency of the element # which occurs most is less than or # equal to (n + 1)/2 . if mx > (n+1) // 2: print("NO") else: print("YES") # Driver Codeif __name__ == "__main__": a = [7, 7, 7, 7] n = len(a) distantAdjacentElement(a, n) # This code is contributed by# sanjeev2552
// C# program to check if we can make// neighbors distinct.using System;using System.Collections.Generic; class GFG { public static void distinctAdjacentElement(int[] a, int n){ // map used to count the frequency // of each element occurring in the // array Dictionary<int, int> m = new Dictionary<int, int>(); // In this loop we count the frequency // of element through map m . for (int i = 0; i < n; ++i) { // checks if map already // contains a[i] then // update the previous // value by incrementing // by 1 if (m.ContainsKey(a[i])) { int x = m[a[i]] + 1; m[a[i]] = x; } else { m[a[i]] = 1; } } // mx store the frequency // of element which // occurs most in array . int mx = 0; // In this loop we calculate // the maximum frequency and // store it in variable mx. for (int i = 0; i < n; ++i) { if (mx < m[a[i]]) { mx = m[a[i]]; } } // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > (n + 1) / 2) { Console.WriteLine("NO"); } else { Console.WriteLine("YES"); }} // Main Method public static void Main(string[] args) { int[] a = new int[] {7, 7, 7, 7}; int n = 4; distinctAdjacentElement(a, n); }} // This code is contributed// by Shrikant13
// Java program to check if we can make// neighbors distinct.import java.io.*;import java.util.HashMap;import java.util.Map;class GFG { static void distinctAdjacentElement(int a[], int n){// map used to count the frequency// of each element occurring in the// arrayHashMap<Integer,Integer> m = new HashMap<Integer,Integer>(); // In this loop we count the frequency// of element through map m .for (int i = 0; i < n; ++i){ // checks if map already contains a[i] then// update the previous value by incrementing// by 1if(m.containsKey(a[i])){int x = m.get(a[i]) + 1;m.put(a[i],x);}else{m.put(a[i],1);} } // mx store the frequency of element which// occurs most in array .int mx = 0; // In this loop we calculate the maximum// frequency and store it in variable mx.for (int i = 0; i < n; ++i)if (mx < m.get(a[i]))mx = m.get(a[i]); // By swapping we can adjust array only// when the frequency of the element// which occurs most is less than or// equal to (n + 1)/2 .if (mx > (n + 1) / 2)System.out.println("NO");elseSystem.out.println("YES");} // Driver program to test the above functionpublic static void main (String[] args) {int a[] = { 7, 7, 7, 7 };int n = 4;distinctAdjacentElement(a, n);}}// This code is contributed by Amit Kumar
<script> // JavaScript program to check if we can make// neighbors distinct. function distinctAdjacentElement(a, n) { // map used to count the frequency // of each element occurring in the // array let m = new Map(); // In this loop we count the frequency // of element through map m . for (let i = 0; i < n; ++i) { m[a[i]]++; if (m.has(a[i])) { m.set(a[i], m.get(a[i]) + 1) } else { m.set(a[i], 1) } } // mx store the frequency of element which // occurs most in array . let mx = 0; // In this loop we calculate the maximum // frequency and store it in variable mx. for (let i = 0; i < n; ++i) if (mx < m.get(a[i])) mx = m.get(a[i]); // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > Math.floor((n + 1) / 2)) document.write("NO" + "<br>"); else document.write("YES<br>");} // Driver program to test the above function let a = [7, 7, 7, 7];let n = a.length;distinctAdjacentElement(a, n); </script>
Output:
NO
This article is contributed by Surya Priy. 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.
shrikanth13
sanskar27jain
sanjeev2552
nidhi_biet
soumikcaptain07673
_saurabh_jaiswal
array-rearrange
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Find the Missing Number
|
[
{
"code": null,
"e": 25084,
"s": 25056,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25240,
"s": 25084,
"text": "Given an array, find whether it is possible to obtain an array having distinct neighbouring elements by swapping two neighbouring array elements.Examples: "
},
{
"code": null,
"e": 25466,
"s": 25240,
"text": "Input : 1 1 2\nOutput : YES\nswap 1 (second last element) and 2 (last element), \nto obtain 1 2 1, which has distinct neighbouring \nelements .\n\nInput : 7 7 7 7\nOutput : NO\nWe can't swap to obtain distinct elements in \nneighbor ."
},
{
"code": null,
"e": 25961,
"s": 25466,
"text": "To obtain an array having distinct neighbouring elements is possible only, when the frequency of most occurring element is less than or equal to half of size of array i.e ( <= (n+1)/2 ). To make it more clear consider different examples 1st Example : a[] = {1, 1, 2, 3, 1} We can obtain array {1, 2, 1, 3, 1} by swapping (2nd and 3rd) element from array a. Here 1 occurs most and its frequency is 3 . So that 3 <= ((5+1)/2) .Hence, it is possible. Below is the implementation of this approach. "
},
{
"code": null,
"e": 25965,
"s": 25961,
"text": "C++"
},
{
"code": null,
"e": 25973,
"s": 25965,
"text": "Python3"
},
{
"code": null,
"e": 25976,
"s": 25973,
"text": "C#"
},
{
"code": null,
"e": 25981,
"s": 25976,
"text": "Java"
},
{
"code": null,
"e": 25992,
"s": 25981,
"text": "Javascript"
},
{
"code": "// C++ program to check if we can make// neighbors distinct.#include <bits/stdc++.h>using namespace std; void distinctAdjacentElement(int a[], int n){ // map used to count the frequency // of each element occurring in the // array map<int, int> m; // In this loop we count the frequency // of element through map m . for (int i = 0; i < n; ++i) m[a[i]]++; // mx store the frequency of element which // occurs most in array . int mx = 0; // In this loop we calculate the maximum // frequency and store it in variable mx. for (int i = 0; i < n; ++i) if (mx < m[a[i]]) mx = m[a[i]]; // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > (n + 1) / 2) cout << \"NO\" << endl; else cout << \"YES\" << endl;} // Driver program to test the above functionint main(){ int a[] = { 7, 7, 7, 7 }; int n = sizeof(a) / sizeof(a[0]); distinctAdjacentElement(a, n); return 0;}",
"e": 27053,
"s": 25992,
"text": null
},
{
"code": "# Python program to check if we can make# neighbors distinct.def distantAdjacentElement(a, n): # dict used to count the frequency # of each element occurring in the # array m = dict() # In this loop we count the frequency # of element through map m for i in range(n): if a[i] in m: m[a[i]] += 1 else: m[a[i]] = 1 # mx store the frequency of element which # occurs most in array . mx = 0 # In this loop we calculate the maximum # frequency and store it in variable mx. for i in range(n): if mx < m[a[i]]: mx = m[a[i]] # By swapping we can adjust array only # when the frequency of the element # which occurs most is less than or # equal to (n + 1)/2 . if mx > (n+1) // 2: print(\"NO\") else: print(\"YES\") # Driver Codeif __name__ == \"__main__\": a = [7, 7, 7, 7] n = len(a) distantAdjacentElement(a, n) # This code is contributed by# sanjeev2552",
"e": 28035,
"s": 27053,
"text": null
},
{
"code": "// C# program to check if we can make// neighbors distinct.using System;using System.Collections.Generic; class GFG { public static void distinctAdjacentElement(int[] a, int n){ // map used to count the frequency // of each element occurring in the // array Dictionary<int, int> m = new Dictionary<int, int>(); // In this loop we count the frequency // of element through map m . for (int i = 0; i < n; ++i) { // checks if map already // contains a[i] then // update the previous // value by incrementing // by 1 if (m.ContainsKey(a[i])) { int x = m[a[i]] + 1; m[a[i]] = x; } else { m[a[i]] = 1; } } // mx store the frequency // of element which // occurs most in array . int mx = 0; // In this loop we calculate // the maximum frequency and // store it in variable mx. for (int i = 0; i < n; ++i) { if (mx < m[a[i]]) { mx = m[a[i]]; } } // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > (n + 1) / 2) { Console.WriteLine(\"NO\"); } else { Console.WriteLine(\"YES\"); }} // Main Method public static void Main(string[] args) { int[] a = new int[] {7, 7, 7, 7}; int n = 4; distinctAdjacentElement(a, n); }} // This code is contributed// by Shrikant13",
"e": 29560,
"s": 28035,
"text": null
},
{
"code": "// Java program to check if we can make// neighbors distinct.import java.io.*;import java.util.HashMap;import java.util.Map;class GFG { static void distinctAdjacentElement(int a[], int n){// map used to count the frequency// of each element occurring in the// arrayHashMap<Integer,Integer> m = new HashMap<Integer,Integer>(); // In this loop we count the frequency// of element through map m .for (int i = 0; i < n; ++i){ // checks if map already contains a[i] then// update the previous value by incrementing// by 1if(m.containsKey(a[i])){int x = m.get(a[i]) + 1;m.put(a[i],x);}else{m.put(a[i],1);} } // mx store the frequency of element which// occurs most in array .int mx = 0; // In this loop we calculate the maximum// frequency and store it in variable mx.for (int i = 0; i < n; ++i)if (mx < m.get(a[i]))mx = m.get(a[i]); // By swapping we can adjust array only// when the frequency of the element// which occurs most is less than or// equal to (n + 1)/2 .if (mx > (n + 1) / 2)System.out.println(\"NO\");elseSystem.out.println(\"YES\");} // Driver program to test the above functionpublic static void main (String[] args) {int a[] = { 7, 7, 7, 7 };int n = 4;distinctAdjacentElement(a, n);}}// This code is contributed by Amit Kumar",
"e": 30794,
"s": 29560,
"text": null
},
{
"code": "<script> // JavaScript program to check if we can make// neighbors distinct. function distinctAdjacentElement(a, n) { // map used to count the frequency // of each element occurring in the // array let m = new Map(); // In this loop we count the frequency // of element through map m . for (let i = 0; i < n; ++i) { m[a[i]]++; if (m.has(a[i])) { m.set(a[i], m.get(a[i]) + 1) } else { m.set(a[i], 1) } } // mx store the frequency of element which // occurs most in array . let mx = 0; // In this loop we calculate the maximum // frequency and store it in variable mx. for (let i = 0; i < n; ++i) if (mx < m.get(a[i])) mx = m.get(a[i]); // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > Math.floor((n + 1) / 2)) document.write(\"NO\" + \"<br>\"); else document.write(\"YES<br>\");} // Driver program to test the above function let a = [7, 7, 7, 7];let n = a.length;distinctAdjacentElement(a, n); </script>",
"e": 31935,
"s": 30794,
"text": null
},
{
"code": null,
"e": 31944,
"s": 31935,
"text": "Output: "
},
{
"code": null,
"e": 31947,
"s": 31944,
"text": "NO"
},
{
"code": null,
"e": 32366,
"s": 31947,
"text": "This article is contributed by Surya Priy. 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": 32378,
"s": 32366,
"text": "shrikanth13"
},
{
"code": null,
"e": 32392,
"s": 32378,
"text": "sanskar27jain"
},
{
"code": null,
"e": 32404,
"s": 32392,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32415,
"s": 32404,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32434,
"s": 32415,
"text": "soumikcaptain07673"
},
{
"code": null,
"e": 32451,
"s": 32434,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32467,
"s": 32451,
"text": "array-rearrange"
},
{
"code": null,
"e": 32474,
"s": 32467,
"text": "Arrays"
},
{
"code": null,
"e": 32481,
"s": 32474,
"text": "Arrays"
},
{
"code": null,
"e": 32579,
"s": 32481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32588,
"s": 32579,
"text": "Comments"
},
{
"code": null,
"e": 32601,
"s": 32588,
"text": "Old Comments"
},
{
"code": null,
"e": 32645,
"s": 32601,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32668,
"s": 32645,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32700,
"s": 32668,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32714,
"s": 32700,
"text": "Linear Search"
},
{
"code": null,
"e": 32782,
"s": 32714,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32827,
"s": 32782,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 32848,
"s": 32827,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 32902,
"s": 32848,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 32987,
"s": 32902,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
Depth First Search or DFS for a Graph - GeeksforGeeks
|
30 Jan, 2022
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array.
Example:
Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram:
Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram:
Prerequisites: See this post for all applications of Depth First Traversal.
Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path.
Algorithm: Create a recursive function that takes the index of the node and a visited array.
Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
Mark the current node as visited and print the node.
Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
Implementation: Below are implementations of simple Depth First Traversal. The C++ implementation uses an adjacency list representation of graphs. STL’s list container is used to store lists of adjacent nodes.
C++
Java
Python3
C#
Javascript
// C++ program to print DFS traversal from// a given vertex in a given graph#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph {public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFS(int v){ // Mark the current node as visited and // print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Depth First Traversal" " (starting from vertex 2) \n"; g.DFS(2); return 0;} // improved by Vishnudev C
// Java program to print DFS// mtraversal from a given given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + " "); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() void DFS(int v) { // Mark all the vertices as // not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper // function to print DFS // traversal DFSUtil(v, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( "Following is Depth First Traversal " + "(starting from vertex 2)"); g.DFS(2); }}// This code is contributed by Aakash Hasija
# Python3 program to print DFS traversal# from a given given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print("Following is DFS from (starting from vertex 2)")g.DFS(2) # This code is contributed by Neelam Yadav
// C# program to print DFS traversal// from a given graphusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to Add an edge into the graph void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current node as visited // and print it visited[v] = true; Console.Write(v + " "); // Recur for all the vertices // adjacent to this vertex List<int> vList = adj[v]; foreach(var n in vList) { if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited // (set as false by default in c#) bool[] visited = new bool[V]; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); } // Driver Code public static void Main(String[] args) { Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.WriteLine( "Following is Depth First Traversal " + "(starting from vertex 2)"); g.DFS(2); Console.ReadKey(); }} // This code is contributed by techno2mahi
<script> // Javascript program to print DFS// traversal from a given given// graph // This class represents a// directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { // Add w to v's list. this.adj[v].push(w); } // A function used by DFS DFSUtil(v, visited) { // Mark the current node as visited and print it visited[v] = true; document.write(v + " "); // Recur for all the vertices adjacent to this // vertex for(let i of this.adj[v].values()) { let n = i if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() DFS(v) { // Mark all the vertices as // not visited(set as // false by default in java) let visited = new Array(this.V); for(let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper // function to print DFS // traversal this.DFSUtil(v, visited); }} // Driver Codeg = new Graph(4); g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.addEdge(3, 3); document.write("Following is Depth First Traversal " + "(starting from vertex 2)<br>"); g.DFS(2); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Following is Depth First Traversal (starting from vertex 2)
2 0 1 3
Complexity Analysis:
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Space Complexity: O(V), since an extra visited array of size V is required.
Handling A Disconnected Graph:
Solution: This will happen by handling a corner case. The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex, as in a Disconnected graph. To do a complete DFS traversal of such graphs, run DFS from all unvisited nodes after a DFS. The recursive function remains the same.
Algorithm: Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node.
Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node.
Create a recursive function that takes the index of the node and a visited array.
Mark the current node as visited and print the node.
Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to print DFS// traversal for a given given// graph#include <bits/stdc++.h>using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFSUtil(int v){ // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i);} // The function to do DFS traversal. It uses recursive// DFSUtil()void Graph::DFS(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first);} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << "Following is Depth First Traversal \n"; g.DFS(); return 0;}// improved by Vishnudev C
// Java program to print DFS// traversal from a given given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + " "); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( "Following is Depth First Traversal"); g.DFS(); }}// This code is contributed by Aakash Hasija
'''Python program to print DFS traversal for complete graph'''from collections import defaultdict # this class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited.add(v) print(v,end=" ") # recur for all the vertices adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses recursive DFSUtil def DFS(self): # create a set to store all visited vertices visited = set() # call the recursive helper function to print DFS traversal starting from all # vertices one by one for vertex in self.graph: if vertex not in visited: self.DFSUtil(vertex, visited)# Driver code# create a graph given in the above diagram print("Following is Depth First Traversal \n")g = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)g.DFS() # Improved by Dheeraj Kumar
// C# program to print DFS// traversal from a given given// graphusing System;using System.Collections.Generic; // This class represents a// directed graph using adjacency// list representationpublic class Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current // node as visited and print it visited[v] = true; Console.Write(v + " "); // Recur for all the // vertices adjacent to this // vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) bool[] visited = new bool[V]; // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver code public static void Main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine( "Following is Depth First Traversal"); g.DFS(); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to print DFS // traversal from a given given // graph // This class represents a // directed graph using adjacency // list representation class Graph { // Constructor constructor(v) { this.V = v; this.adj = new Array(v).fill([]); } // Function to Add an edge into the graph AddEdge(v, w) { this.adj[v].push(w); // Add w to v's list. } // A function used by DFS DFSUtil(v, visited) { // Mark the current // node as visited and print it visited[v] = true; document.write(v + " "); // Recur for all the // vertices adjacent to this // vertex for (const n of this.adj[v]) { if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() DFS() { // Mark all the vertices as not visited(set as var visited = new Array(this.V).fill(false); // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (var i = 0; i < this.V; ++i) if (visited[i] == false) this.DFSUtil(i, visited); } } // Driver Code var g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); document.write("Following is Depth First Traversal<br>"); g.DFS(); // This code is contributed by rdtank. </script>
Output:
Following is Depth First Traversal
0 1 2 3 9
Complexity Analysis:
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Space Complexity: O(V), since an extra visited array of size V is required.
https://youtu.be/Y40bRyPQQr0
Applications of DFS.
Breadth-First Traversal for a Graph
Recent Articles on DFS
Would you please write comments if you find anything incorrect or share more information about the topic discussed above?
speak2rk09
techno2mahi
princiraj1992
eshankvaish
andrew1234
draco_malf0y
nikhil104
akashgoac
itisvishnudev
koushalsagar66
rdtank
avanitrachhadiya2155
dheerajkumar33
tanvimoharir
byromjomaa
amartyaghoshgfg
DFS
graph-basics
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Floyd Warshall Algorithm | DP-16
Traveling Salesman Problem (TSP) Implementation
Minimum number of swaps required to sort an array
Strongly Connected Components
Find the number of islands | Set 1 (Using DFS)
Shortest path in an unweighted graph
Iterative Depth First Traversal of Graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
|
[
{
"code": null,
"e": 30545,
"s": 30517,
"text": "\n30 Jan, 2022"
},
{
"code": null,
"e": 30806,
"s": 30545,
"text": "Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. "
},
{
"code": null,
"e": 30816,
"s": 30806,
"text": "Example: "
},
{
"code": null,
"e": 30947,
"s": 30816,
"text": "Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram: "
},
{
"code": null,
"e": 31078,
"s": 30947,
"text": "Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram: "
},
{
"code": null,
"e": 31154,
"s": 31078,
"text": "Prerequisites: See this post for all applications of Depth First Traversal."
},
{
"code": null,
"e": 31734,
"s": 31154,
"text": "Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path."
},
{
"code": null,
"e": 31827,
"s": 31734,
"text": "Algorithm: Create a recursive function that takes the index of the node and a visited array."
},
{
"code": null,
"e": 31993,
"s": 31827,
"text": "Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node."
},
{
"code": null,
"e": 32046,
"s": 31993,
"text": "Mark the current node as visited and print the node."
},
{
"code": null,
"e": 32160,
"s": 32046,
"text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node."
},
{
"code": null,
"e": 32370,
"s": 32160,
"text": "Implementation: Below are implementations of simple Depth First Traversal. The C++ implementation uses an adjacency list representation of graphs. STL’s list container is used to store lists of adjacent nodes."
},
{
"code": null,
"e": 32374,
"s": 32370,
"text": "C++"
},
{
"code": null,
"e": 32379,
"s": 32374,
"text": "Java"
},
{
"code": null,
"e": 32387,
"s": 32379,
"text": "Python3"
},
{
"code": null,
"e": 32390,
"s": 32387,
"text": "C#"
},
{
"code": null,
"e": 32401,
"s": 32390,
"text": "Javascript"
},
{
"code": "// C++ program to print DFS traversal from// a given vertex in a given graph#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph {public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFS(int v){ // Mark the current node as visited and // print it visited[v] = true; cout << v << \" \"; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << \"Following is Depth First Traversal\" \" (starting from vertex 2) \\n\"; g.DFS(2); return 0;} // improved by Vishnudev C",
"e": 33581,
"s": 32401,
"text": null
},
{
"code": "// Java program to print DFS// mtraversal from a given given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + \" \"); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() void DFS(int v) { // Mark all the vertices as // not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper // function to print DFS // traversal DFSUtil(v, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( \"Following is Depth First Traversal \" + \"(starting from vertex 2)\"); g.DFS(2); }}// This code is contributed by Aakash Hasija",
"e": 35496,
"s": 33581,
"text": null
},
{
"code": "# Python3 program to print DFS traversal# from a given given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print(\"Following is DFS from (starting from vertex 2)\")g.DFS(2) # This code is contributed by Neelam Yadav",
"e": 36826,
"s": 35496,
"text": null
},
{
"code": "// C# program to print DFS traversal// from a given graphusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to Add an edge into the graph void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current node as visited // and print it visited[v] = true; Console.Write(v + \" \"); // Recur for all the vertices // adjacent to this vertex List<int> vList = adj[v]; foreach(var n in vList) { if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited // (set as false by default in c#) bool[] visited = new bool[V]; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); } // Driver Code public static void Main(String[] args) { Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.WriteLine( \"Following is Depth First Traversal \" + \"(starting from vertex 2)\"); g.DFS(2); Console.ReadKey(); }} // This code is contributed by techno2mahi",
"e": 38654,
"s": 36826,
"text": null
},
{
"code": "<script> // Javascript program to print DFS// traversal from a given given// graph // This class represents a// directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { // Add w to v's list. this.adj[v].push(w); } // A function used by DFS DFSUtil(v, visited) { // Mark the current node as visited and print it visited[v] = true; document.write(v + \" \"); // Recur for all the vertices adjacent to this // vertex for(let i of this.adj[v].values()) { let n = i if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() DFS(v) { // Mark all the vertices as // not visited(set as // false by default in java) let visited = new Array(this.V); for(let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper // function to print DFS // traversal this.DFSUtil(v, visited); }} // Driver Codeg = new Graph(4); g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.addEdge(3, 3); document.write(\"Following is Depth First Traversal \" + \"(starting from vertex 2)<br>\"); g.DFS(2); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 40304,
"s": 38654,
"text": null
},
{
"code": null,
"e": 40313,
"s": 40304,
"text": "Output: "
},
{
"code": null,
"e": 40381,
"s": 40313,
"text": "Following is Depth First Traversal (starting from vertex 2)\n2 0 1 3"
},
{
"code": null,
"e": 40403,
"s": 40381,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 40507,
"s": 40403,
"text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph."
},
{
"code": null,
"e": 40583,
"s": 40507,
"text": "Space Complexity: O(V), since an extra visited array of size V is required."
},
{
"code": null,
"e": 40615,
"s": 40583,
"text": " Handling A Disconnected Graph:"
},
{
"code": null,
"e": 40971,
"s": 40615,
"text": "Solution: This will happen by handling a corner case. The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex, as in a Disconnected graph. To do a complete DFS traversal of such graphs, run DFS from all unvisited nodes after a DFS. The recursive function remains the same."
},
{
"code": null,
"e": 41379,
"s": 40971,
"text": "Algorithm: Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node."
},
{
"code": null,
"e": 41776,
"s": 41379,
"text": "Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node."
},
{
"code": null,
"e": 41858,
"s": 41776,
"text": "Create a recursive function that takes the index of the node and a visited array."
},
{
"code": null,
"e": 41911,
"s": 41858,
"text": "Mark the current node as visited and print the node."
},
{
"code": null,
"e": 42025,
"s": 41911,
"text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node."
},
{
"code": null,
"e": 42176,
"s": 42025,
"text": "Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node."
},
{
"code": null,
"e": 42193,
"s": 42176,
"text": "Implementation: "
},
{
"code": null,
"e": 42197,
"s": 42193,
"text": "C++"
},
{
"code": null,
"e": 42202,
"s": 42197,
"text": "Java"
},
{
"code": null,
"e": 42210,
"s": 42202,
"text": "Python3"
},
{
"code": null,
"e": 42213,
"s": 42210,
"text": "C#"
},
{
"code": null,
"e": 42224,
"s": 42213,
"text": "Javascript"
},
{
"code": "// C++ program to print DFS// traversal for a given given// graph#include <bits/stdc++.h>using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFSUtil(int v){ // Mark the current node as visited and print it visited[v] = true; cout << v << \" \"; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i);} // The function to do DFS traversal. It uses recursive// DFSUtil()void Graph::DFS(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first);} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << \"Following is Depth First Traversal \\n\"; g.DFS(); return 0;}// improved by Vishnudev C",
"e": 43590,
"s": 42224,
"text": null
},
{
"code": "// Java program to print DFS// traversal from a given given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + \" \"); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( \"Following is Depth First Traversal\"); g.DFS(); }}// This code is contributed by Aakash Hasija",
"e": 45548,
"s": 43590,
"text": null
},
{
"code": "'''Python program to print DFS traversal for complete graph'''from collections import defaultdict # this class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited.add(v) print(v,end=\" \") # recur for all the vertices adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses recursive DFSUtil def DFS(self): # create a set to store all visited vertices visited = set() # call the recursive helper function to print DFS traversal starting from all # vertices one by one for vertex in self.graph: if vertex not in visited: self.DFSUtil(vertex, visited)# Driver code# create a graph given in the above diagram print(\"Following is Depth First Traversal \\n\")g = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)g.DFS() # Improved by Dheeraj Kumar",
"e": 46939,
"s": 45548,
"text": null
},
{
"code": "// C# program to print DFS// traversal from a given given// graphusing System;using System.Collections.Generic; // This class represents a// directed graph using adjacency// list representationpublic class Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current // node as visited and print it visited[v] = true; Console.Write(v + \" \"); // Recur for all the // vertices adjacent to this // vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) bool[] visited = new bool[V]; // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver code public static void Main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine( \"Following is Depth First Traversal\"); g.DFS(); }} // This code is contributed by PrinciRaj1992",
"e": 48857,
"s": 46939,
"text": null
},
{
"code": "<script> // JavaScript program to print DFS // traversal from a given given // graph // This class represents a // directed graph using adjacency // list representation class Graph { // Constructor constructor(v) { this.V = v; this.adj = new Array(v).fill([]); } // Function to Add an edge into the graph AddEdge(v, w) { this.adj[v].push(w); // Add w to v's list. } // A function used by DFS DFSUtil(v, visited) { // Mark the current // node as visited and print it visited[v] = true; document.write(v + \" \"); // Recur for all the // vertices adjacent to this // vertex for (const n of this.adj[v]) { if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() DFS() { // Mark all the vertices as not visited(set as var visited = new Array(this.V).fill(false); // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (var i = 0; i < this.V; ++i) if (visited[i] == false) this.DFSUtil(i, visited); } } // Driver Code var g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); document.write(\"Following is Depth First Traversal<br>\"); g.DFS(); // This code is contributed by rdtank. </script>",
"e": 50583,
"s": 48857,
"text": null
},
{
"code": null,
"e": 50592,
"s": 50583,
"text": "Output: "
},
{
"code": null,
"e": 50637,
"s": 50592,
"text": "Following is Depth First Traversal\n0 1 2 3 9"
},
{
"code": null,
"e": 50659,
"s": 50637,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 50763,
"s": 50659,
"text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph."
},
{
"code": null,
"e": 50839,
"s": 50763,
"text": "Space Complexity: O(V), since an extra visited array of size V is required."
},
{
"code": null,
"e": 50869,
"s": 50839,
"text": "https://youtu.be/Y40bRyPQQr0 "
},
{
"code": null,
"e": 50890,
"s": 50869,
"text": "Applications of DFS."
},
{
"code": null,
"e": 50926,
"s": 50890,
"text": "Breadth-First Traversal for a Graph"
},
{
"code": null,
"e": 50949,
"s": 50926,
"text": "Recent Articles on DFS"
},
{
"code": null,
"e": 51071,
"s": 50949,
"text": "Would you please write comments if you find anything incorrect or share more information about the topic discussed above?"
},
{
"code": null,
"e": 51082,
"s": 51071,
"text": "speak2rk09"
},
{
"code": null,
"e": 51094,
"s": 51082,
"text": "techno2mahi"
},
{
"code": null,
"e": 51108,
"s": 51094,
"text": "princiraj1992"
},
{
"code": null,
"e": 51120,
"s": 51108,
"text": "eshankvaish"
},
{
"code": null,
"e": 51131,
"s": 51120,
"text": "andrew1234"
},
{
"code": null,
"e": 51144,
"s": 51131,
"text": "draco_malf0y"
},
{
"code": null,
"e": 51154,
"s": 51144,
"text": "nikhil104"
},
{
"code": null,
"e": 51164,
"s": 51154,
"text": "akashgoac"
},
{
"code": null,
"e": 51178,
"s": 51164,
"text": "itisvishnudev"
},
{
"code": null,
"e": 51193,
"s": 51178,
"text": "koushalsagar66"
},
{
"code": null,
"e": 51200,
"s": 51193,
"text": "rdtank"
},
{
"code": null,
"e": 51221,
"s": 51200,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 51236,
"s": 51221,
"text": "dheerajkumar33"
},
{
"code": null,
"e": 51249,
"s": 51236,
"text": "tanvimoharir"
},
{
"code": null,
"e": 51260,
"s": 51249,
"text": "byromjomaa"
},
{
"code": null,
"e": 51276,
"s": 51260,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 51280,
"s": 51276,
"text": "DFS"
},
{
"code": null,
"e": 51293,
"s": 51280,
"text": "graph-basics"
},
{
"code": null,
"e": 51299,
"s": 51293,
"text": "Graph"
},
{
"code": null,
"e": 51303,
"s": 51299,
"text": "DFS"
},
{
"code": null,
"e": 51309,
"s": 51303,
"text": "Graph"
},
{
"code": null,
"e": 51407,
"s": 51309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51438,
"s": 51407,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 51506,
"s": 51438,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 51539,
"s": 51506,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 51587,
"s": 51539,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 51637,
"s": 51587,
"text": "Minimum number of swaps required to sort an array"
},
{
"code": null,
"e": 51667,
"s": 51637,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 51714,
"s": 51667,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 51751,
"s": 51714,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 51792,
"s": 51751,
"text": "Iterative Depth First Traversal of Graph"
}
] |
SQL at Scale with Apache Spark SQL and DataFrames — Concepts, Architecture and Examples | by Dipanjan (DJ) Sarkar | Towards Data Science
|
This article covers detailed concepts pertaining to Spark, SQL and DataFrames. Besides this we also cover a hands-on case study around working with SQL at scale using Spark SQL and DataFrames. If the article seems a bit overwhelming or really long to you at the first glance, feel free to check out the same in more bite-sized chunks in the following links at opensource.com
Scaling relational databases with Apache Spark SQL and DataFrames
How to use Spark SQL: A hands-on tutorial
I hope this helps you out on your own journey with Spark and SQL!
Relational Databases are here to stay, regardless of the hype as well as the advent of newer databases often popularly termed as ‘NoSQL’ databases. The simple reason is that these databases enforce essential structure, constraints and provide a nice declarative language to query data, which we love — SQL! However, scale has always been a problem with relational databases. Most enterprises now in the 21st century are loaded with rich data stores and repositories, and want to take maximum advantage of their ‘Big Data’ for actionable insights. Relational databases might be popular, but they don’t scale very well unless we invest in a proper Big Data management strategy. This involves thinking about potential data sources, data volume, constraints, schemas, ETL (extract-transform-load), access and querying patterns and much more!
This article will cover some excellent advances made for leveraging the power of relational databases, but ‘at scale,’ using some of the newer components from Apache Spark — Spark SQL and DataFrames. Most notably, we will cover the following topics.
Goals
Architecture and Features
Performance
Thus, we will be looking at the major challenges and motivation for people working so hard, and investing time in building new components in Apache Spark, so that we could perform SQL at scale. We will also understand major architecture, interfaces, features and performance benchmarks for Spark SQL and DataFrames. Lastly, but most importantly, we will cover a real-world case study on analyzing intrusion attacks based on KDD 99 Cup Data using Spark SQL and DataFrames by leveraging Databricks Cloud Platform for Spark!
Relational data stores are easy to build and query. Also, users as well as developers often prefer writing easy to interpret, declarative queries in a human-like readable language such as SQL. However, as data starts increasing in volume and variety, the relational approach does not scale well enough for building big data applications and analytical system. Following are some major challenges.
Dealing with different types and sources of data which can be structured, semi-structured and unstructured.
Building ETL pipelines to and from various data sources, which may lead to developing a lot of specific custom code, which increases technical debt over time.
Capability to perform both traditional BI (Business Intelligence)-based analytics and advanced analytics (machine learning, statistical modeling etc.) the latter of which is definitely challenging to perform in relational systems.
Big Data Analytics is not something which was just invented yesterday! We have had success in this domain with Hadoop and the Map-Reduce paradigm. This was powerful, but often slow, and also gave users a low-level, procedural programming interface which required people to write a lot of code for even very simple data transformations. However, once Spark was released, it really revolutionized the way big data analytics was done with focus on in-memory computing, fault tolerance, high-level abstractions and ease of use.
From then, several frameworks and systems like Hive, Pig and Shark (which evolved into Spark SQL) provided rich relational interfaces and declarative querying mechanisms to Big Data stores. The challenge remained that these tools were either relational or procedural-based and we couldn’t have the best of both worlds.
However in the real-world, most data and analytical pipelines might involve a combination of relational and procedural code. Thus, forcing users to choose either one ends up complicating things and increasing user efforts in developing, building and maintaining different applications and systems. Apache Spark SQL builds on the previously mentioned SQL-on-Spark effort, called Shark. Instead of forcing users to pick between a relational or a procedural API, Spark SQL tries to enable users to seamlessly intermix the two and perform data querying, retrieval and analysis at scale on Big Data.
Spark SQL essentially tries to bridge the gap between the two models we mentioned previously — the relational and procedural models by two major components.
Spark SQL provides a DataFrame API that can perform relational operations on both external data sources and Spark’s built-in distributed collections — at scale!
To support the a wide variety of diverse data sources and algorithms in big data, Spark SQL introduces a novel extensible optimizer called Catalyst, which makes it easy to add data sources, optimization rules, and data types for advanced analytics such as machine learning.
Essentially, Spark SQL leverages the power of Spark to perform distributed, robust, in-memory computations at massive scale on Big Data. Spark SQL provides state-of-the-art SQL performance, and also maintains compatibility with all existing structures and components supported by Apache Hive (a popular Big Data Warehouse framework) including data formats, user-defined functions (UDFs) and the metastore. Besides this, it also helps in ingesting a wide variety of data formats from Big Data sources and enterprice data warehouses like JSON, Hive, Parquet and so on, and perform a combination of relational and procedural operations for more complex, advanced analytics.
Let’s look at some of the interesting facts about Spark SQL, it’s usage, adoption and goals, some of which I will shamelessly once again copy from the excellent and original paper on Relational Data Processing in Spark. Spark SQL was first released in May 2014, and is perhaps now one of the most actively developed components in Spark. Apache Spark is definitely the most active open source project for big data processing, with hundreds of contributors. Besides being just an open-source project, Spark SQL has actually started seeing mainstream industry adoption! It has already been deployed in very large scale environments. An excellent case-study has been mentioned by Facebook where they talk about ‘Apache Spark @Scale: A 60 TB+ production use case’ — Here, they were doing data preparation for entity ranking and their Hive jobs used to take several days and had many challenges, but they were able to successfully able to scale and increase performance using Spark. Do check out the interesting challenges they faced in this journey!
code.fb.com
Another interesting fact is that 2/3rd of customers of Databricks Cloud (hosted service running Spark), use Spark SQL within other programming languages. We will also showcase a hands-on case study using Spark SQL on Databricks in this article. Stay tuned for that! The major goals for Spark SQL as defined by it’s creators are as follows.
Support relational processing both within Spark programs (on native RDDs) and on external data sources using a programmer friendly API.Provide high performance using established DBMS techniques.Easily support new data sources, including semi-structured data and external databases amenable to query federation.Enable extension with advanced analytics algorithms such as graph processing and machine learning.
Support relational processing both within Spark programs (on native RDDs) and on external data sources using a programmer friendly API.
Provide high performance using established DBMS techniques.
Easily support new data sources, including semi-structured data and external databases amenable to query federation.
Enable extension with advanced analytics algorithms such as graph processing and machine learning.
We will now take a look at the key features and architecture around Spark SQL and DataFrames. Some key concepts to keep in mind here would be around the Spark eco-system which has been constantly evolving over time.
RDDs or “Resilient Distributed Datasets” is perhaps the biggest contributor behind all the success stories of Spark. It is basically a data structure or rather , a distributed memory abstraction to be more precise, that allows programmers to perform in-memory computations on large distributed clusters while retaining aspects like fault tolerance. You can also parallelize a lot of computations, transformations and track the whole lineage of transformations, which can help in efficiently recomputing lost data. Spark enthusiasts do read the excellent paper around RDDs, ‘Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing’. Also, Spark works with the concept of drivers and workers as depicted in the following figure.
You can typically create an RDD by reading in data from files, databases, parallelizing existing collections or even transformations. Typically transformations are operations which can be used to transform the data into different aspects and dimensions depending on the way we want to wrangle and process the data. They are also lazily evaluated meaning that even if you define a transformation, the results are not computed till you apply an action which typically requires a result to be returned to the driver program (and it computed all applied transformations then!).
Shout out to fellow data scientist and friend Favio Vázquez and his excellent article on Deep Learning With Apache Spark from which I got some excellent ideas and content including the preceding figure. Do check it out!
towardsdatascience.com
Now that we know about the general architecture of how Spark works, let’s take a closer look into Spark SQL. Typically, Spark SQL runs as a library on top of Spark, as we have seen in the figure covering the Spark eco-system. The following figure gives a more detailed peek into the typical achitecture and interfaces of Spark SQL.
The figure clearly shows us the various SQL interfaces, which can be accessed through JDBC/ODBC or through a command-line console, as well as the DataFrame API integrated into Spark’s supported programming languages (we will be using Python!). The DataFrame API is very powerful and allows users to finally intermix procedural and relational code! Advanced functions like UDFs (user defined functions) can also be exposed in SQL, which can be used by BI tools.
Spark DataFrames are very interesting and help us leverage the power of Spark SQL and combine its procedural paradigms as needed. A Spark DataFrame is basically a distributed collection of rows (Row types) with the same schema. It is basically a Spark Dataset organized into named columns. A point to note here is that Datasets, are an extension of the DataFrame API that provides a type-safe, object-oriented programming interface. Hence, they are available only in Java and Scala and we will, therefore, be focusing on DataFrames.
A DataFrame is equivalent to a table in a relational database (but with more optimizations under the hood), and can also be manipulated in similar ways to the “native” distributed collections in Spark (RDDs). Spark DataFrames have some interesting properties, some of which are mentioned below.
Unlike RDDs, DataFrames usually keep track of their schema and support various relational operations that lead to a more optimized execution.DataFrames can be constructed from tables, just like existing Hive tables in your Big Data infrastructure, or even from existing RDDs.DataFrames can be manipulated with direct SQL queries and also using the DataFrame DSL (domain-specific language), where we can use various relational operators and transformers such as where and groupByAlso, each DataFrame can also be viewed as an RDD of Row objects, allowing users to call procedural Spark APIs such as mapFinally, a given, but a point to always remember, unlike traditional dataframe APIs (pandas), Spark DataFrames are lazy, in that each DataFrame object represents a logical plan to compute a dataset, but no execution occurs until the user calls a special “output operation” such as save.
Unlike RDDs, DataFrames usually keep track of their schema and support various relational operations that lead to a more optimized execution.
DataFrames can be constructed from tables, just like existing Hive tables in your Big Data infrastructure, or even from existing RDDs.
DataFrames can be manipulated with direct SQL queries and also using the DataFrame DSL (domain-specific language), where we can use various relational operators and transformers such as where and groupBy
Also, each DataFrame can also be viewed as an RDD of Row objects, allowing users to call procedural Spark APIs such as map
Finally, a given, but a point to always remember, unlike traditional dataframe APIs (pandas), Spark DataFrames are lazy, in that each DataFrame object represents a logical plan to compute a dataset, but no execution occurs until the user calls a special “output operation” such as save.
This should give you enough perspective on Spark SQL, DataFrames, essential features, concepts, architecture and interfaces. Let’s wrap up this section by taking a look at performance benchmarks.
Releasing a new feature without the right optimizations can be deadly, and the folks who built Spark did tons of performance tests and benchmarking! Let’s take a look at some interesting results. The first figure showcasing some results is depicted below.
In these experiments, they compared the performance of Spark SQL against Shark and Impala using the AMPLab big data benchmark, which uses a web analytics workload developed by Pavlo et al. The benchmark contains four types of queries with different parameters performing scans, aggregation, joins and a UDF-based MapReduce job. The dataset was 110 GB of data after compression using the columnar Parquet format. We see that in all queries, Spark SQL is substantially faster than Shark, and generally competitive with Impala. The Catalyst optimizer is responsible for this, which reduces CPU overhead (we shall cover this briefly). This feature makes Spark SQL competitive with the C++ and LLVM-based Impala engine in many of these queries. The largest gap from Impala is in query 3a where Impala chooses a better join plan, because the selectivity of the queries makes one of the tables very small.
Following graphs show some more performance benchmarks for DataFrames and regular Spark APIs and Spark + SQL.
Finally, the following graph shows a nice benchmark result of DataFrames vs. RDDs in different languages, which gives an interesting perspective on how optimized DataFrames can be!
Why is Spark SQL so fast and optimized? The reason is, because of a new extensible optimizer, Catalyst, based on functional programming constructs in Scala. While we won’t go into too extensive details about Catalyst here, it is worth a mention since it helps in optimizing DataFrame operations and queries.
Catalyst’s extensible design has two purposes.
Making it easy to add new optimization techniques and features to Spark SQL, especially to tackle diverse problems around ‘Big Data’, semi-structured data and advanced analytics.
Ease of being able to extend the optimizer — for example, by adding data source-specific rules that can push filtering or aggregation into external storage systems, or support for new data types.
Catalyst supports both rule-based and cost-based optimization. While extensible optimizers have been proposed in the past, they have typically required a complex domain-specific language to specify rules. Usually, this leads to having a significant learning curve and maintenance burden. In contrast, Catalyst uses standard features of the Scala programming language, such as pattern-matching, to let developers use the full programming language while still making rules easy to specify.
At its core, Catalyst contains a general library for representing trees and applying rules to manipulate them. On top of this framework, it has libraries specific to relational query processing (e.g., expressions, logical query plans), and several sets of rules that handle different phases of query execution: analysis, logical optimization, physical planning, and code generation to compile parts of queries to Java bytecode. Interested in knowing more details about Catalyst and doing a deep-dive? You can check out an excellent article from Databricks!
databricks.com
We will now do a simple tutorial based on a real-world dataset to look at how to use Spark SQL. We will be using Spark DataFrames but the focus will be more on using SQL. I will be covering a detailed discussion around Spark DataFrames and common operations in a separate article. I love using cloud services for my machine learning, deep learning and even Big Data Analytics needs. Instead of painfully setting up your own Spark cluster, use one of the best in the Cloud! We will be using the Databricks Platform for our Spark needs! Databricks is a company founded by the creators of Apache Spark, that aims to help clients with cloud-based big data processing using Spark.
The simplest way (and free of charge) is to go to the Try Databricks page and sign up for an account using the community edition where you get a cloud-based cluster, which is a single node cluster with 6 GB and unlimited notebooks, not bad for a free version! I definitely recommend using the Databricks Platform if you have serious needs for analyzing Big Data!
Let’s get started with our case study now, feel free to create a new notebook from your home screen in Databricks or your own Spark cluster as depicted in the following snapshot.
You can also import my notebook containing the entire tutorial but do run every cell and play around with it and explore instead of just reading through it. Unsure of how to use Spark on Databricks? Follow this short but useful tutorial and get started today!
databricks.com
This tutorial will familiarize you with essential Spark capabilities to deal with structured data often obtained from databases or flat files. We will explore typical ways of querying and aggregating relational data by leveraging concepts of DataFrames and SQL using Spark. We will work on an interesting dataset from the KDD Cup 1999 and try to query the data using high level abstrations like the dataframe which has already been a hit in popular data analysis tools like R and Python. We will also look at how easy it is to build data queries using the SQL language, which you have learnt, and retrieve insightful information from our data. This also happens at scale without us having to do a lot more since Spark distributes these data structures efficiently in the back-end, which makes our queries scalable and as efficient as possible. We start by loading some basic dependencies.
import pandas as pdimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')
We will use data from the KDD Cup 1999, which is the data set used for The Third International Knowledge Discovery and Data Mining Tools Competition, which was held in conjunction with KDD-99 The Fifth International Conference on Knowledge Discovery and Data Mining. The competition task was to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good, normal connections. This database contains a standard set of data to be audited, which includes a wide variety of intrusions simulated in a military network environment.
We will be using the reduced dataset kddcup.data_10_percent.gz containing nearly half a million nework interactions, since we would be downloading this Gzip file from the web locally, and then work on the same. If you have a good, stable internet connection, feel free to download and work with the full dataset available as kddcup.data.gz.
Dealing with datasets retrieved from the web can be a bit tricky in Databricks. Fortunately, we have some excellent utility packages like dbutils which help in making our job easier. Let's take a quick look at some essential functions for this module.
dbutils.help()This module provides various utilities for users to interact with the rest of Databricks.fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the consolemeta: MetaUtils -> Methods to hook into the compiler (EXPERIMENTAL)notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)preview: Preview -> Utilities under preview categorysecrets: SecretUtils -> Provides utilities for leveraging secrets within notebookswidgets: WidgetsUtils -> Methods to create and get bound value of input widgets inside notebooks
We will now leverage the python urllib library to extract the KDD Cup 99 data from their web repository, store it in a temporary location, and then move it to the Databricks filesystem, which can enable easy access to this data for analysis
Note: If you skip this step and download the data directly, you may end up getting a InvalidInputException: Input path does not exist error
Now that we have our data stored in the Databricks filesystem, let’s load up our data from the disk into Spark’s traditional abstracted data structure, the Resilient Distributed Dataset (RDD)
You can also verify the type of data structure of our data (RDD) using the following code.
type(raw_rdd)
A Spark DataFrame is an interesting data structure representing a distributed collecion of data. Typically the entry point into all SQL functionality in Spark is the SQLContext class. To create a basic instance of this call, all we need is a SparkContext reference. In Databricks, this global context object is available as sc for this purpose.
Each entry in our RDD is a comma-separated line of data which we first need to split before we can parse and build our dataframe.
We can use the following code to check the total number of potential columns in our dataset.
len(csv_rdd.take(1)[0])Out[57]: 42
The KDD 99 Cup data consists of different attributes captured from connection data. The full list of attributes in the data can be obtained here and further details pertaining to the description for each attribute\column can be found here. We will just be using some specific columns from the dataset, the details of which are specified as follows.
We will be extracting the following columns based on their positions in each datapoint (row) and build a new RDD as follows.
Now that our data is neatly parsed and formatted, let’s build our DataFrame!
You can also now check out the schema of our dataframe using the following code.
df.printSchema()
We can leverage the registerTempTable() function to build a temporaty table to run SQL commands on our DataFrame at scale! A point to remember is that the lifetime of this temp table is tied to the session. It creates an in-memory table that is scoped to the cluster in which it was created. The data is stored using Hive's highly-optimized, in-memory columnar format.
You can also check out saveAsTable() which creates a permanent, physical table stored in S3 using the Parquet format. This table is accessible to all clusters. The table metadata including the location of the file(s) is stored within the Hive metastore.
help(df.registerTempTable)
df.registerTempTable("connections")
Let’s look at a few examples of how we can run SQL queries on our table based off our dataframe. We will start with some simple queries and then look at aggregations, filters, sorting, sub-queries and pivots in this tutorial.
Let’s look at how we can get the total number of connections based on the type of connectivity protocol. First, we will get this information using normal DataFrame DSL syntax to perform aggregations.
Can we also use SQL to perform the same aggregation? Yes, we can leverage the table we built earlier for this!
You can clearly see, that you get the same results and you do not need to worry about your background infrastructure or how the code is executed. Just write simple SQL!
We will now run a simple aggregation to check the total number of connections based on good (normal) or bad (intrusion attacks) types.
We have a lot of different attack types. We can visualize this in the form of a bar chart. The simplest way is to use the excellent interface options in the Databricks notebook itself!
This gives us the following nice looking bar chart! Which you can customize further by clicking on Plot Options as needed.
Another way is to write the code yourself to do it. You can extract the aggregated data as a pandas DataFrame and then plot it as a regular bar chart.
Let’s look at which protocols are most vulnerable to attacks now based on the following SQL query.
Well, looks like ICMP connections followed by TCP connections have had the maximum attacks!
Let’s take a look at some statistical measures pertaining to these protocols and attacks for our connection requests.
Looks like average amount of data being transmitted in TCP requests are much higher which is not surprising. Interestingly, attacks have a much higher average payload of data being transmitted from the source to the destination.
Let’s take a closer look at TCP attacks given that we have more relevant data and statistics for the same. We will now aggregate different types of TCP attacks based on service, attack type and observe different metrics.
There are a lot of attack types and the preceding output shows a specific section of the same.
We will now filter some of these attack types by imposing some constraints based on duration, file creations, root accesses in our query.
Interesting to see multihop attacks being able to get root accesses to the destination hosts!
Let’s try to get all the TCP attacks based on service and attack type such that the overall mean duration of these attacks is greater than zero (> 0). For this, we can do an inner query with all aggregation statistics and then extract the relevant queries and apply a mean duration filter in the outer query as shown below.
This is nice! Now an interesting way to also view this data is to use a pivot table where one attribute represents rows, and another one represents columns. Let’s see if we can leverage Spark DataFrames to do this!
Here, we will build upon the previous DataFrame object we obtained where we aggregated attacks based on type and service. For this, we can leverage the power of Spark DataFrames and the DataFrame DSL.
We get a nice neat pivot table showing all the occurrences based on service and attack type!
I would encourage you to go out and play with Spark SQL and DataFrames, you can even import my notebook and play with it yourself in your own account.
Feel free to refer to my GitHub repository also for all the code and notebooks used in this article. What we didn’t cover here includes the following.
Joins
Window Functions
Detailed operations and Transformations of Spark DataFrames
There are plenty of articles\tutorials available online so I would recommend you to check them out. Some useful resources for you to check out include, the complete guide to Spark SQL from Databricks.
docs.databricks.com
Thinking of working with JSON data but unsure of using Spark SQL. They support it! Check out this excellent guide to JSON support in Spark SQL.
databricks.com
Interested in advanced concepts like window functions and ranks in SQL? Check out this excellent article on Window Functions in Spark SQL
databricks.com
I will also write a followup article to this covering some of these concepts in an intuitive way which should be easy for you to understand. Stay tuned!
You can directly access my notebook on Databricks by going to this link and import it directly and play around with it
databricks-prod-cloudfront.cloud.databricks.com
All the code and resources for this tutorial is available on my GitHub
github.com
You can also access my tutorial as a Jupyter Notebook in case you want to use it offline.
nbviewer.jupyter.org
Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn.
www.linkedin.com
Thanks to Durba for editing this article.
|
[
{
"code": null,
"e": 547,
"s": 172,
"text": "This article covers detailed concepts pertaining to Spark, SQL and DataFrames. Besides this we also cover a hands-on case study around working with SQL at scale using Spark SQL and DataFrames. If the article seems a bit overwhelming or really long to you at the first glance, feel free to check out the same in more bite-sized chunks in the following links at opensource.com"
},
{
"code": null,
"e": 613,
"s": 547,
"text": "Scaling relational databases with Apache Spark SQL and DataFrames"
},
{
"code": null,
"e": 655,
"s": 613,
"text": "How to use Spark SQL: A hands-on tutorial"
},
{
"code": null,
"e": 721,
"s": 655,
"text": "I hope this helps you out on your own journey with Spark and SQL!"
},
{
"code": null,
"e": 1559,
"s": 721,
"text": "Relational Databases are here to stay, regardless of the hype as well as the advent of newer databases often popularly termed as ‘NoSQL’ databases. The simple reason is that these databases enforce essential structure, constraints and provide a nice declarative language to query data, which we love — SQL! However, scale has always been a problem with relational databases. Most enterprises now in the 21st century are loaded with rich data stores and repositories, and want to take maximum advantage of their ‘Big Data’ for actionable insights. Relational databases might be popular, but they don’t scale very well unless we invest in a proper Big Data management strategy. This involves thinking about potential data sources, data volume, constraints, schemas, ETL (extract-transform-load), access and querying patterns and much more!"
},
{
"code": null,
"e": 1809,
"s": 1559,
"text": "This article will cover some excellent advances made for leveraging the power of relational databases, but ‘at scale,’ using some of the newer components from Apache Spark — Spark SQL and DataFrames. Most notably, we will cover the following topics."
},
{
"code": null,
"e": 1815,
"s": 1809,
"text": "Goals"
},
{
"code": null,
"e": 1841,
"s": 1815,
"text": "Architecture and Features"
},
{
"code": null,
"e": 1853,
"s": 1841,
"text": "Performance"
},
{
"code": null,
"e": 2375,
"s": 1853,
"text": "Thus, we will be looking at the major challenges and motivation for people working so hard, and investing time in building new components in Apache Spark, so that we could perform SQL at scale. We will also understand major architecture, interfaces, features and performance benchmarks for Spark SQL and DataFrames. Lastly, but most importantly, we will cover a real-world case study on analyzing intrusion attacks based on KDD 99 Cup Data using Spark SQL and DataFrames by leveraging Databricks Cloud Platform for Spark!"
},
{
"code": null,
"e": 2772,
"s": 2375,
"text": "Relational data stores are easy to build and query. Also, users as well as developers often prefer writing easy to interpret, declarative queries in a human-like readable language such as SQL. However, as data starts increasing in volume and variety, the relational approach does not scale well enough for building big data applications and analytical system. Following are some major challenges."
},
{
"code": null,
"e": 2880,
"s": 2772,
"text": "Dealing with different types and sources of data which can be structured, semi-structured and unstructured."
},
{
"code": null,
"e": 3039,
"s": 2880,
"text": "Building ETL pipelines to and from various data sources, which may lead to developing a lot of specific custom code, which increases technical debt over time."
},
{
"code": null,
"e": 3270,
"s": 3039,
"text": "Capability to perform both traditional BI (Business Intelligence)-based analytics and advanced analytics (machine learning, statistical modeling etc.) the latter of which is definitely challenging to perform in relational systems."
},
{
"code": null,
"e": 3794,
"s": 3270,
"text": "Big Data Analytics is not something which was just invented yesterday! We have had success in this domain with Hadoop and the Map-Reduce paradigm. This was powerful, but often slow, and also gave users a low-level, procedural programming interface which required people to write a lot of code for even very simple data transformations. However, once Spark was released, it really revolutionized the way big data analytics was done with focus on in-memory computing, fault tolerance, high-level abstractions and ease of use."
},
{
"code": null,
"e": 4113,
"s": 3794,
"text": "From then, several frameworks and systems like Hive, Pig and Shark (which evolved into Spark SQL) provided rich relational interfaces and declarative querying mechanisms to Big Data stores. The challenge remained that these tools were either relational or procedural-based and we couldn’t have the best of both worlds."
},
{
"code": null,
"e": 4708,
"s": 4113,
"text": "However in the real-world, most data and analytical pipelines might involve a combination of relational and procedural code. Thus, forcing users to choose either one ends up complicating things and increasing user efforts in developing, building and maintaining different applications and systems. Apache Spark SQL builds on the previously mentioned SQL-on-Spark effort, called Shark. Instead of forcing users to pick between a relational or a procedural API, Spark SQL tries to enable users to seamlessly intermix the two and perform data querying, retrieval and analysis at scale on Big Data."
},
{
"code": null,
"e": 4865,
"s": 4708,
"text": "Spark SQL essentially tries to bridge the gap between the two models we mentioned previously — the relational and procedural models by two major components."
},
{
"code": null,
"e": 5026,
"s": 4865,
"text": "Spark SQL provides a DataFrame API that can perform relational operations on both external data sources and Spark’s built-in distributed collections — at scale!"
},
{
"code": null,
"e": 5300,
"s": 5026,
"text": "To support the a wide variety of diverse data sources and algorithms in big data, Spark SQL introduces a novel extensible optimizer called Catalyst, which makes it easy to add data sources, optimization rules, and data types for advanced analytics such as machine learning."
},
{
"code": null,
"e": 5971,
"s": 5300,
"text": "Essentially, Spark SQL leverages the power of Spark to perform distributed, robust, in-memory computations at massive scale on Big Data. Spark SQL provides state-of-the-art SQL performance, and also maintains compatibility with all existing structures and components supported by Apache Hive (a popular Big Data Warehouse framework) including data formats, user-defined functions (UDFs) and the metastore. Besides this, it also helps in ingesting a wide variety of data formats from Big Data sources and enterprice data warehouses like JSON, Hive, Parquet and so on, and perform a combination of relational and procedural operations for more complex, advanced analytics."
},
{
"code": null,
"e": 7016,
"s": 5971,
"text": "Let’s look at some of the interesting facts about Spark SQL, it’s usage, adoption and goals, some of which I will shamelessly once again copy from the excellent and original paper on Relational Data Processing in Spark. Spark SQL was first released in May 2014, and is perhaps now one of the most actively developed components in Spark. Apache Spark is definitely the most active open source project for big data processing, with hundreds of contributors. Besides being just an open-source project, Spark SQL has actually started seeing mainstream industry adoption! It has already been deployed in very large scale environments. An excellent case-study has been mentioned by Facebook where they talk about ‘Apache Spark @Scale: A 60 TB+ production use case’ — Here, they were doing data preparation for entity ranking and their Hive jobs used to take several days and had many challenges, but they were able to successfully able to scale and increase performance using Spark. Do check out the interesting challenges they faced in this journey!"
},
{
"code": null,
"e": 7028,
"s": 7016,
"text": "code.fb.com"
},
{
"code": null,
"e": 7368,
"s": 7028,
"text": "Another interesting fact is that 2/3rd of customers of Databricks Cloud (hosted service running Spark), use Spark SQL within other programming languages. We will also showcase a hands-on case study using Spark SQL on Databricks in this article. Stay tuned for that! The major goals for Spark SQL as defined by it’s creators are as follows."
},
{
"code": null,
"e": 7777,
"s": 7368,
"text": "Support relational processing both within Spark programs (on native RDDs) and on external data sources using a programmer friendly API.Provide high performance using established DBMS techniques.Easily support new data sources, including semi-structured data and external databases amenable to query federation.Enable extension with advanced analytics algorithms such as graph processing and machine learning."
},
{
"code": null,
"e": 7913,
"s": 7777,
"text": "Support relational processing both within Spark programs (on native RDDs) and on external data sources using a programmer friendly API."
},
{
"code": null,
"e": 7973,
"s": 7913,
"text": "Provide high performance using established DBMS techniques."
},
{
"code": null,
"e": 8090,
"s": 7973,
"text": "Easily support new data sources, including semi-structured data and external databases amenable to query federation."
},
{
"code": null,
"e": 8189,
"s": 8090,
"text": "Enable extension with advanced analytics algorithms such as graph processing and machine learning."
},
{
"code": null,
"e": 8405,
"s": 8189,
"text": "We will now take a look at the key features and architecture around Spark SQL and DataFrames. Some key concepts to keep in mind here would be around the Spark eco-system which has been constantly evolving over time."
},
{
"code": null,
"e": 9169,
"s": 8405,
"text": "RDDs or “Resilient Distributed Datasets” is perhaps the biggest contributor behind all the success stories of Spark. It is basically a data structure or rather , a distributed memory abstraction to be more precise, that allows programmers to perform in-memory computations on large distributed clusters while retaining aspects like fault tolerance. You can also parallelize a lot of computations, transformations and track the whole lineage of transformations, which can help in efficiently recomputing lost data. Spark enthusiasts do read the excellent paper around RDDs, ‘Resilient Distributed Datasets: A Fault-Tolerant Abstraction for In-Memory Cluster Computing’. Also, Spark works with the concept of drivers and workers as depicted in the following figure."
},
{
"code": null,
"e": 9743,
"s": 9169,
"text": "You can typically create an RDD by reading in data from files, databases, parallelizing existing collections or even transformations. Typically transformations are operations which can be used to transform the data into different aspects and dimensions depending on the way we want to wrangle and process the data. They are also lazily evaluated meaning that even if you define a transformation, the results are not computed till you apply an action which typically requires a result to be returned to the driver program (and it computed all applied transformations then!)."
},
{
"code": null,
"e": 9964,
"s": 9743,
"text": "Shout out to fellow data scientist and friend Favio Vázquez and his excellent article on Deep Learning With Apache Spark from which I got some excellent ideas and content including the preceding figure. Do check it out!"
},
{
"code": null,
"e": 9987,
"s": 9964,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10319,
"s": 9987,
"text": "Now that we know about the general architecture of how Spark works, let’s take a closer look into Spark SQL. Typically, Spark SQL runs as a library on top of Spark, as we have seen in the figure covering the Spark eco-system. The following figure gives a more detailed peek into the typical achitecture and interfaces of Spark SQL."
},
{
"code": null,
"e": 10780,
"s": 10319,
"text": "The figure clearly shows us the various SQL interfaces, which can be accessed through JDBC/ODBC or through a command-line console, as well as the DataFrame API integrated into Spark’s supported programming languages (we will be using Python!). The DataFrame API is very powerful and allows users to finally intermix procedural and relational code! Advanced functions like UDFs (user defined functions) can also be exposed in SQL, which can be used by BI tools."
},
{
"code": null,
"e": 11313,
"s": 10780,
"text": "Spark DataFrames are very interesting and help us leverage the power of Spark SQL and combine its procedural paradigms as needed. A Spark DataFrame is basically a distributed collection of rows (Row types) with the same schema. It is basically a Spark Dataset organized into named columns. A point to note here is that Datasets, are an extension of the DataFrame API that provides a type-safe, object-oriented programming interface. Hence, they are available only in Java and Scala and we will, therefore, be focusing on DataFrames."
},
{
"code": null,
"e": 11608,
"s": 11313,
"text": "A DataFrame is equivalent to a table in a relational database (but with more optimizations under the hood), and can also be manipulated in similar ways to the “native” distributed collections in Spark (RDDs). Spark DataFrames have some interesting properties, some of which are mentioned below."
},
{
"code": null,
"e": 12495,
"s": 11608,
"text": "Unlike RDDs, DataFrames usually keep track of their schema and support various relational operations that lead to a more optimized execution.DataFrames can be constructed from tables, just like existing Hive tables in your Big Data infrastructure, or even from existing RDDs.DataFrames can be manipulated with direct SQL queries and also using the DataFrame DSL (domain-specific language), where we can use various relational operators and transformers such as where and groupByAlso, each DataFrame can also be viewed as an RDD of Row objects, allowing users to call procedural Spark APIs such as mapFinally, a given, but a point to always remember, unlike traditional dataframe APIs (pandas), Spark DataFrames are lazy, in that each DataFrame object represents a logical plan to compute a dataset, but no execution occurs until the user calls a special “output operation” such as save."
},
{
"code": null,
"e": 12637,
"s": 12495,
"text": "Unlike RDDs, DataFrames usually keep track of their schema and support various relational operations that lead to a more optimized execution."
},
{
"code": null,
"e": 12772,
"s": 12637,
"text": "DataFrames can be constructed from tables, just like existing Hive tables in your Big Data infrastructure, or even from existing RDDs."
},
{
"code": null,
"e": 12976,
"s": 12772,
"text": "DataFrames can be manipulated with direct SQL queries and also using the DataFrame DSL (domain-specific language), where we can use various relational operators and transformers such as where and groupBy"
},
{
"code": null,
"e": 13099,
"s": 12976,
"text": "Also, each DataFrame can also be viewed as an RDD of Row objects, allowing users to call procedural Spark APIs such as map"
},
{
"code": null,
"e": 13386,
"s": 13099,
"text": "Finally, a given, but a point to always remember, unlike traditional dataframe APIs (pandas), Spark DataFrames are lazy, in that each DataFrame object represents a logical plan to compute a dataset, but no execution occurs until the user calls a special “output operation” such as save."
},
{
"code": null,
"e": 13582,
"s": 13386,
"text": "This should give you enough perspective on Spark SQL, DataFrames, essential features, concepts, architecture and interfaces. Let’s wrap up this section by taking a look at performance benchmarks."
},
{
"code": null,
"e": 13838,
"s": 13582,
"text": "Releasing a new feature without the right optimizations can be deadly, and the folks who built Spark did tons of performance tests and benchmarking! Let’s take a look at some interesting results. The first figure showcasing some results is depicted below."
},
{
"code": null,
"e": 14737,
"s": 13838,
"text": "In these experiments, they compared the performance of Spark SQL against Shark and Impala using the AMPLab big data benchmark, which uses a web analytics workload developed by Pavlo et al. The benchmark contains four types of queries with different parameters performing scans, aggregation, joins and a UDF-based MapReduce job. The dataset was 110 GB of data after compression using the columnar Parquet format. We see that in all queries, Spark SQL is substantially faster than Shark, and generally competitive with Impala. The Catalyst optimizer is responsible for this, which reduces CPU overhead (we shall cover this briefly). This feature makes Spark SQL competitive with the C++ and LLVM-based Impala engine in many of these queries. The largest gap from Impala is in query 3a where Impala chooses a better join plan, because the selectivity of the queries makes one of the tables very small."
},
{
"code": null,
"e": 14847,
"s": 14737,
"text": "Following graphs show some more performance benchmarks for DataFrames and regular Spark APIs and Spark + SQL."
},
{
"code": null,
"e": 15028,
"s": 14847,
"text": "Finally, the following graph shows a nice benchmark result of DataFrames vs. RDDs in different languages, which gives an interesting perspective on how optimized DataFrames can be!"
},
{
"code": null,
"e": 15336,
"s": 15028,
"text": "Why is Spark SQL so fast and optimized? The reason is, because of a new extensible optimizer, Catalyst, based on functional programming constructs in Scala. While we won’t go into too extensive details about Catalyst here, it is worth a mention since it helps in optimizing DataFrame operations and queries."
},
{
"code": null,
"e": 15383,
"s": 15336,
"text": "Catalyst’s extensible design has two purposes."
},
{
"code": null,
"e": 15562,
"s": 15383,
"text": "Making it easy to add new optimization techniques and features to Spark SQL, especially to tackle diverse problems around ‘Big Data’, semi-structured data and advanced analytics."
},
{
"code": null,
"e": 15758,
"s": 15562,
"text": "Ease of being able to extend the optimizer — for example, by adding data source-specific rules that can push filtering or aggregation into external storage systems, or support for new data types."
},
{
"code": null,
"e": 16246,
"s": 15758,
"text": "Catalyst supports both rule-based and cost-based optimization. While extensible optimizers have been proposed in the past, they have typically required a complex domain-specific language to specify rules. Usually, this leads to having a significant learning curve and maintenance burden. In contrast, Catalyst uses standard features of the Scala programming language, such as pattern-matching, to let developers use the full programming language while still making rules easy to specify."
},
{
"code": null,
"e": 16803,
"s": 16246,
"text": "At its core, Catalyst contains a general library for representing trees and applying rules to manipulate them. On top of this framework, it has libraries specific to relational query processing (e.g., expressions, logical query plans), and several sets of rules that handle different phases of query execution: analysis, logical optimization, physical planning, and code generation to compile parts of queries to Java bytecode. Interested in knowing more details about Catalyst and doing a deep-dive? You can check out an excellent article from Databricks!"
},
{
"code": null,
"e": 16818,
"s": 16803,
"text": "databricks.com"
},
{
"code": null,
"e": 17494,
"s": 16818,
"text": "We will now do a simple tutorial based on a real-world dataset to look at how to use Spark SQL. We will be using Spark DataFrames but the focus will be more on using SQL. I will be covering a detailed discussion around Spark DataFrames and common operations in a separate article. I love using cloud services for my machine learning, deep learning and even Big Data Analytics needs. Instead of painfully setting up your own Spark cluster, use one of the best in the Cloud! We will be using the Databricks Platform for our Spark needs! Databricks is a company founded by the creators of Apache Spark, that aims to help clients with cloud-based big data processing using Spark."
},
{
"code": null,
"e": 17857,
"s": 17494,
"text": "The simplest way (and free of charge) is to go to the Try Databricks page and sign up for an account using the community edition where you get a cloud-based cluster, which is a single node cluster with 6 GB and unlimited notebooks, not bad for a free version! I definitely recommend using the Databricks Platform if you have serious needs for analyzing Big Data!"
},
{
"code": null,
"e": 18036,
"s": 17857,
"text": "Let’s get started with our case study now, feel free to create a new notebook from your home screen in Databricks or your own Spark cluster as depicted in the following snapshot."
},
{
"code": null,
"e": 18296,
"s": 18036,
"text": "You can also import my notebook containing the entire tutorial but do run every cell and play around with it and explore instead of just reading through it. Unsure of how to use Spark on Databricks? Follow this short but useful tutorial and get started today!"
},
{
"code": null,
"e": 18311,
"s": 18296,
"text": "databricks.com"
},
{
"code": null,
"e": 19200,
"s": 18311,
"text": "This tutorial will familiarize you with essential Spark capabilities to deal with structured data often obtained from databases or flat files. We will explore typical ways of querying and aggregating relational data by leveraging concepts of DataFrames and SQL using Spark. We will work on an interesting dataset from the KDD Cup 1999 and try to query the data using high level abstrations like the dataframe which has already been a hit in popular data analysis tools like R and Python. We will also look at how easy it is to build data queries using the SQL language, which you have learnt, and retrieve insightful information from our data. This also happens at scale without us having to do a lot more since Spark distributes these data structures efficiently in the back-end, which makes our queries scalable and as efficient as possible. We start by loading some basic dependencies."
},
{
"code": null,
"e": 19283,
"s": 19200,
"text": "import pandas as pdimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')"
},
{
"code": null,
"e": 19894,
"s": 19283,
"text": "We will use data from the KDD Cup 1999, which is the data set used for The Third International Knowledge Discovery and Data Mining Tools Competition, which was held in conjunction with KDD-99 The Fifth International Conference on Knowledge Discovery and Data Mining. The competition task was to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good, normal connections. This database contains a standard set of data to be audited, which includes a wide variety of intrusions simulated in a military network environment."
},
{
"code": null,
"e": 20235,
"s": 19894,
"text": "We will be using the reduced dataset kddcup.data_10_percent.gz containing nearly half a million nework interactions, since we would be downloading this Gzip file from the web locally, and then work on the same. If you have a good, stable internet connection, feel free to download and work with the full dataset available as kddcup.data.gz."
},
{
"code": null,
"e": 20487,
"s": 20235,
"text": "Dealing with datasets retrieved from the web can be a bit tricky in Databricks. Fortunately, we have some excellent utility packages like dbutils which help in making our job easier. Let's take a quick look at some essential functions for this module."
},
{
"code": null,
"e": 21052,
"s": 20487,
"text": "dbutils.help()This module provides various utilities for users to interact with the rest of Databricks.fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the consolemeta: MetaUtils -> Methods to hook into the compiler (EXPERIMENTAL)notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)preview: Preview -> Utilities under preview categorysecrets: SecretUtils -> Provides utilities for leveraging secrets within notebookswidgets: WidgetsUtils -> Methods to create and get bound value of input widgets inside notebooks"
},
{
"code": null,
"e": 21293,
"s": 21052,
"text": "We will now leverage the python urllib library to extract the KDD Cup 99 data from their web repository, store it in a temporary location, and then move it to the Databricks filesystem, which can enable easy access to this data for analysis"
},
{
"code": null,
"e": 21433,
"s": 21293,
"text": "Note: If you skip this step and download the data directly, you may end up getting a InvalidInputException: Input path does not exist error"
},
{
"code": null,
"e": 21625,
"s": 21433,
"text": "Now that we have our data stored in the Databricks filesystem, let’s load up our data from the disk into Spark’s traditional abstracted data structure, the Resilient Distributed Dataset (RDD)"
},
{
"code": null,
"e": 21716,
"s": 21625,
"text": "You can also verify the type of data structure of our data (RDD) using the following code."
},
{
"code": null,
"e": 21730,
"s": 21716,
"text": "type(raw_rdd)"
},
{
"code": null,
"e": 22075,
"s": 21730,
"text": "A Spark DataFrame is an interesting data structure representing a distributed collecion of data. Typically the entry point into all SQL functionality in Spark is the SQLContext class. To create a basic instance of this call, all we need is a SparkContext reference. In Databricks, this global context object is available as sc for this purpose."
},
{
"code": null,
"e": 22205,
"s": 22075,
"text": "Each entry in our RDD is a comma-separated line of data which we first need to split before we can parse and build our dataframe."
},
{
"code": null,
"e": 22298,
"s": 22205,
"text": "We can use the following code to check the total number of potential columns in our dataset."
},
{
"code": null,
"e": 22333,
"s": 22298,
"text": "len(csv_rdd.take(1)[0])Out[57]: 42"
},
{
"code": null,
"e": 22682,
"s": 22333,
"text": "The KDD 99 Cup data consists of different attributes captured from connection data. The full list of attributes in the data can be obtained here and further details pertaining to the description for each attribute\\column can be found here. We will just be using some specific columns from the dataset, the details of which are specified as follows."
},
{
"code": null,
"e": 22807,
"s": 22682,
"text": "We will be extracting the following columns based on their positions in each datapoint (row) and build a new RDD as follows."
},
{
"code": null,
"e": 22884,
"s": 22807,
"text": "Now that our data is neatly parsed and formatted, let’s build our DataFrame!"
},
{
"code": null,
"e": 22965,
"s": 22884,
"text": "You can also now check out the schema of our dataframe using the following code."
},
{
"code": null,
"e": 22982,
"s": 22965,
"text": "df.printSchema()"
},
{
"code": null,
"e": 23351,
"s": 22982,
"text": "We can leverage the registerTempTable() function to build a temporaty table to run SQL commands on our DataFrame at scale! A point to remember is that the lifetime of this temp table is tied to the session. It creates an in-memory table that is scoped to the cluster in which it was created. The data is stored using Hive's highly-optimized, in-memory columnar format."
},
{
"code": null,
"e": 23605,
"s": 23351,
"text": "You can also check out saveAsTable() which creates a permanent, physical table stored in S3 using the Parquet format. This table is accessible to all clusters. The table metadata including the location of the file(s) is stored within the Hive metastore."
},
{
"code": null,
"e": 23632,
"s": 23605,
"text": "help(df.registerTempTable)"
},
{
"code": null,
"e": 23668,
"s": 23632,
"text": "df.registerTempTable(\"connections\")"
},
{
"code": null,
"e": 23894,
"s": 23668,
"text": "Let’s look at a few examples of how we can run SQL queries on our table based off our dataframe. We will start with some simple queries and then look at aggregations, filters, sorting, sub-queries and pivots in this tutorial."
},
{
"code": null,
"e": 24094,
"s": 23894,
"text": "Let’s look at how we can get the total number of connections based on the type of connectivity protocol. First, we will get this information using normal DataFrame DSL syntax to perform aggregations."
},
{
"code": null,
"e": 24205,
"s": 24094,
"text": "Can we also use SQL to perform the same aggregation? Yes, we can leverage the table we built earlier for this!"
},
{
"code": null,
"e": 24374,
"s": 24205,
"text": "You can clearly see, that you get the same results and you do not need to worry about your background infrastructure or how the code is executed. Just write simple SQL!"
},
{
"code": null,
"e": 24509,
"s": 24374,
"text": "We will now run a simple aggregation to check the total number of connections based on good (normal) or bad (intrusion attacks) types."
},
{
"code": null,
"e": 24694,
"s": 24509,
"text": "We have a lot of different attack types. We can visualize this in the form of a bar chart. The simplest way is to use the excellent interface options in the Databricks notebook itself!"
},
{
"code": null,
"e": 24817,
"s": 24694,
"text": "This gives us the following nice looking bar chart! Which you can customize further by clicking on Plot Options as needed."
},
{
"code": null,
"e": 24968,
"s": 24817,
"text": "Another way is to write the code yourself to do it. You can extract the aggregated data as a pandas DataFrame and then plot it as a regular bar chart."
},
{
"code": null,
"e": 25067,
"s": 24968,
"text": "Let’s look at which protocols are most vulnerable to attacks now based on the following SQL query."
},
{
"code": null,
"e": 25159,
"s": 25067,
"text": "Well, looks like ICMP connections followed by TCP connections have had the maximum attacks!"
},
{
"code": null,
"e": 25277,
"s": 25159,
"text": "Let’s take a look at some statistical measures pertaining to these protocols and attacks for our connection requests."
},
{
"code": null,
"e": 25506,
"s": 25277,
"text": "Looks like average amount of data being transmitted in TCP requests are much higher which is not surprising. Interestingly, attacks have a much higher average payload of data being transmitted from the source to the destination."
},
{
"code": null,
"e": 25727,
"s": 25506,
"text": "Let’s take a closer look at TCP attacks given that we have more relevant data and statistics for the same. We will now aggregate different types of TCP attacks based on service, attack type and observe different metrics."
},
{
"code": null,
"e": 25822,
"s": 25727,
"text": "There are a lot of attack types and the preceding output shows a specific section of the same."
},
{
"code": null,
"e": 25960,
"s": 25822,
"text": "We will now filter some of these attack types by imposing some constraints based on duration, file creations, root accesses in our query."
},
{
"code": null,
"e": 26054,
"s": 25960,
"text": "Interesting to see multihop attacks being able to get root accesses to the destination hosts!"
},
{
"code": null,
"e": 26378,
"s": 26054,
"text": "Let’s try to get all the TCP attacks based on service and attack type such that the overall mean duration of these attacks is greater than zero (> 0). For this, we can do an inner query with all aggregation statistics and then extract the relevant queries and apply a mean duration filter in the outer query as shown below."
},
{
"code": null,
"e": 26593,
"s": 26378,
"text": "This is nice! Now an interesting way to also view this data is to use a pivot table where one attribute represents rows, and another one represents columns. Let’s see if we can leverage Spark DataFrames to do this!"
},
{
"code": null,
"e": 26794,
"s": 26593,
"text": "Here, we will build upon the previous DataFrame object we obtained where we aggregated attacks based on type and service. For this, we can leverage the power of Spark DataFrames and the DataFrame DSL."
},
{
"code": null,
"e": 26887,
"s": 26794,
"text": "We get a nice neat pivot table showing all the occurrences based on service and attack type!"
},
{
"code": null,
"e": 27038,
"s": 26887,
"text": "I would encourage you to go out and play with Spark SQL and DataFrames, you can even import my notebook and play with it yourself in your own account."
},
{
"code": null,
"e": 27189,
"s": 27038,
"text": "Feel free to refer to my GitHub repository also for all the code and notebooks used in this article. What we didn’t cover here includes the following."
},
{
"code": null,
"e": 27195,
"s": 27189,
"text": "Joins"
},
{
"code": null,
"e": 27212,
"s": 27195,
"text": "Window Functions"
},
{
"code": null,
"e": 27272,
"s": 27212,
"text": "Detailed operations and Transformations of Spark DataFrames"
},
{
"code": null,
"e": 27473,
"s": 27272,
"text": "There are plenty of articles\\tutorials available online so I would recommend you to check them out. Some useful resources for you to check out include, the complete guide to Spark SQL from Databricks."
},
{
"code": null,
"e": 27493,
"s": 27473,
"text": "docs.databricks.com"
},
{
"code": null,
"e": 27637,
"s": 27493,
"text": "Thinking of working with JSON data but unsure of using Spark SQL. They support it! Check out this excellent guide to JSON support in Spark SQL."
},
{
"code": null,
"e": 27652,
"s": 27637,
"text": "databricks.com"
},
{
"code": null,
"e": 27790,
"s": 27652,
"text": "Interested in advanced concepts like window functions and ranks in SQL? Check out this excellent article on Window Functions in Spark SQL"
},
{
"code": null,
"e": 27805,
"s": 27790,
"text": "databricks.com"
},
{
"code": null,
"e": 27958,
"s": 27805,
"text": "I will also write a followup article to this covering some of these concepts in an intuitive way which should be easy for you to understand. Stay tuned!"
},
{
"code": null,
"e": 28077,
"s": 27958,
"text": "You can directly access my notebook on Databricks by going to this link and import it directly and play around with it"
},
{
"code": null,
"e": 28125,
"s": 28077,
"text": "databricks-prod-cloudfront.cloud.databricks.com"
},
{
"code": null,
"e": 28196,
"s": 28125,
"text": "All the code and resources for this tutorial is available on my GitHub"
},
{
"code": null,
"e": 28207,
"s": 28196,
"text": "github.com"
},
{
"code": null,
"e": 28297,
"s": 28207,
"text": "You can also access my tutorial as a Jupyter Notebook in case you want to use it offline."
},
{
"code": null,
"e": 28318,
"s": 28297,
"text": "nbviewer.jupyter.org"
},
{
"code": null,
"e": 28499,
"s": 28318,
"text": "Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn."
},
{
"code": null,
"e": 28516,
"s": 28499,
"text": "www.linkedin.com"
}
] |
Find missing number in a sequence in C#
|
Set a list.
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
Now, get the first and last elements −
int a = myList.OrderBy(x => x).First();
int b = myList.OrderBy(x => x).Last();
In a new list, get all the elements and use the Except to get the missing numbers −
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
List<int> remaining = myList2.Except(myList).ToList();
Let us see the complete code −
Live Demo
using System.Collections.Generic;
using System;
using System.Linq;
public class Program {
public static void Main() {
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
Console.WriteLine("Numbers... ");
foreach(int val in myList) {
Console.WriteLine(val);
}
int a = myList.OrderBy(x => x).First();
int b = myList.OrderBy(x => x).Last();
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
List<int> remaining = myList2.Except(myList).ToList();
Console.WriteLine("Remaining numbers... ");
foreach (int res in remaining) {
Console.WriteLine(res);
}
}
}
Numbers...
1
2
3
5
8
9
Remaining numbers...
4
6
7
|
[
{
"code": null,
"e": 1074,
"s": 1062,
"text": "Set a list."
},
{
"code": null,
"e": 1128,
"s": 1074,
"text": "List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};"
},
{
"code": null,
"e": 1167,
"s": 1128,
"text": "Now, get the first and last elements −"
},
{
"code": null,
"e": 1246,
"s": 1167,
"text": "int a = myList.OrderBy(x => x).First();\nint b = myList.OrderBy(x => x).Last();"
},
{
"code": null,
"e": 1330,
"s": 1246,
"text": "In a new list, get all the elements and use the Except to get the missing numbers −"
},
{
"code": null,
"e": 1446,
"s": 1330,
"text": "List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();\nList<int> remaining = myList2.Except(myList).ToList();"
},
{
"code": null,
"e": 1477,
"s": 1446,
"text": "Let us see the complete code −"
},
{
"code": null,
"e": 1488,
"s": 1477,
"text": " Live Demo"
},
{
"code": null,
"e": 2142,
"s": 1488,
"text": "using System.Collections.Generic;\nusing System;\nusing System.Linq;\n\npublic class Program {\n public static void Main() {\n List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};\n Console.WriteLine(\"Numbers... \");\n foreach(int val in myList) {\n Console.WriteLine(val);\n }\n int a = myList.OrderBy(x => x).First();\n int b = myList.OrderBy(x => x).Last();\n List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();\n List<int> remaining = myList2.Except(myList).ToList();\n Console.WriteLine(\"Remaining numbers... \");\n foreach (int res in remaining) {\n Console.WriteLine(res);\n }\n }\n}"
},
{
"code": null,
"e": 2192,
"s": 2142,
"text": "Numbers...\n1\n2\n3\n5\n8\n9\nRemaining numbers...\n4\n6\n7"
}
] |
Completely Randomized Design with R Programming - GeeksforGeeks
|
23 Oct, 2020
Experimental Designs are part of ANOVA in statistics. They are predefined algorithms that help us in analyzing the differences among group means in an experimental unit. Completely Randomized Design (CRD) is one part of the Anova types.
Completely Randomized Design:
The three basic principles of designing an experiment are replication, blocking, and randomization. In this type of design, blocking is not a part of the algorithm. The samples of the experiment are random with replications are assigned to different experimental units. Let’s consider some experiments below and implement the experiment in R programming.
Adding more baking powder to cakes increases the heights of the cake. Let’s see with CRD how the experiment will be analyzed.
As shown in the above figure the baking powder is divided into 4 different tablespoons(tbsp) and four replicate cakes heights (respectively for A, B, C, D) were made with each tbsp in random order. Then the results of tbsp are compared to see if actually the height is affected by baking powder. The replications are just permutations of the different cakes heights respectively for A, B, C, D. Let’s see the above example in R language. The heights of each cake are randomly noted for each tablespoon.
tbsp 0.25 0.5 0.75 1
1.4 7.8 7.6 1.6
#(A,B,C,D)
2.0 9.2 7.0 3.4
#(A,B,D,C)
2.3 6.8 7.3 3.0
#(B,A,D,C)
2.5 6.0 5.5 3.9 #(B,A,C,D)
# the randomization is done directly by the program
The replications of the cakes are done with the below code:
R
treat <- rep(c("A", "B", "C", "D"), each = 4)fac <- factor(rep(c(0.25, 0.5, 0.75, 1), each = 4))treat
Output:
[1] A A A A B B B B C C C C D D D D
Levels: A B C D
Creating dataframe:
R
height <- c(1.4, 2.0, 2.3, 2.5, 7.8, 9.2, 6.8, 6.0, 7.6, 7.0, 7.3, 5.5, 1.6, 3.4, 3.0, 3.9) exp <- data.frame(treat, treatment = fac, response = height)mod <- aov(response ~ treatment, data = exp)summary(mod)
Output:
Df Sum Sq Mean Sq F value Pr(>F)
treatment 3 88.46 29.486 29.64 7.85e-06 ***
Residuals 12 11.94 0.995
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Explanation:
For every experiment, the significance is either 0.05 or 0.01 which is given by the person taking the experiment. For this example, let’s consider the significance as 5% i.e 0.05. We should see the value of Pr(>F) which is 7.85e-06 ,i.e, < 0.05. Thus reject the hypothesis. If the value is > 0.05 then accept the hypothesis. For this example, as Pr < 0.05, reject the hypothesis. Let’s consider one more example:
Adding rocks to water increases the height of water in the container. Let’s see this experiment in the figure as follows:
Consider that if adding four rocks to 500ml,600ml and 700ml respectively increases the height of water correspondingly. For example: adding 6 rocks to 500 m water has 7 ms height increased.
rocks four six eight
5 5.3 6.2 [500 600 700]
5.5 5 5.7 [600 500 700]
4.8 4.3 3.4 [700 600 500]
Lets code:
R
rocks<- rep(c("four", "six", "eight"), each = 3)rocksfac <- factor(rep(c(500, 600, 700), each = 3))fac
Output:
[1] "four" "four" "four" "six" "six" "six" "eight" "eight" "eight"
[1] 500 500 500 600 600 600 700 700 700
Levels: 500 600 700
Creating dataframe:
R
height <- c(5, 5.5, 4.8, 5.3, 5, 4.3, 4.8, 4.3, 3.4)exp1 <- data.frame(rocks, treatment = fac, response = height)mod <- aov(response ~ treatment, data = exp1)summary(mod)
Output:
Df Sum Sq Mean Sq F value Pr(>F)
treatment 2 1.416 0.7078 2.368 0.175
Residuals 6 1.793 0.2989
Explanation:
Here 0.175>>0.05 thus hypothesis is accepted.
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
Time Series Analysis in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 25479,
"s": 25242,
"text": "Experimental Designs are part of ANOVA in statistics. They are predefined algorithms that help us in analyzing the differences among group means in an experimental unit. Completely Randomized Design (CRD) is one part of the Anova types."
},
{
"code": null,
"e": 25509,
"s": 25479,
"text": "Completely Randomized Design:"
},
{
"code": null,
"e": 25865,
"s": 25509,
"text": "The three basic principles of designing an experiment are replication, blocking, and randomization. In this type of design, blocking is not a part of the algorithm. The samples of the experiment are random with replications are assigned to different experimental units. Let’s consider some experiments below and implement the experiment in R programming."
},
{
"code": null,
"e": 25992,
"s": 25865,
"text": "Adding more baking powder to cakes increases the heights of the cake. Let’s see with CRD how the experiment will be analyzed. "
},
{
"code": null,
"e": 26496,
"s": 25992,
"text": "As shown in the above figure the baking powder is divided into 4 different tablespoons(tbsp) and four replicate cakes heights (respectively for A, B, C, D) were made with each tbsp in random order. Then the results of tbsp are compared to see if actually the height is affected by baking powder. The replications are just permutations of the different cakes heights respectively for A, B, C, D. Let’s see the above example in R language. The heights of each cake are randomly noted for each tablespoon."
},
{
"code": null,
"e": 26722,
"s": 26496,
"text": "tbsp 0.25 0.5 0.75 1 \n 1.4 7.8 7.6 1.6\n #(A,B,C,D)\n 2.0 9.2 7.0 3.4\n #(A,B,D,C)\n 2.3 6.8 7.3 3.0\n #(B,A,D,C)\n 2.5 6.0 5.5 3.9 #(B,A,C,D)\n # the randomization is done directly by the program\n"
},
{
"code": null,
"e": 26782,
"s": 26722,
"text": "The replications of the cakes are done with the below code:"
},
{
"code": null,
"e": 26784,
"s": 26782,
"text": "R"
},
{
"code": "treat <- rep(c(\"A\", \"B\", \"C\", \"D\"), each = 4)fac <- factor(rep(c(0.25, 0.5, 0.75, 1), each = 4))treat",
"e": 26886,
"s": 26784,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26886,
"text": "Output:"
},
{
"code": null,
"e": 26947,
"s": 26894,
"text": "[1] A A A A B B B B C C C C D D D D\nLevels: A B C D\n"
},
{
"code": null,
"e": 26967,
"s": 26947,
"text": "Creating dataframe:"
},
{
"code": null,
"e": 26969,
"s": 26967,
"text": "R"
},
{
"code": "height <- c(1.4, 2.0, 2.3, 2.5, 7.8, 9.2, 6.8, 6.0, 7.6, 7.0, 7.3, 5.5, 1.6, 3.4, 3.0, 3.9) exp <- data.frame(treat, treatment = fac, response = height)mod <- aov(response ~ treatment, data = exp)summary(mod)",
"e": 27219,
"s": 26969,
"text": null
},
{
"code": null,
"e": 27227,
"s": 27219,
"text": "Output:"
},
{
"code": null,
"e": 27447,
"s": 27227,
"text": " Df Sum Sq Mean Sq F value Pr(>F) \ntreatment 3 88.46 29.486 29.64 7.85e-06 ***\nResiduals 12 11.94 0.995 \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n"
},
{
"code": null,
"e": 27460,
"s": 27447,
"text": "Explanation:"
},
{
"code": null,
"e": 27874,
"s": 27460,
"text": "For every experiment, the significance is either 0.05 or 0.01 which is given by the person taking the experiment. For this example, let’s consider the significance as 5% i.e 0.05. We should see the value of Pr(>F) which is 7.85e-06 ,i.e, < 0.05. Thus reject the hypothesis. If the value is > 0.05 then accept the hypothesis. For this example, as Pr < 0.05, reject the hypothesis. Let’s consider one more example:"
},
{
"code": null,
"e": 27996,
"s": 27874,
"text": "Adding rocks to water increases the height of water in the container. Let’s see this experiment in the figure as follows:"
},
{
"code": null,
"e": 28188,
"s": 27996,
"text": "Consider that if adding four rocks to 500ml,600ml and 700ml respectively increases the height of water correspondingly. For example: adding 6 rocks to 500 m water has 7 ms height increased."
},
{
"code": null,
"e": 28297,
"s": 28188,
"text": "rocks four six eight\n 5 5.3 6.2 [500 600 700]\n5.5 5 5.7 [600 500 700]\n4.8 4.3 3.4 [700 600 500]\n"
},
{
"code": null,
"e": 28308,
"s": 28297,
"text": "Lets code:"
},
{
"code": null,
"e": 28310,
"s": 28308,
"text": "R"
},
{
"code": "rocks<- rep(c(\"four\", \"six\", \"eight\"), each = 3)rocksfac <- factor(rep(c(500, 600, 700), each = 3))fac",
"e": 28413,
"s": 28310,
"text": null
},
{
"code": null,
"e": 28421,
"s": 28413,
"text": "Output:"
},
{
"code": null,
"e": 28559,
"s": 28421,
"text": "[1] \"four\" \"four\" \"four\" \"six\" \"six\" \"six\" \"eight\" \"eight\" \"eight\"\n\n[1] 500 500 500 600 600 600 700 700 700\nLevels: 500 600 700\n"
},
{
"code": null,
"e": 28581,
"s": 28559,
"text": "Creating dataframe: "
},
{
"code": null,
"e": 28583,
"s": 28581,
"text": "R"
},
{
"code": "height <- c(5, 5.5, 4.8, 5.3, 5, 4.3, 4.8, 4.3, 3.4)exp1 <- data.frame(rocks, treatment = fac, response = height)mod <- aov(response ~ treatment, data = exp1)summary(mod)",
"e": 28795,
"s": 28583,
"text": null
},
{
"code": null,
"e": 28803,
"s": 28795,
"text": "Output:"
},
{
"code": null,
"e": 28913,
"s": 28803,
"text": "Df Sum Sq Mean Sq F value Pr(>F)\ntreatment 2 1.416 0.7078 2.368 0.175\nResiduals 6 1.793 0.2989 \n"
},
{
"code": null,
"e": 28926,
"s": 28913,
"text": "Explanation:"
},
{
"code": null,
"e": 28972,
"s": 28926,
"text": "Here 0.175>>0.05 thus hypothesis is accepted."
},
{
"code": null,
"e": 28979,
"s": 28972,
"text": "Picked"
},
{
"code": null,
"e": 28992,
"s": 28979,
"text": "R-Statistics"
},
{
"code": null,
"e": 29003,
"s": 28992,
"text": "R Language"
},
{
"code": null,
"e": 29101,
"s": 29003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29110,
"s": 29101,
"text": "Comments"
},
{
"code": null,
"e": 29123,
"s": 29110,
"text": "Old Comments"
},
{
"code": null,
"e": 29175,
"s": 29123,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29213,
"s": 29175,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29248,
"s": 29213,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29306,
"s": 29248,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29355,
"s": 29306,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29392,
"s": 29355,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29442,
"s": 29392,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29459,
"s": 29442,
"text": "R - if statement"
},
{
"code": null,
"e": 29502,
"s": 29459,
"text": "Replace Specific Characters in String in R"
}
] |
C library function - memset()
|
The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
Following is the declaration for memset() function.
void *memset(void *str, int c, size_t n)
str − This is a pointer to the block of memory to fill.
str − This is a pointer to the block of memory to fill.
c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
n − This is the number of bytes to be set to the value.
n − This is the number of bytes to be set to the value.
This function returns a pointer to the memory area str.
The following example shows the usage of memset() function.
#include <stdio.h>
#include <string.h>
int main () {
char str[50];
strcpy(str,"This is string.h library function");
puts(str);
memset(str,'$',7);
puts(str);
return(0);
}
Let us compile and run the above program that will produce the following result −
This is string.h library function
$$$$$$$ string.h library function
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": 2186,
"s": 2007,
"text": "The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str."
},
{
"code": null,
"e": 2238,
"s": 2186,
"text": "Following is the declaration for memset() function."
},
{
"code": null,
"e": 2279,
"s": 2238,
"text": "void *memset(void *str, int c, size_t n)"
},
{
"code": null,
"e": 2335,
"s": 2279,
"text": "str − This is a pointer to the block of memory to fill."
},
{
"code": null,
"e": 2391,
"s": 2335,
"text": "str − This is a pointer to the block of memory to fill."
},
{
"code": null,
"e": 2548,
"s": 2391,
"text": "c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value."
},
{
"code": null,
"e": 2705,
"s": 2548,
"text": "c − This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value."
},
{
"code": null,
"e": 2761,
"s": 2705,
"text": "n − This is the number of bytes to be set to the value."
},
{
"code": null,
"e": 2817,
"s": 2761,
"text": "n − This is the number of bytes to be set to the value."
},
{
"code": null,
"e": 2873,
"s": 2817,
"text": "This function returns a pointer to the memory area str."
},
{
"code": null,
"e": 2933,
"s": 2873,
"text": "The following example shows the usage of memset() function."
},
{
"code": null,
"e": 3128,
"s": 2933,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char str[50];\n\n strcpy(str,\"This is string.h library function\");\n puts(str);\n\n memset(str,'$',7);\n puts(str);\n \n return(0);\n}"
},
{
"code": null,
"e": 3210,
"s": 3128,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3279,
"s": 3210,
"text": "This is string.h library function\n$$$$$$$ string.h library function\n"
},
{
"code": null,
"e": 3312,
"s": 3279,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3327,
"s": 3312,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3362,
"s": 3327,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3377,
"s": 3362,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3412,
"s": 3377,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3426,
"s": 3412,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3459,
"s": 3426,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3477,
"s": 3459,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3512,
"s": 3477,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3531,
"s": 3512,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3564,
"s": 3531,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3576,
"s": 3564,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3583,
"s": 3576,
"text": " Print"
},
{
"code": null,
"e": 3594,
"s": 3583,
"text": " Add Notes"
}
] |
Explain the Difference Between Definition and Declaration
|
In this post, we will understand the difference between definition and declaration.
Definition, with respect to a function indicates that the body of the function has been developed.
Definition, with respect to a function indicates that the body of the function has been developed.
With respect to variable, it means a value has been associated/defined with that variable.
With respect to variable, it means a value has been associated/defined with that variable.
A function can be defined only once.
A function can be defined only once.
Once a function or variable has been defined, it is ready to be used.
Once a function or variable has been defined, it is ready to be used.
A variable can be re-defined multiple times, as and when required. This depends on the language and the scopes.
A variable can be re-defined multiple times, as and when required. This depends on the language and the scopes.
Memory is allocated when function or a variable is defined.
Memory is allocated when function or a variable is defined.
Below is an example of variable definition
sum = 0
A variable named ‘sum’ is assigned to 0.
Below is an example of function definition
def add_val(param_1, param_2)
c = param_1 + param_2
return c
The ‘add_val’ is a method, and ‘param_1’ and ‘param_2’ are parameters passed to it. There is a definition of this method too.
Function declaration basically means that a name has been given and the parameters have been mentioned.
Function declaration basically means that a name has been given and the parameters have been mentioned.
No value is associated with a variable when it is just declared.
No value is associated with a variable when it is just declared.
Its body hasn’t been developed yet.
Its body hasn’t been developed yet.
Once a function or variable has been declared, it is not yet ready to be used.
Once a function or variable has been declared, it is not yet ready to be used.
A function or variable can be declared any number of times.
A function or variable can be declared any number of times.
Memory isn’t allocated when a function or variable is declared.
Memory isn’t allocated when a function or variable is declared.
Below is an example of variable declaration −
sum_val
A variable named ‘sum_val’ is declared.
Below is an example of function declaration −
add_val(p_1, p_2)
The ‘add_val’ is a method, and ‘p_1’ and ‘p_2’ are parameters passed to it. There is no definition of the method.
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "In this post, we will understand the difference between definition and declaration."
},
{
"code": null,
"e": 1245,
"s": 1146,
"text": "Definition, with respect to a function indicates that the body of the function has been developed."
},
{
"code": null,
"e": 1344,
"s": 1245,
"text": "Definition, with respect to a function indicates that the body of the function has been developed."
},
{
"code": null,
"e": 1435,
"s": 1344,
"text": "With respect to variable, it means a value has been associated/defined with that variable."
},
{
"code": null,
"e": 1526,
"s": 1435,
"text": "With respect to variable, it means a value has been associated/defined with that variable."
},
{
"code": null,
"e": 1563,
"s": 1526,
"text": "A function can be defined only once."
},
{
"code": null,
"e": 1600,
"s": 1563,
"text": "A function can be defined only once."
},
{
"code": null,
"e": 1670,
"s": 1600,
"text": "Once a function or variable has been defined, it is ready to be used."
},
{
"code": null,
"e": 1740,
"s": 1670,
"text": "Once a function or variable has been defined, it is ready to be used."
},
{
"code": null,
"e": 1852,
"s": 1740,
"text": "A variable can be re-defined multiple times, as and when required. This depends on the language and the scopes."
},
{
"code": null,
"e": 1964,
"s": 1852,
"text": "A variable can be re-defined multiple times, as and when required. This depends on the language and the scopes."
},
{
"code": null,
"e": 2024,
"s": 1964,
"text": "Memory is allocated when function or a variable is defined."
},
{
"code": null,
"e": 2084,
"s": 2024,
"text": "Memory is allocated when function or a variable is defined."
},
{
"code": null,
"e": 2127,
"s": 2084,
"text": "Below is an example of variable definition"
},
{
"code": null,
"e": 2135,
"s": 2127,
"text": "sum = 0"
},
{
"code": null,
"e": 2176,
"s": 2135,
"text": "A variable named ‘sum’ is assigned to 0."
},
{
"code": null,
"e": 2219,
"s": 2176,
"text": "Below is an example of function definition"
},
{
"code": null,
"e": 2280,
"s": 2219,
"text": "def add_val(param_1, param_2)\nc = param_1 + param_2\nreturn c"
},
{
"code": null,
"e": 2406,
"s": 2280,
"text": "The ‘add_val’ is a method, and ‘param_1’ and ‘param_2’ are parameters passed to it. There is a definition of this method too."
},
{
"code": null,
"e": 2510,
"s": 2406,
"text": "Function declaration basically means that a name has been given and the parameters have been mentioned."
},
{
"code": null,
"e": 2614,
"s": 2510,
"text": "Function declaration basically means that a name has been given and the parameters have been mentioned."
},
{
"code": null,
"e": 2679,
"s": 2614,
"text": "No value is associated with a variable when it is just declared."
},
{
"code": null,
"e": 2744,
"s": 2679,
"text": "No value is associated with a variable when it is just declared."
},
{
"code": null,
"e": 2780,
"s": 2744,
"text": "Its body hasn’t been developed yet."
},
{
"code": null,
"e": 2816,
"s": 2780,
"text": "Its body hasn’t been developed yet."
},
{
"code": null,
"e": 2895,
"s": 2816,
"text": "Once a function or variable has been declared, it is not yet ready to be used."
},
{
"code": null,
"e": 2974,
"s": 2895,
"text": "Once a function or variable has been declared, it is not yet ready to be used."
},
{
"code": null,
"e": 3034,
"s": 2974,
"text": "A function or variable can be declared any number of times."
},
{
"code": null,
"e": 3094,
"s": 3034,
"text": "A function or variable can be declared any number of times."
},
{
"code": null,
"e": 3158,
"s": 3094,
"text": "Memory isn’t allocated when a function or variable is declared."
},
{
"code": null,
"e": 3222,
"s": 3158,
"text": "Memory isn’t allocated when a function or variable is declared."
},
{
"code": null,
"e": 3268,
"s": 3222,
"text": "Below is an example of variable declaration −"
},
{
"code": null,
"e": 3276,
"s": 3268,
"text": "sum_val"
},
{
"code": null,
"e": 3316,
"s": 3276,
"text": "A variable named ‘sum_val’ is declared."
},
{
"code": null,
"e": 3362,
"s": 3316,
"text": "Below is an example of function declaration −"
},
{
"code": null,
"e": 3380,
"s": 3362,
"text": "add_val(p_1, p_2)"
},
{
"code": null,
"e": 3494,
"s": 3380,
"text": "The ‘add_val’ is a method, and ‘p_1’ and ‘p_2’ are parameters passed to it. There is no definition of the method."
}
] |
Binary Tree to Binary Search Tree Conversion in C++
|
A binary tree is a special type of tree in which each node of the tree can have at most two child nodes. These child nodes are known as the right child and left child.
A simple binary tree is −
Binary search tree (BST) is a special type of tree which follows the following rules −
left child node’s value is always less than the parent Note
left child node’s value is always less than the parent Note
The right child node has a greater value than the parent node.
The right child node has a greater value than the parent node.
all the nodes individually form a binary search tree.
all the nodes individually form a binary search tree.
Example of a binary search tree (BST) −
A binary search tree is created in order to reduce the complexity of operations like search, find minimum and maximum.
Here, we are given a binary tree and we have to convert this binary tree (BT) to a binary search tree (BST). In this conversion, the original structure of the binary tree should not be changed.
let's take an example to understand how to convert a BT into BST −
Input −
Output −
This conversion of a binary tree to a binary search tree takes place using three steps. they are −
Step 1 − store data in order traversal of a binary tree into array arr[].
Step 2 − sort the array arr[] using any sorting technique.
Step 3 − Now, do the inorder traversal of the tree and e copy the elements of an array to the nodes of the tree one by one.
Live Demo
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
void Inordertraversal(struct node* node, int inorder[], int *index_ptr){
if (node == NULL)
return;
Inordertraversal(node->left, inorder, index_ptr);
inorder[*index_ptr] = node->data;
(*index_ptr)++;
Inordertraversal(node->right, inorder, index_ptr);
}
int countNodes(struct node* root){
if (root == NULL)
return 0;
return countNodes (root->left) +
countNodes (root->right) + 1;
}
int compare (const void * a, const void * b){
return( *(int*)a - *(int*)b );
}
void arrayToBST (int *arr, struct node* root, int *index_ptr){
if (root == NULL)
return;
arrayToBST (arr, root->left, index_ptr);
root->data = arr[*index_ptr];
(*index_ptr)++;
arrayToBST (arr, root->right, index_ptr);
}
struct node* newNode (int data){
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void printInorder (struct node* node){
if (node == NULL)
return;
printInorder (node->left);
printf("%d ", node->data);
printInorder (node->right);
}
int main(){
struct node *root = NULL;
root = newNode(17);
root->left = newNode(14);
root->right = newNode(2);
root->left->left = newNode(11);
root->right->right = newNode(7);
printf("Inorder Traversal of the binary Tree: \n");
printInorder (root);
int n = countNodes(root);
int *arr = new int[n];
int i = 0;
Inordertraversal(root, arr, &i);
qsort(arr, n, sizeof(arr[0]), compare);
i = 0;
arrayToBST (arr, root, &i);
delete [] arr;
printf("\nInorder Traversal of the converted BST: \n");
printInorder (root);
return 0;
}
Inorder Traversal of the binary Tree:
11 14 17 2 7
Inorder Traversal of the converted BST:
2 7 11 14 17
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "A binary tree is a special type of tree in which each node of the tree can have at most two child nodes. These child nodes are known as the right child and left child."
},
{
"code": null,
"e": 1256,
"s": 1230,
"text": "A simple binary tree is −"
},
{
"code": null,
"e": 1343,
"s": 1256,
"text": "Binary search tree (BST) is a special type of tree which follows the following rules −"
},
{
"code": null,
"e": 1403,
"s": 1343,
"text": "left child node’s value is always less than the parent Note"
},
{
"code": null,
"e": 1463,
"s": 1403,
"text": "left child node’s value is always less than the parent Note"
},
{
"code": null,
"e": 1526,
"s": 1463,
"text": "The right child node has a greater value than the parent node."
},
{
"code": null,
"e": 1589,
"s": 1526,
"text": "The right child node has a greater value than the parent node."
},
{
"code": null,
"e": 1643,
"s": 1589,
"text": "all the nodes individually form a binary search tree."
},
{
"code": null,
"e": 1697,
"s": 1643,
"text": "all the nodes individually form a binary search tree."
},
{
"code": null,
"e": 1737,
"s": 1697,
"text": "Example of a binary search tree (BST) −"
},
{
"code": null,
"e": 1856,
"s": 1737,
"text": "A binary search tree is created in order to reduce the complexity of operations like search, find minimum and maximum."
},
{
"code": null,
"e": 2050,
"s": 1856,
"text": "Here, we are given a binary tree and we have to convert this binary tree (BT) to a binary search tree (BST). In this conversion, the original structure of the binary tree should not be changed."
},
{
"code": null,
"e": 2117,
"s": 2050,
"text": "let's take an example to understand how to convert a BT into BST −"
},
{
"code": null,
"e": 2126,
"s": 2117,
"text": "Input − "
},
{
"code": null,
"e": 2135,
"s": 2126,
"text": "Output −"
},
{
"code": null,
"e": 2234,
"s": 2135,
"text": "This conversion of a binary tree to a binary search tree takes place using three steps. they are −"
},
{
"code": null,
"e": 2308,
"s": 2234,
"text": "Step 1 − store data in order traversal of a binary tree into array arr[]."
},
{
"code": null,
"e": 2367,
"s": 2308,
"text": "Step 2 − sort the array arr[] using any sorting technique."
},
{
"code": null,
"e": 2491,
"s": 2367,
"text": "Step 3 − Now, do the inorder traversal of the tree and e copy the elements of an array to the nodes of the tree one by one."
},
{
"code": null,
"e": 2502,
"s": 2491,
"text": " Live Demo"
},
{
"code": null,
"e": 4254,
"s": 2502,
"text": "#include<stdio.h>\n#include<stdlib.h>\nstruct node{\n int data;\n struct node *left;\n struct node *right;\n};\nvoid Inordertraversal(struct node* node, int inorder[], int *index_ptr){\n if (node == NULL)\n return;\n Inordertraversal(node->left, inorder, index_ptr);\n inorder[*index_ptr] = node->data;\n (*index_ptr)++;\n Inordertraversal(node->right, inorder, index_ptr);\n}\nint countNodes(struct node* root){\n if (root == NULL)\n return 0;\n return countNodes (root->left) +\n countNodes (root->right) + 1;\n}\nint compare (const void * a, const void * b){\n return( *(int*)a - *(int*)b );\n}\nvoid arrayToBST (int *arr, struct node* root, int *index_ptr){\n if (root == NULL)\n return;\n arrayToBST (arr, root->left, index_ptr);\n root->data = arr[*index_ptr];\n (*index_ptr)++;\n arrayToBST (arr, root->right, index_ptr);\n}\nstruct node* newNode (int data){\n struct node *temp = new struct node;\n temp->data = data;\n temp->left = NULL;\n temp->right = NULL;\n return temp;\n}\nvoid printInorder (struct node* node){\n if (node == NULL)\n return;\n printInorder (node->left);\n printf(\"%d \", node->data);\n printInorder (node->right);\n}\nint main(){\n struct node *root = NULL;\n root = newNode(17);\n root->left = newNode(14);\n root->right = newNode(2);\n root->left->left = newNode(11);\n root->right->right = newNode(7);\n printf(\"Inorder Traversal of the binary Tree: \\n\");\n printInorder (root);\n int n = countNodes(root);\n int *arr = new int[n];\n int i = 0;\n Inordertraversal(root, arr, &i);\n qsort(arr, n, sizeof(arr[0]), compare);\n i = 0;\n arrayToBST (arr, root, &i);\n delete [] arr;\n printf(\"\\nInorder Traversal of the converted BST: \\n\");\n printInorder (root);\n return 0;\n}"
},
{
"code": null,
"e": 4358,
"s": 4254,
"text": "Inorder Traversal of the binary Tree:\n11 14 17 2 7\nInorder Traversal of the converted BST:\n2 7 11 14 17"
}
] |
Private vs Protected vs Final Access Modifier in Java - GeeksforGeeks
|
08 Oct, 2021
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members.
Access modifiers:
PrivateProtectedFinal
Private
Protected
Final
Let us do discuss them in-depth to get a better understanding before getting to the differences between them.
Private Access Modifier: This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes. If a variable or methods or constructor is declared as private as we can access them only from within the class i.e from outside the class we can’t access them.
Java
// Java Program to illustrate Private Access Modifier // Importing required packagesimport java.io.*;import java.util.*; // Class 1// Helper classclass A { // Method of this class private void m1() { // Print statement whenever this method is called System.out.println("GFG"); }} // Class 2// Main classclass B { // Main driver method public static void main(String[] args) { // Creating an object of above class A a = new A(); // Accessing the method m1() of above class // by creating object of above class in // main() method of this class a.m1(); }}
Protected Access Modifier: This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface. A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package.
Java
// Java program to illustrate Protected Access Modifier// import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println("GFG"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }}
GFG
GFG
GFG
Output Explanation: In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference.
Final Access Modifier: It is a modifier applicable to classes, methods, and variables. If we declare a parent class method as final then we can’t override that method in the child class because its implementation is final and if a class is declared as final we can’t extend the functionality of that class i.e we can’t create a child class for that class i.e inheritance is not possible for final classes. Every method present inside the final class is always final y default, but every variable present inside the final class need not be final. The main advantage of the final keyword is we can achieve security and we can provide a unique implementation. But the main disadvantage of the final keyword is we are missing key benefits of OOPs like Inheritance(Because of the final class), Polymorphism(Because of the final method) hence if there are no specific requirements then it is not recommended to use the final keyword.
Java
// Java program to illustrate Final keyword // import required packagesimport java.io.*;import java.util.*;// Declaring parent class Pclass P { // Declaring a first name // method public void firstName() { // Display firstname System.out.println("Rahul "); } /// Declaring a final surName // method public final void surName() { // Display surname System.out.println("Trivedi"); }}// Creating a child class// of above parent classclass C extends P { // overriding the surName // method public void surName() { // Display surname System.out.println("Sharma"); } // Main method public static void main(String[] args) { // Display message System.out.println("GFG"); }}
Output:
Now after having an understanding of all of them let us do land on differences between them to conclude out.
gabaa406
prachisoda1234
Java-Modifier
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25307,
"s": 24858,
"text": "Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members."
},
{
"code": null,
"e": 25325,
"s": 25307,
"text": "Access modifiers:"
},
{
"code": null,
"e": 25347,
"s": 25325,
"text": "PrivateProtectedFinal"
},
{
"code": null,
"e": 25355,
"s": 25347,
"text": "Private"
},
{
"code": null,
"e": 25365,
"s": 25355,
"text": "Protected"
},
{
"code": null,
"e": 25371,
"s": 25365,
"text": "Final"
},
{
"code": null,
"e": 25481,
"s": 25371,
"text": "Let us do discuss them in-depth to get a better understanding before getting to the differences between them."
},
{
"code": null,
"e": 25815,
"s": 25481,
"text": "Private Access Modifier: This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes. If a variable or methods or constructor is declared as private as we can access them only from within the class i.e from outside the class we can’t access them."
},
{
"code": null,
"e": 25820,
"s": 25815,
"text": "Java"
},
{
"code": "// Java Program to illustrate Private Access Modifier // Importing required packagesimport java.io.*;import java.util.*; // Class 1// Helper classclass A { // Method of this class private void m1() { // Print statement whenever this method is called System.out.println(\"GFG\"); }} // Class 2// Main classclass B { // Main driver method public static void main(String[] args) { // Creating an object of above class A a = new A(); // Accessing the method m1() of above class // by creating object of above class in // main() method of this class a.m1(); }}",
"e": 26452,
"s": 25820,
"text": null
},
{
"code": null,
"e": 26778,
"s": 26455,
"text": "Protected Access Modifier: This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface. A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package."
},
{
"code": null,
"e": 26785,
"s": 26780,
"text": "Java"
},
{
"code": "// Java program to illustrate Protected Access Modifier// import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println(\"GFG\"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }}",
"e": 27667,
"s": 26785,
"text": null
},
{
"code": null,
"e": 27682,
"s": 27670,
"text": "GFG\nGFG\nGFG"
},
{
"code": null,
"e": 28017,
"s": 27682,
"text": "Output Explanation: In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference."
},
{
"code": null,
"e": 28949,
"s": 28019,
"text": "Final Access Modifier: It is a modifier applicable to classes, methods, and variables. If we declare a parent class method as final then we can’t override that method in the child class because its implementation is final and if a class is declared as final we can’t extend the functionality of that class i.e we can’t create a child class for that class i.e inheritance is not possible for final classes. Every method present inside the final class is always final y default, but every variable present inside the final class need not be final. The main advantage of the final keyword is we can achieve security and we can provide a unique implementation. But the main disadvantage of the final keyword is we are missing key benefits of OOPs like Inheritance(Because of the final class), Polymorphism(Because of the final method) hence if there are no specific requirements then it is not recommended to use the final keyword. "
},
{
"code": null,
"e": 28956,
"s": 28951,
"text": "Java"
},
{
"code": "// Java program to illustrate Final keyword // import required packagesimport java.io.*;import java.util.*;// Declaring parent class Pclass P { // Declaring a first name // method public void firstName() { // Display firstname System.out.println(\"Rahul \"); } /// Declaring a final surName // method public final void surName() { // Display surname System.out.println(\"Trivedi\"); }}// Creating a child class// of above parent classclass C extends P { // overriding the surName // method public void surName() { // Display surname System.out.println(\"Sharma\"); } // Main method public static void main(String[] args) { // Display message System.out.println(\"GFG\"); }}",
"e": 29737,
"s": 28956,
"text": null
},
{
"code": null,
"e": 29745,
"s": 29737,
"text": "Output:"
},
{
"code": null,
"e": 29855,
"s": 29745,
"text": "Now after having an understanding of all of them let us do land on differences between them to conclude out. "
},
{
"code": null,
"e": 29864,
"s": 29855,
"text": "gabaa406"
},
{
"code": null,
"e": 29879,
"s": 29864,
"text": "prachisoda1234"
},
{
"code": null,
"e": 29893,
"s": 29879,
"text": "Java-Modifier"
},
{
"code": null,
"e": 29912,
"s": 29893,
"text": "Difference Between"
},
{
"code": null,
"e": 29917,
"s": 29912,
"text": "Java"
},
{
"code": null,
"e": 29922,
"s": 29917,
"text": "Java"
},
{
"code": null,
"e": 30020,
"s": 29922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30081,
"s": 30020,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30149,
"s": 30081,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 30207,
"s": 30149,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 30262,
"s": 30207,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 30336,
"s": 30262,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 30351,
"s": 30336,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30395,
"s": 30351,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30417,
"s": 30395,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30453,
"s": 30417,
"text": "Arrays.sort() in Java with examples"
}
] |
Levering cheap GPU compute: Connecting to Vast.ai using windows | by Jason Price | Towards Data Science
|
Venturing into the world of crypto-currency and Data-science, it was by no coincidence that I would have built my own supercomputer (by 2002 standards). The cool thing about this is that anyone can have access to cheap GPU compute, that is 3 -10 times cheaper than AWS instances. All this is made possible due to the Vast.ai platform that enables peer to peer sharing of GPU compute power.
In next these series of articles, I’ll be showing how to get started with some various tasks on the Vast.ai platform:
Connecting to Vast.ai using windows: Select and ssh into your rig of choice
Starting a Jupyter notebook
Running benchmarks
Get started: Folding@Home
Getting started: Using hashcat
Getting started: Using fast.ai
In your browser, select your image and rig of choice at https://vast.ai/console/create/
In your browser, select your image and rig of choice at https://vast.ai/console/create/
To get started, select your docker image of choice as shown below. There are several options to chose from, but for this tutorial, I have selected the fastai image from docker hub and selected Run interactive shell server, SSH
We then select the rig of choice (116) and click to rent as shown below.
2. Navigate to your instance that has just been created https://vast.ai/console/instances/. Please note your instance could take from 30 sec to 15 min to load depending on the host connection speed if the image is already on the host rig and the size of the image. Pro tip: ask the host lo pre-load the image for you so you can get started in less than a minute every time.
3. Go to instances and click connect which will show the ip address and port (it is also shown at the top of the instance).
ssh -p 515836 root@ssh5.vast.ai -L 8080:localhost:8080
You will need the port 515836 and the ip address root@ssh5.vast.ai later (note the port and ip address may be different).
4. Download and install PuTTYgen for windows
5. Using PuTTYgen choose RSA , and then press the generate button to generate the public and private key.
6. Add a passphrase for extra security, save the public and private key and copy the public key to your clipboard.
7. Go to https://vast.ai/console/account/ and input the public key generated in step 6.
8. Open PuTTY and input the IP address and port number from step 3.
9. Go to Connection →SSH → Auth and select your private key
10. Navigate back to Session and save your configuration so you can load it easily later on.
11. Click open, accept any popups and log in with the password you used when generating your public key.
12. Go wild !!!!!!!!
If you still having issues, feel free to reach out in the comments below or even better, join the Vast.ai Discord community. More info on Vastai’s peer to peer system can be found in the FAQ.
Note I am not a developer on Vast.ai, but I do have rig (116), that is hosted on the platform, so feel free to show some love 😺.
|
[
{
"code": null,
"e": 562,
"s": 172,
"text": "Venturing into the world of crypto-currency and Data-science, it was by no coincidence that I would have built my own supercomputer (by 2002 standards). The cool thing about this is that anyone can have access to cheap GPU compute, that is 3 -10 times cheaper than AWS instances. All this is made possible due to the Vast.ai platform that enables peer to peer sharing of GPU compute power."
},
{
"code": null,
"e": 680,
"s": 562,
"text": "In next these series of articles, I’ll be showing how to get started with some various tasks on the Vast.ai platform:"
},
{
"code": null,
"e": 756,
"s": 680,
"text": "Connecting to Vast.ai using windows: Select and ssh into your rig of choice"
},
{
"code": null,
"e": 784,
"s": 756,
"text": "Starting a Jupyter notebook"
},
{
"code": null,
"e": 803,
"s": 784,
"text": "Running benchmarks"
},
{
"code": null,
"e": 829,
"s": 803,
"text": "Get started: Folding@Home"
},
{
"code": null,
"e": 860,
"s": 829,
"text": "Getting started: Using hashcat"
},
{
"code": null,
"e": 891,
"s": 860,
"text": "Getting started: Using fast.ai"
},
{
"code": null,
"e": 979,
"s": 891,
"text": "In your browser, select your image and rig of choice at https://vast.ai/console/create/"
},
{
"code": null,
"e": 1067,
"s": 979,
"text": "In your browser, select your image and rig of choice at https://vast.ai/console/create/"
},
{
"code": null,
"e": 1294,
"s": 1067,
"text": "To get started, select your docker image of choice as shown below. There are several options to chose from, but for this tutorial, I have selected the fastai image from docker hub and selected Run interactive shell server, SSH"
},
{
"code": null,
"e": 1367,
"s": 1294,
"text": "We then select the rig of choice (116) and click to rent as shown below."
},
{
"code": null,
"e": 1741,
"s": 1367,
"text": "2. Navigate to your instance that has just been created https://vast.ai/console/instances/. Please note your instance could take from 30 sec to 15 min to load depending on the host connection speed if the image is already on the host rig and the size of the image. Pro tip: ask the host lo pre-load the image for you so you can get started in less than a minute every time."
},
{
"code": null,
"e": 1865,
"s": 1741,
"text": "3. Go to instances and click connect which will show the ip address and port (it is also shown at the top of the instance)."
},
{
"code": null,
"e": 1921,
"s": 1865,
"text": "ssh -p 515836 root@ssh5.vast.ai -L 8080:localhost:8080"
},
{
"code": null,
"e": 2043,
"s": 1921,
"text": "You will need the port 515836 and the ip address root@ssh5.vast.ai later (note the port and ip address may be different)."
},
{
"code": null,
"e": 2088,
"s": 2043,
"text": "4. Download and install PuTTYgen for windows"
},
{
"code": null,
"e": 2194,
"s": 2088,
"text": "5. Using PuTTYgen choose RSA , and then press the generate button to generate the public and private key."
},
{
"code": null,
"e": 2309,
"s": 2194,
"text": "6. Add a passphrase for extra security, save the public and private key and copy the public key to your clipboard."
},
{
"code": null,
"e": 2397,
"s": 2309,
"text": "7. Go to https://vast.ai/console/account/ and input the public key generated in step 6."
},
{
"code": null,
"e": 2465,
"s": 2397,
"text": "8. Open PuTTY and input the IP address and port number from step 3."
},
{
"code": null,
"e": 2525,
"s": 2465,
"text": "9. Go to Connection →SSH → Auth and select your private key"
},
{
"code": null,
"e": 2618,
"s": 2525,
"text": "10. Navigate back to Session and save your configuration so you can load it easily later on."
},
{
"code": null,
"e": 2723,
"s": 2618,
"text": "11. Click open, accept any popups and log in with the password you used when generating your public key."
},
{
"code": null,
"e": 2744,
"s": 2723,
"text": "12. Go wild !!!!!!!!"
},
{
"code": null,
"e": 2936,
"s": 2744,
"text": "If you still having issues, feel free to reach out in the comments below or even better, join the Vast.ai Discord community. More info on Vastai’s peer to peer system can be found in the FAQ."
}
] |
jQuery Tutorial
|
jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery is easy to learn.
With our online editor, you can edit the code, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Use the correct selector to hide all <p> elements.
$("").hide();
Start the Exercise
Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself.
Test your jQuery skills at W3Schools!
At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events.
Get certified by completing the JQUERY course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 32,
"s": 0,
"text": "jQuery is a JavaScript Library."
},
{
"code": null,
"e": 82,
"s": 32,
"text": "jQuery greatly simplifies JavaScript programming."
},
{
"code": null,
"e": 107,
"s": 82,
"text": "jQuery is easy to learn."
},
{
"code": null,
"e": 196,
"s": 107,
"text": "With our online editor, you can edit the code, and click on a button to view the result."
},
{
"code": null,
"e": 255,
"s": 196,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 306,
"s": 255,
"text": "Use the correct selector to hide all <p> elements."
},
{
"code": null,
"e": 321,
"s": 306,
"text": "$(\"\").hide();\n"
},
{
"code": null,
"e": 340,
"s": 321,
"text": "Start the Exercise"
},
{
"code": null,
"e": 438,
"s": 340,
"text": "Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself."
},
{
"code": null,
"e": 476,
"s": 438,
"text": "Test your jQuery skills at W3Schools!"
},
{
"code": null,
"e": 581,
"s": 476,
"text": "At W3Schools you will find a complete reference of all jQuery selectors, methods, properties and events."
},
{
"code": null,
"e": 627,
"s": 581,
"text": "Get certified by completing the JQUERY course"
},
{
"code": null,
"e": 660,
"s": 627,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 702,
"s": 660,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 809,
"s": 702,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 828,
"s": 809,
"text": "help@w3schools.com"
}
] |
How to replace space between two words with underscore in an R data frame column?
|
To replace space between two words with underscore in an R data frame column, we can use gsub function. For example, if we have a data frame called df that contains character column x having two words having a single space between them then we can replace that space using the command dfx<−gsub("","",dfx)
Consider the below data frame −
Live Demo
x1<-sample(c("id 1","id 2","id 3","id 4"),20,replace=TRUE)
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1
x1 x2
1 id 4 6
2 id 4 5
3 id 1 6
4 id 3 8
5 id 4 12
6 id 4 8
7 id 3 2
8 id 3 5
9 id 4 8
10 id 1 1
11 id 3 4
12 id 3 5
13 id 2 3
14 id 1 2
15 id 3 5
16 id 1 8
17 id 4 8
18 id 3 5
19 id 2 2
20 id 3 4
Replacing space between id and the number in column x1 with underscore −
df1$x1<-gsub(" ", "_", df1$x1)
df1
x1 x2
1 id_4 6
2 id_4 5
3 id_1 6
4 id_3 8
5 id_4 12
6 id_4 8
7 id_3 2
8 id_3 5
9 id_4 8
10 id_1 1
11 id_3 4
12 id_3 5
13 id_2 3
14 id_1 2
15 id_3 5
16 id_1 8
17 id_4 8
18 id_3 5
19 id_2 2
20 id_3 4
Live Demo
y1<-sample(c("class 1","class 2","class 3"),20,replace=TRUE)
y2<-rnorm(20)
df2<-data.frame(y1,y2)
df2
y1 y2
1 class 1 0.62986928
2 class 2 1.65731515
3 class 3 -1.13406383
4 class 1 -0.35842133
5 class 1 0.58141698
6 class 3 -0.18424254
7 class 3 -1.05955455
8 class 2 -0.80841041
9 class 3 1.05838028
10 class 2 -1.06141883
11 class 3 -0.54195571
12 class 3 -0.18038280
13 class 2 0.75236011
14 class 2 -0.55374067
15 class 1 0.38737080
16 class 3 0.35892853
17 class 2 -0.44576804
18 class 1 0.62543133
19 class 2 -0.05862987
20 class 1 -0.01508226
Replacing space between id and the number in column y1 with underscore −
df2$y1<-gsub(" ", "_",df2$y1)
df2
y1 y2
1 class_1 0.62986928
2 class_2 1.65731515
3 class_3 -1.13406383
4 class_1 -0.35842133
5 class_1 0.58141698
6 class_3 -0.18424254
7 class_3 -1.05955455
8 class_2 -0.80841041
9 class_3 1.05838028
10 class_2 -1.06141883
11 class_3 -0.54195571
12 class_3 -0.18038280
13 class_2 0.75236011
14 class_2 -0.55374067
15 class_1 0.38737080
16 class_3 0.35892853
17 class_2 -0.44576804
18 class_1 0.62543133
19 class_2 -0.05862987
20 class_1 -0.01508226
|
[
{
"code": null,
"e": 1368,
"s": 1062,
"text": "To replace space between two words with underscore in an R data frame column, we can use gsub function. For example, if we have a data frame called df that contains character column x having two words having a single space between them then we can replace that space using the command dfx<−gsub(\"\",\"\",dfx)"
},
{
"code": null,
"e": 1400,
"s": 1368,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1411,
"s": 1400,
"text": " Live Demo"
},
{
"code": null,
"e": 1513,
"s": 1411,
"text": "x1<-sample(c(\"id 1\",\"id 2\",\"id 3\",\"id 4\"),20,replace=TRUE)\nx2<-rpois(20,5)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1745,
"s": 1513,
"text": " x1 x2\n1 id 4 6\n2 id 4 5\n3 id 1 6\n4 id 3 8\n5 id 4 12\n6 id 4 8\n7 id 3 2\n8 id 3 5\n9 id 4 8\n10 id 1 1\n11 id 3 4\n12 id 3 5\n13 id 2 3\n14 id 1 2\n15 id 3 5\n16 id 1 8\n17 id 4 8\n18 id 3 5\n19 id 2 2\n20 id 3 4"
},
{
"code": null,
"e": 1818,
"s": 1745,
"text": "Replacing space between id and the number in column x1 with underscore −"
},
{
"code": null,
"e": 1853,
"s": 1818,
"text": "df1$x1<-gsub(\" \", \"_\", df1$x1)\ndf1"
},
{
"code": null,
"e": 2085,
"s": 1853,
"text": " x1 x2\n1 id_4 6\n2 id_4 5\n3 id_1 6\n4 id_3 8\n5 id_4 12\n6 id_4 8\n7 id_3 2\n8 id_3 5\n9 id_4 8\n10 id_1 1\n11 id_3 4\n12 id_3 5\n13 id_2 3\n14 id_1 2\n15 id_3 5\n16 id_1 8\n17 id_4 8\n18 id_3 5\n19 id_2 2\n20 id_3 4"
},
{
"code": null,
"e": 2096,
"s": 2085,
"text": " Live Demo"
},
{
"code": null,
"e": 2198,
"s": 2096,
"text": "y1<-sample(c(\"class 1\",\"class 2\",\"class 3\"),20,replace=TRUE)\ny2<-rnorm(20)\ndf2<-data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 2697,
"s": 2198,
"text": " y1 y2\n1 class 1 0.62986928\n2 class 2 1.65731515\n3 class 3 -1.13406383\n4 class 1 -0.35842133\n5 class 1 0.58141698\n6 class 3 -0.18424254\n7 class 3 -1.05955455\n8 class 2 -0.80841041\n9 class 3 1.05838028\n10 class 2 -1.06141883\n11 class 3 -0.54195571\n12 class 3 -0.18038280\n13 class 2 0.75236011\n14 class 2 -0.55374067\n15 class 1 0.38737080\n16 class 3 0.35892853\n17 class 2 -0.44576804\n18 class 1 0.62543133\n19 class 2 -0.05862987\n20 class 1 -0.01508226"
},
{
"code": null,
"e": 2770,
"s": 2697,
"text": "Replacing space between id and the number in column y1 with underscore −"
},
{
"code": null,
"e": 2804,
"s": 2770,
"text": "df2$y1<-gsub(\" \", \"_\",df2$y1)\ndf2"
},
{
"code": null,
"e": 3303,
"s": 2804,
"text": " y1 y2\n1 class_1 0.62986928\n2 class_2 1.65731515\n3 class_3 -1.13406383\n4 class_1 -0.35842133\n5 class_1 0.58141698\n6 class_3 -0.18424254\n7 class_3 -1.05955455\n8 class_2 -0.80841041\n9 class_3 1.05838028\n10 class_2 -1.06141883\n11 class_3 -0.54195571\n12 class_3 -0.18038280\n13 class_2 0.75236011\n14 class_2 -0.55374067\n15 class_1 0.38737080\n16 class_3 0.35892853\n17 class_2 -0.44576804\n18 class_1 0.62543133\n19 class_2 -0.05862987\n20 class_1 -0.01508226"
}
] |
Python Program for Recursive Insertion Sort - GeeksforGeeks
|
31 Aug, 2021
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Below is an iterative algorithm for insertion sortAlgorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
a) Pick element arr[i] and insert
it into sorted sequence arr[0..i-1]
Python
Python
# Recursive Python program for insertion sort # Recursive function to sort an array using insertion sortdef insertionSortRecursive(arr, n): # base case if n <= 1: return # Sort first n-1 elements insertionSortRecursive(arr, n - 1) # Insert last element at its correct position in sorted array. last = arr[n - 1] j = n - 2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while (j >= 0 and arr[j] > last): arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = last # Driver program to test insertion sortif __name__ == '__main__': A = [-7, 11, 6, 0, -3, 5, 10, 2] n = len(A) insertionSortRecursive(A, n) print(A) # Contributed by Harsh Valecha,# Edited by Abraar Masud Nafiz.
Please refer complete article on Recursive Insertion Sort for more details!
3gcp5bon7ageb76qt65bn0b5f8p0uyj7ciyogztl
Insertion Sort
python sorting-exercises
Python Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Take Matrix input from user in Python
Differences and Applications of List, Tuple, Set and Dictionary in Python
|
[
{
"code": null,
"e": 24956,
"s": 24928,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 25117,
"s": 24956,
"text": "Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Below is an iterative algorithm for insertion sortAlgorithm "
},
{
"code": null,
"e": 25283,
"s": 25117,
"text": "// Sort an arr[] of size n\ninsertionSort(arr, n) \n Loop from i = 1 to n-1.\n a) Pick element arr[i] and insert\n it into sorted sequence arr[0..i-1] "
},
{
"code": null,
"e": 25290,
"s": 25283,
"text": "Python"
},
{
"code": null,
"e": 25297,
"s": 25290,
"text": "Python"
},
{
"code": "# Recursive Python program for insertion sort # Recursive function to sort an array using insertion sortdef insertionSortRecursive(arr, n): # base case if n <= 1: return # Sort first n-1 elements insertionSortRecursive(arr, n - 1) # Insert last element at its correct position in sorted array. last = arr[n - 1] j = n - 2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while (j >= 0 and arr[j] > last): arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = last # Driver program to test insertion sortif __name__ == '__main__': A = [-7, 11, 6, 0, -3, 5, 10, 2] n = len(A) insertionSortRecursive(A, n) print(A) # Contributed by Harsh Valecha,# Edited by Abraar Masud Nafiz.",
"e": 26096,
"s": 25297,
"text": null
},
{
"code": null,
"e": 26172,
"s": 26096,
"text": "Please refer complete article on Recursive Insertion Sort for more details!"
},
{
"code": null,
"e": 26213,
"s": 26172,
"text": "3gcp5bon7ageb76qt65bn0b5f8p0uyj7ciyogztl"
},
{
"code": null,
"e": 26228,
"s": 26213,
"text": "Insertion Sort"
},
{
"code": null,
"e": 26253,
"s": 26228,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 26269,
"s": 26253,
"text": "Python Programs"
},
{
"code": null,
"e": 26277,
"s": 26269,
"text": "Sorting"
},
{
"code": null,
"e": 26285,
"s": 26277,
"text": "Sorting"
},
{
"code": null,
"e": 26383,
"s": 26285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26422,
"s": 26383,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 26486,
"s": 26422,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 26522,
"s": 26486,
"text": "How to inverse a matrix using NumPy"
},
{
"code": null,
"e": 26560,
"s": 26522,
"text": "Take Matrix input from user in Python"
}
] |
Perl ord Function
|
This function returns the ASCII numeric value of the character specified by EXPR, or $_ if omitted. For example, ord('A') returns a value of 65.
Following is the simple syntax for this function −
ord EXPR
ord
This function returns Integer.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
print("ord() ", ord('G'), "\n");
When above code is executed, it produces the following result −
ord() 71
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2365,
"s": 2220,
"text": "This function returns the ASCII numeric value of the character specified by EXPR, or $_ if omitted. For example, ord('A') returns a value of 65."
},
{
"code": null,
"e": 2416,
"s": 2365,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2431,
"s": 2416,
"text": "ord EXPR\n\nord\n"
},
{
"code": null,
"e": 2462,
"s": 2431,
"text": "This function returns Integer."
},
{
"code": null,
"e": 2518,
"s": 2462,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2571,
"s": 2518,
"text": "#!/usr/bin/perl -w\n\nprint(\"ord() \", ord('G'), \"\\n\");"
},
{
"code": null,
"e": 2635,
"s": 2571,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2645,
"s": 2635,
"text": "ord() 71\n"
},
{
"code": null,
"e": 2680,
"s": 2645,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2694,
"s": 2680,
"text": " Devi Killada"
},
{
"code": null,
"e": 2729,
"s": 2694,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2749,
"s": 2729,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2782,
"s": 2749,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2798,
"s": 2782,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2831,
"s": 2798,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2848,
"s": 2831,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 2881,
"s": 2848,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2904,
"s": 2881,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 2939,
"s": 2904,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2962,
"s": 2939,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 2969,
"s": 2962,
"text": " Print"
},
{
"code": null,
"e": 2980,
"s": 2969,
"text": " Add Notes"
}
] |
XQuery - Custom Functions
|
XQuery provides the capability to write custom functions. Listed below are the guidelines to create a custom function.
Use the keyword declare function to define a function.
Use the keyword declare function to define a function.
Use the data types defined in the current XML Schema
Use the data types defined in the current XML Schema
Enclose the body of function inside curly braces.
Enclose the body of function inside curly braces.
Prefix the name of the function with an XML namespace.
Prefix the name of the function with an XML namespace.
The following syntax is used while creating a custom function.
declare function prefix:function_name($parameter as datatype?...)
as returnDatatype?
{
function body...
};
The following example shows how to create a user-defined function in XQuery.
declare function local:discount($price as xs:decimal?,$percentDiscount as xs:decimal?)
as xs:decimal? {
let $discount := $price - ($price * $percentDiscount div 100)
return $discount
};
let $originalPrice := 100
let $discountAvailed := 10
return ( local:discount($originalPrice, $discountAvailed))
90
To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1991,
"s": 1872,
"text": "XQuery provides the capability to write custom functions. Listed below are the guidelines to create a custom function."
},
{
"code": null,
"e": 2046,
"s": 1991,
"text": "Use the keyword declare function to define a function."
},
{
"code": null,
"e": 2101,
"s": 2046,
"text": "Use the keyword declare function to define a function."
},
{
"code": null,
"e": 2154,
"s": 2101,
"text": "Use the data types defined in the current XML Schema"
},
{
"code": null,
"e": 2207,
"s": 2154,
"text": "Use the data types defined in the current XML Schema"
},
{
"code": null,
"e": 2257,
"s": 2207,
"text": "Enclose the body of function inside curly braces."
},
{
"code": null,
"e": 2307,
"s": 2257,
"text": "Enclose the body of function inside curly braces."
},
{
"code": null,
"e": 2362,
"s": 2307,
"text": "Prefix the name of the function with an XML namespace."
},
{
"code": null,
"e": 2417,
"s": 2362,
"text": "Prefix the name of the function with an XML namespace."
},
{
"code": null,
"e": 2480,
"s": 2417,
"text": "The following syntax is used while creating a custom function."
},
{
"code": null,
"e": 2590,
"s": 2480,
"text": "declare function prefix:function_name($parameter as datatype?...)\nas returnDatatype?\n{\n function body...\n};"
},
{
"code": null,
"e": 2667,
"s": 2590,
"text": "The following example shows how to create a user-defined function in XQuery."
},
{
"code": null,
"e": 2976,
"s": 2667,
"text": "declare function local:discount($price as xs:decimal?,$percentDiscount as xs:decimal?)\nas xs:decimal? {\n let $discount := $price - ($price * $percentDiscount div 100) \n return $discount\n};\n\nlet $originalPrice := 100\n\nlet $discountAvailed := 10\n\nreturn ( local:discount($originalPrice, $discountAvailed)) "
},
{
"code": null,
"e": 2980,
"s": 2976,
"text": "90\n"
},
{
"code": null,
"e": 3153,
"s": 2980,
"text": "To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program."
},
{
"code": null,
"e": 3160,
"s": 3153,
"text": " Print"
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": " Add Notes"
}
] |
Python | yield Keyword - GeeksforGeeks
|
27 May, 2021
Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator. Hence, yield is what makes a generator. The yield keyword in Python is less known off but has a greater utility which one can think of.
Code #1 : Demonstrating yield working
Python3
# Python3 code to demonstrate# yield keyword # generator to print even numbersdef print_even(test_list) : for i in test_list: if i % 2 == 0: yield i # initializing listtest_list = [1, 4, 5, 6, 7] # printing initial listprint ("The original list is : " + str(test_list)) # printing even numbersprint ("The even numbers in list are : ", end = " ")for j in print_even(test_list): print (j, end = " ")
Output :
The original list is : [1, 4, 5, 6, 7]
The even numbers in list are : 4 6
Code #2:
Python3
# A Python program to generate squares from 1# to 100 using yield and therefore generator # An infinite generator function that prints# next square number. It starts with 1def nextSquare(): i = 1 # An Infinite loop to generate squares while True: yield i*i i += 1 # Next execution resumes # from this point # Driver codefor num in nextSquare(): if num > 100: break print(num)
Output:
1
4
9
16
25
36
49
64
81
100
Advantages of yield:
Since it stores the local variable states, hence overhead of memory allocation is controlled.
Since the old state is retained, the flow doesn’t start from the beginning and hence saves time.
Disadvantages of yield:
Sometimes, the use of yield becomes erroneous if the calling of function is not handled properly.
Time and memory optimization has a cost of complexity of code and hence sometimes hard to understand the logic behind it.
Practical Applications: The possible practical application is that when handling the last amount of data and searching particulars from it, yield can be used as we don’t need to look up again from start and hence would save time. There can possibly be many applications of yield depending upon the use cases.
Python3
# Python3 code to demonstrate yield keyword # Checking number of occurrence of# geeks in string # generator to print even numbersdef print_even(test_string) : for i in test_string: if i == "geeks": yield i # initializing stringtest_string = " The are many geeks around you, \ geeks are known for teaching other geeks" # printing even numbers using yieldcount = 0print ("The number of geeks in string is : ", end = "" )test_string = test_string.split() for j in print_even(test_string): count = count + 1 print (count)
Output :
The number of geeks in string is : 3
shivach31
Python-Functions
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24324,
"s": 24296,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 24732,
"s": 24324,
"text": "Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator. Hence, yield is what makes a generator. The yield keyword in Python is less known off but has a greater utility which one can think of. "
},
{
"code": null,
"e": 24771,
"s": 24732,
"text": "Code #1 : Demonstrating yield working "
},
{
"code": null,
"e": 24779,
"s": 24771,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# yield keyword # generator to print even numbersdef print_even(test_list) : for i in test_list: if i % 2 == 0: yield i # initializing listtest_list = [1, 4, 5, 6, 7] # printing initial listprint (\"The original list is : \" + str(test_list)) # printing even numbersprint (\"The even numbers in list are : \", end = \" \")for j in print_even(test_list): print (j, end = \" \")",
"e": 25202,
"s": 24779,
"text": null
},
{
"code": null,
"e": 25213,
"s": 25202,
"text": "Output : "
},
{
"code": null,
"e": 25289,
"s": 25213,
"text": "The original list is : [1, 4, 5, 6, 7]\nThe even numbers in list are : 4 6 "
},
{
"code": null,
"e": 25302,
"s": 25289,
"text": " Code #2: "
},
{
"code": null,
"e": 25310,
"s": 25302,
"text": "Python3"
},
{
"code": "# A Python program to generate squares from 1# to 100 using yield and therefore generator # An infinite generator function that prints# next square number. It starts with 1def nextSquare(): i = 1 # An Infinite loop to generate squares while True: yield i*i i += 1 # Next execution resumes # from this point # Driver codefor num in nextSquare(): if num > 100: break print(num)",
"e": 25761,
"s": 25310,
"text": null
},
{
"code": null,
"e": 25771,
"s": 25761,
"text": "Output: "
},
{
"code": null,
"e": 25799,
"s": 25771,
"text": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100"
},
{
"code": null,
"e": 25821,
"s": 25799,
"text": "Advantages of yield: "
},
{
"code": null,
"e": 25915,
"s": 25821,
"text": "Since it stores the local variable states, hence overhead of memory allocation is controlled."
},
{
"code": null,
"e": 26012,
"s": 25915,
"text": "Since the old state is retained, the flow doesn’t start from the beginning and hence saves time."
},
{
"code": null,
"e": 26037,
"s": 26012,
"text": "Disadvantages of yield: "
},
{
"code": null,
"e": 26135,
"s": 26037,
"text": "Sometimes, the use of yield becomes erroneous if the calling of function is not handled properly."
},
{
"code": null,
"e": 26257,
"s": 26135,
"text": "Time and memory optimization has a cost of complexity of code and hence sometimes hard to understand the logic behind it."
},
{
"code": null,
"e": 26569,
"s": 26257,
"text": "Practical Applications: The possible practical application is that when handling the last amount of data and searching particulars from it, yield can be used as we don’t need to look up again from start and hence would save time. There can possibly be many applications of yield depending upon the use cases. "
},
{
"code": null,
"e": 26577,
"s": 26569,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate yield keyword # Checking number of occurrence of# geeks in string # generator to print even numbersdef print_even(test_string) : for i in test_string: if i == \"geeks\": yield i # initializing stringtest_string = \" The are many geeks around you, \\ geeks are known for teaching other geeks\" # printing even numbers using yieldcount = 0print (\"The number of geeks in string is : \", end = \"\" )test_string = test_string.split() for j in print_even(test_string): count = count + 1 print (count)",
"e": 27132,
"s": 26577,
"text": null
},
{
"code": null,
"e": 27143,
"s": 27132,
"text": "Output : "
},
{
"code": null,
"e": 27180,
"s": 27143,
"text": "The number of geeks in string is : 3"
},
{
"code": null,
"e": 27192,
"s": 27182,
"text": "shivach31"
},
{
"code": null,
"e": 27209,
"s": 27192,
"text": "Python-Functions"
},
{
"code": null,
"e": 27216,
"s": 27209,
"text": "Python"
},
{
"code": null,
"e": 27314,
"s": 27216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27332,
"s": 27314,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27367,
"s": 27332,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27399,
"s": 27367,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27441,
"s": 27399,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27467,
"s": 27441,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27504,
"s": 27467,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27547,
"s": 27504,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27591,
"s": 27547,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27620,
"s": 27591,
"text": "*args and **kwargs in Python"
}
] |
C++ Program for cube sum of first n natural numbers - GeeksforGeeks
|
17 Mar, 2022
Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples:
Input : n = 5
Output : 225
13 + 23 + 33 + 43 + 53 = 225
Input : n = 7
Output : 784
13 + 23 + 33 + 43 + 53 +
63 + 73 = 784
CPP
CPP
// Simple C++ program to find sum of series// with cubes of first n natural numbers#include <iostream>using namespace std; /* Returns the sum of series */int sumOfSeries(int n){ int sum = 0; for (int x=1; x<=n; x++) sum += x*x*x; return sum;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;}
Output :
225
Time Complexity : O(n) An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2
For n = 5 sum by formula is
(5*(5 + 1 ) / 2)) ^ 2
= (5*6/2) ^ 2
= (15) ^ 2
= 225
For n = 7, sum by formula is
(7*(7 + 1 ) / 2)) ^ 2
= (7*8/2) ^ 2
= (28) ^ 2
= 784
Output:
225
Time Complexity : O(1) How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1.
Let the formula be true for n = k-1.
Sum of first (k-1) natural numbers =
[((k - 1) * k)/2]2
Sum of first k natural numbers =
= Sum of (k-1) numbers + k3
= [((k - 1) * k)/2]2 + k3
= [k2(k2 - 2k + 1) + 4k3]/4
= [k4 + 2k3 + k2]/4
= k2(k2 + 2k + 1)/4
= [k*(k+1)/2]2
The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first.
CPP
CPP
// Efficient CPP program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be within// limits.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint sumOfSeries(int n){ int x; if (n % 2 == 0) x = (n/2) * (n+1); else x = ((n + 1) / 2) * n; return x * x;} // Driver codeint main(){ int n = 5; cout << sumOfSeries(n); return 0;}
Output:
225
Please refer complete article on Program for cube sum of first n natural numbers for more details!
surinderdawra388
maths-cube
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
cin in C++
Shallow Copy and Deep Copy in C++
Check if given number is perfect square
C++ Program to check if a given String is Palindrome or not
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
C Program to Swap two Numbers
CSV file management using C++
cout in C++
Pi(π) in C++ with Examples
|
[
{
"code": null,
"e": 24667,
"s": 24639,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 24750,
"s": 24667,
"text": "Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples: "
},
{
"code": null,
"e": 24874,
"s": 24750,
"text": "Input : n = 5\nOutput : 225\n13 + 23 + 33 + 43 + 53 = 225\n\nInput : n = 7\nOutput : 784\n13 + 23 + 33 + 43 + 53 + \n63 + 73 = 784"
},
{
"code": null,
"e": 24878,
"s": 24874,
"text": "CPP"
},
{
"code": null,
"e": 24882,
"s": 24878,
"text": "CPP"
},
{
"code": "// Simple C++ program to find sum of series// with cubes of first n natural numbers#include <iostream>using namespace std; /* Returns the sum of series */int sumOfSeries(int n){ int sum = 0; for (int x=1; x<=n; x++) sum += x*x*x; return sum;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;}",
"e": 25221,
"s": 24882,
"text": null
},
{
"code": null,
"e": 25231,
"s": 25221,
"text": "Output : "
},
{
"code": null,
"e": 25235,
"s": 25231,
"text": "225"
},
{
"code": null,
"e": 25351,
"s": 25235,
"text": "Time Complexity : O(n) An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 "
},
{
"code": null,
"e": 25589,
"s": 25351,
"text": "For n = 5 sum by formula is\n (5*(5 + 1 ) / 2)) ^ 2\n = (5*6/2) ^ 2\n = (15) ^ 2\n = 225\n\nFor n = 7, sum by formula is\n (7*(7 + 1 ) / 2)) ^ 2\n = (7*8/2) ^ 2\n = (28) ^ 2\n = 784"
},
{
"code": null,
"e": 25599,
"s": 25589,
"text": "Output: "
},
{
"code": null,
"e": 25603,
"s": 25599,
"text": "225"
},
{
"code": null,
"e": 25808,
"s": 25603,
"text": "Time Complexity : O(1) How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. "
},
{
"code": null,
"e": 26146,
"s": 25808,
"text": "Let the formula be true for n = k-1.\nSum of first (k-1) natural numbers = \n [((k - 1) * k)/2]2\n\nSum of first k natural numbers = \n = Sum of (k-1) numbers + k3\n = [((k - 1) * k)/2]2 + k3\n = [k2(k2 - 2k + 1) + 4k3]/4\n = [k4 + 2k3 + k2]/4\n = k2(k2 + 2k + 1)/4\n = [k*(k+1)/2]2"
},
{
"code": null,
"e": 26310,
"s": 26146,
"text": "The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. "
},
{
"code": null,
"e": 26314,
"s": 26310,
"text": "CPP"
},
{
"code": null,
"e": 26318,
"s": 26314,
"text": "CPP"
},
{
"code": "// Efficient CPP program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be within// limits.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint sumOfSeries(int n){ int x; if (n % 2 == 0) x = (n/2) * (n+1); else x = ((n + 1) / 2) * n; return x * x;} // Driver codeint main(){ int n = 5; cout << sumOfSeries(n); return 0;}",
"e": 26751,
"s": 26318,
"text": null
},
{
"code": null,
"e": 26760,
"s": 26751,
"text": "Output: "
},
{
"code": null,
"e": 26764,
"s": 26760,
"text": "225"
},
{
"code": null,
"e": 26864,
"s": 26764,
"text": "Please refer complete article on Program for cube sum of first n natural numbers for more details! "
},
{
"code": null,
"e": 26881,
"s": 26864,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26892,
"s": 26881,
"text": "maths-cube"
},
{
"code": null,
"e": 26905,
"s": 26892,
"text": "C++ Programs"
},
{
"code": null,
"e": 27003,
"s": 26905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27012,
"s": 27003,
"text": "Comments"
},
{
"code": null,
"e": 27025,
"s": 27012,
"text": "Old Comments"
},
{
"code": null,
"e": 27036,
"s": 27025,
"text": "cin in C++"
},
{
"code": null,
"e": 27070,
"s": 27036,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 27110,
"s": 27070,
"text": "Check if given number is perfect square"
},
{
"code": null,
"e": 27170,
"s": 27110,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 27211,
"s": 27170,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 27270,
"s": 27211,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 27300,
"s": 27270,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 27330,
"s": 27300,
"text": "CSV file management using C++"
},
{
"code": null,
"e": 27342,
"s": 27330,
"text": "cout in C++"
}
] |
Bootstrap Progress Bars
|
A progress bar can be used to show a user how far along he/she is in a
process.
Bootstrap provides several types of progress bars.
A default progress bar in Bootstrap looks like this:
To create a default progress bar, add a .progress class to a <div> element:
Note: Progress bars are not supported in Internet Explorer 9 and
earlier (because they use CSS3 transitions and animations to achieve some of
their effects).Note: To help improve accessibility for
people using screen readers, you should include the aria-* attributes.
A progress bar with a label looks like this:
Remove the .sr-only class from the progress bar to show a visible percentage:
Contextual classes are used to provide "meaning through colors".
The contextual classes that can be used with progress bars are:
.progress-bar-success
.progress-bar-info
.progress-bar-warning
.progress-bar-danger
The following example shows how to create progress bars with the different
contextual classes:
Progress bars can also be striped:
Add class .progress-bar-striped to add stripes to the progress bars:
Add class .active to animate the progress bar:
Progress bars can also be stacked:
Create a stacked progress bar by placing multiple bars into the same <div class="progress">:
Add the correct classes to make this HTML code behave as a progress bar.
<div class="">
<div class=""
role="progressbar"
style="width:70%">
</div>
</div>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 81,
"s": 0,
"text": "A progress bar can be used to show a user how far along he/she is in a \nprocess."
},
{
"code": null,
"e": 132,
"s": 81,
"text": "Bootstrap provides several types of progress bars."
},
{
"code": null,
"e": 185,
"s": 132,
"text": "A default progress bar in Bootstrap looks like this:"
},
{
"code": null,
"e": 261,
"s": 185,
"text": "To create a default progress bar, add a .progress class to a <div> element:"
},
{
"code": null,
"e": 532,
"s": 261,
"text": "Note: Progress bars are not supported in Internet Explorer 9 and \nearlier (because they use CSS3 transitions and animations to achieve some of \ntheir effects).Note: To help improve accessibility for \npeople using screen readers, you should include the aria-* attributes."
},
{
"code": null,
"e": 577,
"s": 532,
"text": "A progress bar with a label looks like this:"
},
{
"code": null,
"e": 655,
"s": 577,
"text": "Remove the .sr-only class from the progress bar to show a visible percentage:"
},
{
"code": null,
"e": 720,
"s": 655,
"text": "Contextual classes are used to provide \"meaning through colors\"."
},
{
"code": null,
"e": 784,
"s": 720,
"text": "The contextual classes that can be used with progress bars are:"
},
{
"code": null,
"e": 806,
"s": 784,
"text": ".progress-bar-success"
},
{
"code": null,
"e": 825,
"s": 806,
"text": ".progress-bar-info"
},
{
"code": null,
"e": 847,
"s": 825,
"text": ".progress-bar-warning"
},
{
"code": null,
"e": 868,
"s": 847,
"text": ".progress-bar-danger"
},
{
"code": null,
"e": 964,
"s": 868,
"text": "The following example shows how to create progress bars with the different \ncontextual classes:"
},
{
"code": null,
"e": 999,
"s": 964,
"text": "Progress bars can also be striped:"
},
{
"code": null,
"e": 1068,
"s": 999,
"text": "Add class .progress-bar-striped to add stripes to the progress bars:"
},
{
"code": null,
"e": 1115,
"s": 1068,
"text": "Add class .active to animate the progress bar:"
},
{
"code": null,
"e": 1150,
"s": 1115,
"text": "Progress bars can also be stacked:"
},
{
"code": null,
"e": 1243,
"s": 1150,
"text": "Create a stacked progress bar by placing multiple bars into the same <div class=\"progress\">:"
},
{
"code": null,
"e": 1316,
"s": 1243,
"text": "Add the correct classes to make this HTML code behave as a progress bar."
},
{
"code": null,
"e": 1410,
"s": 1316,
"text": "<div class=\"\">\n <div class=\"\"\n role=\"progressbar\"\n style=\"width:70%\">\n </div>\n</div>\n"
},
{
"code": null,
"e": 1429,
"s": 1410,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1462,
"s": 1429,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1504,
"s": 1462,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1611,
"s": 1504,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1630,
"s": 1611,
"text": "help@w3schools.com"
}
] |
How to append to array in MongoDB?
|
To append to array in MongoDB, use $concatArrays. Let us create a collection with documents −
> db.demo435.insertOne({"FirstName":["Chris"],"LastName":["Brown"]} );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7719b1bbc41e36cc3cae97")
}
> db.demo435.insertOne({"FirstName":["David"],"LastName":["Miller"]} );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7719bdbbc41e36cc3cae98")
}
> db.demo435.insertOne({"FirstName":["John"],"LastName":["Doe"]} );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7719c6bbc41e36cc3cae99")
}
Display all documents from a collection with the help of find() method −
> db.demo435.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e7719b1bbc41e36cc3cae97"),
"FirstName" : [
"Chris"
],
"LastName" : [
"Brown"
]
}
{
"_id" : ObjectId("5e7719bdbbc41e36cc3cae98"),
"FirstName" : [
"David"
],
"LastName" : [
"Miller"
]
}
{
"_id" : ObjectId("5e7719c6bbc41e36cc3cae99"),
"FirstName" : [
"John"
],
"LastName" : [
"Doe"
]
}
Following is the query to append to array in MongoDB −
> db.demo435.aggregate([ { $project: { FullName: { $concatArrays: [ "$FirstName", "$LastName" ] } } } ])
This will produce the following output −
{ "_id" : ObjectId("5e7719b1bbc41e36cc3cae97"), "FullName" : [ "Chris", "Brown" ] }
{ "_id" : ObjectId("5e7719bdbbc41e36cc3cae98"), "FullName" : [ "David", "Miller" ] }
{ "_id" : ObjectId("5e7719c6bbc41e36cc3cae99"), "FullName" : [ "John", "Doe" ] }
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To append to array in MongoDB, use $concatArrays. Let us create a collection with documents −"
},
{
"code": null,
"e": 1622,
"s": 1156,
"text": "> db.demo435.insertOne({\"FirstName\":[\"Chris\"],\"LastName\":[\"Brown\"]} );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7719b1bbc41e36cc3cae97\")\n}\n> db.demo435.insertOne({\"FirstName\":[\"David\"],\"LastName\":[\"Miller\"]} );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7719bdbbc41e36cc3cae98\")\n}\n> db.demo435.insertOne({\"FirstName\":[\"John\"],\"LastName\":[\"Doe\"]} );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7719c6bbc41e36cc3cae99\")\n}"
},
{
"code": null,
"e": 1695,
"s": 1622,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1725,
"s": 1695,
"text": "> db.demo435.find().pretty();"
},
{
"code": null,
"e": 1766,
"s": 1725,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2214,
"s": 1766,
"text": "{\n \"_id\" : ObjectId(\"5e7719b1bbc41e36cc3cae97\"),\n \"FirstName\" : [\n \"Chris\"\n ],\n \"LastName\" : [\n \"Brown\"\n ]\n }\n {\n \"_id\" : ObjectId(\"5e7719bdbbc41e36cc3cae98\"),\n \"FirstName\" : [\n \"David\"\n ],\n \"LastName\" : [\n \"Miller\"\n ]\n }\n {\n \"_id\" : ObjectId(\"5e7719c6bbc41e36cc3cae99\"),\n \"FirstName\" : [\n \"John\"\n ],\n \"LastName\" : [\n \"Doe\"\n ]\n}"
},
{
"code": null,
"e": 2269,
"s": 2214,
"text": "Following is the query to append to array in MongoDB −"
},
{
"code": null,
"e": 2374,
"s": 2269,
"text": "> db.demo435.aggregate([ { $project: { FullName: { $concatArrays: [ \"$FirstName\", \"$LastName\" ] } } } ])"
},
{
"code": null,
"e": 2415,
"s": 2374,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2665,
"s": 2415,
"text": "{ \"_id\" : ObjectId(\"5e7719b1bbc41e36cc3cae97\"), \"FullName\" : [ \"Chris\", \"Brown\" ] }\n{ \"_id\" : ObjectId(\"5e7719bdbbc41e36cc3cae98\"), \"FullName\" : [ \"David\", \"Miller\" ] }\n{ \"_id\" : ObjectId(\"5e7719c6bbc41e36cc3cae99\"), \"FullName\" : [ \"John\", \"Doe\" ] }"
}
] |
What is React Native?
|
React Native is an open source JavaScript Mobile framework from Facebook specially designed to build native mobile apps for iOS and Android. React Native is based on ReactJS JavaScript library that helps to build the user interface for mobile platforms.
React Native can be directly used inside an existing IOS or android app or you can build a native app right from scratch. At present React Native is used with some popular apps like Facebook mobile app, Instagram, Pinterest, Skype, etc.
Some important features of React Native that makes it a very popular mobile development app today are −
Cross Platform Support − To develop mobile apps you don’t need a team expert in IOS and Android programming instead JavaScript developers who are enthusiastic to build apps can use React Native to build native apps without having to learn Kotlin or Java for Android and Swift or Objective-C for IOS apps. You can write one common code and React Native will take care of displaying it in IOS and Android.
React Native Components − React Native offers native components like View, Text, and Image that are changed to the IOS or Android native UI.
Here is a simple example using react native that displays the text Hello World:
import React from 'react';
import { Text, View} from 'react-native';
const App = () => {
return (
<View style={{flex :1, justifyContent: 'center', margin: 15}}>
<Text style={{color:'red', fontSize:30}}>Hello World</Text>
</View>
);
}
export default App;
JSX − As ReactJS is for the web world, React Native is meant for the mobile app world. React Native makes use of JSX i.e., an XML for writing code that replaces HTML and CSS. The advantage of JSX is as follows −
It is faster because it performs optimization while compiling code to JavaScript.
It is faster because it performs optimization while compiling code to JavaScript.
It is also type-safe and most of the errors can be caught during compilation.
It is also type-safe and most of the errors can be caught during compilation.
It makes it easier and faster to write templates, if you are familiar with HTML.
It makes it easier and faster to write templates, if you are familiar with HTML.
React Native App Build and Testing − It is very easy to build your app in react native and also to test the changes without any compilation headache. The changes are available soon for display the moment you save your code.
About React Native Release − The first version of React Native was released by Facebook in the year 2015 and from there onwards they are updating and maintaining it. It has gained a lot of popularity post the release as it is one of the top most frameworks used for mobile apps development. As per React Native official website, in 2018 React Native has been the 2nd highest number of contributors for any repository in GitHub. Today, React Native is supported by contributions from individuals and companies around the world including Callstack, Expo, Infinite Red, Microsoft and Software Mansion. The Facebook community has been very active and updates the projects regularly with new updates across platforms.
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "React Native is an open source JavaScript Mobile framework from Facebook specially designed to build native mobile apps for iOS and Android. React Native is based on ReactJS JavaScript library that helps to build the user interface for mobile platforms."
},
{
"code": null,
"e": 1553,
"s": 1316,
"text": "React Native can be directly used inside an existing IOS or android app or you can build a native app right from scratch. At present React Native is used with some popular apps like Facebook mobile app, Instagram, Pinterest, Skype, etc."
},
{
"code": null,
"e": 1657,
"s": 1553,
"text": "Some important features of React Native that makes it a very popular mobile development app today are −"
},
{
"code": null,
"e": 2061,
"s": 1657,
"text": "Cross Platform Support − To develop mobile apps you don’t need a team expert in IOS and Android programming instead JavaScript developers who are enthusiastic to build apps can use React Native to build native apps without having to learn Kotlin or Java for Android and Swift or Objective-C for IOS apps. You can write one common code and React Native will take care of displaying it in IOS and Android."
},
{
"code": null,
"e": 2202,
"s": 2061,
"text": "React Native Components − React Native offers native components like View, Text, and Image that are changed to the IOS or Android native UI."
},
{
"code": null,
"e": 2282,
"s": 2202,
"text": "Here is a simple example using react native that displays the text Hello World:"
},
{
"code": null,
"e": 2562,
"s": 2282,
"text": "import React from 'react';\nimport { Text, View} from 'react-native';\n\nconst App = () => {\n return (\n <View style={{flex :1, justifyContent: 'center', margin: 15}}>\n <Text style={{color:'red', fontSize:30}}>Hello World</Text>\n </View>\n );\n}\n\nexport default App;"
},
{
"code": null,
"e": 2774,
"s": 2562,
"text": "JSX − As ReactJS is for the web world, React Native is meant for the mobile app world. React Native makes use of JSX i.e., an XML for writing code that replaces HTML and CSS. The advantage of JSX is as follows −"
},
{
"code": null,
"e": 2856,
"s": 2774,
"text": "It is faster because it performs optimization while compiling code to JavaScript."
},
{
"code": null,
"e": 2938,
"s": 2856,
"text": "It is faster because it performs optimization while compiling code to JavaScript."
},
{
"code": null,
"e": 3016,
"s": 2938,
"text": "It is also type-safe and most of the errors can be caught during compilation."
},
{
"code": null,
"e": 3094,
"s": 3016,
"text": "It is also type-safe and most of the errors can be caught during compilation."
},
{
"code": null,
"e": 3175,
"s": 3094,
"text": "It makes it easier and faster to write templates, if you are familiar with HTML."
},
{
"code": null,
"e": 3256,
"s": 3175,
"text": "It makes it easier and faster to write templates, if you are familiar with HTML."
},
{
"code": null,
"e": 3480,
"s": 3256,
"text": "React Native App Build and Testing − It is very easy to build your app in react native and also to test the changes without any compilation headache. The changes are available soon for display the moment you save your code."
},
{
"code": null,
"e": 4193,
"s": 3480,
"text": "About React Native Release − The first version of React Native was released by Facebook in the year 2015 and from there onwards they are updating and maintaining it. It has gained a lot of popularity post the release as it is one of the top most frameworks used for mobile apps development. As per React Native official website, in 2018 React Native has been the 2nd highest number of contributors for any repository in GitHub. Today, React Native is supported by contributions from individuals and companies around the world including Callstack, Expo, Infinite Red, Microsoft and Software Mansion. The Facebook community has been very active and updates the projects regularly with new updates across platforms."
}
] |
MongoDB query to get only distinct values
|
To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.
Let us create a collection with documents −
> db.demo287.insertOne({"details":{"AllVowels":["a","u","u","o","e","a","o","i"]}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4c014cf49383b52759cbbd")
}
Display all documents from a collection with the help of find() method −
> db.demo287.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e4c014cf49383b52759cbbd"),
"details" : {
"AllVowels" : [ "a", "u", "u", "o", "e", "a", "o", "i" ]
}
}
Following is the query to get distinct values −
> db.demo287.distinct("details.AllVowels");
This will produce the following output −
[ "a", "e", "i", "o", "u" ]
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array."
},
{
"code": null,
"e": 1280,
"s": 1236,
"text": "Let us create a collection with documents −"
},
{
"code": null,
"e": 1450,
"s": 1280,
"text": "> db.demo287.insertOne({\"details\":{\"AllVowels\":[\"a\",\"u\",\"u\",\"o\",\"e\",\"a\",\"o\",\"i\"]}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4c014cf49383b52759cbbd\")\n}"
},
{
"code": null,
"e": 1523,
"s": 1450,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1553,
"s": 1523,
"text": "> db.demo287.find().pretty();"
},
{
"code": null,
"e": 1594,
"s": 1553,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1732,
"s": 1594,
"text": "{\n \"_id\" : ObjectId(\"5e4c014cf49383b52759cbbd\"),\n \"details\" : {\n \"AllVowels\" : [ \"a\", \"u\", \"u\", \"o\", \"e\", \"a\", \"o\", \"i\" ]\n }\n}"
},
{
"code": null,
"e": 1780,
"s": 1732,
"text": "Following is the query to get distinct values −"
},
{
"code": null,
"e": 1824,
"s": 1780,
"text": "> db.demo287.distinct(\"details.AllVowels\");"
},
{
"code": null,
"e": 1865,
"s": 1824,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1893,
"s": 1865,
"text": "[ \"a\", \"e\", \"i\", \"o\", \"u\" ]"
}
] |
Unique Subsets | Practice | GeeksforGeeks
|
Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets.
Note: Each subset should be sorted.
Example 1:
Input: N = 3, arr[] = {2,1,2}
Output:(),(1),(1 2),(1 2 2),(2),(2 2)
Explanation:
All possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)
After Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2)
Unique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)
Example 2:
Input: N = 4, arr[] = {1,2,3,3}
Output: (),(1),(1 2),(1 2 3)
(1 2 3 3),(1 3),(1 3 3),(2),(2 3)
(2 3 3),(3),(3 3)
Your Task:
Your task is to complete the function AllSubsets() which takes the array arr[] and N as input parameters and returns list of all possible unique subsets in lexicographical order.
Expected Time Complexity: O(2N).
Expected Auxiliary Space: O(2N * X), X = Length of each subset.
Constraints:
1 ≤ N ≤ 12
1 ≤ arr[i] ≤ 9
+1
atulsharma28231 hour ago
public: //Function to find all possible unique subsets. set<vector<int>>st; void generate(vector<int>arr,vector<int>&v) { if(arr.size()==0) { sort(v.begin(),v.end()); st.insert(v); return; } else { vector<int>v1,v2; v1=v; v2=v; v2.push_back(arr[0]); arr.erase(arr.begin()+0); generate(arr,v1); generate(arr,v2); } } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here vector<int>v; generate(arr,v); vector<vector<int>>vac; for(auto &v:st) { vac.push_back(v); } return vac; }
0
rockzthakur1998091 day ago
vector<vector<int> > AllSubsets(vector<int> arr, int n)
{
vector<vector<int>>v;
int t=pow(2,n);
set<vector<int>>s;
for(int i=0;i<t;i++)
{
vector<int>a;
for(int j=0;j<n;j++)
{
if(i&(1<<j))
{
a.push_back(arr[j]);
}
}
sort(a.begin(),a.end());
s.insert(a);
}
for(auto it:s)
{
v.push_back(it);
}
return v;
}
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(2^N) and space complexity as O(2^N) is as follows :-
Execution Time :- 0.77 / 1.32 sec
set<vector<int>> s; void helper(vector<int> &arr,int ind,vector<int> output){ if(ind == arr.size()){ s.insert(output); return; } int ele = arr[ind]; helper(arr,ind+1,output); output.push_back(ele); helper(arr,ind+1,output); } vector<vector<int> > AllSubsets(vector<int> arr, int n){ sort(arr.begin(),arr.end()); vector<int> output; helper(arr,0,output); vector<vector<int>> ans; set<vector<int>>::iterator iter; for(iter = s.begin(); iter != s.end(); iter++){ ans.push_back(*iter); } return (ans); }
0
abytespaceneeded3 weeks ago
class Solution
{
public:
//Function to find all possible unique subsets.
vector<vector<int> > AllSubsets(vector<int> arr, int n)
{
// code here
vector<vector<int>> ans;
for(int i=0;i<(1<<n);i++)
{
vector<int> temp;
for(int j=0;j<n;j++)
{
if((i & (1<<j)))
temp.push_back(arr[j]);
}
ans.push_back(temp);
temp.clear();
}
for(int i=0;i<ans.size();i++)
sort(ans[i].begin(),ans[i].end());
set<vector<int>> s;
for(int i=0;i<ans.size();i++)
{
s.insert(ans[i]);
}
ans.clear();
for(auto it: s)
{
ans.push_back(it);
}
return ans;
}
};
0
abytespaceneeded
This comment was deleted.
0
kuldeepy104591 month ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution{ public: //Function to find all possible unique subsets. vector<vector<int>> ans; set<vector<int> > s; vector<int> vec; void helper(vector<int>arr,int i,int n){ if(i==n){ s.insert(vec); return; } vec.push_back(arr[i]); helper(arr,i+1,n); vec.pop_back(); helper(arr,i+1,n); } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here sort(arr.begin(),arr.end()); helper(arr,0,n); for(auto x:s){ ans.push_back(x); } return ans; }};
// { Driver Code Starts.
int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vector<int> A; int x; for(int i=0;i<n;i++){ cin>>x; A.push_back(x); } Solution obj; vector<vector<int> > result = obj.AllSubsets(A,n); // printing the output for(int i=0;i<result.size();i++){ cout<<'('; for(int j=0;j<result[i].size();j++){ cout<<result[i][j]; if(j<result[i].size()-1) cout<<" "; } cout<<")"; } cout<<"\n"; }}
// } Driver Code Ends
0
vinamrajha1 month ago
vector<vector<int>>res;
void helper(vector<int>&arr, vector<int>&temp, int i){
res.push_back(temp);
for(int j =i; j<arr.size(); ++j){
/*as we're prompt to only consider unique elements, we skip the duplicates. Below line of code does that part*/
if(j!=i && arr[j]==arr[j-1])continue;
temp.push_back(arr[j]);
helper(arr, temp, j+1);
temp.pop_back();
}
}
vector<vector<int>>AllSubsets(vector<int> arr, int n)
{
// code here
sort(arr.begin(), arr.end());
vector<int>temp;
helper(arr, temp, 0);
return res;
}
+1
prakashsuraj4141
This comment was deleted.
+2
rajatsingh16032 months ago
void recursive(vector<int> arr,vector<vector<int>> &ans,vector<int> &ds,int indx){ ans.push_back(ds); for(int i = indx; i<arr.size(); i++){ if(i != indx && arr[i] == arr[i-1])continue; ds.push_back(arr[i]); recursive(arr,ans,ds,i+1); ds.pop_back(); } } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here vector<vector<int>> ans; vector<int> ds; sort(arr.begin(),arr.end()); recursive(arr,ans,ds,0); return ans; }
0
lindan1232 months ago
public:
//Function to find all possible unique subsets.
vector<vector<int>> ans;
set<vector<int> > s;
vector<int> vec;
void solve(vector<int> arr,int i,int n)
{
if(i==n)
{
s.insert(vec);
return ;
}
vec.push_back(arr[i]);
solve(arr,i+1,n);
vec.pop_back();
solve(arr,i+1,n);
}
vector<vector<int> > AllSubsets(vector<int> arr, int n)
{
sort(arr.begin(),arr.end());
solve(arr,0,n);
for(auto x :s)
{
ans.push_back(x);
}
return ans;
}
Time Taken : 0.7sec
Cpp
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 361,
"s": 238,
"text": "Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets."
},
{
"code": null,
"e": 397,
"s": 361,
"text": "Note: Each subset should be sorted."
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Example 1:"
},
{
"code": null,
"e": 699,
"s": 408,
"text": "Input: N = 3, arr[] = {2,1,2}\nOutput:(),(1),(1 2),(1 2 2),(2),(2 2)\nExplanation: \nAll possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)\nAfter Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2) \nUnique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)\n"
},
{
"code": null,
"e": 710,
"s": 699,
"text": "Example 2:"
},
{
"code": null,
"e": 823,
"s": 710,
"text": "Input: N = 4, arr[] = {1,2,3,3}\nOutput: (),(1),(1 2),(1 2 3)\n(1 2 3 3),(1 3),(1 3 3),(2),(2 3)\n(2 3 3),(3),(3 3)"
},
{
"code": null,
"e": 1014,
"s": 823,
"text": "Your Task:\nYour task is to complete the function AllSubsets() which takes the array arr[] and N as input parameters and returns list of all possible unique subsets in lexicographical order. "
},
{
"code": null,
"e": 1111,
"s": 1014,
"text": "Expected Time Complexity: O(2N).\nExpected Auxiliary Space: O(2N * X), X = Length of each subset."
},
{
"code": null,
"e": 1150,
"s": 1111,
"text": "Constraints:\n1 ≤ N ≤ 12\n1 ≤ arr[i] ≤ 9"
},
{
"code": null,
"e": 1153,
"s": 1150,
"text": "+1"
},
{
"code": null,
"e": 1178,
"s": 1153,
"text": "atulsharma28231 hour ago"
},
{
"code": null,
"e": 1885,
"s": 1178,
"text": "public: //Function to find all possible unique subsets. set<vector<int>>st; void generate(vector<int>arr,vector<int>&v) { if(arr.size()==0) { sort(v.begin(),v.end()); st.insert(v); return; } else { vector<int>v1,v2; v1=v; v2=v; v2.push_back(arr[0]); arr.erase(arr.begin()+0); generate(arr,v1); generate(arr,v2); } } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here vector<int>v; generate(arr,v); vector<vector<int>>vac; for(auto &v:st) { vac.push_back(v); } return vac; }"
},
{
"code": null,
"e": 1887,
"s": 1885,
"text": "0"
},
{
"code": null,
"e": 1914,
"s": 1887,
"text": "rockzthakur1998091 day ago"
},
{
"code": null,
"e": 2443,
"s": 1914,
"text": " vector<vector<int> > AllSubsets(vector<int> arr, int n)\n {\n vector<vector<int>>v;\n int t=pow(2,n);\n set<vector<int>>s;\n for(int i=0;i<t;i++)\n {\n vector<int>a;\n for(int j=0;j<n;j++)\n {\n if(i&(1<<j))\n {\n a.push_back(arr[j]);\n }\n }\n sort(a.begin(),a.end());\n s.insert(a);\n }\n \n for(auto it:s)\n {\n v.push_back(it);\n }\n return v;\n }"
},
{
"code": null,
"e": 2446,
"s": 2443,
"text": "+1"
},
{
"code": null,
"e": 2473,
"s": 2446,
"text": "aloksinghbais022 weeks ago"
},
{
"code": null,
"e": 2568,
"s": 2473,
"text": "C++ solution having time complexity as O(2^N) and space complexity as O(2^N) is as follows :- "
},
{
"code": null,
"e": 2604,
"s": 2570,
"text": "Execution Time :- 0.77 / 1.32 sec"
},
{
"code": null,
"e": 3255,
"s": 2606,
"text": "set<vector<int>> s; void helper(vector<int> &arr,int ind,vector<int> output){ if(ind == arr.size()){ s.insert(output); return; } int ele = arr[ind]; helper(arr,ind+1,output); output.push_back(ele); helper(arr,ind+1,output); } vector<vector<int> > AllSubsets(vector<int> arr, int n){ sort(arr.begin(),arr.end()); vector<int> output; helper(arr,0,output); vector<vector<int>> ans; set<vector<int>>::iterator iter; for(iter = s.begin(); iter != s.end(); iter++){ ans.push_back(*iter); } return (ans); }"
},
{
"code": null,
"e": 3257,
"s": 3255,
"text": "0"
},
{
"code": null,
"e": 3285,
"s": 3257,
"text": "abytespaceneeded3 weeks ago"
},
{
"code": null,
"e": 4166,
"s": 3285,
"text": "class Solution\n{\n public:\n //Function to find all possible unique subsets.\n vector<vector<int> > AllSubsets(vector<int> arr, int n)\n {\n // code here \n vector<vector<int>> ans;\n \n for(int i=0;i<(1<<n);i++)\n {\n vector<int> temp;\n for(int j=0;j<n;j++)\n {\n if((i & (1<<j)))\n temp.push_back(arr[j]);\n }\n \n ans.push_back(temp);\n temp.clear();\n }\n \n for(int i=0;i<ans.size();i++)\n sort(ans[i].begin(),ans[i].end());\n \n set<vector<int>> s;\n for(int i=0;i<ans.size();i++)\n {\n s.insert(ans[i]);\n }\n \n ans.clear();\n \n for(auto it: s)\n {\n ans.push_back(it);\n }\n \n return ans;\n }\n};\n"
},
{
"code": null,
"e": 4168,
"s": 4166,
"text": "0"
},
{
"code": null,
"e": 4185,
"s": 4168,
"text": "abytespaceneeded"
},
{
"code": null,
"e": 4211,
"s": 4185,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4213,
"s": 4211,
"text": "0"
},
{
"code": null,
"e": 4238,
"s": 4213,
"text": "kuldeepy104591 month ago"
},
{
"code": null,
"e": 4306,
"s": 4238,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 4933,
"s": 4306,
"text": "// } Driver Code Endsclass Solution{ public: //Function to find all possible unique subsets. vector<vector<int>> ans; set<vector<int> > s; vector<int> vec; void helper(vector<int>arr,int i,int n){ if(i==n){ s.insert(vec); return; } vec.push_back(arr[i]); helper(arr,i+1,n); vec.pop_back(); helper(arr,i+1,n); } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here sort(arr.begin(),arr.end()); helper(arr,0,n); for(auto x:s){ ans.push_back(x); } return ans; }};"
},
{
"code": null,
"e": 4958,
"s": 4933,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 5526,
"s": 4958,
"text": "int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vector<int> A; int x; for(int i=0;i<n;i++){ cin>>x; A.push_back(x); } Solution obj; vector<vector<int> > result = obj.AllSubsets(A,n); // printing the output for(int i=0;i<result.size();i++){ cout<<'('; for(int j=0;j<result[i].size();j++){ cout<<result[i][j]; if(j<result[i].size()-1) cout<<\" \"; } cout<<\")\"; } cout<<\"\\n\"; }} "
},
{
"code": null,
"e": 5549,
"s": 5526,
"text": " // } Driver Code Ends"
},
{
"code": null,
"e": 5551,
"s": 5549,
"text": "0"
},
{
"code": null,
"e": 5573,
"s": 5551,
"text": "vinamrajha1 month ago"
},
{
"code": null,
"e": 6205,
"s": 5573,
"text": "vector<vector<int>>res;\n void helper(vector<int>&arr, vector<int>&temp, int i){\n res.push_back(temp);\n for(int j =i; j<arr.size(); ++j){\n /*as we're prompt to only consider unique elements, we skip the duplicates. Below line of code does that part*/\n if(j!=i && arr[j]==arr[j-1])continue; \n temp.push_back(arr[j]);\n helper(arr, temp, j+1);\n temp.pop_back();\n }\n }\n vector<vector<int>>AllSubsets(vector<int> arr, int n)\n {\n // code here\n sort(arr.begin(), arr.end());\n vector<int>temp;\n helper(arr, temp, 0);\n return res;\n }"
},
{
"code": null,
"e": 6208,
"s": 6205,
"text": "+1"
},
{
"code": null,
"e": 6225,
"s": 6208,
"text": "prakashsuraj4141"
},
{
"code": null,
"e": 6251,
"s": 6225,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6254,
"s": 6251,
"text": "+2"
},
{
"code": null,
"e": 6281,
"s": 6254,
"text": "rajatsingh16032 months ago"
},
{
"code": null,
"e": 6820,
"s": 6281,
"text": "void recursive(vector<int> arr,vector<vector<int>> &ans,vector<int> &ds,int indx){ ans.push_back(ds); for(int i = indx; i<arr.size(); i++){ if(i != indx && arr[i] == arr[i-1])continue; ds.push_back(arr[i]); recursive(arr,ans,ds,i+1); ds.pop_back(); } } vector<vector<int> > AllSubsets(vector<int> arr, int n) { // code here vector<vector<int>> ans; vector<int> ds; sort(arr.begin(),arr.end()); recursive(arr,ans,ds,0); return ans; }"
},
{
"code": null,
"e": 6822,
"s": 6820,
"text": "0"
},
{
"code": null,
"e": 6844,
"s": 6822,
"text": "lindan1232 months ago"
},
{
"code": null,
"e": 7485,
"s": 6844,
"text": " public:\n //Function to find all possible unique subsets.\n vector<vector<int>> ans;\n set<vector<int> > s;\n vector<int> vec;\n void solve(vector<int> arr,int i,int n)\n {\n if(i==n)\n {\n s.insert(vec);\n return ;\n }\n \n vec.push_back(arr[i]);\n solve(arr,i+1,n);\n vec.pop_back();\n solve(arr,i+1,n);\n }\n vector<vector<int> > AllSubsets(vector<int> arr, int n)\n {\n \n \n sort(arr.begin(),arr.end()); \n \n solve(arr,0,n);\n for(auto x :s)\n {\n ans.push_back(x);\n }\n return ans;\n }"
},
{
"code": null,
"e": 7505,
"s": 7485,
"text": "Time Taken : 0.7sec"
},
{
"code": null,
"e": 7509,
"s": 7505,
"text": "Cpp"
},
{
"code": null,
"e": 7655,
"s": 7509,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7691,
"s": 7655,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7701,
"s": 7691,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7711,
"s": 7701,
"text": "\nContest\n"
},
{
"code": null,
"e": 7774,
"s": 7711,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7922,
"s": 7774,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8130,
"s": 7922,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8236,
"s": 8130,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Pairs with Difference less than K - GeeksforGeeks
|
18 May, 2021
Given an array of n integers, We need to find all pairs with difference less than k
Examples :
Input : a[] = {1, 10, 4, 2}
K = 3
Output : 2
We can make only two pairs
with difference less than 3.
(1, 2) and (4, 2)
Input : a[] = {1, 8, 7}
K = 7
Output : 2
Pairs with difference less than 7
are (1, 7) and (8, 7)
Method 1 (Simple) : Run two nested loops. The outer loop picks every element x one by one. The inner loop considers all elements after x and checks if difference is within limits or not.
C++
Java
Python3
C#
PHP
Javascript
// CPP code to find count of Pairs with// difference less than K.#include <bits/stdc++.h>using namespace std; int countPairs(int a[], int n, int k){ int res = 0; for (int i = 0; i < n; i++) for (int j=i+1; j<n; j++) if (abs(a[j] - a[i]) < k) res++; return res;} // Driver codeint main(){ int a[] = {1, 10, 4, 2}; int k = 3; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n, k) << endl; return 0;}
// java code to find count of Pairs with// difference less than K.import java.io.*; class GFG { static int countPairs(int a[], int n, int k) { int res = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (Math.abs(a[j] - a[i]) < k) res++; return res; } // Driver code public static void main (String[] args) { int a[] = {1, 10, 4, 2}; int k = 3; int n = a.length; System.out.println(countPairs(a, n, k)); }} // This code is contributed by vt_m.
# Python3 code to find count of Pairs # with difference less than K. def countPairs(a, n, k): res = 0 for i in range(n): for j in range(i + 1, n): if (abs(a[j] - a[i]) < k): res += 1 return res # Driver codea = [1, 10, 4, 2]k = 3n = len(a)print(countPairs(a, n, k), end = "") # This code is contributed by Azkia Anam.
// C# code to find count of Pairs// with difference less than K.using System; class GFG { // Function to count pairs static int countPairs(int []a, int n, int k) { int res = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (Math.Abs(a[j] - a[i]) < k) res++; return res; } // Driver code public static void Main () { int []a = {1, 10, 4, 2}; int k = 3; int n = a.Length; Console.WriteLine(countPairs(a, n, k)); }} // This code is contributed by vt_m.
<?php// PHP code to find count of Pairs// with difference less than K. function countPairs( $a, $n, $k){ $res = 0; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) if (abs($a[$j] - $a[$i]) < $k) $res++; return $res;} // Driver code $a = array(1, 10, 4, 2); $k = 3; $n = count($a); echo countPairs($a, $n, $k); // This code is contributed by anuj_67.?>
<script> // Javascript code to find count of Pairs// with difference less than K.function countPairs(a, n, k){ var res = 0; for(var i = 0; i < n; i++) for(var j = i + 1; j < n; j++) if (Math.abs(a[j] - a[i]) < k) res++; return res;} // Driver codevar a = [ 1, 10, 4, 2 ];var k = 3;var n = a.length; document.write(countPairs(a, n, k)); // This code is contributed by bunnyram19 </script>
Output :
2
Time Complexity : O(n2) Auxiliary Space : O(1)
Method 2 (Sorting) : First we sort the array. Then we start from first element and keep considering pairs while difference is less than k. If we stop the loop when we find difference more than or equal to k and move to next element.
C++
Java
Python3
C#
PHP
Javascript
// C++ code to find count of Pairs with// difference less than K.#include <bits/stdc++.h>using namespace std; int countPairs(int a[], int n, int k){ // to sort the array. sort(a, a + n); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i+1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res;} // Driver codeint main(){ int a[] = {1, 10, 4, 2}; int k = 3; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n, k) << endl; return 0;}
// Java code to find count of Pairs with// difference less than K.import java.io.*;import java.util.Arrays; class GFG{ static int countPairs(int a[], int n, int k) { // to sort the array. Arrays.sort(a); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res; } // Driver code public static void main (String[] args) { int a[] = {1, 10, 4, 2}; int k = 3; int n = a.length; System.out.println(countPairs(a, n, k)); }} // This code is contributed by vt_m.
# Python code to find count of Pairs # with difference less than K. def countPairs(a, n, k): # to sort the array a.sort() res = 0 for i in range(n): # Keep incrementing result while # subsequent elements are within limits. j = i+1 while (j < n and a[j] - a[i] < k): res += 1 j += 1 return res # Driver codea = [1, 10, 4, 2]k = 3n = len(a)print(countPairs(a, n, k), end = "") # This code is contributed by Azkia Anam.
// C# code to find count of Pairs// with difference less than K.using System; class GFG { // Function to count pairs static int countPairs(int []a, int n, int k) { // to sort the array. Array.Sort(a); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res; } // Driver code public static void Main () { int []a = {1, 10, 4, 2}; int k = 3; int n = a.Length; Console.WriteLine(countPairs(a, n, k)); }} // This code is contributed by vt_m.
<?php// PHP code to find count of// Pairs with difference less than K. function countPairs( $a, $n, $k){ // to sort the array. sort($a); $res = 0; for ( $i = 0; $i < $n; $i++) { // Keep incrementing result // while subsequent elements // are within limits. $j = $i + 1; while ($j < $n and $a[$j] - $a[$i] < $k) { $res++; $j++; } } return $res;} // Driver code$a = array(1, 10, 4, 2);$k = 3;$n = count($a);echo countPairs($a, $n, $k); // This code is contributed by anuj_67.?>
<script> // JavaScript code to find count of Pairs with// difference less than K.function countPairs(a, n, k){ // To sort the array. a.sort((a, b) => a - b); let res = 0; for(let i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. let j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res;} // Driver codelet a = [ 1, 10, 4, 2 ];let k = 3;let n = a.length; document.write(countPairs(a, n, k) + "<br>"); // This code is contributed by Surbhi Tyagi. </script>
Output :
2
Time complexity : O(res) where res is number of pairs in output. Note that in worst case this also takes O(n2) time but works much better in general.
This article is contributed by Harsha Mogali. If you like GeeksforGeeks and write.geeksforgeeks.org”>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.
vt_m
bunnyram19
surbhityagi15
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Find duplicates in O(n) time and O(1) extra space | Set 1
Reversal algorithm for array rotation
Next Greater Element
|
[
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 24904,
"s": 24820,
"text": "Given an array of n integers, We need to find all pairs with difference less than k"
},
{
"code": null,
"e": 24917,
"s": 24904,
"text": "Examples : "
},
{
"code": null,
"e": 25151,
"s": 24917,
"text": "Input : a[] = {1, 10, 4, 2}\n K = 3\nOutput : 2\nWe can make only two pairs \nwith difference less than 3.\n(1, 2) and (4, 2)\n\nInput : a[] = {1, 8, 7}\n K = 7\nOutput : 2\nPairs with difference less than 7\nare (1, 7) and (8, 7)"
},
{
"code": null,
"e": 25340,
"s": 25151,
"text": "Method 1 (Simple) : Run two nested loops. The outer loop picks every element x one by one. The inner loop considers all elements after x and checks if difference is within limits or not. "
},
{
"code": null,
"e": 25344,
"s": 25340,
"text": "C++"
},
{
"code": null,
"e": 25349,
"s": 25344,
"text": "Java"
},
{
"code": null,
"e": 25357,
"s": 25349,
"text": "Python3"
},
{
"code": null,
"e": 25360,
"s": 25357,
"text": "C#"
},
{
"code": null,
"e": 25364,
"s": 25360,
"text": "PHP"
},
{
"code": null,
"e": 25375,
"s": 25364,
"text": "Javascript"
},
{
"code": "// CPP code to find count of Pairs with// difference less than K.#include <bits/stdc++.h>using namespace std; int countPairs(int a[], int n, int k){ int res = 0; for (int i = 0; i < n; i++) for (int j=i+1; j<n; j++) if (abs(a[j] - a[i]) < k) res++; return res;} // Driver codeint main(){ int a[] = {1, 10, 4, 2}; int k = 3; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n, k) << endl; return 0;}",
"e": 25831,
"s": 25375,
"text": null
},
{
"code": "// java code to find count of Pairs with// difference less than K.import java.io.*; class GFG { static int countPairs(int a[], int n, int k) { int res = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (Math.abs(a[j] - a[i]) < k) res++; return res; } // Driver code public static void main (String[] args) { int a[] = {1, 10, 4, 2}; int k = 3; int n = a.length; System.out.println(countPairs(a, n, k)); }} // This code is contributed by vt_m.",
"e": 26413,
"s": 25831,
"text": null
},
{
"code": "# Python3 code to find count of Pairs # with difference less than K. def countPairs(a, n, k): res = 0 for i in range(n): for j in range(i + 1, n): if (abs(a[j] - a[i]) < k): res += 1 return res # Driver codea = [1, 10, 4, 2]k = 3n = len(a)print(countPairs(a, n, k), end = \"\") # This code is contributed by Azkia Anam.",
"e": 26778,
"s": 26413,
"text": null
},
{
"code": "// C# code to find count of Pairs// with difference less than K.using System; class GFG { // Function to count pairs static int countPairs(int []a, int n, int k) { int res = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (Math.Abs(a[j] - a[i]) < k) res++; return res; } // Driver code public static void Main () { int []a = {1, 10, 4, 2}; int k = 3; int n = a.Length; Console.WriteLine(countPairs(a, n, k)); }} // This code is contributed by vt_m.",
"e": 27401,
"s": 26778,
"text": null
},
{
"code": "<?php// PHP code to find count of Pairs// with difference less than K. function countPairs( $a, $n, $k){ $res = 0; for($i = 0; $i < $n; $i++) for($j = $i + 1; $j < $n; $j++) if (abs($a[$j] - $a[$i]) < $k) $res++; return $res;} // Driver code $a = array(1, 10, 4, 2); $k = 3; $n = count($a); echo countPairs($a, $n, $k); // This code is contributed by anuj_67.?>",
"e": 27810,
"s": 27401,
"text": null
},
{
"code": "<script> // Javascript code to find count of Pairs// with difference less than K.function countPairs(a, n, k){ var res = 0; for(var i = 0; i < n; i++) for(var j = i + 1; j < n; j++) if (Math.abs(a[j] - a[i]) < k) res++; return res;} // Driver codevar a = [ 1, 10, 4, 2 ];var k = 3;var n = a.length; document.write(countPairs(a, n, k)); // This code is contributed by bunnyram19 </script>",
"e": 28265,
"s": 27810,
"text": null
},
{
"code": null,
"e": 28275,
"s": 28265,
"text": "Output : "
},
{
"code": null,
"e": 28279,
"s": 28275,
"text": " 2"
},
{
"code": null,
"e": 28326,
"s": 28279,
"text": "Time Complexity : O(n2) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 28561,
"s": 28326,
"text": "Method 2 (Sorting) : First we sort the array. Then we start from first element and keep considering pairs while difference is less than k. If we stop the loop when we find difference more than or equal to k and move to next element. "
},
{
"code": null,
"e": 28565,
"s": 28561,
"text": "C++"
},
{
"code": null,
"e": 28570,
"s": 28565,
"text": "Java"
},
{
"code": null,
"e": 28578,
"s": 28570,
"text": "Python3"
},
{
"code": null,
"e": 28581,
"s": 28578,
"text": "C#"
},
{
"code": null,
"e": 28585,
"s": 28581,
"text": "PHP"
},
{
"code": null,
"e": 28596,
"s": 28585,
"text": "Javascript"
},
{
"code": "// C++ code to find count of Pairs with// difference less than K.#include <bits/stdc++.h>using namespace std; int countPairs(int a[], int n, int k){ // to sort the array. sort(a, a + n); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i+1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res;} // Driver codeint main(){ int a[] = {1, 10, 4, 2}; int k = 3; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n, k) << endl; return 0;}",
"e": 29226,
"s": 28596,
"text": null
},
{
"code": "// Java code to find count of Pairs with// difference less than K.import java.io.*;import java.util.Arrays; class GFG{ static int countPairs(int a[], int n, int k) { // to sort the array. Arrays.sort(a); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res; } // Driver code public static void main (String[] args) { int a[] = {1, 10, 4, 2}; int k = 3; int n = a.length; System.out.println(countPairs(a, n, k)); }} // This code is contributed by vt_m.",
"e": 30044,
"s": 29226,
"text": null
},
{
"code": "# Python code to find count of Pairs # with difference less than K. def countPairs(a, n, k): # to sort the array a.sort() res = 0 for i in range(n): # Keep incrementing result while # subsequent elements are within limits. j = i+1 while (j < n and a[j] - a[i] < k): res += 1 j += 1 return res # Driver codea = [1, 10, 4, 2]k = 3n = len(a)print(countPairs(a, n, k), end = \"\") # This code is contributed by Azkia Anam.",
"e": 30540,
"s": 30044,
"text": null
},
{
"code": "// C# code to find count of Pairs// with difference less than K.using System; class GFG { // Function to count pairs static int countPairs(int []a, int n, int k) { // to sort the array. Array.Sort(a); int res = 0; for (int i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. int j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res; } // Driver code public static void Main () { int []a = {1, 10, 4, 2}; int k = 3; int n = a.Length; Console.WriteLine(countPairs(a, n, k)); }} // This code is contributed by vt_m.",
"e": 31383,
"s": 30540,
"text": null
},
{
"code": "<?php// PHP code to find count of// Pairs with difference less than K. function countPairs( $a, $n, $k){ // to sort the array. sort($a); $res = 0; for ( $i = 0; $i < $n; $i++) { // Keep incrementing result // while subsequent elements // are within limits. $j = $i + 1; while ($j < $n and $a[$j] - $a[$i] < $k) { $res++; $j++; } } return $res;} // Driver code$a = array(1, 10, 4, 2);$k = 3;$n = count($a);echo countPairs($a, $n, $k); // This code is contributed by anuj_67.?>",
"e": 31967,
"s": 31383,
"text": null
},
{
"code": "<script> // JavaScript code to find count of Pairs with// difference less than K.function countPairs(a, n, k){ // To sort the array. a.sort((a, b) => a - b); let res = 0; for(let i = 0; i < n; i++) { // Keep incrementing result while // subsequent elements are within // limits. let j = i + 1; while (j < n && a[j] - a[i] < k) { res++; j++; } } return res;} // Driver codelet a = [ 1, 10, 4, 2 ];let k = 3;let n = a.length; document.write(countPairs(a, n, k) + \"<br>\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 32599,
"s": 31967,
"text": null
},
{
"code": null,
"e": 32609,
"s": 32599,
"text": "Output : "
},
{
"code": null,
"e": 32613,
"s": 32609,
"text": " 2"
},
{
"code": null,
"e": 32763,
"s": 32613,
"text": "Time complexity : O(res) where res is number of pairs in output. Note that in worst case this also takes O(n2) time but works much better in general."
},
{
"code": null,
"e": 33148,
"s": 32763,
"text": "This article is contributed by Harsha Mogali. If you like GeeksforGeeks and write.geeksforgeeks.org”>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": 33153,
"s": 33148,
"text": "vt_m"
},
{
"code": null,
"e": 33164,
"s": 33153,
"text": "bunnyram19"
},
{
"code": null,
"e": 33178,
"s": 33164,
"text": "surbhityagi15"
},
{
"code": null,
"e": 33185,
"s": 33178,
"text": "Arrays"
},
{
"code": null,
"e": 33193,
"s": 33185,
"text": "Sorting"
},
{
"code": null,
"e": 33200,
"s": 33193,
"text": "Arrays"
},
{
"code": null,
"e": 33208,
"s": 33200,
"text": "Sorting"
},
{
"code": null,
"e": 33306,
"s": 33208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33315,
"s": 33306,
"text": "Comments"
},
{
"code": null,
"e": 33328,
"s": 33315,
"text": "Old Comments"
},
{
"code": null,
"e": 33353,
"s": 33328,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33402,
"s": 33353,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33460,
"s": 33402,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 33498,
"s": 33460,
"text": "Reversal algorithm for array rotation"
}
] |
Python MongoDB - Quick Guide
|
Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python.
To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command.
C:\WINDOWS\system32>pip install pymongo
Collecting pymongo
Using cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.9.0
Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py.
import pymongo
If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues.
D:\Python_MongoDB>test.py
D:\Python_MongoDB>
Unlike other databases, MongoDB does not provide separate command to create a database.
In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created.
Therefore, you can create a database in MongoDB using the Use command.
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Following command creates a database named in mydb.
>use mydb
switched to db mydb
You can verify your creation by using the db command, this displays the current database.
>db
mydb
To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion.
Following example creates a database in MangoDB.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
print("Database created........")
Database created........
A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases.
You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter.
Using this you can specify the following −
The size of the collection.
The size of the collection.
The max number of documents allowed in the capped collection.
The max number of documents allowed in the capped collection.
Whether the collection we create should be capped collection (fixed size collection).
Whether the collection we create should be capped collection (fixed size collection).
Whether the collection we create should be auto-indexed.
Whether the collection we create should be auto-indexed.
Following is the syntax to create a collection in MongoDB.
db.createCollection("CollectionName")
Following method creates a collection named ExampleCollection.
> use mydb
switched to db mydb
> db.createCollection("ExampleCollection")
{ "ok" : 1 }
>
Similarly, following is a query that creates a collection using the options of the createCollection() method.
>db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>
Following python example connects to a database in MongoDB (mydb) and, creates a collection in it.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
collection = db['example']
print("Collection created........")
Collection created........
You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter.
Following is the syntax of the insert method.
>db.COLLECTION_NAME.insert(DOCUMENT_NAME)
> use mydb
switched to db mydb
> db.createCollection("sample")
{ "ok" : 1 }
> doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
{ "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
> db.sample.insert(doc1)
WriteResult({ "nInserted" : 1 })
>
Similarly, you can also insert multiple documents using the insert() method.
> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
{"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
{"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"},
{"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"},
{"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format.
Following example inserts a document in the collection named example.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())
{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
Data inserted ......
['101', '102', '103']
You can read/retrieve stored documents from MongoDB using the find() method. This method retrieves and displays all the documents in MongoDB in a non-structured way.
Following is the syntax of the find() method.
>db.COLLECTION_NAME.find()
Assume we have inserted 3 documents into a database named testDB in a collection named sample using the following queries −
> use testDB
> db.createCollection("sample")
> data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
{"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
> db.sample.insert(data)
You can retrieve the inserted documents using the find() method as −
> use testDB
switched to db testDB
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
>
You can also retrieve first document in the collection using the findOne() method as −
> db.sample.findOne()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn’t use any query it returns the first document of the collection.
This method comes handy whenever you need to retrieve only one document of a result or, if you are sure that your query returns only one document.
Following python example retrieve first document of a collection −
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydatabase']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
#Retrieving the first record using the find_one() method
print("First record of the collection: ")
print(coll.find_one())
#Retrieving a record with is 103 using the find_one() method
print("Record whose id is 103: ")
print(coll.find_one({"_id": "103"}))
Data inserted ......
['101', '102', '103']
First record of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
Record whose id is 103:
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
To get multiple documents in a single query (single call od find method), you can use the find() method of the pymongo. If haven’t passed any query, this returns all the documents of a collection and, if you have passed a query to this method, it returns all the matched documents.
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Records of the collection: ")
for doc1 in coll.find():
print(doc1)
#Retrieving records with age greater than 26 using the find() method
print("Record whose age is more than 26: ")
for doc2 in coll.find({"age":{"$gt":"26"}}):
print(doc2)
Data inserted ......
Records of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Record whose age is more than 26:
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method.
Following is the list of operators used in the queries in MongoDB.
Following example retrieves the document in a collection whose name is sarmista.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sdsegf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc1 in coll.find({"name":"Sarmista"}):
print(doc1)
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
Following example retrieves the document in a collection whose age value is greater than 26.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['ghhj']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc in coll.find({"age":{"$gt":"26"}}):
print(doc)
Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
While retrieving the contents of a collection, you can sort and arrange them in ascending or descending orders using the sort() method.
To this method, you can pass the field(s) and the sorting order which is 1 or -1. Where, 1 is for ascending order and -1 is descending order.
Following is the syntax of the sort() method.
>db.COLLECTION_NAME.find().sort({KEY:1})
Assume we have created a collection and inserted 5 documents into it as shown below −
> use testDB
switched to db testDB
> db.createCollection("myColl")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Following line retrieves all the documents of the collection which are sorted in ascending order based on age.
> db.sample.find().sort({age:1})
{ "_id" : "1005", "name" : "Sarmista", "age" : 23, "city" : "Delhi" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
To sort the results of a query in ascending or, descending order pymongo provides the sort() method. To this method, pass a number value representing the number of documents you need in the result.
By default, this method sorts the documents in ascending order based on the specified field. If you need to sort in descending order pass -1 along with the field name −
coll.find().sort("age",-1)
Following example retrieves all the documents of a collection arranged according to the age values in ascending order −
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['b_mydb']
#Creating a collection
coll = db['myColl']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving first 3 documents using the find() and limit() methods
print("List of documents (sorted in ascending order based on age): ")
for doc1 in coll.find().sort("age"):
print(doc1)
Data inserted ......
List of documents (sorted in ascending order based on age):
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'}
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters −
Deletion criteria specifying the condition to delete documents.
Deletion criteria specifying the condition to delete documents.
Just one, if you pass true or 1 as second parameter, then only one document will be deleted.
Just one, if you pass true or 1 as second parameter, then only one document will be deleted.
Following is the syntax of the remove() method −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Assume we have created a collection and inserted 5 documents into it as shown below −
> use testDB
switched to db testDB
> db.createCollection("myColl")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Following query deletes the document(s) of the collection which have name value as Sarmista.
> db.sample.remove({"name": "Sarmista"})
WriteResult({ "nRemoved" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted.
> db.sample.remove({})
WriteResult({ "nRemoved" : 5 })
> db.sample.find()
To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods.
These methods accept a query object specifying the condition for deleting documents.
The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection.
Following python example deletes the document in the collection which has id value as 1006.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['lpaksgf']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting one document
coll.delete_one({"_id" : "1006"})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition.
Following example deletes all the documents in the collection whose age value is greater than 26 −
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['sampleDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": "25", "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": "23", "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": "26", "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting multiple documents
coll.delete_many({"age":{"$gt":"26"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}
If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection.
coll.delete_many({})
You can delete collections using drop() method of MongoDB.
Following is the syntax of drop() method −
db.COLLECTION_NAME.drop()
Following example drops collection with name sample −
> show collections
myColl
sample
> db.sample.drop()
true
> show collections
myColl
You can drop/delete a collection from the current by invoking drop() method.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['example2']
#Creating a collection
col1 = db['collection']
col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"})
col2 = db['coll']
col2.insert_one({"name": "Rahim", "age": "27", "city": "Bangalore"})
col3 = db['myColl']
col3.insert_one({"name": "Robert", "age": "28", "city": "Mumbai"})
col4 = db['data']
col4.insert_one({"name": "Romeo", "age": "25", "city": "Pune"})
#List of collections
print("List of collections:")
collections = db.list_collection_names()
for coll in collections:
print(coll)
#Dropping a collection
col1.drop()
col4.drop()
print("List of collections after dropping two of them: ")
#List of collections
collections = db.list_collection_names()
for coll in collections:
print(coll)
List of collections:
coll
data
collection
myColl
List of collections after dropping two of them:
coll
myColl
You can update the contents of an existing documents using the update() method or save() method.
The update method modifies the existing document whereas the save method replaces the existing document with the new one.
Following is the syntax of the update() and save() methods of MangoDB −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Or,
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Assume we have created a collection in a database and inserted 3 records in it as shown below −
> use testdatabase
switched to db testdatabase
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
{"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"},
{"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"},
{"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"}
]
> db.createCollection("sample")
{ "ok" : 1 }
> db.sample.insert(data)
Following method updates the city value of the document with id 1002.
>db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Similarly you can replace the document with new data by saving it with same id using the save() method.
> db.sample.save({ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Similar to find_one() method which retrieves single document, the update_one() method of pymongo updates a single document.
This method accepts a query specifying which document to update and the update operation.
Following python example updates the location value of a document in a collection.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Similarly, the update_many() method of pymongo updates all the documents that satisfies the specified condition.
Following example updates the location value in all the documents in a collection (empty condition) −
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_many({},{"$set":{"city":"Visakhapatnam"}})
#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")
for doc2 in coll.find():
print(doc2)
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}
While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result.
Following is the syntax of the limit() method −
>db.COLLECTION_NAME.find().limit(NUMBER)
Assume we have created a collection and inserted 5 documents into it as shown below −
> use testDB
switched to db testDB
> db.createCollection("sample")
{ "ok" : 1 }
> data = [
... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
... {"_id": "1002", "name": "Rahim", "age": 27, "city": "Bangalore"},
... {"_id": "1003", "name": "Robert", "age": 28, "city": "Mumbai"},
... {"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
... {"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
... {"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Following line retrieves the first 3 documents of the collection.
> db.sample.find().limit(3)
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result.
Following example retrieves first three documents in a collection.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['l']
#Creating a collection
coll = db['myColl']
#Inserting document into a collection
data = [
{"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
{"_id": "1002", "name": "Rahim", "age": "27", "city": "Bangalore"},
{"_id": "1003", "name": "Robert", "age": "28", "city": "Mumbai"},
{"_id": "1004", "name": "Romeo", "age": 25, "city": "Pune"},
{"_id": "1005", "name": "Sarmista", "age": 23, "city": "Delhi"},
{"_id": "1006", "name": "Rasajna", "age": 26, "city": "Chennai"}
]
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving first 3 documents using the find() and limit() methods
print("First 3 documents in the collection: ")
for doc1 in coll.find().limit(3):
print(doc1)
Data inserted ......
First 3 documents in the collection:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2089,
"s": 1934,
"text": "Pymongo is a python distribution which provides tools to work with MongoDB, it is the most preferred way to communicate with MongoDB database from python."
},
{
"code": null,
"e": 2233,
"s": 2089,
"text": "To install pymongo first of all make sure you have installed python3 (along with PIP) and MongoDB properly. Then execute the following command."
},
{
"code": null,
"e": 2524,
"s": 2233,
"text": "C:\\WINDOWS\\system32>pip install pymongo\nCollecting pymongo\nUsing cached https://files.pythonhosted.org/packages/cb/a6/b0ae3781b0ad75825e00e29dc5489b53512625e02328d73556e1ecdf12f8/pymongo-3.9.0-cp37-cp37m-win32.whl\nInstalling collected packages: pymongo\nSuccessfully installed pymongo-3.9.0\n"
},
{
"code": null,
"e": 2639,
"s": 2524,
"text": "Once you have installed pymongo, open a new text document, paste the following line in it and, save it as test.py."
},
{
"code": null,
"e": 2655,
"s": 2639,
"text": "import pymongo\n"
},
{
"code": null,
"e": 2769,
"s": 2655,
"text": "If you have installed pymongo properly, if you execute the test.py as shown below, you should not get any issues."
},
{
"code": null,
"e": 2815,
"s": 2769,
"text": "D:\\Python_MongoDB>test.py\nD:\\Python_MongoDB>\n"
},
{
"code": null,
"e": 2903,
"s": 2815,
"text": "Unlike other databases, MongoDB does not provide separate command to create a database."
},
{
"code": null,
"e": 3175,
"s": 2903,
"text": "In general, the use command is used to select/switch to the specific database. This command initially verifies whether the database we specify exists, if so, it connects to it. If the database, we specify with the use command doesn’t exist a new database will be created."
},
{
"code": null,
"e": 3246,
"s": 3175,
"text": "Therefore, you can create a database in MongoDB using the Use command."
},
{
"code": null,
"e": 3301,
"s": 3246,
"text": "Basic syntax of use DATABASE statement is as follows −"
},
{
"code": null,
"e": 3320,
"s": 3301,
"text": "use DATABASE_NAME\n"
},
{
"code": null,
"e": 3372,
"s": 3320,
"text": "Following command creates a database named in mydb."
},
{
"code": null,
"e": 3403,
"s": 3372,
"text": ">use mydb\nswitched to db mydb\n"
},
{
"code": null,
"e": 3493,
"s": 3403,
"text": "You can verify your creation by using the db command, this displays the current database."
},
{
"code": null,
"e": 3503,
"s": 3493,
"text": ">db\nmydb\n"
},
{
"code": null,
"e": 3668,
"s": 3503,
"text": "To connect to MongoDB using pymongo, you need to import and create a MongoClient, then you can directly access the database you need to create in attribute passion."
},
{
"code": null,
"e": 3717,
"s": 3668,
"text": "Following example creates a database in MangoDB."
},
{
"code": null,
"e": 4005,
"s": 3717,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")\n\n#Verification\nprint(\"List of databases after creating new one\")\nprint(client.list_database_names())"
},
{
"code": null,
"e": 4110,
"s": 4005,
"text": "Database created........\nList of databases after creating new one:\n['admin', 'config', 'local', 'mydb']\n"
},
{
"code": null,
"e": 4234,
"s": 4110,
"text": "You can also specify the port and host names while creating a MongoClient and can access the databases in dictionary style."
},
{
"code": null,
"e": 4421,
"s": 4234,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created........\")"
},
{
"code": null,
"e": 4447,
"s": 4421,
"text": "Database created........\n"
},
{
"code": null,
"e": 4549,
"s": 4447,
"text": "A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases."
},
{
"code": null,
"e": 4740,
"s": 4549,
"text": "You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter."
},
{
"code": null,
"e": 4783,
"s": 4740,
"text": "Using this you can specify the following −"
},
{
"code": null,
"e": 4811,
"s": 4783,
"text": "The size of the collection."
},
{
"code": null,
"e": 4839,
"s": 4811,
"text": "The size of the collection."
},
{
"code": null,
"e": 4901,
"s": 4839,
"text": "The max number of documents allowed in the capped collection."
},
{
"code": null,
"e": 4963,
"s": 4901,
"text": "The max number of documents allowed in the capped collection."
},
{
"code": null,
"e": 5049,
"s": 4963,
"text": "Whether the collection we create should be capped collection (fixed size collection)."
},
{
"code": null,
"e": 5135,
"s": 5049,
"text": "Whether the collection we create should be capped collection (fixed size collection)."
},
{
"code": null,
"e": 5192,
"s": 5135,
"text": "Whether the collection we create should be auto-indexed."
},
{
"code": null,
"e": 5249,
"s": 5192,
"text": "Whether the collection we create should be auto-indexed."
},
{
"code": null,
"e": 5308,
"s": 5249,
"text": "Following is the syntax to create a collection in MongoDB."
},
{
"code": null,
"e": 5347,
"s": 5308,
"text": "db.createCollection(\"CollectionName\")\n"
},
{
"code": null,
"e": 5410,
"s": 5347,
"text": "Following method creates a collection named ExampleCollection."
},
{
"code": null,
"e": 5499,
"s": 5410,
"text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"ExampleCollection\")\n{ \"ok\" : 1 }\n>"
},
{
"code": null,
"e": 5609,
"s": 5499,
"text": "Similarly, following is a query that creates a collection using the options of the createCollection() method."
},
{
"code": null,
"e": 5723,
"s": 5609,
"text": ">db.createCollection(\"mycol\", { capped : true, autoIndexId : true, size :\n6142800, max : 10000 } )\n{ \"ok\" : 1 }\n>"
},
{
"code": null,
"e": 5822,
"s": 5723,
"text": "Following python example connects to a database in MongoDB (mydb) and, creates a collection in it."
},
{
"code": null,
"e": 6062,
"s": 5822,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncollection = db['example']\nprint(\"Collection created........\")"
},
{
"code": null,
"e": 6090,
"s": 6062,
"text": "Collection created........\n"
},
{
"code": null,
"e": 6206,
"s": 6090,
"text": "You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter."
},
{
"code": null,
"e": 6252,
"s": 6206,
"text": "Following is the syntax of the insert method."
},
{
"code": null,
"e": 6295,
"s": 6252,
"text": ">db.COLLECTION_NAME.insert(DOCUMENT_NAME)\n"
},
{
"code": null,
"e": 6545,
"s": 6295,
"text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> doc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\n{ \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n> db.sample.insert(doc1)\nWriteResult({ \"nInserted\" : 1 })\n>"
},
{
"code": null,
"e": 6622,
"s": 6545,
"text": "Similarly, you can also insert multiple documents using the insert() method."
},
{
"code": null,
"e": 7370,
"s": 6622,
"text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}, \n {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }, \n {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n[\n {\"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\"},\n {\"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\"},\n {\"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 3,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})\n>"
},
{
"code": null,
"e": 7515,
"s": 7370,
"text": "Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format."
},
{
"code": null,
"e": 7585,
"s": 7515,
"text": "Following example inserts a document in the collection named example."
},
{
"code": null,
"e": 7924,
"s": 7585,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndoc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\ncoll.insert_one(doc1)\nprint(coll.find_one())"
},
{
"code": null,
"e": 8020,
"s": 7924,
"text": "{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n"
},
{
"code": null,
"e": 8122,
"s": 8020,
"text": "To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method."
},
{
"code": null,
"e": 8658,
"s": 8122,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\nprint(res.inserted_ids)"
},
{
"code": null,
"e": 8702,
"s": 8658,
"text": "Data inserted ......\n['101', '102', '103']\n"
},
{
"code": null,
"e": 8868,
"s": 8702,
"text": "You can read/retrieve stored documents from MongoDB using the find() method. This method retrieves and displays all the documents in MongoDB in a non-structured way."
},
{
"code": null,
"e": 8914,
"s": 8868,
"text": "Following is the syntax of the find() method."
},
{
"code": null,
"e": 8942,
"s": 8914,
"text": ">db.COLLECTION_NAME.find()\n"
},
{
"code": null,
"e": 9066,
"s": 8942,
"text": "Assume we have inserted 3 documents into a database named testDB in a collection named sample using the following queries −"
},
{
"code": null,
"e": 9361,
"s": 9066,
"text": "> use testDB\n> db.createCollection(\"sample\")\n> data = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" },\n {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n> db.sample.insert(data)"
},
{
"code": null,
"e": 9430,
"s": 9361,
"text": "You can retrieve the inserted documents using the find() method as −"
},
{
"code": null,
"e": 9697,
"s": 9430,
"text": "> use testDB\nswitched to db testDB\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n>"
},
{
"code": null,
"e": 9784,
"s": 9697,
"text": "You can also retrieve first document in the collection using the findOne() method as −"
},
{
"code": null,
"e": 9877,
"s": 9784,
"text": "> db.sample.findOne()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }"
},
{
"code": null,
"e": 10101,
"s": 9877,
"text": "The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn’t use any query it returns the first document of the collection."
},
{
"code": null,
"e": 10248,
"s": 10101,
"text": "This method comes handy whenever you need to retrieve only one document of a result or, if you are sure that your query returns only one document."
},
{
"code": null,
"e": 10315,
"s": 10248,
"text": "Following python example retrieve first document of a collection −"
},
{
"code": null,
"e": 11113,
"s": 10315,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydatabase']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\nprint(res.inserted_ids)\n\n#Retrieving the first record using the find_one() method\nprint(\"First record of the collection: \")\nprint(coll.find_one())\n\n#Retrieving a record with is 103 using the find_one() method\nprint(\"Record whose id is 103: \")\nprint(coll.find_one({\"_id\": \"103\"}))"
},
{
"code": null,
"e": 11341,
"s": 11113,
"text": "Data inserted ......\n['101', '102', '103']\nFirst record of the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\nRecord whose id is 103:\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 11623,
"s": 11341,
"text": "To get multiple documents in a single query (single call od find method), you can use the find() method of the pymongo. If haven’t passed any query, this returns all the documents of a collection and, if you have passed a query to this method, it returns all the matched documents."
},
{
"code": null,
"e": 12337,
"s": 11623,
"text": "#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Records of the collection: \")\nfor doc1 in coll.find():\n print(doc1)\n\n#Retrieving records with age greater than 26 using the find() method\nprint(\"Record whose age is more than 26: \")\nfor doc2 in coll.find({\"age\":{\"$gt\":\"26\"}}):\n print(doc2)"
},
{
"code": null,
"e": 12744,
"s": 12337,
"text": "Data inserted ......\nRecords of the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nRecord whose age is more than 26:\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 12941,
"s": 12744,
"text": "While retrieving using find() method, you can filter the documents using the query object. You can pass the query specifying the condition for the required documents as a parameter to this method."
},
{
"code": null,
"e": 13008,
"s": 12941,
"text": "Following is the list of operators used in the queries in MongoDB."
},
{
"code": null,
"e": 13089,
"s": 13008,
"text": "Following example retrieves the document in a collection whose name is sarmista."
},
{
"code": null,
"e": 13929,
"s": 13089,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['sdsegf']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving data\nprint(\"Documents in the collection: \")\nfor doc1 in coll.find({\"name\":\"Sarmista\"}):\n print(doc1)"
},
{
"code": null,
"e": 14046,
"s": 13929,
"text": "Data inserted ......\nDocuments in the collection:\n{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}\n"
},
{
"code": null,
"e": 14139,
"s": 14046,
"text": "Following example retrieves the document in a collection whose age value is greater than 26."
},
{
"code": null,
"e": 14976,
"s": 14139,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['ghhj']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving data\nprint(\"Documents in the collection: \")\nfor doc in coll.find({\"age\":{\"$gt\":\"26\"}}):\n print(doc)"
},
{
"code": null,
"e": 15159,
"s": 14976,
"text": "Data inserted ......\nDocuments in the collection:\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 15295,
"s": 15159,
"text": "While retrieving the contents of a collection, you can sort and arrange them in ascending or descending orders using the sort() method."
},
{
"code": null,
"e": 15437,
"s": 15295,
"text": "To this method, you can pass the field(s) and the sorting order which is 1 or -1. Where, 1 is for ascending order and -1 is descending order."
},
{
"code": null,
"e": 15483,
"s": 15437,
"text": "Following is the syntax of the sort() method."
},
{
"code": null,
"e": 15525,
"s": 15483,
"text": ">db.COLLECTION_NAME.find().sort({KEY:1})\n"
},
{
"code": null,
"e": 15611,
"s": 15525,
"text": "Assume we have created a collection and inserted 5 documents into it as shown below −"
},
{
"code": null,
"e": 16352,
"s": 15611,
"text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"myColl\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})"
},
{
"code": null,
"e": 16463,
"s": 16352,
"text": "Following line retrieves all the documents of the collection which are sorted in ascending order based on age."
},
{
"code": null,
"e": 16914,
"s": 16463,
"text": "> db.sample.find().sort({age:1})\n{ \"_id\" : \"1005\", \"name\" : \"Sarmista\", \"age\" : 23, \"city\" : \"Delhi\" }\n{ \"_id\" : \"1004\", \"name\" : \"Romeo\", \"age\" : 25, \"city\" : \"Pune\" }\n{ \"_id\" : \"1006\", \"name\" : \"Rasajna\", \"age\" : 26, \"city\" : \"Chennai\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }"
},
{
"code": null,
"e": 17112,
"s": 16914,
"text": "To sort the results of a query in ascending or, descending order pymongo provides the sort() method. To this method, pass a number value representing the number of documents you need in the result."
},
{
"code": null,
"e": 17281,
"s": 17112,
"text": "By default, this method sorts the documents in ascending order based on the specified field. If you need to sort in descending order pass -1 along with the field name −"
},
{
"code": null,
"e": 17309,
"s": 17281,
"text": "coll.find().sort(\"age\",-1)\n"
},
{
"code": null,
"e": 17429,
"s": 17309,
"text": "Following example retrieves all the documents of a collection arranged according to the age values in ascending order −"
},
{
"code": null,
"e": 18336,
"s": 17429,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['b_mydb']\n\n#Creating a collection\ncoll = db['myColl']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving first 3 documents using the find() and limit() methods\nprint(\"List of documents (sorted in ascending order based on age): \")\nfor doc1 in coll.find().sort(\"age\"):\n print(doc1)"
},
{
"code": null,
"e": 18804,
"s": 18336,
"text": "Data inserted ......\nList of documents (sorted in ascending order based on age):\n{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}\n{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}\n{'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'}\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 18929,
"s": 18804,
"text": "You can delete documents in a collection using the remove() method of MongoDB. This method accepts two optional parameters −"
},
{
"code": null,
"e": 18993,
"s": 18929,
"text": "Deletion criteria specifying the condition to delete documents."
},
{
"code": null,
"e": 19057,
"s": 18993,
"text": "Deletion criteria specifying the condition to delete documents."
},
{
"code": null,
"e": 19150,
"s": 19057,
"text": "Just one, if you pass true or 1 as second parameter, then only one document will be deleted."
},
{
"code": null,
"e": 19243,
"s": 19150,
"text": "Just one, if you pass true or 1 as second parameter, then only one document will be deleted."
},
{
"code": null,
"e": 19292,
"s": 19243,
"text": "Following is the syntax of the remove() method −"
},
{
"code": null,
"e": 19341,
"s": 19292,
"text": ">db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)\n"
},
{
"code": null,
"e": 19427,
"s": 19341,
"text": "Assume we have created a collection and inserted 5 documents into it as shown below −"
},
{
"code": null,
"e": 20168,
"s": 19427,
"text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"myColl\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})"
},
{
"code": null,
"e": 20261,
"s": 20168,
"text": "Following query deletes the document(s) of the collection which have name value as Sarmista."
},
{
"code": null,
"e": 20701,
"s": 20261,
"text": "> db.sample.remove({\"name\": \"Sarmista\"})\nWriteResult({ \"nRemoved\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n{ \"_id\" : \"1004\", \"name\" : \"Romeo\", \"age\" : 25, \"city\" : \"Pune\" }\n{ \"_id\" : \"1006\", \"name\" : \"Rasajna\", \"age\" : 26, \"city\" : \"Chennai\" }"
},
{
"code": null,
"e": 20819,
"s": 20701,
"text": "If you invoke remove() method without passing deletion criteria, all the documents in the collection will be deleted."
},
{
"code": null,
"e": 20893,
"s": 20819,
"text": "> db.sample.remove({})\nWriteResult({ \"nRemoved\" : 5 })\n> db.sample.find()"
},
{
"code": null,
"e": 21045,
"s": 20893,
"text": "To delete documents from a collection of MangoDB, you can delete documents from a collections using the methods delete_one() and delete_many() methods."
},
{
"code": null,
"e": 21130,
"s": 21045,
"text": "These methods accept a query object specifying the condition for deleting documents."
},
{
"code": null,
"e": 21284,
"s": 21130,
"text": "The detele_one() method deletes a single document, in case of a match. If no query is specified this method deletes the first document in the collection."
},
{
"code": null,
"e": 21376,
"s": 21284,
"text": "Following python example deletes the document in the collection which has id value as 1006."
},
{
"code": null,
"e": 22308,
"s": 21376,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['lpaksgf']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting one document\ncoll.delete_one({\"_id\" : \"1006\"})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 22703,
"s": 22308,
"text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}\n"
},
{
"code": null,
"e": 22816,
"s": 22703,
"text": "Similarly, the delete_many() method of pymongo deletes all the documents that satisfies the specified condition."
},
{
"code": null,
"e": 22915,
"s": 22816,
"text": "Following example deletes all the documents in the collection whose age value is greater than 26 −"
},
{
"code": null,
"e": 23865,
"s": 22915,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['sampleDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": \"23\", \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": \"26\", \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Deleting multiple documents\ncoll.delete_many({\"age\":{\"$gt\":\"26\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 24199,
"s": 23865,
"text": "Data inserted ......\nDocuments in the collection after update operation:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}\n{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}\n{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}\n"
},
{
"code": null,
"e": 24322,
"s": 24199,
"text": "If you invoke the delete_many() method without passing any query, this method deletes all the documents in the collection."
},
{
"code": null,
"e": 24344,
"s": 24322,
"text": "coll.delete_many({})\n"
},
{
"code": null,
"e": 24403,
"s": 24344,
"text": "You can delete collections using drop() method of MongoDB."
},
{
"code": null,
"e": 24446,
"s": 24403,
"text": "Following is the syntax of drop() method −"
},
{
"code": null,
"e": 24473,
"s": 24446,
"text": "db.COLLECTION_NAME.drop()\n"
},
{
"code": null,
"e": 24527,
"s": 24473,
"text": "Following example drops collection with name sample −"
},
{
"code": null,
"e": 24610,
"s": 24527,
"text": "> show collections\nmyColl\nsample\n> db.sample.drop()\ntrue\n> show collections\nmyColl"
},
{
"code": null,
"e": 24687,
"s": 24610,
"text": "You can drop/delete a collection from the current by invoking drop() method."
},
{
"code": null,
"e": 25557,
"s": 24687,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['example2']\n\n#Creating a collection\ncol1 = db['collection']\ncol1.insert_one({\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"})\ncol2 = db['coll']\ncol2.insert_one({\"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"})\ncol3 = db['myColl']\ncol3.insert_one({\"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"})\ncol4 = db['data']\ncol4.insert_one({\"name\": \"Romeo\", \"age\": \"25\", \"city\": \"Pune\"})\n\n#List of collections\nprint(\"List of collections:\")\ncollections = db.list_collection_names()\nfor coll in collections:\n print(coll)\n\n#Dropping a collection\ncol1.drop()\ncol4.drop()\nprint(\"List of collections after dropping two of them: \")\n\n#List of collections\ncollections = db.list_collection_names()\nfor coll in collections:\n print(coll)"
},
{
"code": null,
"e": 25667,
"s": 25557,
"text": "List of collections:\ncoll\ndata\ncollection\nmyColl\nList of collections after dropping two of them:\ncoll\nmyColl\n"
},
{
"code": null,
"e": 25764,
"s": 25667,
"text": "You can update the contents of an existing documents using the update() method or save() method."
},
{
"code": null,
"e": 25886,
"s": 25764,
"text": "The update method modifies the existing document whereas the save method replaces the existing document with the new one."
},
{
"code": null,
"e": 25958,
"s": 25886,
"text": "Following is the syntax of the update() and save() methods of MangoDB −"
},
{
"code": null,
"e": 26075,
"s": 25958,
"text": ">db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)\nOr,\ndb.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})\n"
},
{
"code": null,
"e": 26171,
"s": 26075,
"text": "Assume we have created a collection in a database and inserted 3 records in it as shown below −"
},
{
"code": null,
"e": 26745,
"s": 26171,
"text": "> use testdatabase\nswitched to db testdatabase\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" },\n ... {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n[\n {\"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\"},\n {\"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\"},\n {\"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\"}\n]\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> db.sample.insert(data)"
},
{
"code": null,
"e": 26815,
"s": 26745,
"text": "Following method updates the city value of the document with id 1002."
},
{
"code": null,
"e": 27183,
"s": 26815,
"text": ">db.sample.update({\"_id\":\"1002\"},{\"$set\":{\"city\":\"Visakhapatnam\"}})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Visakhapatnam\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }"
},
{
"code": null,
"e": 27287,
"s": 27183,
"text": "Similarly you can replace the document with new data by saving it with same id using the save() method."
},
{
"code": null,
"e": 27678,
"s": 27287,
"text": "> db.sample.save({ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Vijayawada\" })\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.sample.find()\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Vijayawada\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Visakhapatnam\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }"
},
{
"code": null,
"e": 27802,
"s": 27678,
"text": "Similar to find_one() method which retrieves single document, the update_one() method of pymongo updates a single document."
},
{
"code": null,
"e": 27892,
"s": 27802,
"text": "This method accepts a query specifying which document to update and the update operation."
},
{
"code": null,
"e": 27975,
"s": 27892,
"text": "Following python example updates the location value of a document in a collection."
},
{
"code": null,
"e": 28839,
"s": 27975,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection: \")\nfor doc1 in coll.find():\n print(doc1)\ncoll.update_one({\"_id\":\"102\"},{\"$set\":{\"city\":\"Visakhapatnam\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 29334,
"s": 28839,
"text": "Data inserted ......\nDocuments in the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nDocuments in the collection after update operation:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 29447,
"s": 29334,
"text": "Similarly, the update_many() method of pymongo updates all the documents that satisfies the specified condition."
},
{
"code": null,
"e": 29549,
"s": 29447,
"text": "Following example updates the location value in all the documents in a collection (empty condition) −"
},
{
"code": null,
"e": 30403,
"s": 29549,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['myDB']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection: \")\nfor doc1 in coll.find():\n print(doc1)\ncoll.update_many({},{\"$set\":{\"city\":\"Visakhapatnam\"}})\n\n#Retrieving all the records using the find() method\nprint(\"Documents in the collection after update operation: \")\nfor doc2 in coll.find():\n print(doc2)"
},
{
"code": null,
"e": 30909,
"s": 30403,
"text": "Data inserted ......\nDocuments in the collection:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\nDocuments in the collection after update operation:\n{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}\n{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}\n{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}\n"
},
{
"code": null,
"e": 31129,
"s": 30909,
"text": "While retrieving the contents of a collection you can limit the number of documents in the result using the limit() method. This method accepts a number value representing the number of documents you want in the result."
},
{
"code": null,
"e": 31177,
"s": 31129,
"text": "Following is the syntax of the limit() method −"
},
{
"code": null,
"e": 31219,
"s": 31177,
"text": ">db.COLLECTION_NAME.find().limit(NUMBER)\n"
},
{
"code": null,
"e": 31305,
"s": 31219,
"text": "Assume we have created a collection and inserted 5 documents into it as shown below −"
},
{
"code": null,
"e": 32046,
"s": 31305,
"text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = [\n ... {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n ... {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": 27, \"city\": \"Bangalore\"},\n ... {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": 28, \"city\": \"Mumbai\"},\n ... {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n ... {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n ... {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 6,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})"
},
{
"code": null,
"e": 32112,
"s": 32046,
"text": "Following line retrieves the first 3 documents of the collection."
},
{
"code": null,
"e": 32351,
"s": 32112,
"text": "> db.sample.find().limit(3)\n{ \"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n{ \"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }\n{ \"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }"
},
{
"code": null,
"e": 32555,
"s": 32351,
"text": "To restrict the results of a query to a particular number of documents pymongo provides the limit() method. To this method pass a number value representing the number of documents you need in the result."
},
{
"code": null,
"e": 32622,
"s": 32555,
"text": "Following example retrieves first three documents in a collection."
},
{
"code": null,
"e": 33498,
"s": 32622,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['l']\n\n#Creating a collection\ncoll = db['myColl']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"1002\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"1003\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"},\n {\"_id\": \"1004\", \"name\": \"Romeo\", \"age\": 25, \"city\": \"Pune\"},\n {\"_id\": \"1005\", \"name\": \"Sarmista\", \"age\": 23, \"city\": \"Delhi\"},\n {\"_id\": \"1006\", \"name\": \"Rasajna\", \"age\": 26, \"city\": \"Chennai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\n\n#Retrieving first 3 documents using the find() and limit() methods\nprint(\"First 3 documents in the collection: \")\nfor doc1 in coll.find().limit(3):\n print(doc1)"
},
{
"code": null,
"e": 33754,
"s": 33498,
"text": "Data inserted ......\nFirst 3 documents in the collection:\n{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}\n{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}\n"
},
{
"code": null,
"e": 33791,
"s": 33754,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 33807,
"s": 33791,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 33840,
"s": 33807,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 33859,
"s": 33840,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 33894,
"s": 33859,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 33916,
"s": 33894,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 33950,
"s": 33916,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 33978,
"s": 33950,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 34013,
"s": 33978,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 34027,
"s": 34013,
"text": " Lets Kode It"
},
{
"code": null,
"e": 34060,
"s": 34027,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 34077,
"s": 34060,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 34084,
"s": 34077,
"text": " Print"
},
{
"code": null,
"e": 34095,
"s": 34084,
"text": " Add Notes"
}
] |
Struts 2 - Redirect Action
|
The redirect result type calls the standard response.sendRedirect() method, causing the browser to create a new request to the given location.
We can provide the location either in the body of the <result...> element or as a <param name = "location"> element. Redirect also supports the parse parameter. Here's an example configured using XML −
<action name = "hello"
class = "com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name = "success" type = "redirect">
<param name = "location">
/NewWorld.jsp
</param >
</result>
</action>
So just modify your WebContent/WEB-INF/classes/struts.xml file to define redirect type as mentioned above −
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "hello"
class = "com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name = "success" type = "redirect">
<param name = "location">
/NewWorld.jsp
</param >
</result>
</action>
<action name = "index">
<result >/index.jsp</result>
</action>
</package>
</struts>
Here NewWorld.jsp is a new page where you will be redirected whenever your action retruns "success". Let us keep WebContent/WEB-INF/lib/web.xml without any change, so its content will be as follows −
<?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"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Create action class file Java Resources/src/HelloWorldAction.java as follows −
package com.tutorialspoint.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport{
private String name;
public String execute() throws Exception {
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Let create main page WebContent/WEB-INF/index.jsp with the following content −
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World From Struts2</h1>
<form action = "hello">
<label for = "name">Please enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Say Hello"/>
</form>
</body>
</html>
Let us create WebContent/WEB-INF/NewWorld.jsp where request will be redirected in case action returns "success" −
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Redirected Page</title>
</head>
<body>
<h1>New Page after redirection</h1>
</body>
</html>
Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.action. This will give you following screen −
Enter any value in the text box and submit the page. You should see the next page after redirection −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2389,
"s": 2246,
"text": "The redirect result type calls the standard response.sendRedirect() method, causing the browser to create a new request to the given location."
},
{
"code": null,
"e": 2591,
"s": 2389,
"text": "We can provide the location either in the body of the <result...> element or as a <param name = \"location\"> element. Redirect also supports the parse parameter. Here's an example configured using XML −"
},
{
"code": null,
"e": 2837,
"s": 2591,
"text": "<action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\"\n method = \"execute\">\n <result name = \"success\" type = \"redirect\">\n <param name = \"location\">\n /NewWorld.jsp\n </param >\n </result>\n</action>"
},
{
"code": null,
"e": 2945,
"s": 2837,
"text": "So just modify your WebContent/WEB-INF/classes/struts.xml file to define redirect type as mentioned above −"
},
{
"code": null,
"e": 3667,
"s": 2945,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\"\n method = \"execute\">\n <result name = \"success\" type = \"redirect\">\n <param name = \"location\">\n /NewWorld.jsp\n </param >\n </result>\n </action>\n\n <action name = \"index\"> \n <result >/index.jsp</result>\n </action>\n\n </package>\n</struts>"
},
{
"code": null,
"e": 3867,
"s": 3667,
"text": "Here NewWorld.jsp is a new page where you will be redirected whenever your action retruns \"success\". Let us keep WebContent/WEB-INF/lib/web.xml without any change, so its content will be as follows −"
},
{
"code": null,
"e": 4676,
"s": 3867,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n\n <display-name>Struts 2</display-name>\n\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n \n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n\n</web-app>"
},
{
"code": null,
"e": 4755,
"s": 4676,
"text": "Create action class file Java Resources/src/HelloWorldAction.java as follows −"
},
{
"code": null,
"e": 5119,
"s": 4755,
"text": "package com.tutorialspoint.struts2;\n\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class HelloWorldAction extends ActionSupport{\n private String name;\n\n public String execute() throws Exception {\n return \"success\";\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 5198,
"s": 5119,
"text": "Let create main page WebContent/WEB-INF/index.jsp with the following content −"
},
{
"code": null,
"e": 5803,
"s": 5198,
"text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n <body>\n <h1>Hello World From Struts2</h1>\n <form action = \"hello\">\n <label for = \"name\">Please enter your name</label><br/>\n <input type = \"text\" name = \"name\"/>\n <input type = \"submit\" value = \"Say Hello\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 5917,
"s": 5803,
"text": "Let us create WebContent/WEB-INF/NewWorld.jsp where request will be redirected in case action returns \"success\" −"
},
{
"code": null,
"e": 6319,
"s": 5917,
"text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Redirected Page</title>\n </head>\n <body>\n <h1>New Page after redirection</h1>\n </body>\n</html>"
},
{
"code": null,
"e": 6604,
"s": 6319,
"text": "Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.action. This will give you following screen −"
},
{
"code": null,
"e": 6706,
"s": 6604,
"text": "Enter any value in the text box and submit the page. You should see the next page after redirection −"
},
{
"code": null,
"e": 6713,
"s": 6706,
"text": " Print"
},
{
"code": null,
"e": 6724,
"s": 6713,
"text": " Add Notes"
}
] |
HTML | onerror Event Attribute - GeeksforGeeks
|
30 Jul, 2021
This attribute works when an error occurs while loading an external file. The external file may contain document file or image file.Supported Tags
<input type=”image”>
, <object>
, <link>
, <script>
Syntax:
<element onerror = "script">
Attribute Value: This attribute contains single value script which works when onerror event attribute call. This attribute is supported by <img>, <input type=”image”>, <object>, <link>, and <script> tags.Example:
html
<!DOCTYPE html><html> <head> <title>onerror event attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <img src="image.gif" onerror="myFunction()"> <h1>GeeksforGeeks</h1> <h2>onerror event attribute</h2> <script> function myFunction() { alert("The image could not be loaded."); } </script> </body></html>
Output:
Supported Browsers: The browser supported by onerror attribute are listed below:
Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 23671,
"s": 23643,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 23818,
"s": 23671,
"text": "This attribute works when an error occurs while loading an external file. The external file may contain document file or image file.Supported Tags"
},
{
"code": null,
"e": 23839,
"s": 23818,
"text": "<input type=”image”>"
},
{
"code": null,
"e": 23850,
"s": 23839,
"text": ", <object>"
},
{
"code": null,
"e": 23859,
"s": 23850,
"text": ", <link>"
},
{
"code": null,
"e": 23870,
"s": 23859,
"text": ", <script>"
},
{
"code": null,
"e": 23880,
"s": 23870,
"text": "Syntax: "
},
{
"code": null,
"e": 23909,
"s": 23880,
"text": "<element onerror = \"script\">"
},
{
"code": null,
"e": 24124,
"s": 23909,
"text": "Attribute Value: This attribute contains single value script which works when onerror event attribute call. This attribute is supported by <img>, <input type=”image”>, <object>, <link>, and <script> tags.Example: "
},
{
"code": null,
"e": 24129,
"s": 24124,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>onerror event attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <img src=\"image.gif\" onerror=\"myFunction()\"> <h1>GeeksforGeeks</h1> <h2>onerror event attribute</h2> <script> function myFunction() { alert(\"The image could not be loaded.\"); } </script> </body></html> ",
"e": 24665,
"s": 24129,
"text": null
},
{
"code": null,
"e": 24675,
"s": 24665,
"text": "Output: "
},
{
"code": null,
"e": 24758,
"s": 24675,
"text": "Supported Browsers: The browser supported by onerror attribute are listed below: "
},
{
"code": null,
"e": 24765,
"s": 24758,
"text": "Chrome"
},
{
"code": null,
"e": 24783,
"s": 24765,
"text": "Internet Explorer"
},
{
"code": null,
"e": 24791,
"s": 24783,
"text": "Firefox"
},
{
"code": null,
"e": 24798,
"s": 24791,
"text": "Safari"
},
{
"code": null,
"e": 24804,
"s": 24798,
"text": "Opera"
},
{
"code": null,
"e": 24943,
"s": 24806,
"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": 24963,
"s": 24943,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 24979,
"s": 24963,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 24983,
"s": 24979,
"text": "CSS"
},
{
"code": null,
"e": 24988,
"s": 24983,
"text": "HTML"
},
{
"code": null,
"e": 25005,
"s": 24988,
"text": "Web Technologies"
},
{
"code": null,
"e": 25010,
"s": 25005,
"text": "HTML"
},
{
"code": null,
"e": 25108,
"s": 25010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25170,
"s": 25108,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25220,
"s": 25170,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25278,
"s": 25220,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 25326,
"s": 25278,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25376,
"s": 25326,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 25438,
"s": 25376,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25488,
"s": 25438,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25548,
"s": 25488,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 25596,
"s": 25548,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Create an Azure Machine Learning Web Service with Python and Azure DSVM | by Philip Roimon Domingo | Towards Data Science
|
Last week, while I was reading the documentation about Microsoft CNTK, and checking out the code samples from their GitHub repository, I bumped into another GitHub repository which is about Azure Machine Learning Operationalization.
Azure Machine Learning Operationalization is a component of the Azure CLI that enables operationalization of models that you create through Vienna that use the CNTK, SPARK, and Python machine learning platforms.
I’ve been playing around with Python and Machine Learning recently, so I thought I’d give this one a try and create an AzureML Web Service using a machine learning model built with Python.
Important note: Azure Machine Learning Operationalization is still in preview as of this time of writing. There could be some breaking changes that might happen in the future.
To get started with Azure Machine Learning Operationalization, you need the following:
Azure Account (if you don’t have one, you can get a free trial here)Azure Data Science Virtual Machine (DSVM) - though this one is not exactly required but I would say that this is the fastest and easiest way to get started. You can check the documentation here to create one.
Azure Account (if you don’t have one, you can get a free trial here)
Azure Data Science Virtual Machine (DSVM) - though this one is not exactly required but I would say that this is the fastest and easiest way to get started. You can check the documentation here to create one.
Once you have your Azure DSVM created, first thing we’re going to do is to update our azure-cli, azure-cli-ml and azure-ml-api-sdk packages by uninstalling and installing them.
$ pip uninstall azure-cli azure-cli-ml azure-ml-api-sdk$ pip install azure-cli azure-cli-ml azure-ml-api-sdk
Previously, I tried updating the packages with the --upgrade option in pip install but I keep on having an error upgrading the packages. So uninstalling and installing it will do the fix because later on, we will be using these packages for generating a schema and deploying our trained model to our web service.
Next is we’re going to create a model that will predict whether the person is a male or female based on the given body metrics (height, width and shoe size) using scikit-learn machine learning library. Create a file named train.py and you can copy the code below:
Run the code and it should create a model.pkl in your project folder.
To deploy our model as a web service, we need to create a score.py that will be used to generate a schema JSON file.
Run the score.py and you should see that the service_schema.json is created. Now our project folder should contain the following files:
PROJECT_FOLDER- train.py- score.py- model.pkl- service_schema.json
Now that we have everything setup, we will now create our web service and deploy the model by doing the following:
In order for us to be able to create our environment and model management account using azure cli we will first need to authenticate with this command:
$ az login
This will then show a message that you need to open up your web browser and go to https://aka.ms/devicelogin and enter the code provided in your terminal.
Once you’re able to authenticate your account using azure cli type the following command to create our environment:
$ az ml env setup -c -n YOUR_CLUSTER_NAME -l YOUR_LOCATION
This is what I’ve used for this tutorial:
$ az ml env setup -c -n azmldemo -l australiaeast
It’s also important to keep in mind that the supported location for now is westcentralus, eastus2, and australiaeast.
It will take at least 10–20 minutes for our environment to be completely provisioned, so while waiting, we can now then create our model management account which is a one time setup thing.
$ az ml account modelmanagement create -l YOUR_LOCATION -n YOUR_MODEL_MANAGEMENT_ACCOUNT_NAME -g YOUR_RESOURCE_GROUP
This is what I’ve used for this tutorial:
$ az ml account modelmanagement create -l australiaeast -n azmldemoacc -g azmldemorg
Just in case you’re wondering, the azmldemorg resource group was automatically created when we created our environment earlier, it basically added an rg to the name of our cluster which is azmldemo.
Once the Model Management Account and your environment is successfully created, we will now set the Model Management Account and the environment with the following command:
$ az ml account modelmanagement set -n YOUR_MODEL_MANAGEMENT_ACCOUNT_NAME -g YOUR_RESOURCE_GROUP$ az ml env set -n YOUR_CLUSTER_NAME -g YOUR_RESOURCE_GROUP
This is what I’ve used for this tutorial:
$ az ml account modelmanagement set -n azmldemoacc -g azmldemorg$ az ml env set -n azmldemo -g azmldemorg
It’s also important to keep in mind that your environment Provisioning State should show Succeeded for you to be able to set it successfully. You can check the Provisioning State with the following command:
$ az ml env show -g YOUR_RESOURCE_GROUP -n YOUR_CLUSTER_NAME
Once you’re able to successfully set your Model Management Account and environment, we will now create the web service by:
Go to the project folder in where we’ve created the Gender Classifier Model and JSON schemaType the following command to create the web service:
Go to the project folder in where we’ve created the Gender Classifier Model and JSON schema
Type the following command to create the web service:
$ az ml service create realtime -f score.py --m model.pkl -s service_schema.json -n genderclassifier -r pythonor you can also use --help or -h to know the other arguments available$ az ml service create realtime -h
Once the web service is successfully created, you can use the following command to get all the important details that you can use to test the web service (like the sample CLI command, Swagger URL, Authorization Bearer Key, and etc):
$ az ml service usage realtime -i YOUR_SERVICE_ID
You can get your Service Id with the following command:
$ az ml service list realtime
$ az ml service run realtime -i YOUR_SERVICE_ID -d "{\"input_df\": [{\"width\": 60, \"shoe_size\": 38, \"height\": 190}]}"
It should look like this when your run in your terminal:
Here’s an example on how you can test the web service via Scoring URL
And we’re done, so what do you think about the Azure Machine Learning Operationalization? Again, you can check out their GitHub Repository here for other samples.
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "Last week, while I was reading the documentation about Microsoft CNTK, and checking out the code samples from their GitHub repository, I bumped into another GitHub repository which is about Azure Machine Learning Operationalization."
},
{
"code": null,
"e": 617,
"s": 405,
"text": "Azure Machine Learning Operationalization is a component of the Azure CLI that enables operationalization of models that you create through Vienna that use the CNTK, SPARK, and Python machine learning platforms."
},
{
"code": null,
"e": 806,
"s": 617,
"text": "I’ve been playing around with Python and Machine Learning recently, so I thought I’d give this one a try and create an AzureML Web Service using a machine learning model built with Python."
},
{
"code": null,
"e": 982,
"s": 806,
"text": "Important note: Azure Machine Learning Operationalization is still in preview as of this time of writing. There could be some breaking changes that might happen in the future."
},
{
"code": null,
"e": 1069,
"s": 982,
"text": "To get started with Azure Machine Learning Operationalization, you need the following:"
},
{
"code": null,
"e": 1346,
"s": 1069,
"text": "Azure Account (if you don’t have one, you can get a free trial here)Azure Data Science Virtual Machine (DSVM) - though this one is not exactly required but I would say that this is the fastest and easiest way to get started. You can check the documentation here to create one."
},
{
"code": null,
"e": 1415,
"s": 1346,
"text": "Azure Account (if you don’t have one, you can get a free trial here)"
},
{
"code": null,
"e": 1624,
"s": 1415,
"text": "Azure Data Science Virtual Machine (DSVM) - though this one is not exactly required but I would say that this is the fastest and easiest way to get started. You can check the documentation here to create one."
},
{
"code": null,
"e": 1801,
"s": 1624,
"text": "Once you have your Azure DSVM created, first thing we’re going to do is to update our azure-cli, azure-cli-ml and azure-ml-api-sdk packages by uninstalling and installing them."
},
{
"code": null,
"e": 1910,
"s": 1801,
"text": "$ pip uninstall azure-cli azure-cli-ml azure-ml-api-sdk$ pip install azure-cli azure-cli-ml azure-ml-api-sdk"
},
{
"code": null,
"e": 2223,
"s": 1910,
"text": "Previously, I tried updating the packages with the --upgrade option in pip install but I keep on having an error upgrading the packages. So uninstalling and installing it will do the fix because later on, we will be using these packages for generating a schema and deploying our trained model to our web service."
},
{
"code": null,
"e": 2487,
"s": 2223,
"text": "Next is we’re going to create a model that will predict whether the person is a male or female based on the given body metrics (height, width and shoe size) using scikit-learn machine learning library. Create a file named train.py and you can copy the code below:"
},
{
"code": null,
"e": 2557,
"s": 2487,
"text": "Run the code and it should create a model.pkl in your project folder."
},
{
"code": null,
"e": 2674,
"s": 2557,
"text": "To deploy our model as a web service, we need to create a score.py that will be used to generate a schema JSON file."
},
{
"code": null,
"e": 2810,
"s": 2674,
"text": "Run the score.py and you should see that the service_schema.json is created. Now our project folder should contain the following files:"
},
{
"code": null,
"e": 2877,
"s": 2810,
"text": "PROJECT_FOLDER- train.py- score.py- model.pkl- service_schema.json"
},
{
"code": null,
"e": 2992,
"s": 2877,
"text": "Now that we have everything setup, we will now create our web service and deploy the model by doing the following:"
},
{
"code": null,
"e": 3144,
"s": 2992,
"text": "In order for us to be able to create our environment and model management account using azure cli we will first need to authenticate with this command:"
},
{
"code": null,
"e": 3155,
"s": 3144,
"text": "$ az login"
},
{
"code": null,
"e": 3310,
"s": 3155,
"text": "This will then show a message that you need to open up your web browser and go to https://aka.ms/devicelogin and enter the code provided in your terminal."
},
{
"code": null,
"e": 3426,
"s": 3310,
"text": "Once you’re able to authenticate your account using azure cli type the following command to create our environment:"
},
{
"code": null,
"e": 3486,
"s": 3426,
"text": "$ az ml env setup -c -n YOUR_CLUSTER_NAME -l YOUR_LOCATION"
},
{
"code": null,
"e": 3528,
"s": 3486,
"text": "This is what I’ve used for this tutorial:"
},
{
"code": null,
"e": 3578,
"s": 3528,
"text": "$ az ml env setup -c -n azmldemo -l australiaeast"
},
{
"code": null,
"e": 3696,
"s": 3578,
"text": "It’s also important to keep in mind that the supported location for now is westcentralus, eastus2, and australiaeast."
},
{
"code": null,
"e": 3885,
"s": 3696,
"text": "It will take at least 10–20 minutes for our environment to be completely provisioned, so while waiting, we can now then create our model management account which is a one time setup thing."
},
{
"code": null,
"e": 4002,
"s": 3885,
"text": "$ az ml account modelmanagement create -l YOUR_LOCATION -n YOUR_MODEL_MANAGEMENT_ACCOUNT_NAME -g YOUR_RESOURCE_GROUP"
},
{
"code": null,
"e": 4044,
"s": 4002,
"text": "This is what I’ve used for this tutorial:"
},
{
"code": null,
"e": 4129,
"s": 4044,
"text": "$ az ml account modelmanagement create -l australiaeast -n azmldemoacc -g azmldemorg"
},
{
"code": null,
"e": 4328,
"s": 4129,
"text": "Just in case you’re wondering, the azmldemorg resource group was automatically created when we created our environment earlier, it basically added an rg to the name of our cluster which is azmldemo."
},
{
"code": null,
"e": 4501,
"s": 4328,
"text": "Once the Model Management Account and your environment is successfully created, we will now set the Model Management Account and the environment with the following command:"
},
{
"code": null,
"e": 4657,
"s": 4501,
"text": "$ az ml account modelmanagement set -n YOUR_MODEL_MANAGEMENT_ACCOUNT_NAME -g YOUR_RESOURCE_GROUP$ az ml env set -n YOUR_CLUSTER_NAME -g YOUR_RESOURCE_GROUP"
},
{
"code": null,
"e": 4699,
"s": 4657,
"text": "This is what I’ve used for this tutorial:"
},
{
"code": null,
"e": 4805,
"s": 4699,
"text": "$ az ml account modelmanagement set -n azmldemoacc -g azmldemorg$ az ml env set -n azmldemo -g azmldemorg"
},
{
"code": null,
"e": 5012,
"s": 4805,
"text": "It’s also important to keep in mind that your environment Provisioning State should show Succeeded for you to be able to set it successfully. You can check the Provisioning State with the following command:"
},
{
"code": null,
"e": 5073,
"s": 5012,
"text": "$ az ml env show -g YOUR_RESOURCE_GROUP -n YOUR_CLUSTER_NAME"
},
{
"code": null,
"e": 5196,
"s": 5073,
"text": "Once you’re able to successfully set your Model Management Account and environment, we will now create the web service by:"
},
{
"code": null,
"e": 5341,
"s": 5196,
"text": "Go to the project folder in where we’ve created the Gender Classifier Model and JSON schemaType the following command to create the web service:"
},
{
"code": null,
"e": 5433,
"s": 5341,
"text": "Go to the project folder in where we’ve created the Gender Classifier Model and JSON schema"
},
{
"code": null,
"e": 5487,
"s": 5433,
"text": "Type the following command to create the web service:"
},
{
"code": null,
"e": 5702,
"s": 5487,
"text": "$ az ml service create realtime -f score.py --m model.pkl -s service_schema.json -n genderclassifier -r pythonor you can also use --help or -h to know the other arguments available$ az ml service create realtime -h"
},
{
"code": null,
"e": 5935,
"s": 5702,
"text": "Once the web service is successfully created, you can use the following command to get all the important details that you can use to test the web service (like the sample CLI command, Swagger URL, Authorization Bearer Key, and etc):"
},
{
"code": null,
"e": 5985,
"s": 5935,
"text": "$ az ml service usage realtime -i YOUR_SERVICE_ID"
},
{
"code": null,
"e": 6041,
"s": 5985,
"text": "You can get your Service Id with the following command:"
},
{
"code": null,
"e": 6071,
"s": 6041,
"text": "$ az ml service list realtime"
},
{
"code": null,
"e": 6194,
"s": 6071,
"text": "$ az ml service run realtime -i YOUR_SERVICE_ID -d \"{\\\"input_df\\\": [{\\\"width\\\": 60, \\\"shoe_size\\\": 38, \\\"height\\\": 190}]}\""
},
{
"code": null,
"e": 6251,
"s": 6194,
"text": "It should look like this when your run in your terminal:"
},
{
"code": null,
"e": 6321,
"s": 6251,
"text": "Here’s an example on how you can test the web service via Scoring URL"
}
] |
Keras and R: Predicting Blood Glucose Levels with the Sequential Model | by Michael Grogan | Towards Data Science
|
With the advent of TensorFlow 2.0, Keras is now the default API for this version. Keras is used to build neural networks for deep learning purposes. As such, Keras is a highly useful tool for conducting analysis of large datasets.
However, did you realise that the Keras API can also be run in R?
In this example, Keras is used to generate a neural network — with the aim of solving a regression problem in R.
Specifically, the Pima Indians Diabetes dataset is used in order to predict blood glucose levels for patients using the relevant features.
In this regard, this article provides an overview of:
Feature selection methods in R
How to define a Sequential model in Keras
Methods to validate and test model predictions
The Pima Indians Diabetes dataset is partitioned into three separate datasets for this example.
Training and validation: pima-indians-diabetes1.csv. 80% of the original dataset is split from the full dataset. In turn, 70% of this dataset is used for training the model, and the remaining 30% is used for validating the predictions.
Test: pima-indians-diabetes2.csv and pima-indians-diabetes3.csv. The remaining 20% of the original dataset is used as unseen data, to determine whether the predictions being yielded by the model would perform well when dealing with completely new data. pima-indians-diabetes2 contains the features (or independent variables), while pima-indians-diabetes3 contains the dependent variable (blood glucose levels).
The purpose of feature selection is to determine those features that have the most influence on the dependent variable.
In our example, there are eight features — some will be more important than others in determining blood glucose levels.
The two feature selection methods used here are:
Correlation plots
Multiple Linear Regression
Correlation plots allow us to visually determine:
Features that are highly correlated with the dependent variableFeatures that are highly correlated with each other
Features that are highly correlated with the dependent variable
Features that are highly correlated with each other
If certain features are highly correlated with blood glucose levels, then this is an indication that these features are important in predicting the same. Features with low correlation are indicated to be insignificant.
However, features that are highly correlated with each other would indicate that some of these features are redundant (since they are in effect attempting to explain the same thing).
Here is the first correlation plot:
M <- cor(diabetes1)corrplot(M, method = "circle")
We can see that the Insulin and Outcome variables are particularly correlated with the Glucose variable, while there is also correlation between Age and Pregnancies and Insulin and Skin Thickness.
However, we can go into more detail and obtain specific correlation coefficients for each feature:
corrplot(M, method = "number")
The purpose of a multiple linear regression is to:
Determine the size and nature of the coefficient for each feature in explaining the dependent variable.Determine the signficance or insignificance of each feature.
Determine the size and nature of the coefficient for each feature in explaining the dependent variable.
Determine the signficance or insignificance of each feature.
Here are the results for the linear regression:
Call:lm(formula = Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data = diabetes1)Residuals: Min 1Q Median 3Q Max -68.709 -18.148 -2.212 15.176 80.950 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 78.401064 6.363612 12.320 < 2e-16 ***Pregnancies -0.481865 0.363730 -1.325 0.18575 Outcome 25.590805 2.384153 10.734 < 2e-16 ***Age 0.527262 0.106097 4.970 8.8e-07 ***DiabetesPedigreeFunction 0.052534 3.198192 0.016 0.98690 BMI 0.318452 0.167106 1.906 0.05718 . Insulin 0.082208 0.009843 8.352 4.8e-16 ***SkinThickness -0.202236 0.077372 -2.614 0.00918 ** BloodPressure 0.083865 0.058081 1.444 0.14929 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 24.94 on 590 degrees of freedomMultiple R-squared: 0.362, Adjusted R-squared: 0.3533 F-statistic: 41.84 on 8 and 590 DF, p-value: < 2.2e-16
At the 5% level, Outcome, Age, Insulin and Skin Thickness are deemed significant. Other features are deemed insignificant at the 5% level.
It is not deemed necessary to run a formal test for multicollinearity in this instance, as the correlation plots indicate features that are highly correlated with each other.
However, heteroscedasticity (uneven variance across standard errors) could be present, e.g. due to differing age across patients. In order to test this, the Breusch-Pagan test is run — with a p-value below 0.05 indicating the presence of heteroscedasticity.
> bptest(fit) studentized Breusch-Pagan testdata: fitBP = 36.585, df = 8, p-value = 1.372e-05
As heteroscedasticity is indicated to be present, a robust regression is run — specifically using Huber weights. The purpose of this is to place less value on the outliers present in the dataset.
> # Huber Weights (Robust Regression)> summary(rr.huber <- rlm(Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data=diabetes1))Call: rlm(formula = Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data = diabetes1)Residuals: Min 1Q Median 3Q Max -68.627 -16.842 -1.543 15.576 83.793 Coefficients: Value Std. Error t value(Intercept) 78.3319 6.2990 12.4357Pregnancies -0.4675 0.3600 -1.2984Outcome 25.0513 2.3599 10.6152Age 0.5448 0.1050 5.1881DiabetesPedigreeFunction -0.5482 3.1657 -0.1732BMI 0.3297 0.1654 1.9935Insulin 0.0925 0.0097 9.4912SkinThickness -0.2530 0.0766 -3.3032BloodPressure 0.0673 0.0575 1.1706Residual standard error: 24.53 on 590 degrees of freedom
On 590 degrees of freedom, the two-tailed t critical value is as follows:
> abs(qt(0.05/2, 590))[1] 1.963993
When the t statistic > t critical value, the null hypothesis is rejected. In this regard, Outcome, Age, BMI, Insulin, and Skin Thickness have an absolute t-value greater than the critical value.
Taking the findings of both the correlation plots and multiple linear regression into account, Outcome, Age, Insulin and Skin Thickness are selected as the relevant features for the analysis.
Now that the relevant features have been selected, the neural network can be constructed. Before doing so:
Max-Min Normalization is used to scale each variable between 0 and 1. This is to ensure a common scale among the variables so that the neural network can interpret them properly.
Max-Min Normalization is used to scale each variable between 0 and 1. This is to ensure a common scale among the variables so that the neural network can interpret them properly.
normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x)))}maxmindf <- as.data.frame(lapply(df, normalize))attach(maxmindf)maxmindf<-as.matrix(maxmindf)
The train-validation set is split 70/30.
The train-validation set is split 70/30.
ind <- sample(2, nrow(maxmindf), replace=TRUE, prob = c(0.7,0.3))X_train <- maxmindf[ind==1, 1:4]X_val <- maxmindf[ind==2, 1:4]y_train <- maxmindf[ind==1, 5]y_val <- maxmindf[ind==2, 5]
Now, the Sequential model is defined. The four input features (Outcome, Age, Insulin, Skin Thickness) are included in the input layer with 9 neurons defined in the layer. One hidden layer with 60 neurons is defined, and a linear output layer with 1 neuron is defined.
As explained in this article by Farhad Malik, the number of neurons in each layer is configured as follows:
Input layer: The number of neurons in the input layer is calculated as follows:
Number of features in the training set + 1
In this case, as there were 8 features in the training set to begin with, 9 input neurons are defined accordingly.
Hidden layer: One hidden layer is defined, as a single layer is suitable when working with most datasets. The number of neurons in the hidden layer is determined as follows:
Training Data Samples/Factor * (Input Neurons + Output Neurons)
A factor of 1 is set in this case, the purpose of the factor being to prevent overfitting. A factor can take a value between 1 and 10. With 9 neurons in the input layer, 1 neuron in the output layer and 599 observations in the training set, the hidden layer is assigned 60 neurons.
Output layer: As this is the result layer, the output layer takes a value of 1 by default.
model <- keras_model_sequential() model %>% layer_dense(units = 9, activation = 'relu', kernel_initializer='RandomNormal', input_shape = c(4)) %>% layer_dense(units = 60, activation = 'relu') %>% layer_dense(units = 1, activation = 'linear')summary(model)
Here is the output:
Model: "sequential"________________________________________________________________________________Layer (type) Output Shape Param # ================================================================================dense (Dense) (None, 9) 45 ________________________________________________________________________________dense_1 (Dense) (None, 60) 600 ________________________________________________________________________________dense_2 (Dense) (None, 1) 61 ================================================================================Total params: 706Trainable params: 706Non-trainable params: 0________________________________________________________________________________
The model is now trained over 30 epochs, and evaluated based on its loss and mean absolute error. Given that the dependent variable is interval, the mean squared error is used to determine the deviation between the predictions and actual values.
model %>% compile( loss = 'mean_squared_error', optimizer = 'adam', metrics = c('mae'))history <- model %>% fit( X_train, y_train, epochs = 30, batch_size = 50, validation_split = 0.2)
The predicted and actual values are scaled back to their original formats:
model %>% evaluate(X_val, y_val)modelpred <- data.frame(y = predict(model, as.matrix(X_val)))predicted=pred$y * abs(diff(range(df$Glucose))) + min(df$Glucose)actual=y_val * abs(diff(range(df$Glucose))) + min(df$Glucose)df<-data.frame(predicted,actual)attach(df)
Here is the output:
$loss 0.0266957393988254$mae 0.132186755537987ModelModel: "sequential"________________________________________________________________________________Layer (type) Output Shape Param # ================================================================================dense (Dense) (None, 9) 45 ________________________________________________________________________________dense_1 (Dense) (None, 60) 600 ________________________________________________________________________________dense_2 (Dense) (None, 1) 61 ================================================================================Total params: 706Trainable params: 706Non-trainable params: 0________________________________________________________________________________
Here is a plot of the loss and mean absolute error:
The model yields a loss of just above 2% and a mean absolute error of just above 13%.
The MLmetrics library can also be used to calculate the MAPE (mean absolute percentage error).
install.packages("MLmetrics")library(MLmetrics)MAPE(predicted, actual)
The MAPE for the validation set comes in at 18%. Increasing the number of hidden layers in the model did not improve MAPE and it was therefore decided to keep one hidden layer in the model configuration.
Even though the model has shown strong predictive power, our work is not done yet.
While the model has performed well on the validation data, we now need to assess whether the model will also perform well on completely unseen data.
The feature variables are loaded from pima-indians-diabetes2, and max0min normalization is invoked once again:
normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x)))}maxmindf2 <- as.data.frame(lapply(df2, normalize))attach(maxmindf2)
Using the predict function in R, predictions are generated for the Glucose variable:
pred_test <- data.frame(y = predict(model, as.matrix(maxmindf2)))predicted_test = pred_test$y * abs(diff(range(diabetes1$Glucose))) + min(diabetes1$Glucose)predicted_test
The predicted values are then compared to the actual values in pima-indians-diabetes3:
actual_test = diabetes3$Glucosedf2<-data.frame(predicted_test,actual_test)attach(df2)df2
Now, the mean absolute percentage error is calculated using the test values:
MAPE(predicted_test, actual_test)
A mean percentage error of 17% is calculated:
0.177895157636775
It is observed that while the mean percentage error is slightly higher than that calculated using the training and validation data, the model still performs well in predicting blood glucose levels across unseen observations on the test set.
In this example, we have seen:
How to implement feature selection methods in R
Construct a neural network to analyse regression data using the Keras API
Gauge prediction accuracy using test data
Many thanks for your time! You can also find more of my data science content at michael-grogan.com.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way.
|
[
{
"code": null,
"e": 402,
"s": 171,
"text": "With the advent of TensorFlow 2.0, Keras is now the default API for this version. Keras is used to build neural networks for deep learning purposes. As such, Keras is a highly useful tool for conducting analysis of large datasets."
},
{
"code": null,
"e": 468,
"s": 402,
"text": "However, did you realise that the Keras API can also be run in R?"
},
{
"code": null,
"e": 581,
"s": 468,
"text": "In this example, Keras is used to generate a neural network — with the aim of solving a regression problem in R."
},
{
"code": null,
"e": 720,
"s": 581,
"text": "Specifically, the Pima Indians Diabetes dataset is used in order to predict blood glucose levels for patients using the relevant features."
},
{
"code": null,
"e": 774,
"s": 720,
"text": "In this regard, this article provides an overview of:"
},
{
"code": null,
"e": 805,
"s": 774,
"text": "Feature selection methods in R"
},
{
"code": null,
"e": 847,
"s": 805,
"text": "How to define a Sequential model in Keras"
},
{
"code": null,
"e": 894,
"s": 847,
"text": "Methods to validate and test model predictions"
},
{
"code": null,
"e": 990,
"s": 894,
"text": "The Pima Indians Diabetes dataset is partitioned into three separate datasets for this example."
},
{
"code": null,
"e": 1226,
"s": 990,
"text": "Training and validation: pima-indians-diabetes1.csv. 80% of the original dataset is split from the full dataset. In turn, 70% of this dataset is used for training the model, and the remaining 30% is used for validating the predictions."
},
{
"code": null,
"e": 1637,
"s": 1226,
"text": "Test: pima-indians-diabetes2.csv and pima-indians-diabetes3.csv. The remaining 20% of the original dataset is used as unseen data, to determine whether the predictions being yielded by the model would perform well when dealing with completely new data. pima-indians-diabetes2 contains the features (or independent variables), while pima-indians-diabetes3 contains the dependent variable (blood glucose levels)."
},
{
"code": null,
"e": 1757,
"s": 1637,
"text": "The purpose of feature selection is to determine those features that have the most influence on the dependent variable."
},
{
"code": null,
"e": 1877,
"s": 1757,
"text": "In our example, there are eight features — some will be more important than others in determining blood glucose levels."
},
{
"code": null,
"e": 1926,
"s": 1877,
"text": "The two feature selection methods used here are:"
},
{
"code": null,
"e": 1944,
"s": 1926,
"text": "Correlation plots"
},
{
"code": null,
"e": 1971,
"s": 1944,
"text": "Multiple Linear Regression"
},
{
"code": null,
"e": 2021,
"s": 1971,
"text": "Correlation plots allow us to visually determine:"
},
{
"code": null,
"e": 2136,
"s": 2021,
"text": "Features that are highly correlated with the dependent variableFeatures that are highly correlated with each other"
},
{
"code": null,
"e": 2200,
"s": 2136,
"text": "Features that are highly correlated with the dependent variable"
},
{
"code": null,
"e": 2252,
"s": 2200,
"text": "Features that are highly correlated with each other"
},
{
"code": null,
"e": 2471,
"s": 2252,
"text": "If certain features are highly correlated with blood glucose levels, then this is an indication that these features are important in predicting the same. Features with low correlation are indicated to be insignificant."
},
{
"code": null,
"e": 2654,
"s": 2471,
"text": "However, features that are highly correlated with each other would indicate that some of these features are redundant (since they are in effect attempting to explain the same thing)."
},
{
"code": null,
"e": 2690,
"s": 2654,
"text": "Here is the first correlation plot:"
},
{
"code": null,
"e": 2740,
"s": 2690,
"text": "M <- cor(diabetes1)corrplot(M, method = \"circle\")"
},
{
"code": null,
"e": 2937,
"s": 2740,
"text": "We can see that the Insulin and Outcome variables are particularly correlated with the Glucose variable, while there is also correlation between Age and Pregnancies and Insulin and Skin Thickness."
},
{
"code": null,
"e": 3036,
"s": 2937,
"text": "However, we can go into more detail and obtain specific correlation coefficients for each feature:"
},
{
"code": null,
"e": 3067,
"s": 3036,
"text": "corrplot(M, method = \"number\")"
},
{
"code": null,
"e": 3118,
"s": 3067,
"text": "The purpose of a multiple linear regression is to:"
},
{
"code": null,
"e": 3282,
"s": 3118,
"text": "Determine the size and nature of the coefficient for each feature in explaining the dependent variable.Determine the signficance or insignificance of each feature."
},
{
"code": null,
"e": 3386,
"s": 3282,
"text": "Determine the size and nature of the coefficient for each feature in explaining the dependent variable."
},
{
"code": null,
"e": 3447,
"s": 3386,
"text": "Determine the signficance or insignificance of each feature."
},
{
"code": null,
"e": 3495,
"s": 3447,
"text": "Here are the results for the linear regression:"
},
{
"code": null,
"e": 4644,
"s": 3495,
"text": "Call:lm(formula = Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data = diabetes1)Residuals: Min 1Q Median 3Q Max -68.709 -18.148 -2.212 15.176 80.950 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 78.401064 6.363612 12.320 < 2e-16 ***Pregnancies -0.481865 0.363730 -1.325 0.18575 Outcome 25.590805 2.384153 10.734 < 2e-16 ***Age 0.527262 0.106097 4.970 8.8e-07 ***DiabetesPedigreeFunction 0.052534 3.198192 0.016 0.98690 BMI 0.318452 0.167106 1.906 0.05718 . Insulin 0.082208 0.009843 8.352 4.8e-16 ***SkinThickness -0.202236 0.077372 -2.614 0.00918 ** BloodPressure 0.083865 0.058081 1.444 0.14929 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 24.94 on 590 degrees of freedomMultiple R-squared: 0.362,\tAdjusted R-squared: 0.3533 F-statistic: 41.84 on 8 and 590 DF, p-value: < 2.2e-16"
},
{
"code": null,
"e": 4783,
"s": 4644,
"text": "At the 5% level, Outcome, Age, Insulin and Skin Thickness are deemed significant. Other features are deemed insignificant at the 5% level."
},
{
"code": null,
"e": 4958,
"s": 4783,
"text": "It is not deemed necessary to run a formal test for multicollinearity in this instance, as the correlation plots indicate features that are highly correlated with each other."
},
{
"code": null,
"e": 5216,
"s": 4958,
"text": "However, heteroscedasticity (uneven variance across standard errors) could be present, e.g. due to differing age across patients. In order to test this, the Breusch-Pagan test is run — with a p-value below 0.05 indicating the presence of heteroscedasticity."
},
{
"code": null,
"e": 5311,
"s": 5216,
"text": "> bptest(fit)\tstudentized Breusch-Pagan testdata: fitBP = 36.585, df = 8, p-value = 1.372e-05"
},
{
"code": null,
"e": 5507,
"s": 5311,
"text": "As heteroscedasticity is indicated to be present, a robust regression is run — specifically using Huber weights. The purpose of this is to place less value on the outliers present in the dataset."
},
{
"code": null,
"e": 6525,
"s": 5507,
"text": "> # Huber Weights (Robust Regression)> summary(rr.huber <- rlm(Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data=diabetes1))Call: rlm(formula = Glucose ~ Pregnancies + Outcome + Age + DiabetesPedigreeFunction + BMI + Insulin + SkinThickness + BloodPressure, data = diabetes1)Residuals: Min 1Q Median 3Q Max -68.627 -16.842 -1.543 15.576 83.793 Coefficients: Value Std. Error t value(Intercept) 78.3319 6.2990 12.4357Pregnancies -0.4675 0.3600 -1.2984Outcome 25.0513 2.3599 10.6152Age 0.5448 0.1050 5.1881DiabetesPedigreeFunction -0.5482 3.1657 -0.1732BMI 0.3297 0.1654 1.9935Insulin 0.0925 0.0097 9.4912SkinThickness -0.2530 0.0766 -3.3032BloodPressure 0.0673 0.0575 1.1706Residual standard error: 24.53 on 590 degrees of freedom"
},
{
"code": null,
"e": 6599,
"s": 6525,
"text": "On 590 degrees of freedom, the two-tailed t critical value is as follows:"
},
{
"code": null,
"e": 6634,
"s": 6599,
"text": "> abs(qt(0.05/2, 590))[1] 1.963993"
},
{
"code": null,
"e": 6829,
"s": 6634,
"text": "When the t statistic > t critical value, the null hypothesis is rejected. In this regard, Outcome, Age, BMI, Insulin, and Skin Thickness have an absolute t-value greater than the critical value."
},
{
"code": null,
"e": 7021,
"s": 6829,
"text": "Taking the findings of both the correlation plots and multiple linear regression into account, Outcome, Age, Insulin and Skin Thickness are selected as the relevant features for the analysis."
},
{
"code": null,
"e": 7128,
"s": 7021,
"text": "Now that the relevant features have been selected, the neural network can be constructed. Before doing so:"
},
{
"code": null,
"e": 7307,
"s": 7128,
"text": "Max-Min Normalization is used to scale each variable between 0 and 1. This is to ensure a common scale among the variables so that the neural network can interpret them properly."
},
{
"code": null,
"e": 7486,
"s": 7307,
"text": "Max-Min Normalization is used to scale each variable between 0 and 1. This is to ensure a common scale among the variables so that the neural network can interpret them properly."
},
{
"code": null,
"e": 7650,
"s": 7486,
"text": "normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x)))}maxmindf <- as.data.frame(lapply(df, normalize))attach(maxmindf)maxmindf<-as.matrix(maxmindf)"
},
{
"code": null,
"e": 7691,
"s": 7650,
"text": "The train-validation set is split 70/30."
},
{
"code": null,
"e": 7732,
"s": 7691,
"text": "The train-validation set is split 70/30."
},
{
"code": null,
"e": 7918,
"s": 7732,
"text": "ind <- sample(2, nrow(maxmindf), replace=TRUE, prob = c(0.7,0.3))X_train <- maxmindf[ind==1, 1:4]X_val <- maxmindf[ind==2, 1:4]y_train <- maxmindf[ind==1, 5]y_val <- maxmindf[ind==2, 5]"
},
{
"code": null,
"e": 8186,
"s": 7918,
"text": "Now, the Sequential model is defined. The four input features (Outcome, Age, Insulin, Skin Thickness) are included in the input layer with 9 neurons defined in the layer. One hidden layer with 60 neurons is defined, and a linear output layer with 1 neuron is defined."
},
{
"code": null,
"e": 8294,
"s": 8186,
"text": "As explained in this article by Farhad Malik, the number of neurons in each layer is configured as follows:"
},
{
"code": null,
"e": 8374,
"s": 8294,
"text": "Input layer: The number of neurons in the input layer is calculated as follows:"
},
{
"code": null,
"e": 8417,
"s": 8374,
"text": "Number of features in the training set + 1"
},
{
"code": null,
"e": 8532,
"s": 8417,
"text": "In this case, as there were 8 features in the training set to begin with, 9 input neurons are defined accordingly."
},
{
"code": null,
"e": 8706,
"s": 8532,
"text": "Hidden layer: One hidden layer is defined, as a single layer is suitable when working with most datasets. The number of neurons in the hidden layer is determined as follows:"
},
{
"code": null,
"e": 8770,
"s": 8706,
"text": "Training Data Samples/Factor * (Input Neurons + Output Neurons)"
},
{
"code": null,
"e": 9052,
"s": 8770,
"text": "A factor of 1 is set in this case, the purpose of the factor being to prevent overfitting. A factor can take a value between 1 and 10. With 9 neurons in the input layer, 1 neuron in the output layer and 599 observations in the training set, the hidden layer is assigned 60 neurons."
},
{
"code": null,
"e": 9143,
"s": 9052,
"text": "Output layer: As this is the result layer, the output layer takes a value of 1 by default."
},
{
"code": null,
"e": 9404,
"s": 9143,
"text": "model <- keras_model_sequential() model %>% layer_dense(units = 9, activation = 'relu', kernel_initializer='RandomNormal', input_shape = c(4)) %>% layer_dense(units = 60, activation = 'relu') %>% layer_dense(units = 1, activation = 'linear')summary(model)"
},
{
"code": null,
"e": 9424,
"s": 9404,
"text": "Here is the output:"
},
{
"code": null,
"e": 10305,
"s": 9424,
"text": "Model: \"sequential\"________________________________________________________________________________Layer (type) Output Shape Param # ================================================================================dense (Dense) (None, 9) 45 ________________________________________________________________________________dense_1 (Dense) (None, 60) 600 ________________________________________________________________________________dense_2 (Dense) (None, 1) 61 ================================================================================Total params: 706Trainable params: 706Non-trainable params: 0________________________________________________________________________________"
},
{
"code": null,
"e": 10551,
"s": 10305,
"text": "The model is now trained over 30 epochs, and evaluated based on its loss and mean absolute error. Given that the dependent variable is interval, the mean squared error is used to determine the deviation between the predictions and actual values."
},
{
"code": null,
"e": 10744,
"s": 10551,
"text": "model %>% compile( loss = 'mean_squared_error', optimizer = 'adam', metrics = c('mae'))history <- model %>% fit( X_train, y_train, epochs = 30, batch_size = 50, validation_split = 0.2)"
},
{
"code": null,
"e": 10819,
"s": 10744,
"text": "The predicted and actual values are scaled back to their original formats:"
},
{
"code": null,
"e": 11081,
"s": 10819,
"text": "model %>% evaluate(X_val, y_val)modelpred <- data.frame(y = predict(model, as.matrix(X_val)))predicted=pred$y * abs(diff(range(df$Glucose))) + min(df$Glucose)actual=y_val * abs(diff(range(df$Glucose))) + min(df$Glucose)df<-data.frame(predicted,actual)attach(df)"
},
{
"code": null,
"e": 11101,
"s": 11081,
"text": "Here is the output:"
},
{
"code": null,
"e": 12039,
"s": 11101,
"text": "$loss 0.0266957393988254$mae 0.132186755537987ModelModel: \"sequential\"________________________________________________________________________________Layer (type) Output Shape Param # ================================================================================dense (Dense) (None, 9) 45 ________________________________________________________________________________dense_1 (Dense) (None, 60) 600 ________________________________________________________________________________dense_2 (Dense) (None, 1) 61 ================================================================================Total params: 706Trainable params: 706Non-trainable params: 0________________________________________________________________________________"
},
{
"code": null,
"e": 12091,
"s": 12039,
"text": "Here is a plot of the loss and mean absolute error:"
},
{
"code": null,
"e": 12177,
"s": 12091,
"text": "The model yields a loss of just above 2% and a mean absolute error of just above 13%."
},
{
"code": null,
"e": 12272,
"s": 12177,
"text": "The MLmetrics library can also be used to calculate the MAPE (mean absolute percentage error)."
},
{
"code": null,
"e": 12343,
"s": 12272,
"text": "install.packages(\"MLmetrics\")library(MLmetrics)MAPE(predicted, actual)"
},
{
"code": null,
"e": 12547,
"s": 12343,
"text": "The MAPE for the validation set comes in at 18%. Increasing the number of hidden layers in the model did not improve MAPE and it was therefore decided to keep one hidden layer in the model configuration."
},
{
"code": null,
"e": 12630,
"s": 12547,
"text": "Even though the model has shown strong predictive power, our work is not done yet."
},
{
"code": null,
"e": 12779,
"s": 12630,
"text": "While the model has performed well on the validation data, we now need to assess whether the model will also perform well on completely unseen data."
},
{
"code": null,
"e": 12890,
"s": 12779,
"text": "The feature variables are loaded from pima-indians-diabetes2, and max0min normalization is invoked once again:"
},
{
"code": null,
"e": 13028,
"s": 12890,
"text": "normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x)))}maxmindf2 <- as.data.frame(lapply(df2, normalize))attach(maxmindf2)"
},
{
"code": null,
"e": 13113,
"s": 13028,
"text": "Using the predict function in R, predictions are generated for the Glucose variable:"
},
{
"code": null,
"e": 13284,
"s": 13113,
"text": "pred_test <- data.frame(y = predict(model, as.matrix(maxmindf2)))predicted_test = pred_test$y * abs(diff(range(diabetes1$Glucose))) + min(diabetes1$Glucose)predicted_test"
},
{
"code": null,
"e": 13371,
"s": 13284,
"text": "The predicted values are then compared to the actual values in pima-indians-diabetes3:"
},
{
"code": null,
"e": 13460,
"s": 13371,
"text": "actual_test = diabetes3$Glucosedf2<-data.frame(predicted_test,actual_test)attach(df2)df2"
},
{
"code": null,
"e": 13537,
"s": 13460,
"text": "Now, the mean absolute percentage error is calculated using the test values:"
},
{
"code": null,
"e": 13571,
"s": 13537,
"text": "MAPE(predicted_test, actual_test)"
},
{
"code": null,
"e": 13617,
"s": 13571,
"text": "A mean percentage error of 17% is calculated:"
},
{
"code": null,
"e": 13635,
"s": 13617,
"text": "0.177895157636775"
},
{
"code": null,
"e": 13876,
"s": 13635,
"text": "It is observed that while the mean percentage error is slightly higher than that calculated using the training and validation data, the model still performs well in predicting blood glucose levels across unseen observations on the test set."
},
{
"code": null,
"e": 13907,
"s": 13876,
"text": "In this example, we have seen:"
},
{
"code": null,
"e": 13955,
"s": 13907,
"text": "How to implement feature selection methods in R"
},
{
"code": null,
"e": 14029,
"s": 13955,
"text": "Construct a neural network to analyse regression data using the Keras API"
},
{
"code": null,
"e": 14071,
"s": 14029,
"text": "Gauge prediction accuracy using test data"
},
{
"code": null,
"e": 14171,
"s": 14071,
"text": "Many thanks for your time! You can also find more of my data science content at michael-grogan.com."
}
] |
Evaluate Topic Models: Latent Dirichlet Allocation (LDA) | by Shashank Kapadia | Towards Data Science
|
Preface: This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code
In the previous article, I introduced the concept of topic modeling and walked through the code for developing your first topic model using Latent Dirichlet Allocation (LDA) method in the python using Gensim implementation.
Pursuing on that understanding, in this article, we’ll go a few steps deeper by outlining the framework to quantitatively evaluate topic models through the measure of topic coherence and share the code template in python using Gensim implementation to allow for end-to-end model development.
We know probabilistic topic models, such as LDA, are popular tools for text analysis, providing both a predictive and latent topic representation of the corpus. However, there is a longstanding assumption that the latent space discovered by these models is generally meaningful and useful, and that evaluating such assumptions is challenging due to its unsupervised training process. Besides, there is a no-gold standard list of topics to compare against every corpus.
Nevertheless, it is equally important to identify if a trained model is objectively good or bad, as well have an ability to compare different models/methods. To do so, one would require an objective measure for the quality. Traditionally, and still for many practical applications, to evaluate if “the correct thing” has been learned about the corpus, an implicit knowledge and “eyeballing” approaches are used. Ideally, we’d like to capture this information in a single metric that can be maximized, and compared.
Let’s take a look at roughly what approaches are commonly used for the evaluation:
Eye Balling Models
Top N words
Topics / Documents
Intrinsic Evaluation Metrics
Capturing model semantics
Topics interpretability
Human Judgements
What is a topic
Extrinsic Evaluation Metrics/Evaluation at task
Is model good at performing predefined tasks, such as classification
Natural language is messy, ambiguous and full of subjective interpretation, and sometimes trying to cleanse ambiguity reduces the language to an unnatural form. In this article, we’ll explore more about topic coherence, an intrinsic evaluation metric, and how you can use it to quantitatively justify the model selection.
Before we understand topic coherence, let’s briefly look at the perplexity measure. Perplexity as well is one of the intrinsic evaluation metric, and is widely used for language model evaluation. It captures how surprised a model is of new data it has not seen before, and is measured as the normalized log-likelihood of a held-out test set.
Focussing on the log-likelihood part, you can think of the perplexity metric as measuring how probable some new unseen data is given the model that was learned earlier. That is to say, how well does the model represent or reproduce the statistics of the held-out data.
However, recent studies have shown that predictive likelihood (or equivalently, perplexity) and human judgment are often not correlated, and even sometimes slightly anti-correlated.
Optimizing for perplexity may not yield human interpretable topics
This limitation of perplexity measure served as a motivation for more work trying to model the human judgment, and thus Topic Coherence.
The concept of topic coherence combines a number of measures into a framework to evaluate the coherence between topics inferred by a model. But before that...
What is topic coherence?
Topic Coherence measures score a single topic by measuring the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable topics and topics that are artifacts of statistical inference. But ...
What is coherence?
A set of statements or facts is said to be coherent, if they support each other. Thus, a coherent fact set can be interpreted in a context that covers all or most of the facts. An example of a coherent fact set is “the game is a team sport”, “the game is played with a ball”, “the game demands great physical efforts”
Let’s take quick look at different coherence measures, and how they are calculated:
C_v measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarityC_p is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherenceC_uci measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top wordsC_umass is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measureC_npmi is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)C_a is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity
C_v measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity
C_p is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherence
C_uci measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top words
C_umass is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measure
C_npmi is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)
C_a is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity
There is, of course, a lot more to the concept of topic model evaluation, and the coherence measure. However, keeping in mind the length, and purpose of this article, let’s apply these concepts into developing a model that is at least better than with the default parameters. Also, we’ll be re-purposing already available online pieces of code to support this exercise instead of re-inventing the wheel.
The complete code is available as a Jupyter Notebook on GitHub
Loading dataData CleaningPhrase Modeling: Bi-grams and Tri-gramsData transformation: Corpus and DictionaryBase ModelHyperparameter TuningFinal ModelVisualize Results
Loading data
Data Cleaning
Phrase Modeling: Bi-grams and Tri-grams
Data transformation: Corpus and Dictionary
Base Model
Hyperparameter Tuning
Final Model
Visualize Results
For this tutorial, we’ll use the dataset of papers published in NIPS conference. The NIPS conference (Neural Information Processing Systems) is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more.
Let’s start by looking at the content of the file
# Importing modulesimport pandas as pdimport osos.chdir('..')# Read data into paperspapers = pd.read_csv('./data/NIPS Papers/papers.csv')# Print headpapers.head()
Since the goal of this analysis is to perform topic modeling, we will solely focus on the text data from each paper, and drop other metadata columns
# Remove the columnspapers = papers.drop(columns=['id', 'title', 'abstract', 'event_type', 'pdf_name', 'year'], axis=1)# sample only 100 paperspapers = papers.sample(100)# Print out the first rows of paperspapers.head()
Remove punctuation/lower casing
Next, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text
# Load the regular expression libraryimport re# Remove punctuationpapers['paper_text_processed'] = papers['paper_text'].map(lambda x: re.sub('[,\.!?]', '', x))# Convert the titles to lowercasepapers['paper_text_processed'] = papers['paper_text_processed'].map(lambda x: x.lower())# Print out the first rows of paperspapers['paper_text_processed'].head()
Tokenize words and further clean-up text
Let’s tokenize each sentence into a list of words, removing punctuations and unnecessary characters altogether.
import gensimfrom gensim.utils import simple_preprocessdef sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuationsdata = papers.paper_text_processed.values.tolist()data_words = list(sent_to_words(data))print(data_words[:1][0][:30])
Bigrams are two words frequently occurring together in the document. Trigrams are 3 words frequently occurring. Some examples in our example are: ‘back_bumper’, ‘oil_leakage’, ‘maryland_college_park’ etc.
Gensim’s Phrases model can build and implement the bigrams, trigrams, quadgrams and more. The two important arguments to Phrases are min_count and threshold.
The higher the values of these param, the harder it is for words to be combined.
# Build the bigram and trigram modelsbigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.trigram = gensim.models.Phrases(bigram[data_words], threshold=100)# Faster way to get a sentence clubbed as a trigram/bigrambigram_mod = gensim.models.phrases.Phraser(bigram)trigram_mod = gensim.models.phrases.Phraser(trigram)
Remove Stopwords, Make Bigrams and Lemmatize
The phrase models are ready. Let’s define the functions to remove the stopwords, make trigrams and lemmatization and call them sequentially.
# NLTK Stop words# import nltk# nltk.download('stopwords')from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['from', 'subject', 're', 'edu', 'use'])# Define functions for stopwords, bigrams, trigrams and lemmatizationdef remove_stopwords(texts): return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]def make_bigrams(texts): return [bigram_mod[doc] for doc in texts]def make_trigrams(texts): return [trigram_mod[bigram_mod[doc]] for doc in texts]def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" texts_out = [] for sent in texts: doc = nlp(" ".join(sent)) texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags]) return texts_out
Let’s call the functions in order.
import spacy# Remove Stop Wordsdata_words_nostops = remove_stopwords(data_words)# Form Bigramsdata_words_bigrams = make_bigrams(data_words_nostops)# Initialize spacy 'en' model, keeping only tagger component (for efficiency)nlp = spacy.load("en_core_web_sm", disable=['parser', 'ner'])# Do lemmatization keeping only noun, adj, vb, advdata_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])print(data_lemmatized[:1])
The two main inputs to the LDA topic model are the dictionary(id2word) and the corpus. Let’s create them.
import gensim.corpora as corpora# Create Dictionaryid2word = corpora.Dictionary(data_lemmatized)# Create Corpustexts = data_lemmatized# Term Document Frequencycorpus = [id2word.doc2bow(text) for text in texts]# Viewprint(corpus[:1])
Gensim creates a unique id for each word in the document. The produced corpus shown above is a mapping of (word_id, word_frequency).
For example, (0, 7) above implies, word id 0 occurs seven times in the first document. Likewise, word id 1 occurs thrice and so on
We have everything required to train the base LDA model. In addition to the corpus and dictionary, you need to provide the number of topics as well. Apart from that, alpha and eta are hyperparameters that affect sparsity of the topics. According to the Gensim docs, both defaults to 1.0/num_topics prior (we’ll use default for the base model).
chunksize controls how many documents are processed at a time in the training algorithm. Increasing chunksize will speed up training, at least as long as the chunk of documents easily fit into memory.
passes controls how often we train the model on the entire corpus (set to 10). Another word for passes might be “epochs”. iterations is somewhat technical, but essentially it controls how often we repeat a particular loop over each document. It is important to set the number of “passes” and “iterations” high enough.
# Build LDA modellda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=10, random_state=100, chunksize=100, passes=10, per_word_topics=True)
View the topics in LDA model
The above LDA model is built with 10 different topics where each topic is a combination of keywords and each keyword contributes a certain weightage to the topic.
You can see the keywords for each topic and the weightage(importance) of each keyword using lda_model.print_topics()
from pprint import pprint# Print the Keyword in the 10 topicspprint(lda_model.print_topics())doc_lda = lda_model[corpus]
Compute Model Perplexity and Coherence Score
Let’s calculate the baseline coherence score
from gensim.models import CoherenceModel# Compute Coherence Scorecoherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')coherence_lda = coherence_model_lda.get_coherence()print('\nCoherence Score: ', coherence_lda)
Coherence Score: 0.301
First, let’s differentiate between model hyperparameters and model parameters :
Model hyperparameters can be thought of as settings for a machine learning algorithm that are tuned by the data scientist before training. Examples would be the number of trees in the random forest, or in our case, number of topics K
Model parameters can be thought of as what the model learns during training, such as the weights for each word in a given topic
Now that we have the baseline coherence score for the default LDA model, let’s perform a series of sensitivity tests to help determine the following model hyperparameters:
Number of Topics (K)Dirichlet hyperparameter alpha: Document-Topic DensityDirichlet hyperparameter beta: Word-Topic Density
Number of Topics (K)
Dirichlet hyperparameter alpha: Document-Topic Density
Dirichlet hyperparameter beta: Word-Topic Density
We’ll perform these tests in sequence, one parameter at a time by keeping others constant and run them over the two different validation corpus sets. We’ll use C_v as our choice of metric for performance comparison
# supporting functiondef compute_coherence_values(corpus, dictionary, k, a, b): lda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=dictionary, num_topics=k, random_state=100, chunksize=100, passes=10, alpha=a, eta=b) coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v') return coherence_model_lda.get_coherence()
Let’s call the function, and iterate it over the range of topics, alpha, and beta parameter values
import numpy as npimport tqdmgrid = {}grid['Validation_Set'] = {}# Topics rangemin_topics = 2max_topics = 11step_size = 1topics_range = range(min_topics, max_topics, step_size)# Alpha parameteralpha = list(np.arange(0.01, 1, 0.3))alpha.append('symmetric')alpha.append('asymmetric')# Beta parameterbeta = list(np.arange(0.01, 1, 0.3))beta.append('symmetric')# Validation setsnum_of_docs = len(corpus)corpus_sets = [# gensim.utils.ClippedCorpus(corpus, num_of_docs*0.25), # gensim.utils.ClippedCorpus(corpus, num_of_docs*0.5), gensim.utils.ClippedCorpus(corpus, num_of_docs*0.75), corpus]corpus_title = ['75% Corpus', '100% Corpus']model_results = {'Validation_Set': [], 'Topics': [], 'Alpha': [], 'Beta': [], 'Coherence': [] }# Can take a long time to runif 1 == 1: pbar = tqdm.tqdm(total=540) # iterate through validation corpuses for i in range(len(corpus_sets)): # iterate through number of topics for k in topics_range: # iterate through alpha values for a in alpha: # iterare through beta values for b in beta: # get the coherence score for the given parameters cv = compute_coherence_values(corpus=corpus_sets[i], dictionary=id2word, k=k, a=a, b=b) # Save the model results model_results['Validation_Set'].append(corpus_title[i]) model_results['Topics'].append(k) model_results['Alpha'].append(a) model_results['Beta'].append(b) model_results['Coherence'].append(cv) pbar.update(1) pd.DataFrame(model_results).to_csv('lda_tuning_results.csv', index=False) pbar.close()
Let’s start by determining the optimal number of topics. The chart below outlines the coherence score, C_v, for the number of topics across two validation sets, and a fixed alpha = 0.01 and beta = 0.1
With the coherence score seems to keep increasing with the number of topics, it may make better sense to pick the model that gave the highest CV before flattening out or a major drop. In this case, we picked K=8
Next, we want to select the optimal alpha and beta parameters. While there are other sophisticated approaches to tackle the selection process, for this tutorial, we choose the values that yielded maximum C_v score for K=8
alpha=0.01
beta=0.9
K=8
That yields approx. 17% improvement over the baseline score
Let’s train the final model using the above selected parameters
lda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=8, random_state=100, chunksize=100, passes=10, alpha=0.01, eta=0.9)
import pyLDAvis.gensimimport pickle import pyLDAvis# Visualize the topicspyLDAvis.enable_notebook()LDAvis_prepared = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)LDAvis_prepared
We started with understanding why evaluating the topic model is essential. Next, we reviewed existing methods and scratched the surface of topic coherence, along with the available coherence measures. Then we built a default LDA model using Gensim implementation to establish the baseline coherence score and reviewed practical ways to optimize the LDA hyperparameters.
Hopefully, this article has managed to shed light on the underlying topic evaluation strategies, and intuitions behind it.
References:
http://qpleple.com/perplexity-to-evaluate-topic-models/https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdfhttps://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynbhttps://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdfhttp://palmetto.aksw.org/palmetto-webapp/
http://qpleple.com/perplexity-to-evaluate-topic-models/
https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020
https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdf
https://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynb
https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/
http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf
http://palmetto.aksw.org/palmetto-webapp/
Thanks for reading. If you have any feedback, please feel to reach out by commenting on this post, messaging me on LinkedIn, or shooting me an email (shmkapadia[at]gmail.com)
If you enjoyed this article, visit my other articles
|
[
{
"code": null,
"e": 431,
"s": 172,
"text": "Preface: This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code"
},
{
"code": null,
"e": 655,
"s": 431,
"text": "In the previous article, I introduced the concept of topic modeling and walked through the code for developing your first topic model using Latent Dirichlet Allocation (LDA) method in the python using Gensim implementation."
},
{
"code": null,
"e": 947,
"s": 655,
"text": "Pursuing on that understanding, in this article, we’ll go a few steps deeper by outlining the framework to quantitatively evaluate topic models through the measure of topic coherence and share the code template in python using Gensim implementation to allow for end-to-end model development."
},
{
"code": null,
"e": 1416,
"s": 947,
"text": "We know probabilistic topic models, such as LDA, are popular tools for text analysis, providing both a predictive and latent topic representation of the corpus. However, there is a longstanding assumption that the latent space discovered by these models is generally meaningful and useful, and that evaluating such assumptions is challenging due to its unsupervised training process. Besides, there is a no-gold standard list of topics to compare against every corpus."
},
{
"code": null,
"e": 1931,
"s": 1416,
"text": "Nevertheless, it is equally important to identify if a trained model is objectively good or bad, as well have an ability to compare different models/methods. To do so, one would require an objective measure for the quality. Traditionally, and still for many practical applications, to evaluate if “the correct thing” has been learned about the corpus, an implicit knowledge and “eyeballing” approaches are used. Ideally, we’d like to capture this information in a single metric that can be maximized, and compared."
},
{
"code": null,
"e": 2014,
"s": 1931,
"text": "Let’s take a look at roughly what approaches are commonly used for the evaluation:"
},
{
"code": null,
"e": 2033,
"s": 2014,
"text": "Eye Balling Models"
},
{
"code": null,
"e": 2045,
"s": 2033,
"text": "Top N words"
},
{
"code": null,
"e": 2064,
"s": 2045,
"text": "Topics / Documents"
},
{
"code": null,
"e": 2093,
"s": 2064,
"text": "Intrinsic Evaluation Metrics"
},
{
"code": null,
"e": 2119,
"s": 2093,
"text": "Capturing model semantics"
},
{
"code": null,
"e": 2143,
"s": 2119,
"text": "Topics interpretability"
},
{
"code": null,
"e": 2160,
"s": 2143,
"text": "Human Judgements"
},
{
"code": null,
"e": 2176,
"s": 2160,
"text": "What is a topic"
},
{
"code": null,
"e": 2224,
"s": 2176,
"text": "Extrinsic Evaluation Metrics/Evaluation at task"
},
{
"code": null,
"e": 2293,
"s": 2224,
"text": "Is model good at performing predefined tasks, such as classification"
},
{
"code": null,
"e": 2615,
"s": 2293,
"text": "Natural language is messy, ambiguous and full of subjective interpretation, and sometimes trying to cleanse ambiguity reduces the language to an unnatural form. In this article, we’ll explore more about topic coherence, an intrinsic evaluation metric, and how you can use it to quantitatively justify the model selection."
},
{
"code": null,
"e": 2957,
"s": 2615,
"text": "Before we understand topic coherence, let’s briefly look at the perplexity measure. Perplexity as well is one of the intrinsic evaluation metric, and is widely used for language model evaluation. It captures how surprised a model is of new data it has not seen before, and is measured as the normalized log-likelihood of a held-out test set."
},
{
"code": null,
"e": 3226,
"s": 2957,
"text": "Focussing on the log-likelihood part, you can think of the perplexity metric as measuring how probable some new unseen data is given the model that was learned earlier. That is to say, how well does the model represent or reproduce the statistics of the held-out data."
},
{
"code": null,
"e": 3408,
"s": 3226,
"text": "However, recent studies have shown that predictive likelihood (or equivalently, perplexity) and human judgment are often not correlated, and even sometimes slightly anti-correlated."
},
{
"code": null,
"e": 3475,
"s": 3408,
"text": "Optimizing for perplexity may not yield human interpretable topics"
},
{
"code": null,
"e": 3612,
"s": 3475,
"text": "This limitation of perplexity measure served as a motivation for more work trying to model the human judgment, and thus Topic Coherence."
},
{
"code": null,
"e": 3771,
"s": 3612,
"text": "The concept of topic coherence combines a number of measures into a framework to evaluate the coherence between topics inferred by a model. But before that..."
},
{
"code": null,
"e": 3796,
"s": 3771,
"text": "What is topic coherence?"
},
{
"code": null,
"e": 4088,
"s": 3796,
"text": "Topic Coherence measures score a single topic by measuring the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable topics and topics that are artifacts of statistical inference. But ..."
},
{
"code": null,
"e": 4107,
"s": 4088,
"text": "What is coherence?"
},
{
"code": null,
"e": 4425,
"s": 4107,
"text": "A set of statements or facts is said to be coherent, if they support each other. Thus, a coherent fact set can be interpreted in a context that covers all or most of the facts. An example of a coherent fact set is “the game is a team sport”, “the game is played with a ball”, “the game demands great physical efforts”"
},
{
"code": null,
"e": 4509,
"s": 4425,
"text": "Let’s take quick look at different coherence measures, and how they are calculated:"
},
{
"code": null,
"e": 5411,
"s": 4509,
"text": "C_v measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarityC_p is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherenceC_uci measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top wordsC_umass is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measureC_npmi is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)C_a is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity"
},
{
"code": null,
"e": 5611,
"s": 5411,
"text": "C_v measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity"
},
{
"code": null,
"e": 5742,
"s": 5611,
"text": "C_p is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherence"
},
{
"code": null,
"e": 5869,
"s": 5742,
"text": "C_uci measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top words"
},
{
"code": null,
"e": 6014,
"s": 5869,
"text": "C_umass is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measure"
},
{
"code": null,
"e": 6124,
"s": 6014,
"text": "C_npmi is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)"
},
{
"code": null,
"e": 6318,
"s": 6124,
"text": "C_a is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity"
},
{
"code": null,
"e": 6722,
"s": 6318,
"text": "There is, of course, a lot more to the concept of topic model evaluation, and the coherence measure. However, keeping in mind the length, and purpose of this article, let’s apply these concepts into developing a model that is at least better than with the default parameters. Also, we’ll be re-purposing already available online pieces of code to support this exercise instead of re-inventing the wheel."
},
{
"code": null,
"e": 6785,
"s": 6722,
"text": "The complete code is available as a Jupyter Notebook on GitHub"
},
{
"code": null,
"e": 6951,
"s": 6785,
"text": "Loading dataData CleaningPhrase Modeling: Bi-grams and Tri-gramsData transformation: Corpus and DictionaryBase ModelHyperparameter TuningFinal ModelVisualize Results"
},
{
"code": null,
"e": 6964,
"s": 6951,
"text": "Loading data"
},
{
"code": null,
"e": 6978,
"s": 6964,
"text": "Data Cleaning"
},
{
"code": null,
"e": 7018,
"s": 6978,
"text": "Phrase Modeling: Bi-grams and Tri-grams"
},
{
"code": null,
"e": 7061,
"s": 7018,
"text": "Data transformation: Corpus and Dictionary"
},
{
"code": null,
"e": 7072,
"s": 7061,
"text": "Base Model"
},
{
"code": null,
"e": 7094,
"s": 7072,
"text": "Hyperparameter Tuning"
},
{
"code": null,
"e": 7106,
"s": 7094,
"text": "Final Model"
},
{
"code": null,
"e": 7124,
"s": 7106,
"text": "Visualize Results"
},
{
"code": null,
"e": 7595,
"s": 7124,
"text": "For this tutorial, we’ll use the dataset of papers published in NIPS conference. The NIPS conference (Neural Information Processing Systems) is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more."
},
{
"code": null,
"e": 7645,
"s": 7595,
"text": "Let’s start by looking at the content of the file"
},
{
"code": null,
"e": 7808,
"s": 7645,
"text": "# Importing modulesimport pandas as pdimport osos.chdir('..')# Read data into paperspapers = pd.read_csv('./data/NIPS Papers/papers.csv')# Print headpapers.head()"
},
{
"code": null,
"e": 7957,
"s": 7808,
"text": "Since the goal of this analysis is to perform topic modeling, we will solely focus on the text data from each paper, and drop other metadata columns"
},
{
"code": null,
"e": 8207,
"s": 7957,
"text": "# Remove the columnspapers = papers.drop(columns=['id', 'title', 'abstract', 'event_type', 'pdf_name', 'year'], axis=1)# sample only 100 paperspapers = papers.sample(100)# Print out the first rows of paperspapers.head()"
},
{
"code": null,
"e": 8239,
"s": 8207,
"text": "Remove punctuation/lower casing"
},
{
"code": null,
"e": 8479,
"s": 8239,
"text": "Next, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text"
},
{
"code": null,
"e": 8833,
"s": 8479,
"text": "# Load the regular expression libraryimport re# Remove punctuationpapers['paper_text_processed'] = papers['paper_text'].map(lambda x: re.sub('[,\\.!?]', '', x))# Convert the titles to lowercasepapers['paper_text_processed'] = papers['paper_text_processed'].map(lambda x: x.lower())# Print out the first rows of paperspapers['paper_text_processed'].head()"
},
{
"code": null,
"e": 8874,
"s": 8833,
"text": "Tokenize words and further clean-up text"
},
{
"code": null,
"e": 8986,
"s": 8874,
"text": "Let’s tokenize each sentence into a list of words, removing punctuations and unnecessary characters altogether."
},
{
"code": null,
"e": 9325,
"s": 8986,
"text": "import gensimfrom gensim.utils import simple_preprocessdef sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuationsdata = papers.paper_text_processed.values.tolist()data_words = list(sent_to_words(data))print(data_words[:1][0][:30])"
},
{
"code": null,
"e": 9530,
"s": 9325,
"text": "Bigrams are two words frequently occurring together in the document. Trigrams are 3 words frequently occurring. Some examples in our example are: ‘back_bumper’, ‘oil_leakage’, ‘maryland_college_park’ etc."
},
{
"code": null,
"e": 9688,
"s": 9530,
"text": "Gensim’s Phrases model can build and implement the bigrams, trigrams, quadgrams and more. The two important arguments to Phrases are min_count and threshold."
},
{
"code": null,
"e": 9769,
"s": 9688,
"text": "The higher the values of these param, the harder it is for words to be combined."
},
{
"code": null,
"e": 10137,
"s": 9769,
"text": "# Build the bigram and trigram modelsbigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.trigram = gensim.models.Phrases(bigram[data_words], threshold=100)# Faster way to get a sentence clubbed as a trigram/bigrambigram_mod = gensim.models.phrases.Phraser(bigram)trigram_mod = gensim.models.phrases.Phraser(trigram)"
},
{
"code": null,
"e": 10182,
"s": 10137,
"text": "Remove Stopwords, Make Bigrams and Lemmatize"
},
{
"code": null,
"e": 10323,
"s": 10182,
"text": "The phrase models are ready. Let’s define the functions to remove the stopwords, make trigrams and lemmatization and call them sequentially."
},
{
"code": null,
"e": 11161,
"s": 10323,
"text": "# NLTK Stop words# import nltk# nltk.download('stopwords')from nltk.corpus import stopwordsstop_words = stopwords.words('english')stop_words.extend(['from', 'subject', 're', 'edu', 'use'])# Define functions for stopwords, bigrams, trigrams and lemmatizationdef remove_stopwords(texts): return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]def make_bigrams(texts): return [bigram_mod[doc] for doc in texts]def make_trigrams(texts): return [trigram_mod[bigram_mod[doc]] for doc in texts]def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): \"\"\"https://spacy.io/api/annotation\"\"\" texts_out = [] for sent in texts: doc = nlp(\" \".join(sent)) texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags]) return texts_out"
},
{
"code": null,
"e": 11196,
"s": 11161,
"text": "Let’s call the functions in order."
},
{
"code": null,
"e": 11657,
"s": 11196,
"text": "import spacy# Remove Stop Wordsdata_words_nostops = remove_stopwords(data_words)# Form Bigramsdata_words_bigrams = make_bigrams(data_words_nostops)# Initialize spacy 'en' model, keeping only tagger component (for efficiency)nlp = spacy.load(\"en_core_web_sm\", disable=['parser', 'ner'])# Do lemmatization keeping only noun, adj, vb, advdata_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])print(data_lemmatized[:1])"
},
{
"code": null,
"e": 11763,
"s": 11657,
"text": "The two main inputs to the LDA topic model are the dictionary(id2word) and the corpus. Let’s create them."
},
{
"code": null,
"e": 11996,
"s": 11763,
"text": "import gensim.corpora as corpora# Create Dictionaryid2word = corpora.Dictionary(data_lemmatized)# Create Corpustexts = data_lemmatized# Term Document Frequencycorpus = [id2word.doc2bow(text) for text in texts]# Viewprint(corpus[:1])"
},
{
"code": null,
"e": 12129,
"s": 11996,
"text": "Gensim creates a unique id for each word in the document. The produced corpus shown above is a mapping of (word_id, word_frequency)."
},
{
"code": null,
"e": 12260,
"s": 12129,
"text": "For example, (0, 7) above implies, word id 0 occurs seven times in the first document. Likewise, word id 1 occurs thrice and so on"
},
{
"code": null,
"e": 12604,
"s": 12260,
"text": "We have everything required to train the base LDA model. In addition to the corpus and dictionary, you need to provide the number of topics as well. Apart from that, alpha and eta are hyperparameters that affect sparsity of the topics. According to the Gensim docs, both defaults to 1.0/num_topics prior (we’ll use default for the base model)."
},
{
"code": null,
"e": 12805,
"s": 12604,
"text": "chunksize controls how many documents are processed at a time in the training algorithm. Increasing chunksize will speed up training, at least as long as the chunk of documents easily fit into memory."
},
{
"code": null,
"e": 13123,
"s": 12805,
"text": "passes controls how often we train the model on the entire corpus (set to 10). Another word for passes might be “epochs”. iterations is somewhat technical, but essentially it controls how often we repeat a particular loop over each document. It is important to set the number of “passes” and “iterations” high enough."
},
{
"code": null,
"e": 13521,
"s": 13123,
"text": "# Build LDA modellda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=10, random_state=100, chunksize=100, passes=10, per_word_topics=True)"
},
{
"code": null,
"e": 13550,
"s": 13521,
"text": "View the topics in LDA model"
},
{
"code": null,
"e": 13713,
"s": 13550,
"text": "The above LDA model is built with 10 different topics where each topic is a combination of keywords and each keyword contributes a certain weightage to the topic."
},
{
"code": null,
"e": 13830,
"s": 13713,
"text": "You can see the keywords for each topic and the weightage(importance) of each keyword using lda_model.print_topics()"
},
{
"code": null,
"e": 13951,
"s": 13830,
"text": "from pprint import pprint# Print the Keyword in the 10 topicspprint(lda_model.print_topics())doc_lda = lda_model[corpus]"
},
{
"code": null,
"e": 13996,
"s": 13951,
"text": "Compute Model Perplexity and Coherence Score"
},
{
"code": null,
"e": 14041,
"s": 13996,
"text": "Let’s calculate the baseline coherence score"
},
{
"code": null,
"e": 14314,
"s": 14041,
"text": "from gensim.models import CoherenceModel# Compute Coherence Scorecoherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')coherence_lda = coherence_model_lda.get_coherence()print('\\nCoherence Score: ', coherence_lda)"
},
{
"code": null,
"e": 14337,
"s": 14314,
"text": "Coherence Score: 0.301"
},
{
"code": null,
"e": 14417,
"s": 14337,
"text": "First, let’s differentiate between model hyperparameters and model parameters :"
},
{
"code": null,
"e": 14651,
"s": 14417,
"text": "Model hyperparameters can be thought of as settings for a machine learning algorithm that are tuned by the data scientist before training. Examples would be the number of trees in the random forest, or in our case, number of topics K"
},
{
"code": null,
"e": 14779,
"s": 14651,
"text": "Model parameters can be thought of as what the model learns during training, such as the weights for each word in a given topic"
},
{
"code": null,
"e": 14951,
"s": 14779,
"text": "Now that we have the baseline coherence score for the default LDA model, let’s perform a series of sensitivity tests to help determine the following model hyperparameters:"
},
{
"code": null,
"e": 15075,
"s": 14951,
"text": "Number of Topics (K)Dirichlet hyperparameter alpha: Document-Topic DensityDirichlet hyperparameter beta: Word-Topic Density"
},
{
"code": null,
"e": 15096,
"s": 15075,
"text": "Number of Topics (K)"
},
{
"code": null,
"e": 15151,
"s": 15096,
"text": "Dirichlet hyperparameter alpha: Document-Topic Density"
},
{
"code": null,
"e": 15201,
"s": 15151,
"text": "Dirichlet hyperparameter beta: Word-Topic Density"
},
{
"code": null,
"e": 15416,
"s": 15201,
"text": "We’ll perform these tests in sequence, one parameter at a time by keeping others constant and run them over the two different validation corpus sets. We’ll use C_v as our choice of metric for performance comparison"
},
{
"code": null,
"e": 16117,
"s": 15416,
"text": "# supporting functiondef compute_coherence_values(corpus, dictionary, k, a, b): lda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=dictionary, num_topics=k, random_state=100, chunksize=100, passes=10, alpha=a, eta=b) coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v') return coherence_model_lda.get_coherence()"
},
{
"code": null,
"e": 16216,
"s": 16117,
"text": "Let’s call the function, and iterate it over the range of topics, alpha, and beta parameter values"
},
{
"code": null,
"e": 18140,
"s": 16216,
"text": "import numpy as npimport tqdmgrid = {}grid['Validation_Set'] = {}# Topics rangemin_topics = 2max_topics = 11step_size = 1topics_range = range(min_topics, max_topics, step_size)# Alpha parameteralpha = list(np.arange(0.01, 1, 0.3))alpha.append('symmetric')alpha.append('asymmetric')# Beta parameterbeta = list(np.arange(0.01, 1, 0.3))beta.append('symmetric')# Validation setsnum_of_docs = len(corpus)corpus_sets = [# gensim.utils.ClippedCorpus(corpus, num_of_docs*0.25), # gensim.utils.ClippedCorpus(corpus, num_of_docs*0.5), gensim.utils.ClippedCorpus(corpus, num_of_docs*0.75), corpus]corpus_title = ['75% Corpus', '100% Corpus']model_results = {'Validation_Set': [], 'Topics': [], 'Alpha': [], 'Beta': [], 'Coherence': [] }# Can take a long time to runif 1 == 1: pbar = tqdm.tqdm(total=540) # iterate through validation corpuses for i in range(len(corpus_sets)): # iterate through number of topics for k in topics_range: # iterate through alpha values for a in alpha: # iterare through beta values for b in beta: # get the coherence score for the given parameters cv = compute_coherence_values(corpus=corpus_sets[i], dictionary=id2word, k=k, a=a, b=b) # Save the model results model_results['Validation_Set'].append(corpus_title[i]) model_results['Topics'].append(k) model_results['Alpha'].append(a) model_results['Beta'].append(b) model_results['Coherence'].append(cv) pbar.update(1) pd.DataFrame(model_results).to_csv('lda_tuning_results.csv', index=False) pbar.close()"
},
{
"code": null,
"e": 18341,
"s": 18140,
"text": "Let’s start by determining the optimal number of topics. The chart below outlines the coherence score, C_v, for the number of topics across two validation sets, and a fixed alpha = 0.01 and beta = 0.1"
},
{
"code": null,
"e": 18553,
"s": 18341,
"text": "With the coherence score seems to keep increasing with the number of topics, it may make better sense to pick the model that gave the highest CV before flattening out or a major drop. In this case, we picked K=8"
},
{
"code": null,
"e": 18775,
"s": 18553,
"text": "Next, we want to select the optimal alpha and beta parameters. While there are other sophisticated approaches to tackle the selection process, for this tutorial, we choose the values that yielded maximum C_v score for K=8"
},
{
"code": null,
"e": 18786,
"s": 18775,
"text": "alpha=0.01"
},
{
"code": null,
"e": 18795,
"s": 18786,
"text": "beta=0.9"
},
{
"code": null,
"e": 18799,
"s": 18795,
"text": "K=8"
},
{
"code": null,
"e": 18859,
"s": 18799,
"text": "That yields approx. 17% improvement over the baseline score"
},
{
"code": null,
"e": 18923,
"s": 18859,
"text": "Let’s train the final model using the above selected parameters"
},
{
"code": null,
"e": 19368,
"s": 18923,
"text": "lda_model = gensim.models.LdaMulticore(corpus=corpus, id2word=id2word, num_topics=8, random_state=100, chunksize=100, passes=10, alpha=0.01, eta=0.9)"
},
{
"code": null,
"e": 19552,
"s": 19368,
"text": "import pyLDAvis.gensimimport pickle import pyLDAvis# Visualize the topicspyLDAvis.enable_notebook()LDAvis_prepared = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)LDAvis_prepared"
},
{
"code": null,
"e": 19922,
"s": 19552,
"text": "We started with understanding why evaluating the topic model is essential. Next, we reviewed existing methods and scratched the surface of topic coherence, along with the available coherence measures. Then we built a default LDA model using Gensim implementation to establish the baseline coherence score and reviewed practical ways to optimize the LDA hyperparameters."
},
{
"code": null,
"e": 20045,
"s": 19922,
"text": "Hopefully, this article has managed to shed light on the underlying topic evaluation strategies, and intuitions behind it."
},
{
"code": null,
"e": 20057,
"s": 20045,
"text": "References:"
},
{
"code": null,
"e": 20570,
"s": 20057,
"text": "http://qpleple.com/perplexity-to-evaluate-topic-models/https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdfhttps://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynbhttps://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdfhttp://palmetto.aksw.org/palmetto-webapp/"
},
{
"code": null,
"e": 20626,
"s": 20570,
"text": "http://qpleple.com/perplexity-to-evaluate-topic-models/"
},
{
"code": null,
"e": 20718,
"s": 20626,
"text": "https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020"
},
{
"code": null,
"e": 20809,
"s": 20718,
"text": "https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdf"
},
{
"code": null,
"e": 20912,
"s": 20809,
"text": "https://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynb"
},
{
"code": null,
"e": 20982,
"s": 20912,
"text": "https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/"
},
{
"code": null,
"e": 21047,
"s": 20982,
"text": "http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf"
},
{
"code": null,
"e": 21089,
"s": 21047,
"text": "http://palmetto.aksw.org/palmetto-webapp/"
},
{
"code": null,
"e": 21264,
"s": 21089,
"text": "Thanks for reading. If you have any feedback, please feel to reach out by commenting on this post, messaging me on LinkedIn, or shooting me an email (shmkapadia[at]gmail.com)"
}
] |
Difference between Preprocessor Directives and Function Templates in C++ - GeeksforGeeks
|
05 Jan, 2021
Preprocessor Directives are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++.
Below is the program to illustrate the functionality of Function Templates:
C++
// C++ program to illustrate
// preprocessor directives
#include <bits/stdc++.h>
#define min(a, b) ((a < b) ? a : b)
using namespace std;
// Driver code
int main()
{
int a = 2, b = 4;
// Find the minimum of a and b
cout << "Minimum of both is: "
<< min(a, b);
return 0;
}
Minimum of both is: 2
Function Templates are the generic function that can handle different data types without the need for any separate code.
Below is the program to illustrate the functionality of Function Templates:
C++
// C++ program to illustrate the use
// of Function Templates
#include <iostream>
#include <stdio.h>
using namespace std;
// Function Template
template <class T>
T Min(T x, T y)
{
return (x < y) ? x : y;
}
// Driver Code
int main()
{
int a = 4, b = 8;
// Find the minimum of a and b
cout << "Minimum of both is: " << min(a, b);
return 0;
}
Minimum of both is: 4
Function templates are used to make generic functions that can work with any data type. For example, the function template used for calculating the minimum of 2 values of any type can be defined as:
template <class T>
T minimum(T a, T b)
{
return (a < b) ? a : b;
}
But, this task can also be performed using Pre-processor directives created using preprocessor directive #define. So, the minimum of the two numbers can be defined as as:
#define minimum(a, b) ((a < b) ? a : b)
The Pre-processor directives can also be achieved by using the below statements:
minimum(30, 35);
minimum(30.5, 40.5);
In C++, most of us prefer using templates over Pre-processor directives because:
In the case of Pre-processor directives, there is no type checking. But in the case of templates, full type checking is done by the compiler.
Pre-processor directives can call an unexpected result. Consider a macro that calculates the square of any number as:
#define sqr(x) (x*x)
Now if this macro is called using the following statement, x = sqr(4 + 4); then expected output is 64 but it generates 24 because any x in macro body replaced by 4 + 4 which leads to x = 4 + 4 * 4 + 4 = 24 but in the case of templates, such unexpected results are not obtained.
Below is the tabular difference between the two:
Templates
Articles
C++
C++ Programs
Difference Between
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Min Heap and Max Heap
SQL | Date functions
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
|
[
{
"code": null,
"e": 24107,
"s": 24076,
"text": " \n05 Jan, 2021\n"
},
{
"code": null,
"e": 24292,
"s": 24107,
"text": "Preprocessor Directives are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++."
},
{
"code": null,
"e": 24368,
"s": 24292,
"text": "Below is the program to illustrate the functionality of Function Templates:"
},
{
"code": null,
"e": 24372,
"s": 24368,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate \n// preprocessor directives \n#include <bits/stdc++.h> \n \n#define min(a, b) ((a < b) ? a : b) \n \nusing namespace std; \n \n// Driver code \nint main() \n{ \n int a = 2, b = 4; \n \n // Find the minimum of a and b \n cout << \"Minimum of both is: \"\n << min(a, b); \n \n return 0; \n} \n\n\n\n\n\n",
"e": 24720,
"s": 24382,
"text": null
},
{
"code": null,
"e": 24743,
"s": 24720,
"text": "Minimum of both is: 2\n"
},
{
"code": null,
"e": 24864,
"s": 24743,
"text": "Function Templates are the generic function that can handle different data types without the need for any separate code."
},
{
"code": null,
"e": 24940,
"s": 24864,
"text": "Below is the program to illustrate the functionality of Function Templates:"
},
{
"code": null,
"e": 24944,
"s": 24940,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate the use \n// of Function Templates \n#include <iostream> \n#include <stdio.h> \nusing namespace std; \n \n// Function Template \ntemplate <class T> \nT Min(T x, T y) \n{ \n return (x < y) ? x : y; \n} \n \n// Driver Code \nint main() \n{ \n int a = 4, b = 8; \n \n // Find the minimum of a and b \n cout << \"Minimum of both is: \" << min(a, b); \n \n return 0; \n} \n\n\n\n\n\n",
"e": 25358,
"s": 24954,
"text": null
},
{
"code": null,
"e": 25381,
"s": 25358,
"text": "Minimum of both is: 4\n"
},
{
"code": null,
"e": 25580,
"s": 25381,
"text": "Function templates are used to make generic functions that can work with any data type. For example, the function template used for calculating the minimum of 2 values of any type can be defined as:"
},
{
"code": null,
"e": 25650,
"s": 25580,
"text": "template <class T>\nT minimum(T a, T b)\n{\n return (a < b) ? a : b;\n}"
},
{
"code": null,
"e": 25821,
"s": 25650,
"text": "But, this task can also be performed using Pre-processor directives created using preprocessor directive #define. So, the minimum of the two numbers can be defined as as:"
},
{
"code": null,
"e": 25861,
"s": 25821,
"text": "#define minimum(a, b) ((a < b) ? a : b)"
},
{
"code": null,
"e": 25942,
"s": 25861,
"text": "The Pre-processor directives can also be achieved by using the below statements:"
},
{
"code": null,
"e": 25980,
"s": 25942,
"text": "minimum(30, 35);\nminimum(30.5, 40.5);"
},
{
"code": null,
"e": 26061,
"s": 25980,
"text": "In C++, most of us prefer using templates over Pre-processor directives because:"
},
{
"code": null,
"e": 26203,
"s": 26061,
"text": "In the case of Pre-processor directives, there is no type checking. But in the case of templates, full type checking is done by the compiler."
},
{
"code": null,
"e": 26321,
"s": 26203,
"text": "Pre-processor directives can call an unexpected result. Consider a macro that calculates the square of any number as:"
},
{
"code": null,
"e": 26342,
"s": 26321,
"text": "#define sqr(x) (x*x)"
},
{
"code": null,
"e": 26620,
"s": 26342,
"text": "Now if this macro is called using the following statement, x = sqr(4 + 4); then expected output is 64 but it generates 24 because any x in macro body replaced by 4 + 4 which leads to x = 4 + 4 * 4 + 4 = 24 but in the case of templates, such unexpected results are not obtained."
},
{
"code": null,
"e": 26669,
"s": 26620,
"text": "Below is the tabular difference between the two:"
},
{
"code": null,
"e": 26681,
"s": 26669,
"text": "\nTemplates\n"
},
{
"code": null,
"e": 26692,
"s": 26681,
"text": "\nArticles\n"
},
{
"code": null,
"e": 26698,
"s": 26692,
"text": "\nC++\n"
},
{
"code": null,
"e": 26713,
"s": 26698,
"text": "\nC++ Programs\n"
},
{
"code": null,
"e": 26734,
"s": 26713,
"text": "\nDifference Between\n"
},
{
"code": null,
"e": 26757,
"s": 26734,
"text": "\nProgramming Language\n"
},
{
"code": null,
"e": 26962,
"s": 26757,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26999,
"s": 26962,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 27025,
"s": 26999,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27072,
"s": 27025,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 27113,
"s": 27072,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 27134,
"s": 27113,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 27152,
"s": 27134,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27168,
"s": 27152,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27214,
"s": 27168,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27257,
"s": 27214,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Two Mirror Trees | Practice | GeeksforGeeks
|
Given a Two Binary Trees, write a function that returns true if one is mirror of other, else returns false.
Example 1:
Input:
T1: 1 T2: 1
/ \ / \
2 3 3 2
Output: 1
Example 2:
Input:
T1: 10 T2: 10
/ \ / \
20 30 20 30
/ \ / \
40 60 40 60
Output: 0
Your Task:
You don't need to take input. Just complete the function areMirror() that takes root node of two tree as parameter and returns true, if one is the mirror of other else returns false. (The driver's code print 1 if the returned value is true, otherwise 0)
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= Number of nodes<= 10000
-1000 <= Data of a node<= 1000
0
anuragkr8981 month ago
Java solution in 2 lines!
class Solution {
boolean areMirror(Node a, Node b) {
if(a==null || b==null) return a==b;
return (a.data==b.data) && areMirror(a.left, b.right) && areMirror(a.right, b.left);
}
}
0
vrajeshmodi992 months ago
int areMirror(Node* a, Node* b) {
if(!a && !b)return 1;
if(!a || !b)return 0;
if(a->data != b->data)return 0;
return areMirror(a->left,b->right) || areMirror(a->right,b->left);
}
0
anonymous0022 months ago
The Simplest One !!
class Solution {
boolean areMirror(Node a, Node b) {
if(a == null || b == null){
return a == b ;
}
if(a.data != b.data){
return false ;
}
return areMirror(a.left , b.right) && areMirror(a.right,b.left) ;
}
}
0
mohitm15092 months ago
//Java Time(0.5)
class Solution { boolean areMirror(Node a, Node b) { // Your code here if(a== null && b == null) return true; if(a != null && b== null || a == null && b != null) return false; if ((a!=null && b!=null) && (a.data == b.data)) return(areMirror(a.left,b.right) && areMirror(a.right,b.left)); return false; }}
+1
vedirajnish2 months ago
class Solution {
boolean areMirror(Node a, Node b) {
if(a==null && b==null)return true;
if(a==null &&b!=null ||a!=null && b==null)return false;
if(a.data!=b.data)return false;
return areMirror(a.left,b.right);
}
}
0
abhisheksanwal2 months ago
Simple Python Solution:
def areMirror(self,root1,root2): ''' :param root1,root2: two root of the given trees. :return: True False ''' if root1 is None and root2 is None: return True elif root1 is not None and root2 is not None: return root1.data==root2.data and self.areMirror(root1.left,root2.right) and self.areMirror(root1.right,root2.left) else: return False
0
hridayec202 months ago
int areMirror(Node* a, Node* b) { // Y if(a ==NULL && b==NULL) return 1; if(a ==NULL && b!=NULL || a !=NULL && b==NULL) return 0; if(a->data!=b->data) return 0; if(a->data==b->data) { areMirror(a->left,b->right); }
+1
ashishbutola73 months ago
Javascript -:
areMirror(root1,root2){ //code here const mirror = (root) => { if (!root) return null let leftNode = mirror(root.right) let rightNode = mirror(root.left) root.left = leftNode root.right = rightNode return root } mirror (root1) if (JSON.stringify(root1) === JSON.stringify(root2)) return true return false }
0
mayank20213 months ago
C++class Solution{ public: int areMirror(Node* a, Node* b) {
if(!a && !b) return 1; else if (a==NULL || b==NULL) return 0; else if(a->data != b->data) return 0; else if ( (areMirror(a->left, b->right)) && (areMirror(a->right, b->left)) ) return 1;
}
};
+1
kronizerdeltac3 months ago
JAVA RECURSIVE SOLUTION
NOTE: Similar questions :
https://practice.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1https://practice.geeksforgeeks.org/problems/symmetric-tree/1
https://practice.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1
https://practice.geeksforgeeks.org/problems/symmetric-tree/1
boolean areMirror(Node root1, Node root2) { if (root1 == null && root2 == null) return true;
if (root1 != null && root2 != null && root1.data == root2.data && areMirror(root1.left, root2.right) && areMirror(root1.right, root2.left)) return true; else return false; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 360,
"s": 238,
"text": "Given a Two Binary Trees, write a function that returns true if one is mirror of other, else returns false.\n "
},
{
"code": null,
"e": 371,
"s": 360,
"text": "Example 1:"
},
{
"code": null,
"e": 466,
"s": 371,
"text": "Input:\nT1: 1 T2: 1\n / \\ / \\\n 2 3 3 2\nOutput: 1\n"
},
{
"code": null,
"e": 477,
"s": 466,
"text": "Example 2:"
},
{
"code": null,
"e": 621,
"s": 477,
"text": "Input:\nT1: 10 T2: 10\n / \\ / \\\n 20 30 20 30\n / \\ / \\\n 40 60 40 60\nOutput: 0"
},
{
"code": null,
"e": 1045,
"s": 621,
"text": "\nYour Task:\nYou don't need to take input. Just complete the function areMirror() that takes root node of two tree as parameter and returns true, if one is the mirror of other else returns false. (The driver's code print 1 if the returned value is true, otherwise 0)\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree).\n\nConstraints:\n1 <= Number of nodes<= 10000\n-1000 <= Data of a node<= 1000\n\n "
},
{
"code": null,
"e": 1047,
"s": 1045,
"text": "0"
},
{
"code": null,
"e": 1070,
"s": 1047,
"text": "anuragkr8981 month ago"
},
{
"code": null,
"e": 1096,
"s": 1070,
"text": "Java solution in 2 lines!"
},
{
"code": null,
"e": 1298,
"s": 1096,
"text": "class Solution {\n boolean areMirror(Node a, Node b) {\n if(a==null || b==null) return a==b;\n return (a.data==b.data) && areMirror(a.left, b.right) && areMirror(a.right, b.left);\n }\n}"
},
{
"code": null,
"e": 1300,
"s": 1298,
"text": "0"
},
{
"code": null,
"e": 1326,
"s": 1300,
"text": "vrajeshmodi992 months ago"
},
{
"code": null,
"e": 1568,
"s": 1326,
"text": "int areMirror(Node* a, Node* b) {\n if(!a && !b)return 1;\n \n if(!a || !b)return 0;\n \n if(a->data != b->data)return 0;\n \n return areMirror(a->left,b->right) || areMirror(a->right,b->left);\n }"
},
{
"code": null,
"e": 1570,
"s": 1568,
"text": "0"
},
{
"code": null,
"e": 1595,
"s": 1570,
"text": "anonymous0022 months ago"
},
{
"code": null,
"e": 1615,
"s": 1595,
"text": "The Simplest One !!"
},
{
"code": null,
"e": 1920,
"s": 1615,
"text": "class Solution {\n boolean areMirror(Node a, Node b) {\n \n if(a == null || b == null){\n return a == b ; \n }\n \n if(a.data != b.data){\n return false ;\n }\n \n return areMirror(a.left , b.right) && areMirror(a.right,b.left) ;\n \n }\n}"
},
{
"code": null,
"e": 1922,
"s": 1920,
"text": "0"
},
{
"code": null,
"e": 1945,
"s": 1922,
"text": "mohitm15092 months ago"
},
{
"code": null,
"e": 1962,
"s": 1945,
"text": "//Java Time(0.5)"
},
{
"code": null,
"e": 2312,
"s": 1962,
"text": "class Solution { boolean areMirror(Node a, Node b) { // Your code here if(a== null && b == null) return true; if(a != null && b== null || a == null && b != null) return false; if ((a!=null && b!=null) && (a.data == b.data)) return(areMirror(a.left,b.right) && areMirror(a.right,b.left)); return false; }}"
},
{
"code": null,
"e": 2315,
"s": 2312,
"text": "+1"
},
{
"code": null,
"e": 2339,
"s": 2315,
"text": "vedirajnish2 months ago"
},
{
"code": null,
"e": 2594,
"s": 2339,
"text": "class Solution {\n boolean areMirror(Node a, Node b) {\n if(a==null && b==null)return true;\n if(a==null &&b!=null ||a!=null && b==null)return false;\n if(a.data!=b.data)return false;\n return areMirror(a.left,b.right);\n }\n}"
},
{
"code": null,
"e": 2596,
"s": 2594,
"text": "0"
},
{
"code": null,
"e": 2623,
"s": 2596,
"text": "abhisheksanwal2 months ago"
},
{
"code": null,
"e": 2647,
"s": 2623,
"text": "Simple Python Solution:"
},
{
"code": null,
"e": 3085,
"s": 2649,
"text": "def areMirror(self,root1,root2): ''' :param root1,root2: two root of the given trees. :return: True False ''' if root1 is None and root2 is None: return True elif root1 is not None and root2 is not None: return root1.data==root2.data and self.areMirror(root1.left,root2.right) and self.areMirror(root1.right,root2.left) else: return False"
},
{
"code": null,
"e": 3087,
"s": 3085,
"text": "0"
},
{
"code": null,
"e": 3110,
"s": 3087,
"text": "hridayec202 months ago"
},
{
"code": null,
"e": 3373,
"s": 3110,
"text": "int areMirror(Node* a, Node* b) { // Y if(a ==NULL && b==NULL) return 1; if(a ==NULL && b!=NULL || a !=NULL && b==NULL) return 0; if(a->data!=b->data) return 0; if(a->data==b->data) { areMirror(a->left,b->right); }"
},
{
"code": null,
"e": 3376,
"s": 3373,
"text": "+1"
},
{
"code": null,
"e": 3402,
"s": 3376,
"text": "ashishbutola73 months ago"
},
{
"code": null,
"e": 3419,
"s": 3402,
"text": "Javascript -: "
},
{
"code": null,
"e": 3785,
"s": 3419,
"text": " areMirror(root1,root2){ //code here const mirror = (root) => { if (!root) return null let leftNode = mirror(root.right) let rightNode = mirror(root.left) root.left = leftNode root.right = rightNode return root } mirror (root1) if (JSON.stringify(root1) === JSON.stringify(root2)) return true return false }"
},
{
"code": null,
"e": 3787,
"s": 3785,
"text": "0"
},
{
"code": null,
"e": 3810,
"s": 3787,
"text": "mayank20213 months ago"
},
{
"code": null,
"e": 3875,
"s": 3810,
"text": "C++class Solution{ public: int areMirror(Node* a, Node* b) {"
},
{
"code": null,
"e": 4087,
"s": 3875,
"text": " if(!a && !b) return 1; else if (a==NULL || b==NULL) return 0; else if(a->data != b->data) return 0; else if ( (areMirror(a->left, b->right)) && (areMirror(a->right, b->left)) ) return 1;"
},
{
"code": null,
"e": 4092,
"s": 4087,
"text": " }"
},
{
"code": null,
"e": 4095,
"s": 4092,
"text": "};"
},
{
"code": null,
"e": 4098,
"s": 4095,
"text": "+1"
},
{
"code": null,
"e": 4125,
"s": 4098,
"text": "kronizerdeltac3 months ago"
},
{
"code": null,
"e": 4149,
"s": 4125,
"text": "JAVA RECURSIVE SOLUTION"
},
{
"code": null,
"e": 4177,
"s": 4151,
"text": "NOTE: Similar questions :"
},
{
"code": null,
"e": 4320,
"s": 4177,
"text": "https://practice.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1https://practice.geeksforgeeks.org/problems/symmetric-tree/1"
},
{
"code": null,
"e": 4403,
"s": 4320,
"text": "https://practice.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1"
},
{
"code": null,
"e": 4464,
"s": 4403,
"text": "https://practice.geeksforgeeks.org/problems/symmetric-tree/1"
},
{
"code": null,
"e": 4573,
"s": 4464,
"text": "boolean areMirror(Node root1, Node root2) { if (root1 == null && root2 == null) return true;"
},
{
"code": null,
"e": 4782,
"s": 4573,
"text": " if (root1 != null && root2 != null && root1.data == root2.data && areMirror(root1.left, root2.right) && areMirror(root1.right, root2.left)) return true; else return false; }"
},
{
"code": null,
"e": 4928,
"s": 4782,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4964,
"s": 4928,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4974,
"s": 4964,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4984,
"s": 4974,
"text": "\nContest\n"
},
{
"code": null,
"e": 5047,
"s": 4984,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5195,
"s": 5047,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5403,
"s": 5195,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5509,
"s": 5403,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C++ Program For Deleting A Linked List Node At A Given Position - GeeksforGeeks
|
29 Dec, 2021
Given a singly linked list and a position, delete a linked list node at the given position.
Example:
Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7
Input: position = 0, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
If the node to be deleted is the root, simply delete it. To delete a middle node, we must have a pointer to the node previous to the node to be deleted. So if positions are not zero, we run a loop position-1 times and get a pointer to the previous node.
Below is the implementation of the above idea.
C++
// A complete working C++ program to delete// a node in a linked list at a given position#include <iostream>using namespace std; // A linked list nodeclass Node{ public: int data; Node *next;}; // Given a reference (pointer to pointer) to // the head of a list and an int inserts a // new node on the front of the list. void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Given a reference (pointer to pointer) to// the head of a list and a position, deletes// the node at the given position void deleteNode(Node **head_ref, int position){ // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { // Change head *head_ref = temp->next; // Free old head free(temp); return; } // Find previous node of the node to be deleted for(int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; // If position is more than number of nodes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node *next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory // Unlink the deleted node from list temp->next = next; } // This function prints contents of linked // list starting from the given nodevoid printList( Node *node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); push(&head, 8); cout << "Created Linked List: "; printList(head); deleteNode(&head, 4); cout << "Linked List after Deletion at position 4: "; printList(head); return 0;} // This code is contributed by premsai2030
Output:
Created Linked List:
8 2 3 1 7
Linked List after Deletion at position 4:
8 2 3 1
Please refer complete article on Delete a Linked List node at a given position for more details!
Linked Lists
Samsung
C++
C++ Programs
Linked List
Samsung
Linked List
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 24176,
"s": 24148,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 24268,
"s": 24176,
"text": "Given a singly linked list and a position, delete a linked list node at the given position."
},
{
"code": null,
"e": 24279,
"s": 24268,
"text": "Example: "
},
{
"code": null,
"e": 24445,
"s": 24279,
"text": "Input: position = 1, Linked List = 8->2->3->1->7\nOutput: Linked List = 8->3->1->7\n\nInput: position = 0, Linked List = 8->2->3->1->7\nOutput: Linked List = 2->3->1->7"
},
{
"code": null,
"e": 24699,
"s": 24445,
"text": "If the node to be deleted is the root, simply delete it. To delete a middle node, we must have a pointer to the node previous to the node to be deleted. So if positions are not zero, we run a loop position-1 times and get a pointer to the previous node."
},
{
"code": null,
"e": 24746,
"s": 24699,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 24750,
"s": 24746,
"text": "C++"
},
{
"code": "// A complete working C++ program to delete// a node in a linked list at a given position#include <iostream>using namespace std; // A linked list nodeclass Node{ public: int data; Node *next;}; // Given a reference (pointer to pointer) to // the head of a list and an int inserts a // new node on the front of the list. void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Given a reference (pointer to pointer) to// the head of a list and a position, deletes// the node at the given position void deleteNode(Node **head_ref, int position){ // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { // Change head *head_ref = temp->next; // Free old head free(temp); return; } // Find previous node of the node to be deleted for(int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; // If position is more than number of nodes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node *next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory // Unlink the deleted node from list temp->next = next; } // This function prints contents of linked // list starting from the given nodevoid printList( Node *node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); push(&head, 8); cout << \"Created Linked List: \"; printList(head); deleteNode(&head, 4); cout << \"Linked List after Deletion at position 4: \"; printList(head); return 0;} // This code is contributed by premsai2030",
"e": 26899,
"s": 24750,
"text": null
},
{
"code": null,
"e": 26908,
"s": 26899,
"text": "Output: "
},
{
"code": null,
"e": 27002,
"s": 26908,
"text": "Created Linked List: \n 8 2 3 1 7 \nLinked List after Deletion at position 4: \n 8 2 3 1 "
},
{
"code": null,
"e": 27099,
"s": 27002,
"text": "Please refer complete article on Delete a Linked List node at a given position for more details!"
},
{
"code": null,
"e": 27112,
"s": 27099,
"text": "Linked Lists"
},
{
"code": null,
"e": 27120,
"s": 27112,
"text": "Samsung"
},
{
"code": null,
"e": 27124,
"s": 27120,
"text": "C++"
},
{
"code": null,
"e": 27137,
"s": 27124,
"text": "C++ Programs"
},
{
"code": null,
"e": 27149,
"s": 27137,
"text": "Linked List"
},
{
"code": null,
"e": 27157,
"s": 27149,
"text": "Samsung"
},
{
"code": null,
"e": 27169,
"s": 27157,
"text": "Linked List"
},
{
"code": null,
"e": 27173,
"s": 27169,
"text": "CPP"
},
{
"code": null,
"e": 27271,
"s": 27173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27299,
"s": 27271,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27319,
"s": 27299,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27352,
"s": 27319,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27376,
"s": 27352,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27397,
"s": 27376,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27432,
"s": 27397,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27458,
"s": 27432,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27517,
"s": 27458,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27561,
"s": 27517,
"text": "Program to print ASCII Value of a character"
}
] |
How to select records that begin with a specific value in MySQL?
|
To select records that begin with a specific value, you need to use LIKE operator. Let us first create a table −
mysql> create table DemoTable690(
UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserValue varchar(100)
);
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable690(UserValue) values('567890');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable690(UserValue) values('789032');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable690(UserValue) values('567342');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable690(UserValue) values('890678');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable690;
This will produce the following output −
+--------+-----------+
| UserId | UserValue |
+--------+-----------+
| 1 | 567890 |
| 2 | 789032 |
| 3 | 567342 |
| 4 | 890678 |
+--------+-----------+
4 rows in set (0.00 sec)
Following is the query to select records that begin with a specific value −
mysql> select *from DemoTable690 where UserValue LIKE '567%';
This will produce the following output −
+--------+-----------+
| UserId | UserValue |
+--------+-----------+
| 1 | 567890 |
| 3 | 567342 |
+--------+-----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To select records that begin with a specific value, you need to use LIKE operator. Let us first create a table −"
},
{
"code": null,
"e": 1326,
"s": 1175,
"text": "mysql> create table DemoTable690(\n UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserValue varchar(100)\n);\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1382,
"s": 1326,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1770,
"s": 1382,
"text": "mysql> insert into DemoTable690(UserValue) values('567890');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable690(UserValue) values('789032');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable690(UserValue) values('567342');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable690(UserValue) values('890678');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1830,
"s": 1770,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1864,
"s": 1830,
"text": "mysql> select *from DemoTable690;"
},
{
"code": null,
"e": 1905,
"s": 1864,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2114,
"s": 1905,
"text": "+--------+-----------+\n| UserId | UserValue |\n+--------+-----------+\n| 1 | 567890 |\n| 2 | 789032 |\n| 3 | 567342 |\n| 4 | 890678 |\n+--------+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2190,
"s": 2114,
"text": "Following is the query to select records that begin with a specific value −"
},
{
"code": null,
"e": 2252,
"s": 2190,
"text": "mysql> select *from DemoTable690 where UserValue LIKE '567%';"
},
{
"code": null,
"e": 2293,
"s": 2252,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2456,
"s": 2293,
"text": "+--------+-----------+\n| UserId | UserValue |\n+--------+-----------+\n| 1 | 567890 |\n| 3 | 567342 |\n+--------+-----------+\n2 rows in set (0.00 sec)"
}
] |
Materialize - Buttons
|
Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to the buttons. Following table mentions the available classes and their effects.
btn
Sets button or anchor as a Materialize button, required. Sets raised display effect to a button.
btn-floating
Creates a circular button.
btn-flat
Sets flat display effect to a button, default.
btn-large
Creates large buttons.
disabled
Creates a disabled button.
type="submit"
Represents an anchor or button as a primary button.
waves-effect
Sets ripple click effect, can be used in combination with any other classes.
The following example demonstrates the use of mdl-button classes to show different types of buttons.
<!DOCTYPE html>
<html>
<head>
<title>The Materialize Buttons Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
</head>
<body class="container">
<div class="card-panel">
<h5>Raised Buttons</h5>
<button class="btn waves-effect waves-teal">Add</button></td>
<button class="btn waves-effect waves-teal"><i class="material-icons left">add</i>Add</button></td>
<button class="btn waves-effect waves-teal"><i class="material-icons right">add</i>Add</button></td>
<button class="btn waves-effect waves-teal disabled">Add</button></td>
</div>
<div class="card-panel">
<h5>Flat Buttons</h5>
<button class="btn-flat waves-effect waves-teal">Add</button></td>
<button class="btn-flat waves-effect waves-teal disabled" ><i class="material-icons left">add</i>Add</button></td>
</div>
<div class="card-panel">
<h5>Floating Buttons</h5>
<a class="btn-floating waves-effect waves-light red"><i class="material-icons">add</i></a>
<a class="btn-floating waves-effect waves-light red disabled" ><i class="material-icons">add</i></a>
</div>
<div class="card-panel">
<h5>Primary Buttons</h5>
<button class="btn waves-effect waves-light red" type="submit">Send<i class="material-icons right">send</i></button>
<button class="btn waves-effect waves-light red disabled" type="submit" >Cancel<i class="material-icons right">cancel</i></button>
</div>
<div class="card-panel">
<h5>Large Buttons</h5>
<a class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
<a class="btn-floating btn-large waves-effect waves-light red disabled"><i class="material-icons">add</i></a>
</div>
</body>
</html>
Verify the output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2375,
"s": 2187,
"text": "Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to the buttons. Following table mentions the available classes and their effects."
},
{
"code": null,
"e": 2379,
"s": 2375,
"text": "btn"
},
{
"code": null,
"e": 2476,
"s": 2379,
"text": "Sets button or anchor as a Materialize button, required. Sets raised display effect to a button."
},
{
"code": null,
"e": 2489,
"s": 2476,
"text": "btn-floating"
},
{
"code": null,
"e": 2516,
"s": 2489,
"text": "Creates a circular button."
},
{
"code": null,
"e": 2525,
"s": 2516,
"text": "btn-flat"
},
{
"code": null,
"e": 2572,
"s": 2525,
"text": "Sets flat display effect to a button, default."
},
{
"code": null,
"e": 2582,
"s": 2572,
"text": "btn-large"
},
{
"code": null,
"e": 2605,
"s": 2582,
"text": "Creates large buttons."
},
{
"code": null,
"e": 2614,
"s": 2605,
"text": "disabled"
},
{
"code": null,
"e": 2641,
"s": 2614,
"text": "Creates a disabled button."
},
{
"code": null,
"e": 2655,
"s": 2641,
"text": "type=\"submit\""
},
{
"code": null,
"e": 2707,
"s": 2655,
"text": "Represents an anchor or button as a primary button."
},
{
"code": null,
"e": 2720,
"s": 2707,
"text": "waves-effect"
},
{
"code": null,
"e": 2797,
"s": 2720,
"text": "Sets ripple click effect, can be used in combination with any other classes."
},
{
"code": null,
"e": 2898,
"s": 2797,
"text": "The following example demonstrates the use of mdl-button classes to show different types of buttons."
},
{
"code": null,
"e": 5208,
"s": 2898,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Buttons Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body class=\"container\">\n <div class=\"card-panel\">\n <h5>Raised Buttons</h5>\n <button class=\"btn waves-effect waves-teal\">Add</button></td>\n <button class=\"btn waves-effect waves-teal\"><i class=\"material-icons left\">add</i>Add</button></td>\n <button class=\"btn waves-effect waves-teal\"><i class=\"material-icons right\">add</i>Add</button></td>\n <button class=\"btn waves-effect waves-teal disabled\">Add</button></td>\n </div>\n <div class=\"card-panel\">\n <h5>Flat Buttons</h5>\n <button class=\"btn-flat waves-effect waves-teal\">Add</button></td>\n <button class=\"btn-flat waves-effect waves-teal disabled\" ><i class=\"material-icons left\">add</i>Add</button></td>\n </div>\n <div class=\"card-panel\">\n <h5>Floating Buttons</h5>\n <a class=\"btn-floating waves-effect waves-light red\"><i class=\"material-icons\">add</i></a>\n <a class=\"btn-floating waves-effect waves-light red disabled\" ><i class=\"material-icons\">add</i></a>\n </div>\n <div class=\"card-panel\">\n <h5>Primary Buttons</h5>\n <button class=\"btn waves-effect waves-light red\" type=\"submit\">Send<i class=\"material-icons right\">send</i></button>\n <button class=\"btn waves-effect waves-light red disabled\" type=\"submit\" >Cancel<i class=\"material-icons right\">cancel</i></button>\n </div>\n <div class=\"card-panel\">\n <h5>Large Buttons</h5>\n <a class=\"btn-floating btn-large waves-effect waves-light red\"><i class=\"material-icons\">add</i></a>\n <a class=\"btn-floating btn-large waves-effect waves-light red disabled\"><i class=\"material-icons\">add</i></a>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5227,
"s": 5208,
"text": "Verify the output."
},
{
"code": null,
"e": 5234,
"s": 5227,
"text": " Print"
},
{
"code": null,
"e": 5245,
"s": 5234,
"text": " Add Notes"
}
] |
How to add 30 minutes to datetime in MySQL?
|
To add minutes to a datetime you can use DATE_ADD() function from MySQL. In PHP, you can use strtotime().
To add 30 minutes in MySQL, the DATE_ADD() function is as follows −
select date_add(yourColumnName,interval 30 minute) from yourTableName;
To use the above syntax, let us create a table. The following is the query to create a table.
mysql> create table Add30MinutesDemo
−> (
−> YourTime datetime
−> );
Query OK, 0 rows affected (0.67 sec)
Insert records in the table with the help of following query −
mysql> insert into Add30MinutesDemo values(now());
Query OK, 1 row affected (0.21 sec)
Display records from table with the help of select statement. The query is as follows −
mysql> select *from Add30MinutesDemo;
The following is the output −
+---------------------+
| YourTime |
+---------------------+
| 2018-12-07 18:03:51 |
+---------------------+
1 row in set (0.00 sec)
Here is the MySQL query to add 30 minutes to a column. The query is as follows −
mysql> select date_add(YourTime,interval 30 minute) from Add30MinutesDemo;
The following is the output −
+---------------------------------------+
| date_add(YourTime,interval 30 minute) |
+---------------------------------------+
| 2018-12-07 18:33:51 |
+---------------------------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To add minutes to a datetime you can use DATE_ADD() function from MySQL. In PHP, you can use strtotime()."
},
{
"code": null,
"e": 1236,
"s": 1168,
"text": "To add 30 minutes in MySQL, the DATE_ADD() function is as follows −"
},
{
"code": null,
"e": 1307,
"s": 1236,
"text": "select date_add(yourColumnName,interval 30 minute) from yourTableName;"
},
{
"code": null,
"e": 1401,
"s": 1307,
"text": "To use the above syntax, let us create a table. The following is the query to create a table."
},
{
"code": null,
"e": 1516,
"s": 1401,
"text": "mysql> create table Add30MinutesDemo\n −> (\n −> YourTime datetime\n −> );\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1579,
"s": 1516,
"text": "Insert records in the table with the help of following query −"
},
{
"code": null,
"e": 1666,
"s": 1579,
"text": "mysql> insert into Add30MinutesDemo values(now());\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 1754,
"s": 1666,
"text": "Display records from table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 1792,
"s": 1754,
"text": "mysql> select *from Add30MinutesDemo;"
},
{
"code": null,
"e": 1822,
"s": 1792,
"text": "The following is the output −"
},
{
"code": null,
"e": 1966,
"s": 1822,
"text": "+---------------------+\n| YourTime |\n+---------------------+\n| 2018-12-07 18:03:51 |\n+---------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2047,
"s": 1966,
"text": "Here is the MySQL query to add 30 minutes to a column. The query is as follows −"
},
{
"code": null,
"e": 2122,
"s": 2047,
"text": "mysql> select date_add(YourTime,interval 30 minute) from Add30MinutesDemo;"
},
{
"code": null,
"e": 2152,
"s": 2122,
"text": "The following is the output −"
},
{
"code": null,
"e": 2386,
"s": 2152,
"text": "+---------------------------------------+\n| date_add(YourTime,interval 30 minute) |\n+---------------------------------------+\n| 2018-12-07 18:33:51 |\n+---------------------------------------+\n1 row in set (0.00 sec)"
}
] |
Find the index of first 1 in an infinite sorted array of 0s and 1s - GeeksforGeeks
|
05 Jul, 2021
Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first ‘1’ in that array. As the array is infinite, therefore it is guaranteed that number ‘1’ will be present in the array.Examples:
Input : arr[] = {0, 0, 1, 1, 1, 1}
Output : 2
Input : arr[] = {1, 1, 1, 1,, 1, 1}
Output : 0
Approach: The problem is closely related to the problem of finding position of an element in a sorted array of infinite numbers. As the array is infinite, therefore we do not know the upper and lower bounds between which we have to find the occurrence of first ‘1’. Below is an algorithm to find the upper and lower bounds. Algorithm:
posOfFirstOne(arr)
Declare l = 0, h = 1
while arr[h] == 0
l = h
h = 2*h;
return indexOfFirstOne(arr, l, h)
}
Here h and l are the required upper and lower bounds. indexOfFirstOne(arr, l, h) is used to find the index of occurrence of first ‘1’ between these two bounds. Refer this post.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the index of first 1// in an infinite sorted array of 0's and 1's#include <bits/stdc++.h>using namespace std; // function to find the index of first '1'// binary search technique is appliedint indexOfFirstOne(int arr[], int low, int high){ int mid; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid;} // function to find the index of first 1 in// an infinite sorted array of 0's and 1'sint posOfFirstOne(int arr[]){ // find the upper and lower bounds between // which the first '1' would be present int l = 0, h = 1; // as the array is being considered infinite // therefore 'h' index will always exist in // the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h);} // Driver program to test aboveint main(){ int arr[] = { 0, 0, 1, 1, 1, 1 }; cout << "Index = " << posOfFirstOne(arr); return 0;}
// JAVA Code For Find the index of first 1// in an infinite sorted array of 0s and 1simport java.util.*; class GFG { // function to find the index of first '1' // binary search technique is applied public static int indexOfFirstOne(int arr[], int low, int high) { int mid=0; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of // first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid; } // function to find the index of first 1 in // an infinite sorted array of 0's and 1's public static int posOfFirstOne(int arr[]) { // find the upper and lower bounds // between which the first '1' would // be present int l = 0, h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 0, 0, 1, 1, 1, 1 }; System.out.println("Index = " + posOfFirstOne(arr)); }} // This code is contributed by Arnav Kr. Mandal.
# Python 3 implementation to find the# index of first 1 in an infinite# sorted array of 0's and 1's # function to find the index of first# '1' binary search technique is applieddef indexOfFirstOne(arr, low, high) : while (low <= high) : mid = (low + high) // 2 # if true, then 'mid' is the index # of first '1' if (arr[mid] == 1 and (mid == 0 or arr[mid - 1] == 0)) : break # first '1' lies to the left of 'mid' elif (arr[mid] == 1) : high = mid - 1 # first '1' lies to the right of 'mid' else : low = mid + 1 # required index return mid # function to find the index of first# 1 in an infinite sorted array of 0's# and 1'sdef posOfFirstOne(arr) : # find the upper and lower bounds between # which the first '1' would be present l = 0 h = 1 # as the array is being considered infinite # therefore 'h' index will always exist in # the array while (arr[h] == 0) : # lower bound l = h # upper bound h = 2 * h # required index of first '1' return indexOfFirstOne(arr, l, h) # Driver programarr = [ 0, 0, 1, 1, 1, 1 ]print( "Index = ", posOfFirstOne(arr)) # This code is contributed by Nikita Tiwari.
// C# Code For Find the index of first 1// in an infinite sorted array of 0's and 1'susing System; class GFG { // function to find the index of first '1' // binary search technique is applied public static int indexOfFirstOne(int[] arr, int low, int high) { int mid = 0; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of // first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid; } // function to find the index of first 1 in // an infinite sorted array of 0's and 1's public static int posOfFirstOne(int[] arr) { // find the upper and lower bounds // between which the first '1' would // be present int l = 0, h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h); } /* Driver program to test above function */ public static void Main() { int[] arr = { 0, 0, 1, 1, 1, 1 }; Console.Write("Index = " + posOfFirstOne(arr)); }} // This code is contributed by Sam007
<?php// PHP implementation to find// the index of first 1 in an// infinite sorted array of// 0's and 1's // function to find the index// of first '1' binary search// technique is appliedfunction indexOfFirstOne($arr, $low, $high){ $mid; while ($low <= $high) { $mid = ($low + $high) / 2; // if true, then 'mid' is // the index of first '1' if ($arr[$mid] == 1 and ($mid == 0 or $arr[$mid - 1] == 0)) break; // first '1' lies to // the left of 'mid' else if ($arr[$mid] == 1) $high = $mid - 1; // first '1' lies to // the right of 'mid' else $low = $mid + 1; } // required index return ceil($mid);} // function to find the index of// first 1 in an infinite sorted// array of 0's and 1'sfunction posOfFirstOne($arr){ // find the upper and lower // bounds between which the // first '1' would be present $l = 0; $h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while ($arr[$h] == 0) { // lower bound $l = $h; // upper bound $h = 2 * $h; } // required index // of first '1' return indexOfFirstOne($arr, $l, $h);} // Driver Code$arr = array(0, 0, 1, 1, 1, 1);echo "Index = " , posOfFirstOne($arr); // This code is contributed by anuj_67.?>
<script> // Javascript implementation to find the index of first 1// in an infinite sorted array of 0's and 1's // function to find the index of first '1'// binary search technique is appliedfunction indexOfFirstOne(arr, low, high){ var mid; while (low <= high) { mid = parseInt((low + high) / 2); // if true, then 'mid' is the index of first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid;} // function to find the index of first 1 in// an infinite sorted array of 0's and 1'sfunction posOfFirstOne(arr){ // find the upper and lower bounds between // which the first '1' would be present var l = 0, h = 1; // as the array is being considered infinite // therefore 'h' index will always exist in // the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h);} // Driver program to test abovevar arr = [0, 0, 1, 1, 1, 1];document.write( "Index = " + posOfFirstOne(arr)); // This code is contributed by rrrtnx.</script>
Output:
Index = 2
Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).This article is contributed by Ayush Jauhari. 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.
vt_m
rrrtnx
kapoorsagar226
Amazon
Binary Search
Arrays
Amazon
Arrays
Binary Search
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
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 25532,
"s": 25504,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 25756,
"s": 25532,
"text": "Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first ‘1’ in that array. As the array is infinite, therefore it is guaranteed that number ‘1’ will be present in the array.Examples: "
},
{
"code": null,
"e": 25851,
"s": 25756,
"text": "Input : arr[] = {0, 0, 1, 1, 1, 1} \nOutput : 2\n\nInput : arr[] = {1, 1, 1, 1,, 1, 1}\nOutput : 0"
},
{
"code": null,
"e": 26190,
"s": 25853,
"text": "Approach: The problem is closely related to the problem of finding position of an element in a sorted array of infinite numbers. As the array is infinite, therefore we do not know the upper and lower bounds between which we have to find the occurrence of first ‘1’. Below is an algorithm to find the upper and lower bounds. Algorithm: "
},
{
"code": null,
"e": 26323,
"s": 26190,
"text": "posOfFirstOne(arr)\n Declare l = 0, h = 1\n while arr[h] == 0\n l = h\n h = 2*h;\n return indexOfFirstOne(arr, l, h)\n}"
},
{
"code": null,
"e": 26501,
"s": 26323,
"text": "Here h and l are the required upper and lower bounds. indexOfFirstOne(arr, l, h) is used to find the index of occurrence of first ‘1’ between these two bounds. Refer this post. "
},
{
"code": null,
"e": 26505,
"s": 26501,
"text": "C++"
},
{
"code": null,
"e": 26510,
"s": 26505,
"text": "Java"
},
{
"code": null,
"e": 26518,
"s": 26510,
"text": "Python3"
},
{
"code": null,
"e": 26521,
"s": 26518,
"text": "C#"
},
{
"code": null,
"e": 26525,
"s": 26521,
"text": "PHP"
},
{
"code": null,
"e": 26536,
"s": 26525,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the index of first 1// in an infinite sorted array of 0's and 1's#include <bits/stdc++.h>using namespace std; // function to find the index of first '1'// binary search technique is appliedint indexOfFirstOne(int arr[], int low, int high){ int mid; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid;} // function to find the index of first 1 in// an infinite sorted array of 0's and 1'sint posOfFirstOne(int arr[]){ // find the upper and lower bounds between // which the first '1' would be present int l = 0, h = 1; // as the array is being considered infinite // therefore 'h' index will always exist in // the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h);} // Driver program to test aboveint main(){ int arr[] = { 0, 0, 1, 1, 1, 1 }; cout << \"Index = \" << posOfFirstOne(arr); return 0;}",
"e": 27921,
"s": 26536,
"text": null
},
{
"code": "// JAVA Code For Find the index of first 1// in an infinite sorted array of 0s and 1simport java.util.*; class GFG { // function to find the index of first '1' // binary search technique is applied public static int indexOfFirstOne(int arr[], int low, int high) { int mid=0; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of // first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid; } // function to find the index of first 1 in // an infinite sorted array of 0's and 1's public static int posOfFirstOne(int arr[]) { // find the upper and lower bounds // between which the first '1' would // be present int l = 0, h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 0, 0, 1, 1, 1, 1 }; System.out.println(\"Index = \" + posOfFirstOne(arr)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 29728,
"s": 27921,
"text": null
},
{
"code": "# Python 3 implementation to find the# index of first 1 in an infinite# sorted array of 0's and 1's # function to find the index of first# '1' binary search technique is applieddef indexOfFirstOne(arr, low, high) : while (low <= high) : mid = (low + high) // 2 # if true, then 'mid' is the index # of first '1' if (arr[mid] == 1 and (mid == 0 or arr[mid - 1] == 0)) : break # first '1' lies to the left of 'mid' elif (arr[mid] == 1) : high = mid - 1 # first '1' lies to the right of 'mid' else : low = mid + 1 # required index return mid # function to find the index of first# 1 in an infinite sorted array of 0's# and 1'sdef posOfFirstOne(arr) : # find the upper and lower bounds between # which the first '1' would be present l = 0 h = 1 # as the array is being considered infinite # therefore 'h' index will always exist in # the array while (arr[h] == 0) : # lower bound l = h # upper bound h = 2 * h # required index of first '1' return indexOfFirstOne(arr, l, h) # Driver programarr = [ 0, 0, 1, 1, 1, 1 ]print( \"Index = \", posOfFirstOne(arr)) # This code is contributed by Nikita Tiwari.",
"e": 31045,
"s": 29728,
"text": null
},
{
"code": "// C# Code For Find the index of first 1// in an infinite sorted array of 0's and 1'susing System; class GFG { // function to find the index of first '1' // binary search technique is applied public static int indexOfFirstOne(int[] arr, int low, int high) { int mid = 0; while (low <= high) { mid = (low + high) / 2; // if true, then 'mid' is the index of // first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid; } // function to find the index of first 1 in // an infinite sorted array of 0's and 1's public static int posOfFirstOne(int[] arr) { // find the upper and lower bounds // between which the first '1' would // be present int l = 0, h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h); } /* Driver program to test above function */ public static void Main() { int[] arr = { 0, 0, 1, 1, 1, 1 }; Console.Write(\"Index = \" + posOfFirstOne(arr)); }} // This code is contributed by Sam007",
"e": 32706,
"s": 31045,
"text": null
},
{
"code": "<?php// PHP implementation to find// the index of first 1 in an// infinite sorted array of// 0's and 1's // function to find the index// of first '1' binary search// technique is appliedfunction indexOfFirstOne($arr, $low, $high){ $mid; while ($low <= $high) { $mid = ($low + $high) / 2; // if true, then 'mid' is // the index of first '1' if ($arr[$mid] == 1 and ($mid == 0 or $arr[$mid - 1] == 0)) break; // first '1' lies to // the left of 'mid' else if ($arr[$mid] == 1) $high = $mid - 1; // first '1' lies to // the right of 'mid' else $low = $mid + 1; } // required index return ceil($mid);} // function to find the index of// first 1 in an infinite sorted// array of 0's and 1'sfunction posOfFirstOne($arr){ // find the upper and lower // bounds between which the // first '1' would be present $l = 0; $h = 1; // as the array is being considered // infinite therefore 'h' index will // always exist in the array while ($arr[$h] == 0) { // lower bound $l = $h; // upper bound $h = 2 * $h; } // required index // of first '1' return indexOfFirstOne($arr, $l, $h);} // Driver Code$arr = array(0, 0, 1, 1, 1, 1);echo \"Index = \" , posOfFirstOne($arr); // This code is contributed by anuj_67.?>",
"e": 34140,
"s": 32706,
"text": null
},
{
"code": "<script> // Javascript implementation to find the index of first 1// in an infinite sorted array of 0's and 1's // function to find the index of first '1'// binary search technique is appliedfunction indexOfFirstOne(arr, low, high){ var mid; while (low <= high) { mid = parseInt((low + high) / 2); // if true, then 'mid' is the index of first '1' if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0)) break; // first '1' lies to the left of 'mid' else if (arr[mid] == 1) high = mid - 1; // first '1' lies to the right of 'mid' else low = mid + 1; } // required index return mid;} // function to find the index of first 1 in// an infinite sorted array of 0's and 1'sfunction posOfFirstOne(arr){ // find the upper and lower bounds between // which the first '1' would be present var l = 0, h = 1; // as the array is being considered infinite // therefore 'h' index will always exist in // the array while (arr[h] == 0) { // lower bound l = h; // upper bound h = 2 * h; } // required index of first '1' return indexOfFirstOne(arr, l, h);} // Driver program to test abovevar arr = [0, 0, 1, 1, 1, 1];document.write( \"Index = \" + posOfFirstOne(arr)); // This code is contributed by rrrtnx.</script>",
"e": 35515,
"s": 34140,
"text": null
},
{
"code": null,
"e": 35525,
"s": 35515,
"text": "Output: "
},
{
"code": null,
"e": 35535,
"s": 35525,
"text": "Index = 2"
},
{
"code": null,
"e": 36283,
"s": 35535,
"text": "Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).This article is contributed by Ayush Jauhari. 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": 36288,
"s": 36283,
"text": "vt_m"
},
{
"code": null,
"e": 36295,
"s": 36288,
"text": "rrrtnx"
},
{
"code": null,
"e": 36310,
"s": 36295,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 36317,
"s": 36310,
"text": "Amazon"
},
{
"code": null,
"e": 36331,
"s": 36317,
"text": "Binary Search"
},
{
"code": null,
"e": 36338,
"s": 36331,
"text": "Arrays"
},
{
"code": null,
"e": 36345,
"s": 36338,
"text": "Amazon"
},
{
"code": null,
"e": 36352,
"s": 36345,
"text": "Arrays"
},
{
"code": null,
"e": 36366,
"s": 36352,
"text": "Binary Search"
},
{
"code": null,
"e": 36464,
"s": 36366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36532,
"s": 36464,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36580,
"s": 36532,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36624,
"s": 36580,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36656,
"s": 36624,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36679,
"s": 36656,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36693,
"s": 36679,
"text": "Linear Search"
},
{
"code": null,
"e": 36738,
"s": 36693,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36759,
"s": 36738,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36844,
"s": 36759,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
How to find the average of non-zero values in a Python dictionary?
|
You can do this by iterating over the dictionary and filtering out zero values first. Then take the sum of the filtered values. Finally, divide by the number of these filtered values.
my_dict = {"foo": 100, "bar": 0, "baz": 200}
filtered_vals = [v for _, v in my_dict.items() if v != 0]
average = sum(filtered_vals) / len(filtered_vals)
print(average)
This will give the output −
150.0
You can also use reduce but for a simple task such as this, it is an overkill. And it is also much less readable than using a list comprehension.
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "You can do this by iterating over the dictionary and filtering out zero values first. Then take the sum of the filtered values. Finally, divide by the number of these filtered values. "
},
{
"code": null,
"e": 1415,
"s": 1247,
"text": "my_dict = {\"foo\": 100, \"bar\": 0, \"baz\": 200}\nfiltered_vals = [v for _, v in my_dict.items() if v != 0]\naverage = sum(filtered_vals) / len(filtered_vals)\nprint(average)"
},
{
"code": null,
"e": 1443,
"s": 1415,
"text": "This will give the output −"
},
{
"code": null,
"e": 1449,
"s": 1443,
"text": "150.0"
},
{
"code": null,
"e": 1595,
"s": 1449,
"text": "You can also use reduce but for a simple task such as this, it is an overkill. And it is also much less readable than using a list comprehension."
}
] |
SimpleDateFormat(“HH:mm:ss Z”) in Java
|
The Z means "zero hour offset", also known as "Zulu time" (UTC) in the ISO 8601 time representation. However, ACP 121 standard defines the list of military time zones and derives the "Zulu time" from theGreenwich Mean Time (GMT).
Let us see the usage of SimpleDateFormat(“HH:mm:ss Z”) −
Format f = new SimpleDateFormat("HH.mm.ss Z");
String strResult = f.format(new Date());
System.out.println("Time = "+strResult);
The following is the complete example that displays time with offset (HH:mm:ss Z) −
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
// current time
Format f = new SimpleDateFormat("HH.mm.ss Z");
String strResult = f.format(new Date());
System.out.println("Time = "+strResult);
// displaying hour
f = new SimpleDateFormat("H");
String strHour = f.format(new Date());
System.out.println("Current Hour = "+strHour);
// displaying minutes
f = new SimpleDateFormat("mm");
String strMinute = f.format(new Date());
System.out.println("Current Minutes = "+strMinute);
// displaying seconds
f = new SimpleDateFormat("ss");
String strSeconds = f.format(new Date());
System.out.println("Current Seconds = "+strSeconds);
}
}
Today's date = 26/November/2018 08:52:33
Time = 08.52.33 +0000
Current Hour = 8
Current Minutes = 52
Current Seconds = 33
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "The Z means \"zero hour offset\", also known as \"Zulu time\" (UTC) in the ISO 8601 time representation. However, ACP 121 standard defines the list of military time zones and derives the \"Zulu time\" from theGreenwich Mean Time (GMT)."
},
{
"code": null,
"e": 1349,
"s": 1292,
"text": "Let us see the usage of SimpleDateFormat(“HH:mm:ss Z”) −"
},
{
"code": null,
"e": 1478,
"s": 1349,
"text": "Format f = new SimpleDateFormat(\"HH.mm.ss Z\");\nString strResult = f.format(new Date());\nSystem.out.println(\"Time = \"+strResult);"
},
{
"code": null,
"e": 1562,
"s": 1478,
"text": "The following is the complete example that displays time with offset (HH:mm:ss Z) −"
},
{
"code": null,
"e": 1573,
"s": 1562,
"text": " Live Demo"
},
{
"code": null,
"e": 2695,
"s": 1573,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy hh:mm:s\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // current time\n Format f = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strResult = f.format(new Date());\n System.out.println(\"Time = \"+strResult);\n // displaying hour\n f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n }\n}"
},
{
"code": null,
"e": 2817,
"s": 2695,
"text": "Today's date = 26/November/2018 08:52:33\nTime = 08.52.33 +0000\nCurrent Hour = 8\nCurrent Minutes = 52\nCurrent Seconds = 33"
}
] |
ReactJS – Axios Interceptors
|
In this article, we are going to learn how to intercept every request or response that is being sent by Axios Interceptors in a React application.
Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.
In this example, we will build a React application that automatically checks and logs the status code that is sent by the server while sending a POST request from our React application.
We have to set all the configuration in the most global file, i.e. index.js, to intercept every request/response.
import React from 'react';
import App from './App';
import ReactDOM from 'react-dom';
import axios from 'axios';
// For GET requests
axios.interceptors.request.use(
(req) => {
// Add configurations here
return req;
},
(err) => {
return Promise.reject(err);
}
);
// For POST requests
axios.interceptors.response.use(
(res) => {
// Add configurations here
if (res.status === 201) {
console.log('Posted Successfully');
}
return res;
},
(err) => {
return Promise.reject(err);
}
);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
import React, { useEffect, useState } from 'react';
import './App.css';
const App = () => {
const [data, setData] = useState(null);
const [val, setVal] = useState('');
const [fetchData, setFetch] = useState(false);
useEffect(() => {
if (fetchData) {
const payload = {
method: 'POST',
body: JSON.stringify({ title: val }),
};
axios.post('https://jsonplaceholder.typicode.com/posts', payload)
.then((res) => setData(res.data.id));
}
}, [fetchData]);
return (
<>
{data && <h1>Your data is saved with Id: {data}</h1>}
<input
placeholder="Title of Post"
value={val}
onChange={(e) => setVal(e.target.value)}
/>
<button onClick={() => setFetch(true)}>Save Data</button>
);
};
export default App;
In the above example, when the request is sent with the data, the response is intercepted and if the status code is 201, then it will log the message 'Posted Successfully'.
This will produce the following result.
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In this article, we are going to learn how to intercept every request or response that is being sent by Axios Interceptors in a React application."
},
{
"code": null,
"e": 1425,
"s": 1209,
"text": "Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received."
},
{
"code": null,
"e": 1611,
"s": 1425,
"text": "In this example, we will build a React application that automatically checks and logs the status code that is sent by the server while sending a POST request from our React application."
},
{
"code": null,
"e": 1725,
"s": 1611,
"text": "We have to set all the configuration in the most global file, i.e. index.js, to intercept every request/response."
},
{
"code": null,
"e": 2401,
"s": 1725,
"text": "import React from 'react';\nimport App from './App';\nimport ReactDOM from 'react-dom';\nimport axios from 'axios';\n\n// For GET requests\naxios.interceptors.request.use(\n (req) => {\n // Add configurations here\n return req;\n },\n (err) => {\n return Promise.reject(err);\n }\n);\n\n// For POST requests\naxios.interceptors.response.use(\n (res) => {\n // Add configurations here\n if (res.status === 201) {\n console.log('Posted Successfully');\n }\n return res;\n },\n (err) => {\n return Promise.reject(err);\n }\n);\n\nReactDOM.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 3233,
"s": 2401,
"text": "import React, { useEffect, useState } from 'react';\nimport './App.css';\nconst App = () => {\n const [data, setData] = useState(null);\n const [val, setVal] = useState('');\n const [fetchData, setFetch] = useState(false);\n\n useEffect(() => {\n\n if (fetchData) {\n const payload = {\n method: 'POST',\n body: JSON.stringify({ title: val }),\n };\n axios.post('https://jsonplaceholder.typicode.com/posts', payload)\n.then((res) => setData(res.data.id));\n }\n }, [fetchData]);\n return (\n <>\n {data && <h1>Your data is saved with Id: {data}</h1>}\n <input\n placeholder=\"Title of Post\"\n value={val}\n onChange={(e) => setVal(e.target.value)}\n />\n <button onClick={() => setFetch(true)}>Save Data</button>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 3406,
"s": 3233,
"text": "In the above example, when the request is sent with the data, the response is intercepted and if the status code is 201, then it will log the message 'Posted Successfully'."
},
{
"code": null,
"e": 3446,
"s": 3406,
"text": "This will produce the following result."
}
] |
Python Program to Find the Sum of Digits in a Number without Recursion
|
When it is required to find the sum of digits in a number without using the method of recursion, the ‘%’ operator, the ‘+’ operator and the ‘//’ operator can be used.
Below is a demonstration for the same −
Live Demo
def sum_of_digits(my_num):
sum_val = 0
while (my_num != 0):
sum_val = sum_val + (my_num % 10)
my_num = my_num//10
return sum_val
my_num = 12345671
print("The number is : ")
print(my_num)
print("The method to calculate sum of digits is being called...")
print("The sum of " +str(my_num) + " is : ")
print(sum_of_digits(my_num))
The number is :
12345671
The method to calculate sum of digits is being called...
The sum of 12345671 is :
29
A method named ‘sum_of_digits’ is defined, that takes a number as parameter.
A sum is initially assigned to 0.
The number is divided by 10 and the remainder obtained is added to the sum.
The number is again floor divided by 10 and assigned to the number itself.
The sum value is returned as output from the function.
A number is defined, and is displayed on the console.
The method is called by passing this number as a parameter.
The output id displayed on the console.
|
[
{
"code": null,
"e": 1229,
"s": 1062,
"text": "When it is required to find the sum of digits in a number without using the method of recursion, the ‘%’ operator, the ‘+’ operator and the ‘//’ operator can be used."
},
{
"code": null,
"e": 1269,
"s": 1229,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1280,
"s": 1269,
"text": " Live Demo"
},
{
"code": null,
"e": 1628,
"s": 1280,
"text": "def sum_of_digits(my_num):\n sum_val = 0\n while (my_num != 0):\n sum_val = sum_val + (my_num % 10)\n my_num = my_num//10\n return sum_val\nmy_num = 12345671\nprint(\"The number is : \")\nprint(my_num)\nprint(\"The method to calculate sum of digits is being called...\")\nprint(\"The sum of \" +str(my_num) + \" is : \")\nprint(sum_of_digits(my_num))"
},
{
"code": null,
"e": 1738,
"s": 1628,
"text": "The number is :\n12345671\nThe method to calculate sum of digits is being called...\nThe sum of 12345671 is :\n29"
},
{
"code": null,
"e": 1815,
"s": 1738,
"text": "A method named ‘sum_of_digits’ is defined, that takes a number as parameter."
},
{
"code": null,
"e": 1849,
"s": 1815,
"text": "A sum is initially assigned to 0."
},
{
"code": null,
"e": 1925,
"s": 1849,
"text": "The number is divided by 10 and the remainder obtained is added to the sum."
},
{
"code": null,
"e": 2000,
"s": 1925,
"text": "The number is again floor divided by 10 and assigned to the number itself."
},
{
"code": null,
"e": 2055,
"s": 2000,
"text": "The sum value is returned as output from the function."
},
{
"code": null,
"e": 2109,
"s": 2055,
"text": "A number is defined, and is displayed on the console."
},
{
"code": null,
"e": 2169,
"s": 2109,
"text": "The method is called by passing this number as a parameter."
},
{
"code": null,
"e": 2209,
"s": 2169,
"text": "The output id displayed on the console."
}
] |
4294967295-gon Number - GeeksforGeeks
|
24 Mar, 2021
4294967295-gon Number is a class of figurate numbers. It has a 4294967295 sided polygon called 4294967295-gon. The N-th 4294967295-gon number counts the 4294967295 number of dots and all other dots are surrounding with a common sharing corner and make a pattern.The first few 4294967295-gonol numbers are:
1, 4294967295, 12884901882,...
Given a number N, the task is to find Nth 4294967295-gon number. Examples:
Input: N = 2 Output: 4294967295 Explanation: The second 4294967295-gonol number is 4294967295. Input: N = 3 Output: 12884901882
Approach: The N-th 4294967295-gon number is given by the formula:
N-th term of S sided polygon =
Therefore N-th term of 4294967295 sided polygon is given by:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find N-th// TetracontapentagonNum number#include<bits/stdc++.h>using namespace std; // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codeint main(){ int n = 3; cout << "3rd 4294967295-gon Number is " << gonNum4294967295(n);} // This code is contributed by Code_Mech
// Java program to find N-th// TetracontapentagonNum numberclass GFG{ // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codepublic static void main(String[] args){ int n = 3; System.out.print("3rd 4294967295-gon Number is " + gonNum4294967295(n));}} // This code is contributed by Pratima Pandey
# Python3 program to find the N-th# 4294967295-gon number # Function to find the N-th# 4294967295-gon numberdef gonNum4294967295(N): return (4294967293 * N * N - 4294967291 * N) // 2 # Driver Code # Given Numbern = 3 # Function Callprint("3rd 4294967295-gon Number is ", gonNum4294967295(n))
// C# program to find N-th// TetracontapentagonNum numberusing System;class GFG{ // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codepublic static void Main(){ int n = 3; Console.Write("3rd 4294967295-gon Number is " + gonNum4294967295(n));}} // This code is contributed by Code_Mech
<script>// Javascript program to find N-th// TetracontapentagonNum number // Function to find the nth // 4294967295-gon number function gonNum4294967295(N) { return ((4294967293 * N * N ) - (4294967291 * N)) / 2; } // Driver code let n = 3; document.write("3rd 4294967295-gon Number is " + gonNum4294967295(n)); // This code is contributed by aashish1995</script>
3rd 4294967295-gon Number is 12884901882
dewantipandeydp
Code_Mech
aashish1995
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Program to multiply two matrices
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 24609,
"s": 24301,
"text": "4294967295-gon Number is a class of figurate numbers. It has a 4294967295 sided polygon called 4294967295-gon. The N-th 4294967295-gon number counts the 4294967295 number of dots and all other dots are surrounding with a common sharing corner and make a pattern.The first few 4294967295-gonol numbers are: "
},
{
"code": null,
"e": 24642,
"s": 24609,
"text": "1, 4294967295, 12884901882,... "
},
{
"code": null,
"e": 24721,
"s": 24644,
"text": "Given a number N, the task is to find Nth 4294967295-gon number. Examples: "
},
{
"code": null,
"e": 24851,
"s": 24721,
"text": "Input: N = 2 Output: 4294967295 Explanation: The second 4294967295-gonol number is 4294967295. Input: N = 3 Output: 12884901882 "
},
{
"code": null,
"e": 24921,
"s": 24853,
"text": "Approach: The N-th 4294967295-gon number is given by the formula: "
},
{
"code": null,
"e": 24954,
"s": 24921,
"text": "N-th term of S sided polygon = "
},
{
"code": null,
"e": 25017,
"s": 24954,
"text": "Therefore N-th term of 4294967295 sided polygon is given by: "
},
{
"code": null,
"e": 25074,
"s": 25021,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25078,
"s": 25074,
"text": "C++"
},
{
"code": null,
"e": 25083,
"s": 25078,
"text": "Java"
},
{
"code": null,
"e": 25091,
"s": 25083,
"text": "Python3"
},
{
"code": null,
"e": 25094,
"s": 25091,
"text": "C#"
},
{
"code": null,
"e": 25105,
"s": 25094,
"text": "Javascript"
},
{
"code": "// C++ program to find N-th// TetracontapentagonNum number#include<bits/stdc++.h>using namespace std; // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codeint main(){ int n = 3; cout << \"3rd 4294967295-gon Number is \" << gonNum4294967295(n);} // This code is contributed by Code_Mech",
"e": 25515,
"s": 25105,
"text": null
},
{
"code": "// Java program to find N-th// TetracontapentagonNum numberclass GFG{ // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codepublic static void main(String[] args){ int n = 3; System.out.print(\"3rd 4294967295-gon Number is \" + gonNum4294967295(n));}} // This code is contributed by Pratima Pandey",
"e": 25960,
"s": 25515,
"text": null
},
{
"code": "# Python3 program to find the N-th# 4294967295-gon number # Function to find the N-th# 4294967295-gon numberdef gonNum4294967295(N): return (4294967293 * N * N - 4294967291 * N) // 2 # Driver Code # Given Numbern = 3 # Function Callprint(\"3rd 4294967295-gon Number is \", gonNum4294967295(n))",
"e": 26271,
"s": 25960,
"text": null
},
{
"code": "// C# program to find N-th// TetracontapentagonNum numberusing System;class GFG{ // Function to find the nth// 4294967295-gon numberstatic long gonNum4294967295(int N){ return (4294967293L * N * N - 4294967291L * N) / 2;} // Driver codepublic static void Main(){ int n = 3; Console.Write(\"3rd 4294967295-gon Number is \" + gonNum4294967295(n));}} // This code is contributed by Code_Mech",
"e": 26703,
"s": 26271,
"text": null
},
{
"code": "<script>// Javascript program to find N-th// TetracontapentagonNum number // Function to find the nth // 4294967295-gon number function gonNum4294967295(N) { return ((4294967293 * N * N ) - (4294967291 * N)) / 2; } // Driver code let n = 3; document.write(\"3rd 4294967295-gon Number is \" + gonNum4294967295(n)); // This code is contributed by aashish1995</script>",
"e": 27114,
"s": 26703,
"text": null
},
{
"code": null,
"e": 27156,
"s": 27114,
"text": "3rd 4294967295-gon Number is 12884901882"
},
{
"code": null,
"e": 27174,
"s": 27158,
"text": "dewantipandeydp"
},
{
"code": null,
"e": 27184,
"s": 27174,
"text": "Code_Mech"
},
{
"code": null,
"e": 27196,
"s": 27184,
"text": "aashish1995"
},
{
"code": null,
"e": 27203,
"s": 27196,
"text": "series"
},
{
"code": null,
"e": 27216,
"s": 27203,
"text": "Mathematical"
},
{
"code": null,
"e": 27229,
"s": 27216,
"text": "Mathematical"
},
{
"code": null,
"e": 27236,
"s": 27229,
"text": "series"
},
{
"code": null,
"e": 27334,
"s": 27236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27343,
"s": 27334,
"text": "Comments"
},
{
"code": null,
"e": 27356,
"s": 27343,
"text": "Old Comments"
},
{
"code": null,
"e": 27401,
"s": 27356,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 27433,
"s": 27401,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 27477,
"s": 27433,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 27511,
"s": 27477,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 27536,
"s": 27511,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 27569,
"s": 27536,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 27608,
"s": 27569,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 27659,
"s": 27608,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 27730,
"s": 27659,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
How to create a line break with JavaScript?
|
To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.
Let’s see it in the below example:
<html>
<body>
<script>
<!--
document.write("Hello World!");
document.write("<br>");
document.write("Demo<br><br>Text!");
//-->
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also."
},
{
"code": null,
"e": 1200,
"s": 1165,
"text": "Let’s see it in the below example:"
},
{
"code": null,
"e": 1426,
"s": 1200,
"text": "<html>\n <body>\n <script>\n <!--\n document.write(\"Hello World!\");\n document.write(\"<br>\");\n document.write(\"Demo<br><br>Text!\");\n //-->\n </script>\n </body>\n</html>"
}
] |
Time Series Forecasting with ThymeBoost | by Tyler Blume | Towards Data Science
|
TLDR: ThymeBoost combines the traditional decomposition process with gradient boosting to provide a flexible mix-and-match time series framework for trend/seasonality/exogenous decomposition and forecasting, all a pip away.
All code lives here: ThymeBoost Github
Here is the newest article in the series: M4 Competition with ThymeBoost.
Traditional time-series decomposition typically involves a sequence of steps:
Approximate Trend/LevelDetrend to Approximate SeasonalityDetrend and Deseasonalize to Approximate Other Factors (Exogenous)Add Trend, Seasonality, and Exogenous for the results
Approximate Trend/Level
Detrend to Approximate Seasonality
Detrend and Deseasonalize to Approximate Other Factors (Exogenous)
Add Trend, Seasonality, and Exogenous for the results
Depending on certain algorithms at each step we may need to switch up the order and deseasonalize first. Either way, at first glance we can convince ourselves that this process flow is...fine.
In fact, it can do quite well in a simple simulation. Let’s make a basic trend + seasonality time-series to show how the process works.
import numpy as npimport matplotlib.pyplot as pltimport seaborn as snssns.set_style("darkgrid")#Here we will just create a simple seriesnp.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))y = trend + seasonality#let's plot itplt.plot(y)plt.show()
And now to do some basic decomposition.
Following the above process, we will first fit a simple linear trend to approximate the trend component:
import statsmodels.api as sm#A simple input matrix for a deterministic trend componentX = np.array([range(1, len(y) + 1), np.ones(len(y))]).Tmod = sm.OLS(y, X)res = mod.fit()fitted_trend = res.predict(X)plt.plot(trend)plt.plot(fitted_trend, linestyle='dashed')plt.show()
That trend line is spot on! We will subtract the fitted trend from our actuals and use that detrended signal to approximate the seasonal component:
detrended_series = y - fitted_trend#Set the seasonal periodseasonal_period = 25#Get the average of every 25 data points to use as seasonalityavg_season = [np.mean(detrended_series[i::seasonal_period], axis=0) for i in range(seasonal_period)]avg_season = np.array(avg_season)fitted_seasonality = np.resize(avg_season, len(y))plt.plot(fitted_seasonality)plt.plot(seasonality)plt.show()
That seasonal component looks good as well! While we see slight deviations, overall the two lines are almost identical. You may have noticed that there is no legend in the plots. This is because our signal has no noise by design, so the decomposition and the series are essentially the same. The decomposition process is quite well behaved, not necessitating a legend...yet.
Let’s put it all together and see our full results:
fitted = fitted_trend + fitted_seasonalityplt.plot(fitted, linestyle='dashed')plt.plot(y, linestyle='dashed')plt.show()
The final results for the decomposition are quite compelling. This process gives us complete control over the different components. Let’s say we needed to treat seasonality differently than the trend, possibly by giving certain samples more or less weight:
We can.
Additionally, if we add an exogenous factor we could approximate that component with any model we want. If we have plenty of data and complicated features we could simply subtract out the trend and seasonal component, then feed those residuals to XGBoost.
But for this example, let’s add a simple ‘holiday’ effect to our current series and fit that with a linear regression. First, we will rebuild our simulated series but now adding in that exogenous factor.
np.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))exogenous = np.random.randint(low=0, high=2, size=len(trend))y = trend + seasonality + exogenous * 20plt.plot(y)plt.show()
We simply created a random series of 1’s and 0’s as our ‘exogenous’ and gave it an effect of adding 20 to our series when 1. Now if we repeat the same process as before we will notice that it doesn’t hold up quite as well.
import statsmodels.api as sm#A simple input matrix for a deterministic trend componentX = np.array([range(1, len(y) + 1), np.ones(len(y))]).Tmod = sm.OLS(y, X)res = mod.fit()fitted_trend = res.predict(X)plt.plot(trend, label='actual trend')plt.plot(fitted_trend, linestyle='dashed', label='fitted trend')plt.legend()plt.show()
Clearly that trend is off. We do approximate the correct slope but we have an incorrect intercept. This is quite concerning because we feed the detrended series to approximate the seasonality, further compounding the error. Additionally, we do not allow any adjustments for the trend.
We have one shot to get it right.
Either way, let’s move on to approximating the seasonal component:
#Set the seasonal periodseasonal_period = 25#Get the average of every 25 data points to use as seasonalityavg_season = [np.mean(detrended_series[i::seasonal_period], axis=0) for i in range(seasonal_period)]avg_season = np.array(avg_season)fitted_seasonality = np.resize(avg_season, len(y))plt.plot(fitted_seasonality, label='fitted seasonality')plt.plot(seasonality, label='actual seasonality')plt.legend()plt.show()
As expected, the seasonal component is not only negatively affected by the incorrect trend, it also appears to be eating up the signal from the exogenous factor. Let’s see if this is the case by plotting the residuals:
residuals = y - fitted_trend - fitted_seasonalityplt.plot(residuals)plt.show()
Recall that the exogenous factor simply added 20 when equal to 1. In a perfect world these residuals should be random noise around 0 along with spikes of 20. Without this, it is doubtful that our exogenous approximation will be correct, but let’s try it out anyway.
To approximate the exogenous component we will fit with the residuals from detrending and deseasonalizing.
X = np.column_stack([exogenous, np.ones(len(y))])mod = sm.OLS(residuals, X)res = mod.fit()print(res.summary())
Let’s take a look at the summary from OLS:
""" OLS Regression Results ==============================================================================Dep. Variable: y R-squared: 0.768Model: OLS Adj. R-squared: 0.766Method: Least Squares F-statistic: 325.1Date: Wed, 10 Nov 2021 Prob (F-statistic): 6.82e-33Time: 09:46:43 Log-Likelihood: -289.29No. Observations: 100 AIC: 582.6Df Residuals: 98 BIC: 587.8Df Model: 1 Covariance Type: nonrobust ============================================================================== coef std err t P>|t| ------------------------------------------------------------------------------x1 15.9072 0.882 18.032 0.000 17.658const -7.9536 0.624 -12.750 0.000 ====================================================================
The expected impact of our exogenous factor has been shrunken from 20 to 16! Based on everything we have seen up to this point, this should not be a surprise. Any slight mistake early on in the process creates compounding errors later and there is no mechanism for adjustments.
Putting everything together:
fitted_exogenous = res.predict(X)fitted = fitted_trend + fitted_seasonality + fitted_exogenousplt.plot(y, label='actuals')plt.plot(fitted, label='fitted')plt.legend()plt.show()
Given everything that went wrong during this process, this result looks ok. Remember this is a simulated ‘pristine’ time-series, so the fact that we were able to break the process quite easily should be concerning. It seems that the process may be too rigid. Since the seasonal component eats up some signal of the exogenous component, should we switch the order of approximation? What if our trend is more complicated and we have to use a more complex method such as Double-Exponential Smoothing? Wouldn’t that also potentially eat the seasonality signal AND exogenous signal?
We can simply fix this issue by NOT doing this process at all. We can move to a method which approximates all components at once such as Facebook’s Prophet model or possibly some other GAM-like setup. But that comes at the cost of losing some control over the individual components. We no longer can fit different components with different methods; the process has been simplified but so have our potential forecasts.
The question is:
How can we obtain the benefits of a single fitting procedure, but retain full control over our individual components?
The answer is:
Apply Gradient Boosting to our Time-Series Decomposition.
A simple adjustment to the previous process flow will aid us in emulating a simultaneous fitting procedure. After we approximate the last step we will use the residuals and refit the whole procedure.
This boosting continues until some global cost function is minimized. Furthermore, we can utilize even more concepts found in gradient boosting, such as a learning rate. But now we can apply a learning rate to each individual component, alleviating any issues of the seasonality eating up exogenous signals. Additionally, we can allow the trend component to search for changepoints via binary segmentation and, through boosting, end up with a very complicated model. The complexity that can now be achieved by simply boosting is bonkers (I believe that is the technical word for it). This newly achieved complexity leads to more shapes we can forecast, meaning higher potential for better accuracy. We can quickly build an ARIMA with 5 changepoints, seasonality approximated via Fourier basis functions, and boosted trees for exogenous forecasting.
But first, let’s just forecast our simple series.
ThymeBoost is a dev package for Python and it contains all of the functionality laid out so far (and more). But a word of warning before continuing, it is still in early development so one could encounter bugs. Please use at your own risk. I recommend going through the README examples on GitHub as well as following along here.
First, let’s install from pip, you will definitely want the most up-to-date statsmodels and sci-kit learn packages:
pip install ThymeBoost
Next let’s rebuild our simulated series here (Note, ThymeBoost requires that exogenous be a 2d array/ DataFrame):
import numpy as npimport matplotlib.pyplot as pltimport seaborn as snssns.set_style('darkgrid')np.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))exogenous = np.random.randint(low=0, high=2, size=len(trend))y = trend + seasonality + exogenous * 20#reshape for 2d to pass to ThymeBoostexogenous = exogenous.reshape(-1, 1)
Import ThymeBoost and build the class:
from ThymeBoost import ThymeBoost as tbboosted_model = tb.ThymeBoost(verbose=1)
The verbose argument simply denotes whether to print logs of the boosting process. All that is left to do is to fit our series exactly as before, but this time with some added ThymeBoost magic.
output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=25, global_cost='maicc', fit_type='global', exogenous=exogenous)
First, let’s walkthrough some of these arguments:
trend_estimator: How you want to approximate the trend, here ‘linear’ is a simple regression as before.
seasonal_estimator: I’m sure you guessed it, the method to approximate seasonality, ‘classic’ uses a simple average of every seasonal_period.
exogenous_estimator: The method used to calculate the exogenous component.
seasonal_period: The expected seasonal period.
global_cost: Finally, an interesting argument! This controls the boosting procedure, ‘maicc’ is a ‘modified Akaike-Information Criterion’ where the modifications are used to incorporate boosting rounds into the formulation.
fit_type: Here we denote whether we want ThymeBoost to look for changepoints or not, ‘global’ will fit our trend_estimator to all data. If we pass ‘local’ then we will do binary segmentation to find a potential changepoint.
The results saved to ‘output’ is a Pandas DataFrame with the fitted values and each individual component. If you have experience with Prophet then this should remind you of that.
Let’s plot the fitted trend, seasonality, and exogenous component and see how it did.
Approximated Trend:
plt.plot(trend, label='actual trend')plt.plot(output['trend'], label='fitted trend')plt.legend()plt.show()
Approximated Seasonality:
plt.plot(seasonality, label='actual seasonality')plt.plot(output['seasonality'], label='fitted seasonality')plt.legend()plt.show()
Approximated Exogenous
plt.plot(exogenous * 20, label='actual exogenous')plt.plot(output['exogenous'], label='fitted exogenous')plt.legend()plt.show()
This is quite an improvement over the traditional process. We were able to accurately approximate each individual component. ThymeBoost also provides some helper functions for quicker plotting:
boosted_model.plot_components(output)
The package utilizes the standard fit-predict methods. Let’s use ThymeBoost to create predictions and plot them using the plot_results method :
#create a future exogenous inputforecast_horizon = 20np.random.seed(100)future_exogenous = np.random.randint(low=0, high=2, size=forecast_horizon)#use predict method and pass fitted output, forecast horizon, and future exogenouspredicted_output = boosted_model.predict(output, forecast_horizon=forecast_horizon, future_exogenous=future_exogenous)boosted_model.plot_results(output, predicted_output)
ThymeBoost fixes many of the major issues with traditional time-series decomposition and allows us to retain complete control over each component. The procedure even gives us access to interesting new features due to the boosting iterations. For example, a common issue in time-series is multiple seasonality. Thymeboost can solve this quite naturally by changing the seasonal period during each boosting round, with a simple change to our fit call, now passing a list to seasonal_period.
From:
output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=25, global_cost='maicc', fit_type='global', exogenous=exogenous)
To:
output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=[25, 5], global_cost='maicc', fit_type='global', exogenous=exogenous)
ThymeBoost will go back and forth between the two seasonal periods provided in the list, making adjustments to the total seasonal component each time. But it doesn’t stop at seasonality. We can also do this with every argument passed to fit. Meaning we can start with a simple linear trend followed by ARIMA and then Double-Exponential Smoothing in the final boosting round. You have complete control over the entire procedure.
As mentioned before, this package is still in early development. The sheer number of possible configurations makes debugging an involved procedure, so use at your own risk. But please, play around and open any issues you encounter on GitHub!
|
[
{
"code": null,
"e": 396,
"s": 172,
"text": "TLDR: ThymeBoost combines the traditional decomposition process with gradient boosting to provide a flexible mix-and-match time series framework for trend/seasonality/exogenous decomposition and forecasting, all a pip away."
},
{
"code": null,
"e": 435,
"s": 396,
"text": "All code lives here: ThymeBoost Github"
},
{
"code": null,
"e": 509,
"s": 435,
"text": "Here is the newest article in the series: M4 Competition with ThymeBoost."
},
{
"code": null,
"e": 587,
"s": 509,
"text": "Traditional time-series decomposition typically involves a sequence of steps:"
},
{
"code": null,
"e": 764,
"s": 587,
"text": "Approximate Trend/LevelDetrend to Approximate SeasonalityDetrend and Deseasonalize to Approximate Other Factors (Exogenous)Add Trend, Seasonality, and Exogenous for the results"
},
{
"code": null,
"e": 788,
"s": 764,
"text": "Approximate Trend/Level"
},
{
"code": null,
"e": 823,
"s": 788,
"text": "Detrend to Approximate Seasonality"
},
{
"code": null,
"e": 890,
"s": 823,
"text": "Detrend and Deseasonalize to Approximate Other Factors (Exogenous)"
},
{
"code": null,
"e": 944,
"s": 890,
"text": "Add Trend, Seasonality, and Exogenous for the results"
},
{
"code": null,
"e": 1137,
"s": 944,
"text": "Depending on certain algorithms at each step we may need to switch up the order and deseasonalize first. Either way, at first glance we can convince ourselves that this process flow is...fine."
},
{
"code": null,
"e": 1273,
"s": 1137,
"text": "In fact, it can do quite well in a simple simulation. Let’s make a basic trend + seasonality time-series to show how the process works."
},
{
"code": null,
"e": 1569,
"s": 1273,
"text": "import numpy as npimport matplotlib.pyplot as pltimport seaborn as snssns.set_style(\"darkgrid\")#Here we will just create a simple seriesnp.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))y = trend + seasonality#let's plot itplt.plot(y)plt.show()"
},
{
"code": null,
"e": 1609,
"s": 1569,
"text": "And now to do some basic decomposition."
},
{
"code": null,
"e": 1714,
"s": 1609,
"text": "Following the above process, we will first fit a simple linear trend to approximate the trend component:"
},
{
"code": null,
"e": 1998,
"s": 1714,
"text": "import statsmodels.api as sm#A simple input matrix for a deterministic trend componentX = np.array([range(1, len(y) + 1), np.ones(len(y))]).Tmod = sm.OLS(y, X)res = mod.fit()fitted_trend = res.predict(X)plt.plot(trend)plt.plot(fitted_trend, linestyle='dashed')plt.show()"
},
{
"code": null,
"e": 2146,
"s": 1998,
"text": "That trend line is spot on! We will subtract the fitted trend from our actuals and use that detrended signal to approximate the seasonal component:"
},
{
"code": null,
"e": 2530,
"s": 2146,
"text": "detrended_series = y - fitted_trend#Set the seasonal periodseasonal_period = 25#Get the average of every 25 data points to use as seasonalityavg_season = [np.mean(detrended_series[i::seasonal_period], axis=0) for i in range(seasonal_period)]avg_season = np.array(avg_season)fitted_seasonality = np.resize(avg_season, len(y))plt.plot(fitted_seasonality)plt.plot(seasonality)plt.show()"
},
{
"code": null,
"e": 2905,
"s": 2530,
"text": "That seasonal component looks good as well! While we see slight deviations, overall the two lines are almost identical. You may have noticed that there is no legend in the plots. This is because our signal has no noise by design, so the decomposition and the series are essentially the same. The decomposition process is quite well behaved, not necessitating a legend...yet."
},
{
"code": null,
"e": 2957,
"s": 2905,
"text": "Let’s put it all together and see our full results:"
},
{
"code": null,
"e": 3077,
"s": 2957,
"text": "fitted = fitted_trend + fitted_seasonalityplt.plot(fitted, linestyle='dashed')plt.plot(y, linestyle='dashed')plt.show()"
},
{
"code": null,
"e": 3334,
"s": 3077,
"text": "The final results for the decomposition are quite compelling. This process gives us complete control over the different components. Let’s say we needed to treat seasonality differently than the trend, possibly by giving certain samples more or less weight:"
},
{
"code": null,
"e": 3342,
"s": 3334,
"text": "We can."
},
{
"code": null,
"e": 3598,
"s": 3342,
"text": "Additionally, if we add an exogenous factor we could approximate that component with any model we want. If we have plenty of data and complicated features we could simply subtract out the trend and seasonal component, then feed those residuals to XGBoost."
},
{
"code": null,
"e": 3802,
"s": 3598,
"text": "But for this example, let’s add a simple ‘holiday’ effect to our current series and fit that with a linear regression. First, we will rebuild our simulated series but now adding in that exogenous factor."
},
{
"code": null,
"e": 4026,
"s": 3802,
"text": "np.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))exogenous = np.random.randint(low=0, high=2, size=len(trend))y = trend + seasonality + exogenous * 20plt.plot(y)plt.show()"
},
{
"code": null,
"e": 4249,
"s": 4026,
"text": "We simply created a random series of 1’s and 0’s as our ‘exogenous’ and gave it an effect of adding 20 to our series when 1. Now if we repeat the same process as before we will notice that it doesn’t hold up quite as well."
},
{
"code": null,
"e": 4589,
"s": 4249,
"text": "import statsmodels.api as sm#A simple input matrix for a deterministic trend componentX = np.array([range(1, len(y) + 1), np.ones(len(y))]).Tmod = sm.OLS(y, X)res = mod.fit()fitted_trend = res.predict(X)plt.plot(trend, label='actual trend')plt.plot(fitted_trend, linestyle='dashed', label='fitted trend')plt.legend()plt.show()"
},
{
"code": null,
"e": 4874,
"s": 4589,
"text": "Clearly that trend is off. We do approximate the correct slope but we have an incorrect intercept. This is quite concerning because we feed the detrended series to approximate the seasonality, further compounding the error. Additionally, we do not allow any adjustments for the trend."
},
{
"code": null,
"e": 4908,
"s": 4874,
"text": "We have one shot to get it right."
},
{
"code": null,
"e": 4975,
"s": 4908,
"text": "Either way, let’s move on to approximating the seasonal component:"
},
{
"code": null,
"e": 5392,
"s": 4975,
"text": "#Set the seasonal periodseasonal_period = 25#Get the average of every 25 data points to use as seasonalityavg_season = [np.mean(detrended_series[i::seasonal_period], axis=0) for i in range(seasonal_period)]avg_season = np.array(avg_season)fitted_seasonality = np.resize(avg_season, len(y))plt.plot(fitted_seasonality, label='fitted seasonality')plt.plot(seasonality, label='actual seasonality')plt.legend()plt.show()"
},
{
"code": null,
"e": 5611,
"s": 5392,
"text": "As expected, the seasonal component is not only negatively affected by the incorrect trend, it also appears to be eating up the signal from the exogenous factor. Let’s see if this is the case by plotting the residuals:"
},
{
"code": null,
"e": 5690,
"s": 5611,
"text": "residuals = y - fitted_trend - fitted_seasonalityplt.plot(residuals)plt.show()"
},
{
"code": null,
"e": 5956,
"s": 5690,
"text": "Recall that the exogenous factor simply added 20 when equal to 1. In a perfect world these residuals should be random noise around 0 along with spikes of 20. Without this, it is doubtful that our exogenous approximation will be correct, but let’s try it out anyway."
},
{
"code": null,
"e": 6063,
"s": 5956,
"text": "To approximate the exogenous component we will fit with the residuals from detrending and deseasonalizing."
},
{
"code": null,
"e": 6174,
"s": 6063,
"text": "X = np.column_stack([exogenous, np.ones(len(y))])mod = sm.OLS(residuals, X)res = mod.fit()print(res.summary())"
},
{
"code": null,
"e": 6217,
"s": 6174,
"text": "Let’s take a look at the summary from OLS:"
},
{
"code": null,
"e": 7374,
"s": 6217,
"text": "\"\"\" OLS Regression Results ==============================================================================Dep. Variable: y R-squared: 0.768Model: OLS Adj. R-squared: 0.766Method: Least Squares F-statistic: 325.1Date: Wed, 10 Nov 2021 Prob (F-statistic): 6.82e-33Time: 09:46:43 Log-Likelihood: -289.29No. Observations: 100 AIC: 582.6Df Residuals: 98 BIC: 587.8Df Model: 1 Covariance Type: nonrobust ============================================================================== coef std err t P>|t| ------------------------------------------------------------------------------x1 15.9072 0.882 18.032 0.000 17.658const -7.9536 0.624 -12.750 0.000 ===================================================================="
},
{
"code": null,
"e": 7652,
"s": 7374,
"text": "The expected impact of our exogenous factor has been shrunken from 20 to 16! Based on everything we have seen up to this point, this should not be a surprise. Any slight mistake early on in the process creates compounding errors later and there is no mechanism for adjustments."
},
{
"code": null,
"e": 7681,
"s": 7652,
"text": "Putting everything together:"
},
{
"code": null,
"e": 7858,
"s": 7681,
"text": "fitted_exogenous = res.predict(X)fitted = fitted_trend + fitted_seasonality + fitted_exogenousplt.plot(y, label='actuals')plt.plot(fitted, label='fitted')plt.legend()plt.show()"
},
{
"code": null,
"e": 8436,
"s": 7858,
"text": "Given everything that went wrong during this process, this result looks ok. Remember this is a simulated ‘pristine’ time-series, so the fact that we were able to break the process quite easily should be concerning. It seems that the process may be too rigid. Since the seasonal component eats up some signal of the exogenous component, should we switch the order of approximation? What if our trend is more complicated and we have to use a more complex method such as Double-Exponential Smoothing? Wouldn’t that also potentially eat the seasonality signal AND exogenous signal?"
},
{
"code": null,
"e": 8854,
"s": 8436,
"text": "We can simply fix this issue by NOT doing this process at all. We can move to a method which approximates all components at once such as Facebook’s Prophet model or possibly some other GAM-like setup. But that comes at the cost of losing some control over the individual components. We no longer can fit different components with different methods; the process has been simplified but so have our potential forecasts."
},
{
"code": null,
"e": 8871,
"s": 8854,
"text": "The question is:"
},
{
"code": null,
"e": 8989,
"s": 8871,
"text": "How can we obtain the benefits of a single fitting procedure, but retain full control over our individual components?"
},
{
"code": null,
"e": 9004,
"s": 8989,
"text": "The answer is:"
},
{
"code": null,
"e": 9062,
"s": 9004,
"text": "Apply Gradient Boosting to our Time-Series Decomposition."
},
{
"code": null,
"e": 9262,
"s": 9062,
"text": "A simple adjustment to the previous process flow will aid us in emulating a simultaneous fitting procedure. After we approximate the last step we will use the residuals and refit the whole procedure."
},
{
"code": null,
"e": 10111,
"s": 9262,
"text": "This boosting continues until some global cost function is minimized. Furthermore, we can utilize even more concepts found in gradient boosting, such as a learning rate. But now we can apply a learning rate to each individual component, alleviating any issues of the seasonality eating up exogenous signals. Additionally, we can allow the trend component to search for changepoints via binary segmentation and, through boosting, end up with a very complicated model. The complexity that can now be achieved by simply boosting is bonkers (I believe that is the technical word for it). This newly achieved complexity leads to more shapes we can forecast, meaning higher potential for better accuracy. We can quickly build an ARIMA with 5 changepoints, seasonality approximated via Fourier basis functions, and boosted trees for exogenous forecasting."
},
{
"code": null,
"e": 10161,
"s": 10111,
"text": "But first, let’s just forecast our simple series."
},
{
"code": null,
"e": 10490,
"s": 10161,
"text": "ThymeBoost is a dev package for Python and it contains all of the functionality laid out so far (and more). But a word of warning before continuing, it is still in early development so one could encounter bugs. Please use at your own risk. I recommend going through the README examples on GitHub as well as following along here."
},
{
"code": null,
"e": 10606,
"s": 10490,
"text": "First, let’s install from pip, you will definitely want the most up-to-date statsmodels and sci-kit learn packages:"
},
{
"code": null,
"e": 10629,
"s": 10606,
"text": "pip install ThymeBoost"
},
{
"code": null,
"e": 10743,
"s": 10629,
"text": "Next let’s rebuild our simulated series here (Note, ThymeBoost requires that exogenous be a 2d array/ DataFrame):"
},
{
"code": null,
"e": 11114,
"s": 10743,
"text": "import numpy as npimport matplotlib.pyplot as pltimport seaborn as snssns.set_style('darkgrid')np.random.seed(100)trend = np.linspace(1, 50, 100) + 50seasonality = ((np.cos(np.arange(1, 101))*10))exogenous = np.random.randint(low=0, high=2, size=len(trend))y = trend + seasonality + exogenous * 20#reshape for 2d to pass to ThymeBoostexogenous = exogenous.reshape(-1, 1)"
},
{
"code": null,
"e": 11153,
"s": 11114,
"text": "Import ThymeBoost and build the class:"
},
{
"code": null,
"e": 11233,
"s": 11153,
"text": "from ThymeBoost import ThymeBoost as tbboosted_model = tb.ThymeBoost(verbose=1)"
},
{
"code": null,
"e": 11427,
"s": 11233,
"text": "The verbose argument simply denotes whether to print logs of the boosting process. All that is left to do is to fit our series exactly as before, but this time with some added ThymeBoost magic."
},
{
"code": null,
"e": 11803,
"s": 11427,
"text": "output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=25, global_cost='maicc', fit_type='global', exogenous=exogenous)"
},
{
"code": null,
"e": 11853,
"s": 11803,
"text": "First, let’s walkthrough some of these arguments:"
},
{
"code": null,
"e": 11957,
"s": 11853,
"text": "trend_estimator: How you want to approximate the trend, here ‘linear’ is a simple regression as before."
},
{
"code": null,
"e": 12099,
"s": 11957,
"text": "seasonal_estimator: I’m sure you guessed it, the method to approximate seasonality, ‘classic’ uses a simple average of every seasonal_period."
},
{
"code": null,
"e": 12174,
"s": 12099,
"text": "exogenous_estimator: The method used to calculate the exogenous component."
},
{
"code": null,
"e": 12221,
"s": 12174,
"text": "seasonal_period: The expected seasonal period."
},
{
"code": null,
"e": 12445,
"s": 12221,
"text": "global_cost: Finally, an interesting argument! This controls the boosting procedure, ‘maicc’ is a ‘modified Akaike-Information Criterion’ where the modifications are used to incorporate boosting rounds into the formulation."
},
{
"code": null,
"e": 12669,
"s": 12445,
"text": "fit_type: Here we denote whether we want ThymeBoost to look for changepoints or not, ‘global’ will fit our trend_estimator to all data. If we pass ‘local’ then we will do binary segmentation to find a potential changepoint."
},
{
"code": null,
"e": 12848,
"s": 12669,
"text": "The results saved to ‘output’ is a Pandas DataFrame with the fitted values and each individual component. If you have experience with Prophet then this should remind you of that."
},
{
"code": null,
"e": 12934,
"s": 12848,
"text": "Let’s plot the fitted trend, seasonality, and exogenous component and see how it did."
},
{
"code": null,
"e": 12954,
"s": 12934,
"text": "Approximated Trend:"
},
{
"code": null,
"e": 13061,
"s": 12954,
"text": "plt.plot(trend, label='actual trend')plt.plot(output['trend'], label='fitted trend')plt.legend()plt.show()"
},
{
"code": null,
"e": 13087,
"s": 13061,
"text": "Approximated Seasonality:"
},
{
"code": null,
"e": 13218,
"s": 13087,
"text": "plt.plot(seasonality, label='actual seasonality')plt.plot(output['seasonality'], label='fitted seasonality')plt.legend()plt.show()"
},
{
"code": null,
"e": 13241,
"s": 13218,
"text": "Approximated Exogenous"
},
{
"code": null,
"e": 13369,
"s": 13241,
"text": "plt.plot(exogenous * 20, label='actual exogenous')plt.plot(output['exogenous'], label='fitted exogenous')plt.legend()plt.show()"
},
{
"code": null,
"e": 13563,
"s": 13369,
"text": "This is quite an improvement over the traditional process. We were able to accurately approximate each individual component. ThymeBoost also provides some helper functions for quicker plotting:"
},
{
"code": null,
"e": 13601,
"s": 13563,
"text": "boosted_model.plot_components(output)"
},
{
"code": null,
"e": 13745,
"s": 13601,
"text": "The package utilizes the standard fit-predict methods. Let’s use ThymeBoost to create predictions and plot them using the plot_results method :"
},
{
"code": null,
"e": 14224,
"s": 13745,
"text": "#create a future exogenous inputforecast_horizon = 20np.random.seed(100)future_exogenous = np.random.randint(low=0, high=2, size=forecast_horizon)#use predict method and pass fitted output, forecast horizon, and future exogenouspredicted_output = boosted_model.predict(output, forecast_horizon=forecast_horizon, future_exogenous=future_exogenous)boosted_model.plot_results(output, predicted_output)"
},
{
"code": null,
"e": 14713,
"s": 14224,
"text": "ThymeBoost fixes many of the major issues with traditional time-series decomposition and allows us to retain complete control over each component. The procedure even gives us access to interesting new features due to the boosting iterations. For example, a common issue in time-series is multiple seasonality. Thymeboost can solve this quite naturally by changing the seasonal period during each boosting round, with a simple change to our fit call, now passing a list to seasonal_period."
},
{
"code": null,
"e": 14719,
"s": 14713,
"text": "From:"
},
{
"code": null,
"e": 15095,
"s": 14719,
"text": "output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=25, global_cost='maicc', fit_type='global', exogenous=exogenous)"
},
{
"code": null,
"e": 15099,
"s": 15095,
"text": "To:"
},
{
"code": null,
"e": 15480,
"s": 15099,
"text": "output = boosted_model.fit(y, trend_estimator='linear', seasonal_estimator='classic', exogenous_estimator='ols', seasonal_period=[25, 5], global_cost='maicc', fit_type='global', exogenous=exogenous)"
},
{
"code": null,
"e": 15908,
"s": 15480,
"text": "ThymeBoost will go back and forth between the two seasonal periods provided in the list, making adjustments to the total seasonal component each time. But it doesn’t stop at seasonality. We can also do this with every argument passed to fit. Meaning we can start with a simple linear trend followed by ARIMA and then Double-Exponential Smoothing in the final boosting round. You have complete control over the entire procedure."
}
] |
How can I insert a string in an Entry widget that is in the "readonly" state using Tkinter?
|
Tkinter Entry widget is used to insert single-line text input. We can use the Entry widget to create forms where single-line input is the prime requirement.
Sometimes, we need to insert a predefined text inside the Entry Widget. In such cases, we can use insert(INSERT,<Your Text>) method. These are generally called as Placeholders for the Entry widget.
Let us suppose that we want to change the state of our text as read-only. Here, we can use state= ‘readonly’ property while configuring the Entry widget.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Create an Entry Widget
entry= ttk.Entry(win, width= 40)
entry.insert(0, 'www.tutorialspoint.com')
#Set the state of Entry widget ReadOnly
entry.configure(state= "readonly")
entry.pack(ipadx= 20,ipady=10)
win.mainloop()
Running the above code will display a window that will have an Entry widget containing a single text which cannot be modified.
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "Tkinter Entry widget is used to insert single-line text input. We can use the Entry widget to create forms where single-line input is the prime requirement."
},
{
"code": null,
"e": 1417,
"s": 1219,
"text": "Sometimes, we need to insert a predefined text inside the Entry Widget. In such cases, we can use insert(INSERT,<Your Text>) method. These are generally called as Placeholders for the Entry widget."
},
{
"code": null,
"e": 1571,
"s": 1417,
"text": "Let us suppose that we want to change the state of our text as read-only. Here, we can use state= ‘readonly’ property while configuring the Entry widget."
},
{
"code": null,
"e": 1975,
"s": 1571,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x270\")\n#Create an Entry Widget\nentry= ttk.Entry(win, width= 40)\nentry.insert(0, 'www.tutorialspoint.com')\n#Set the state of Entry widget ReadOnly\nentry.configure(state= \"readonly\")\nentry.pack(ipadx= 20,ipady=10)\nwin.mainloop()"
},
{
"code": null,
"e": 2102,
"s": 1975,
"text": "Running the above code will display a window that will have an Entry widget containing a single text which cannot be modified."
}
] |
How to convert a NumPy ndarray to a PyTorch Tensor and vice versa?
|
A PyTorch tensor is like numpy.ndarray. The difference between these two is that a tensor utilizes the GPUs to accelerate numeric computation. We convert a numpy.ndarray to a PyTorch tensor using the function torch.from_numpy(). And a tensor is converted to numpy.ndarray using the .numpy() method.
Import the required libraries. Here, the required libraries are torch and numpy.
Import the required libraries. Here, the required libraries are torch and numpy.
Create a numpy.ndarray or a PyTorch tensor.
Create a numpy.ndarray or a PyTorch tensor.
Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method.
Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method.
Finally, print the converted tensor or numpy.ndarray.
Finally, print the converted tensor or numpy.ndarray.
The following Python program converts a numpy.ndarray to a PyTorch tensor.
# import the libraries
import torch
import numpy as np
# Create a numpy.ndarray "a"
a = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("a:\n", a)
print("Type of a :\n", type(a))
# Convert the numpy.ndarray to tensor
t = torch.from_numpy(a)
print("t:\n", t)
print("Type after conversion:\n", type(t))
When you run the above code, it will produce the following output
a:
[[1 2 3]
[2 1 3]
[2 3 5]
[5 6 4]]
Type of a :
<class 'numpy.ndarray'>
t:
tensor([[1, 2, 3],
[2, 1, 3],
[2, 3, 5],
[5, 6, 4]], dtype=torch.int32)
Type after conversion:
<class 'torch.Tensor'>
The following Python program converts a PyTorch tensor to a numpy.ndarray.
# import the libraries
import torch
import numpy
# Create a tensor "t"
t = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("t:\n", t)
print("Type of t :\n", type(t))
# Convert the tensor to numpy.ndarray
a = t.numpy()
print("a:\n", a)
print("Type after conversion:\n", type(a))
When you run the above code, it will produce the following output
t:
tensor([[1., 2., 3.],
[2., 1., 3.],
[2., 3., 5.],
[5., 6., 4.]])
Type of t :
<class 'torch.Tensor'>
a:
[[1. 2. 3.]
[2. 1. 3.]
[2. 3. 5.]
[5. 6. 4.]]
Type after conversion:
<class 'numpy.ndarray'>
|
[
{
"code": null,
"e": 1361,
"s": 1062,
"text": "A PyTorch tensor is like numpy.ndarray. The difference between these two is that a tensor utilizes the GPUs to accelerate numeric computation. We convert a numpy.ndarray to a PyTorch tensor using the function torch.from_numpy(). And a tensor is converted to numpy.ndarray using the .numpy() method."
},
{
"code": null,
"e": 1442,
"s": 1361,
"text": "Import the required libraries. Here, the required libraries are torch and numpy."
},
{
"code": null,
"e": 1523,
"s": 1442,
"text": "Import the required libraries. Here, the required libraries are torch and numpy."
},
{
"code": null,
"e": 1567,
"s": 1523,
"text": "Create a numpy.ndarray or a PyTorch tensor."
},
{
"code": null,
"e": 1611,
"s": 1567,
"text": "Create a numpy.ndarray or a PyTorch tensor."
},
{
"code": null,
"e": 1765,
"s": 1611,
"text": "Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method."
},
{
"code": null,
"e": 1919,
"s": 1765,
"text": "Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method."
},
{
"code": null,
"e": 1973,
"s": 1919,
"text": "Finally, print the converted tensor or numpy.ndarray."
},
{
"code": null,
"e": 2027,
"s": 1973,
"text": "Finally, print the converted tensor or numpy.ndarray."
},
{
"code": null,
"e": 2102,
"s": 2027,
"text": "The following Python program converts a numpy.ndarray to a PyTorch tensor."
},
{
"code": null,
"e": 2407,
"s": 2102,
"text": "# import the libraries\nimport torch\nimport numpy as np\n\n# Create a numpy.ndarray \"a\"\na = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])\nprint(\"a:\\n\", a)\n\nprint(\"Type of a :\\n\", type(a))\n# Convert the numpy.ndarray to tensor\nt = torch.from_numpy(a)\nprint(\"t:\\n\", t)\nprint(\"Type after conversion:\\n\", type(t))"
},
{
"code": null,
"e": 2473,
"s": 2407,
"text": "When you run the above code, it will produce the following output"
},
{
"code": null,
"e": 2694,
"s": 2473,
"text": "a:\n[[1 2 3]\n[2 1 3]\n[2 3 5]\n[5 6 4]]\nType of a :\n<class 'numpy.ndarray'>\nt:\ntensor([[1, 2, 3],\n [2, 1, 3],\n [2, 3, 5],\n [5, 6, 4]], dtype=torch.int32)\nType after conversion:\n<class 'torch.Tensor'>"
},
{
"code": null,
"e": 2769,
"s": 2694,
"text": "The following Python program converts a PyTorch tensor to a numpy.ndarray."
},
{
"code": null,
"e": 3055,
"s": 2769,
"text": "# import the libraries\nimport torch\nimport numpy\n\n# Create a tensor \"t\"\nt = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])\nprint(\"t:\\n\", t)\nprint(\"Type of t :\\n\", type(t))\n\n# Convert the tensor to numpy.ndarray\na = t.numpy()\nprint(\"a:\\n\", a)\nprint(\"Type after conversion:\\n\", type(a))"
},
{
"code": null,
"e": 3121,
"s": 3055,
"text": "When you run the above code, it will produce the following output"
},
{
"code": null,
"e": 3347,
"s": 3121,
"text": "t:\ntensor([[1., 2., 3.],\n [2., 1., 3.],\n [2., 3., 5.],\n [5., 6., 4.]])\nType of t :\n<class 'torch.Tensor'>\na:\n[[1. 2. 3.]\n[2. 1. 3.]\n[2. 3. 5.]\n[5. 6. 4.]]\nType after conversion:\n<class 'numpy.ndarray'>"
}
] |
C# | DateTimePicker Class - GeeksforGeeks
|
05 Sep, 2019
In Windows Forms, the DateTimePicker control is used to select and display the date/time with a specific format in your form. The FlowLayoutPanel class is used to represent windows DateTimePicker control and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. You can create two different types of DateTimePicker, as a drop-down list with a date represented in the text, or as a calendar which appears when you click on the down-arrow next to the given list. In C#, you can create a DateTimePicker in the windows form by using two different ways:
1. Design-Time: It is the easiest way to create a DateTimePicker control as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the DateTimePicker to modify DateTimePicker according to your requirement.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a DateTimePicker programmatically with the help of syntax provided by the DateTimePicker class. The following steps show how to set the create DateTimePicker dynamically:
Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker
DateTimePicker d = new DateTimePicker();
// Creating a DateTimePicker
DateTimePicker d = new DateTimePicker();
Step 2: After creating a DateTimePicker, set the properties of the DateTimePicker provided by the DateTimePicker class.// Setting the location of the DateTimePicker
d.Location = new Point(360, 162);
// Setting the size of the DateTimePicker
d.Size = new Size(292, 26);
// Setting the maximum date of the DateTimePicker
d.MaxDate = new DateTime(2500, 12, 20);
// Setting the minimum date of the DateTimePicker
d.MinDate = new DateTime(1753, 1, 1);
// Setting the format of the DateTimePicker
d.Format = DateTimePickerFormat.Long;
// Setting the name of the DateTimePicker
d.Name = "MyPicker";
// Setting the font of the DateTimePicker
d.Font = new Font("Comic Sans MS", 12);
// Setting the visibility of the DateTimePicker
d.Visible = true;
// Setting the value of the DateTimePicker
d.Value = DateTime.Today;
// Setting the location of the DateTimePicker
d.Location = new Point(360, 162);
// Setting the size of the DateTimePicker
d.Size = new Size(292, 26);
// Setting the maximum date of the DateTimePicker
d.MaxDate = new DateTime(2500, 12, 20);
// Setting the minimum date of the DateTimePicker
d.MinDate = new DateTime(1753, 1, 1);
// Setting the format of the DateTimePicker
d.Format = DateTimePickerFormat.Long;
// Setting the name of the DateTimePicker
d.Name = "MyPicker";
// Setting the font of the DateTimePicker
d.Font = new Font("Comic Sans MS", 12);
// Setting the visibility of the DateTimePicker
d.Visible = true;
// Setting the value of the DateTimePicker
d.Value = DateTime.Today;
Step 3: And last add this DateTimePicker control to the form and also add other controls on the DateTimePicker using the following statements:// Adding this control
// to the form
this.Controls.Add(d);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l = new Label(); l.Location = new Point(183, 162); l.Size = new Size(172, 20); l.Text = "Select Date and Time"; l.Font = new Font("Comic Sans MS", 12); // Adding this control // to the form this.Controls.Add(l); // Creating and setting the // properties of the DateTimePicker DateTimePicker d = new DateTimePicker(); d.Location = new Point(360, 162); d.Size = new Size(292, 26); d.MaxDate = new DateTime(2500, 12, 20); d.MinDate = new DateTime(1753, 1, 1); d.Format = DateTimePickerFormat.Long; d.Name = "MyPicker"; d.Font = new Font("Comic Sans MS", 12); d.Visible = true; d.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(d); }}}Output:
// Adding this control
// to the form
this.Controls.Add(d);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l = new Label(); l.Location = new Point(183, 162); l.Size = new Size(172, 20); l.Text = "Select Date and Time"; l.Font = new Font("Comic Sans MS", 12); // Adding this control // to the form this.Controls.Add(l); // Creating and setting the // properties of the DateTimePicker DateTimePicker d = new DateTimePicker(); d.Location = new Point(360, 162); d.Size = new Size(292, 26); d.MaxDate = new DateTime(2500, 12, 20); d.MinDate = new DateTime(1753, 1, 1); d.Format = DateTimePickerFormat.Long; d.Name = "MyPicker"; d.Font = new Font("Comic Sans MS", 12); d.Visible = true; d.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(d); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 23834,
"s": 23806,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 24446,
"s": 23834,
"text": "In Windows Forms, the DateTimePicker control is used to select and display the date/time with a specific format in your form. The FlowLayoutPanel class is used to represent windows DateTimePicker control and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. You can create two different types of DateTimePicker, as a drop-down list with a date represented in the text, or as a calendar which appears when you click on the down-arrow next to the given list. In C#, you can create a DateTimePicker in the windows form by using two different ways:"
},
{
"code": null,
"e": 24552,
"s": 24446,
"text": "1. Design-Time: It is the easiest way to create a DateTimePicker control as shown in the following steps:"
},
{
"code": null,
"e": 24668,
"s": 24552,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24781,
"s": 24668,
"text": "Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 24924,
"s": 24781,
"text": "Step 3: After drag and drop you will go to the properties of the DateTimePicker to modify DateTimePicker according to your requirement.Output:"
},
{
"code": null,
"e": 24932,
"s": 24924,
"text": "Output:"
},
{
"code": null,
"e": 25198,
"s": 24932,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a DateTimePicker programmatically with the help of syntax provided by the DateTimePicker class. The following steps show how to set the create DateTimePicker dynamically:"
},
{
"code": null,
"e": 25380,
"s": 25198,
"text": "Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker\nDateTimePicker d = new DateTimePicker();\n"
},
{
"code": null,
"e": 25451,
"s": 25380,
"text": "// Creating a DateTimePicker\nDateTimePicker d = new DateTimePicker();\n"
},
{
"code": null,
"e": 26278,
"s": 25451,
"text": "Step 2: After creating a DateTimePicker, set the properties of the DateTimePicker provided by the DateTimePicker class.// Setting the location of the DateTimePicker\nd.Location = new Point(360, 162); \n\n// Setting the size of the DateTimePicker\nd.Size = new Size(292, 26); \n\n// Setting the maximum date of the DateTimePicker\nd.MaxDate = new DateTime(2500, 12, 20); \n\n// Setting the minimum date of the DateTimePicker\nd.MinDate = new DateTime(1753, 1, 1); \n\n// Setting the format of the DateTimePicker\nd.Format = DateTimePickerFormat.Long; \n\n// Setting the name of the DateTimePicker\nd.Name = \"MyPicker\"; \n\n// Setting the font of the DateTimePicker\nd.Font = new Font(\"Comic Sans MS\", 12);\n\n// Setting the visibility of the DateTimePicker \nd.Visible = true; \n\n// Setting the value of the DateTimePicker\nd.Value = DateTime.Today; \n"
},
{
"code": null,
"e": 26986,
"s": 26278,
"text": "// Setting the location of the DateTimePicker\nd.Location = new Point(360, 162); \n\n// Setting the size of the DateTimePicker\nd.Size = new Size(292, 26); \n\n// Setting the maximum date of the DateTimePicker\nd.MaxDate = new DateTime(2500, 12, 20); \n\n// Setting the minimum date of the DateTimePicker\nd.MinDate = new DateTime(1753, 1, 1); \n\n// Setting the format of the DateTimePicker\nd.Format = DateTimePickerFormat.Long; \n\n// Setting the name of the DateTimePicker\nd.Name = \"MyPicker\"; \n\n// Setting the font of the DateTimePicker\nd.Font = new Font(\"Comic Sans MS\", 12);\n\n// Setting the visibility of the DateTimePicker \nd.Visible = true; \n\n// Setting the value of the DateTimePicker\nd.Value = DateTime.Today; \n"
},
{
"code": null,
"e": 28511,
"s": 26986,
"text": "Step 3: And last add this DateTimePicker control to the form and also add other controls on the DateTimePicker using the following statements:// Adding this control \n// to the form \nthis.Controls.Add(d); \nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l = new Label(); l.Location = new Point(183, 162); l.Size = new Size(172, 20); l.Text = \"Select Date and Time\"; l.Font = new Font(\"Comic Sans MS\", 12); // Adding this control // to the form this.Controls.Add(l); // Creating and setting the // properties of the DateTimePicker DateTimePicker d = new DateTimePicker(); d.Location = new Point(360, 162); d.Size = new Size(292, 26); d.MaxDate = new DateTime(2500, 12, 20); d.MinDate = new DateTime(1753, 1, 1); d.Format = DateTimePickerFormat.Long; d.Name = \"MyPicker\"; d.Font = new Font(\"Comic Sans MS\", 12); d.Visible = true; d.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(d); }}}Output:"
},
{
"code": null,
"e": 28575,
"s": 28511,
"text": "// Adding this control \n// to the form \nthis.Controls.Add(d); \n"
},
{
"code": null,
"e": 28584,
"s": 28575,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l = new Label(); l.Location = new Point(183, 162); l.Size = new Size(172, 20); l.Text = \"Select Date and Time\"; l.Font = new Font(\"Comic Sans MS\", 12); // Adding this control // to the form this.Controls.Add(l); // Creating and setting the // properties of the DateTimePicker DateTimePicker d = new DateTimePicker(); d.Location = new Point(360, 162); d.Size = new Size(292, 26); d.MaxDate = new DateTime(2500, 12, 20); d.MinDate = new DateTime(1753, 1, 1); d.Format = DateTimePickerFormat.Long; d.Name = \"MyPicker\"; d.Font = new Font(\"Comic Sans MS\", 12); d.Visible = true; d.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(d); }}}",
"e": 29889,
"s": 28584,
"text": null
},
{
"code": null,
"e": 29897,
"s": 29889,
"text": "Output:"
},
{
"code": null,
"e": 29928,
"s": 29897,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 29931,
"s": 29928,
"text": "C#"
},
{
"code": null,
"e": 30029,
"s": 29931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30038,
"s": 30029,
"text": "Comments"
},
{
"code": null,
"e": 30051,
"s": 30038,
"text": "Old Comments"
},
{
"code": null,
"e": 30074,
"s": 30051,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30102,
"s": 30074,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30148,
"s": 30102,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30163,
"s": 30148,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30203,
"s": 30163,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 30221,
"s": 30203,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30252,
"s": 30221,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 30275,
"s": 30252,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30297,
"s": 30275,
"text": "C# | Class and Object"
}
] |
Designing a Working Table Fan using HTML and CSS - GeeksforGeeks
|
21 Sep, 2021
In this article, we will design a Working Table-fan using HTML and CSS.
List of HTML tags used:
Polyline: The <polyline> element is used to create the HTML <svg> element which is a container for SVG graphics any shape that consists of only straight lines
div: The <div> tag defines a division or a section in an HTML document.
svg: The HTML <svg> element is a container for SVG graphics
circle: The HTML <circle> element is used to create circle
style: The HTML <style> element is used to provide internal CSS.
Example:
HTML
<!DOCTYPE html><html> <head> <style> .blade_container { width: 180px; height: 180px; margin: auto; margin-top: 50px; animation: blade 1s linear infinite; } @keyframes blade { 0% { transform: rotate(360deg); } } .rode { width: 15px; height: 150px; background-color: black; margin: auto; margin-top: 0px; } .main_container { background-color: #308D46; border-radius: 50%; height: 180px; width: 180px; margin: auto; } </style></head> <body> <center> <h3 style="color:green">Its Geek Time</h3> <div class="main_container"> <div class="blade_container"> <svg width="100%" height="100%"> <polyline style="stroke-linejoin:miter; stroke:white; stroke-width:12; fill:white;" points= "90 90, 0 90, 90 90, 90 0,90 90,180 90, 90 90,90 180,90 90, 27 27,90 90, 153 27,90 90, 27 153, 90 90, 153 153" /> </svg> </div> </div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210921173505/bg.png" style="z-index:-1;"> </center></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.
Blogathon-2021
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
Blogathon
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Re-rendering Components in ReactJS
Python NOT EQUAL operator
How to build a basic CRUD app with Node.js and ReactJS ?
Banking Transaction System using Java
How to Connect Python with SQL Database?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 23768,
"s": 23740,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 23840,
"s": 23768,
"text": "In this article, we will design a Working Table-fan using HTML and CSS."
},
{
"code": null,
"e": 23864,
"s": 23840,
"text": "List of HTML tags used:"
},
{
"code": null,
"e": 24023,
"s": 23864,
"text": "Polyline: The <polyline> element is used to create the HTML <svg> element which is a container for SVG graphics any shape that consists of only straight lines"
},
{
"code": null,
"e": 24095,
"s": 24023,
"text": "div: The <div> tag defines a division or a section in an HTML document."
},
{
"code": null,
"e": 24155,
"s": 24095,
"text": "svg: The HTML <svg> element is a container for SVG graphics"
},
{
"code": null,
"e": 24214,
"s": 24155,
"text": "circle: The HTML <circle> element is used to create circle"
},
{
"code": null,
"e": 24279,
"s": 24214,
"text": "style: The HTML <style> element is used to provide internal CSS."
},
{
"code": null,
"e": 24288,
"s": 24279,
"text": "Example:"
},
{
"code": null,
"e": 24293,
"s": 24288,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .blade_container { width: 180px; height: 180px; margin: auto; margin-top: 50px; animation: blade 1s linear infinite; } @keyframes blade { 0% { transform: rotate(360deg); } } .rode { width: 15px; height: 150px; background-color: black; margin: auto; margin-top: 0px; } .main_container { background-color: #308D46; border-radius: 50%; height: 180px; width: 180px; margin: auto; } </style></head> <body> <center> <h3 style=\"color:green\">Its Geek Time</h3> <div class=\"main_container\"> <div class=\"blade_container\"> <svg width=\"100%\" height=\"100%\"> <polyline style=\"stroke-linejoin:miter; stroke:white; stroke-width:12; fill:white;\" points= \"90 90, 0 90, 90 90, 90 0,90 90,180 90, 90 90,90 180,90 90, 27 27,90 90, 153 27,90 90, 27 153, 90 90, 153 153\" /> </svg> </div> </div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210921173505/bg.png\" style=\"z-index:-1;\"> </center></body> </html>",
"e": 25831,
"s": 24293,
"text": null
},
{
"code": null,
"e": 25839,
"s": 25831,
"text": "Output:"
},
{
"code": null,
"e": 25976,
"s": 25839,
"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": 25991,
"s": 25976,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 26006,
"s": 25991,
"text": "CSS-Properties"
},
{
"code": null,
"e": 26020,
"s": 26006,
"text": "CSS-Questions"
},
{
"code": null,
"e": 26035,
"s": 26020,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26045,
"s": 26035,
"text": "HTML-Tags"
},
{
"code": null,
"e": 26055,
"s": 26045,
"text": "Blogathon"
},
{
"code": null,
"e": 26059,
"s": 26055,
"text": "CSS"
},
{
"code": null,
"e": 26064,
"s": 26059,
"text": "HTML"
},
{
"code": null,
"e": 26081,
"s": 26064,
"text": "Web Technologies"
},
{
"code": null,
"e": 26086,
"s": 26081,
"text": "HTML"
},
{
"code": null,
"e": 26184,
"s": 26086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26193,
"s": 26184,
"text": "Comments"
},
{
"code": null,
"e": 26206,
"s": 26193,
"text": "Old Comments"
},
{
"code": null,
"e": 26241,
"s": 26206,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 26267,
"s": 26241,
"text": "Python NOT EQUAL operator"
},
{
"code": null,
"e": 26324,
"s": 26267,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 26362,
"s": 26324,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 26403,
"s": 26362,
"text": "How to Connect Python with SQL Database?"
},
{
"code": null,
"e": 26465,
"s": 26403,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26515,
"s": 26465,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26573,
"s": 26515,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26621,
"s": 26573,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Brothers From Different Roots | Practice | GeeksforGeeks
|
Given two BSTs containing N1 and N2 distinct nodes respectively and given a value x. Your task is to complete the function countPairs(), that returns the count of all pairs from both the BSTs whose sum is equal to x.
Example 1:
Input:
BST1:
5
/ \
3 7
/ \ / \
2 4 6 8
BST2:
10
/ \
6 15
/ \ / \
3 8 11 18
x = 16
Output:
3
Explanation:
The pairs are: (5, 11), (6, 10) and (8, 8)
Example 2:
Input:
BST1:
1
\
3
/
2
BST2:
3
/ \
2 4
/
1
x = 4
Output:
3
Explanation:
The pairs are: (2, 2), (3, 1) and (1, 3)
Your Task:
You don't need to read input or print anything. Your task is to complete the function countPairs(), which takes 2 BST's as parameter in form of root1 and root2 and the integer x, that returns the count of all pairs from both the BSTs whose sum is equal to x.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 106
+1
aakashjangra774 days ago
void inorder(Node* root,map<int,int> &store){ if(root==NULL) { return ; } inorder(root->left,store); store[root->data]=1; inorder(root->right,store); }
int countPairs(Node* root1, Node* root2, int X) { map<int,int> store1,store2; inorder(root1,store1); inorder(root2,store2); int count=0; for(auto i:store1) { if(store2[X-i.first]==1) { count++; } } return count;
}
+1
ricardo991 week ago
int ans=0; // Global Variable to hold the ans
void find(Node* root, unordered_set<int> &s, int x)
{
if(root==NULL)
return;
if(s.find(x-root->data)!=s.end())
ans++;
find(root->left, s, x);
find(root->right, s, x);
}
void fill2nd(Node* root, unordered_set<int>& s)
{
if(root==NULL)
return;
s.insert(root->data);
fill2nd(root->left, s);
fill2nd(root->right, s);
}
int countPairs(Node* root1, Node* root2, int x)
{
unordered_set<int> s;
fill2nd(root2, s);
find(root1, s, x);
return ans;
}
0
aryankhatana352 weeks ago
class Solution{public:int c; bool fetch(Node*root2,int k){ if(root2==NULL){ return false; } // if(!root2) return false; if(k==root2->data){ return true; } bool x,y; x=false; y=false; if(k<root2->data){ x=fetch(root2->left,k); } else if(k>root2->data){ y=fetch(root2->right,k); } return x or y; } void solve(Node* root1, Node* root2, int k){ if(root1==NULL){ return; } solve(root1->left,root2,k); if(fetch(root2,k-root1->data)){ c++; } solve(root1->right,root2,k); } int countPairs(Node* root1, Node* root2, int x) { c=0; solve(root1,root2,x); return c; }};
+1
raj22202 weeks ago
// Java Sloution with O(n) time complexity and O(n) Space Complexity
class Solution{public static int countPairs(Node root1, Node root2, int x){ ArrayList<Integer> in1 = new ArrayList<>(); ArrayList<Integer> in2 = new ArrayList<>(); inOrder(root1, in1); inOrder(root2, in2); int i = 0; int j = in2.size()-1; int count = 0; while(i < in1.size() && j >= 0) { int sum = in1.get(i) + in2.get(j) ; if(sum == x) { count++; i++; j--; } else if(sum < x) { i++; } else { j--; } } return count; }public static void inOrder(Node root, ArrayList<Integer> in){ if(root == null) { return; } inOrder(root.left, in); in.add(root.data); inOrder(root.right, in);}}
+1
sgupta95191 month ago
class Solution
{
public static int countPairs(Node root1, Node root2, int x)
{
// Code here
if(root1==null)
return 0;
return chec(root2,x-root1.data)+countPairs(root1.left,root2,x)+countPairs(root1.right,root2,x);
}
static int chec(Node root2, int x)
{
if(root2==null)
return 0;
if(root2.data==x)
return 1;
if(root2.data<x)
return chec(root2.right,x);
return chec(root2.left,x);
}
}
0
ahmadsahil261 month ago
class Solution{ public static void inorder(Node root,ArrayList<Integer> list){ if(root==null) return; inorder(root.left,list); list.add(root.data); inorder(root.right,list); } public static int countPairs(Node root1, Node root2, int x){ // Code here ArrayList<Integer> first = new ArrayList<>(); ArrayList<Integer> second = new ArrayList<>(); inorder(root1,first); inorder(root2,second); int i = 0; int j = second.size()-1; int count = 0; while(i<first.size()&&j>=0){ int a = first.get(i); int b = second.get(j); if(a+b==x){ count++; i++; j--; } else if(a+b<x){ i++; }else j--; } return count; }}
0
milindprajapatmst191 month ago
Linear Space and Complexity.
const int N = 1e6;
int _hash[N + 1];
class Solution {
public:
void inorder(Node* root, int x, int k, int& cnt) {
if (!root)
return;
inorder(root->left, x, k, cnt);
if (k && x - root->data > 0 && x - root->data <= N)
cnt += _hash[x - root->data];
else if (!k)
_hash[root->data]++;
inorder(root->right, x, k, cnt);
}
int countPairs(Node* root1, Node* root2, int x) {
memset(_hash, 0, sizeof(_hash));
int cnt = 0;
inorder(root1, x, 0, cnt);
inorder(root2, x, 1, cnt);
return cnt;
}
};
+1
sfazal0001 month ago
int cnt;
bool pairs(node* root1 , int k){ if(!root1) return false; if(k == root1->data) return true; bool x = false; bool y = false; if(k< root1->data) { x = pairs(root1->left, k); } else if(k> root1->data) { y = pairs(root1->right ,k); } return x or y;}
void solve(node* root , node* root1 , int k){ if(!root and root1) return ; solve(root->left, root1,k); if(pairs(root1, k-root->data)) { cnt++; } solve(root->right, root1,k);}
int countPairs(node* root, node* root1, int k){ if(!root) return 0; cnt =0; solve(root, root1,k); return cnt;}
+1
golaravi5552 months ago
void inorder(Node *root,vector<int>&v){ if(!root)return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } int countPairs(Node* root1, Node* root2, int x) { vector<int>v1,v2; inorder(root1,v1); inorder(root2,v2); unordered_set<int> s(v1.begin(),v1.end()); int ct = 0; for(int i = 0; i < v2.size(); i++){ if(s.find(x - v2[i]) != s.end()) ct++; } return ct; }
0
sanketbhagat2 months ago
SMPLE JAVA SOLUTION
class Solution{
static void inorder(Node root,Set<Integer> set){
if(root==null) return;
inorder(root.left,set);
set.add(root.data);
inorder(root.right,set);
}
public static int countPairs(Node root1, Node root2, int x){
// Code here
Set<Integer> set1 = new HashSet();
inorder(root1,set1);
Set<Integer> set2 = new HashSet<>();
inorder(root2,set2);
int ans = 0;
for(int i: set1) if(set2.contains(x-i)) ans++;
return ans;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 455,
"s": 238,
"text": "Given two BSTs containing N1 and N2 distinct nodes respectively and given a value x. Your task is to complete the function countPairs(), that returns the count of all pairs from both the BSTs whose sum is equal to x."
},
{
"code": null,
"e": 467,
"s": 455,
"text": "\nExample 1:"
},
{
"code": null,
"e": 689,
"s": 467,
"text": "Input:\nBST1:\n 5\n / \\\n 3 7\n / \\ / \\\n 2 4 6 8\n\nBST2:\n 10\n / \\\n 6 15\n / \\ / \\\n 3 8 11 18\n\nx = 16\nOutput:\n3\nExplanation:\nThe pairs are: (5, 11), (6, 10) and (8, 8)\n"
},
{
"code": null,
"e": 702,
"s": 691,
"text": "Example 2:"
},
{
"code": null,
"e": 848,
"s": 702,
"text": "Input:\nBST1:\n 1\n \\\n 3\n /\n 2\nBST2:\n 3\n / \\\n 2 4\n / \n1\n\nx = 4\nOutput:\n3\nExplanation:\nThe pairs are: (2, 2), (3, 1) and (1, 3)\n"
},
{
"code": null,
"e": 1119,
"s": 848,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countPairs(), which takes 2 BST's as parameter in form of root1 and root2 and the integer x, that returns the count of all pairs from both the BSTs whose sum is equal to x."
},
{
"code": null,
"e": 1182,
"s": 1119,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1247,
"s": 1182,
"text": "\nConstraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 106"
},
{
"code": null,
"e": 1250,
"s": 1247,
"text": "+1"
},
{
"code": null,
"e": 1275,
"s": 1250,
"text": "aakashjangra774 days ago"
},
{
"code": null,
"e": 1450,
"s": 1275,
"text": "void inorder(Node* root,map<int,int> &store){ if(root==NULL) { return ; } inorder(root->left,store); store[root->data]=1; inorder(root->right,store); }"
},
{
"code": null,
"e": 1795,
"s": 1450,
"text": " int countPairs(Node* root1, Node* root2, int X) { map<int,int> store1,store2; inorder(root1,store1); inorder(root2,store2); int count=0; for(auto i:store1) { if(store2[X-i.first]==1) { count++; } } return count;"
},
{
"code": null,
"e": 1800,
"s": 1795,
"text": " }"
},
{
"code": null,
"e": 1803,
"s": 1800,
"text": "+1"
},
{
"code": null,
"e": 1823,
"s": 1803,
"text": "ricardo991 week ago"
},
{
"code": null,
"e": 2379,
"s": 1823,
"text": "int ans=0; // Global Variable to hold the ans \nvoid find(Node* root, unordered_set<int> &s, int x)\n{\n if(root==NULL)\n return;\n if(s.find(x-root->data)!=s.end())\n ans++;\n find(root->left, s, x);\n find(root->right, s, x);\n}\nvoid fill2nd(Node* root, unordered_set<int>& s)\n{\n if(root==NULL)\n return;\n s.insert(root->data);\n fill2nd(root->left, s);\n fill2nd(root->right, s);\n}\n int countPairs(Node* root1, Node* root2, int x)\n {\n unordered_set<int> s;\n fill2nd(root2, s);\n find(root1, s, x);\n return ans;\n }"
},
{
"code": null,
"e": 2381,
"s": 2379,
"text": "0"
},
{
"code": null,
"e": 2407,
"s": 2381,
"text": "aryankhatana352 weeks ago"
},
{
"code": null,
"e": 3168,
"s": 2407,
"text": "class Solution{public:int c; bool fetch(Node*root2,int k){ if(root2==NULL){ return false; } // if(!root2) return false; if(k==root2->data){ return true; } bool x,y; x=false; y=false; if(k<root2->data){ x=fetch(root2->left,k); } else if(k>root2->data){ y=fetch(root2->right,k); } return x or y; } void solve(Node* root1, Node* root2, int k){ if(root1==NULL){ return; } solve(root1->left,root2,k); if(fetch(root2,k-root1->data)){ c++; } solve(root1->right,root2,k); } int countPairs(Node* root1, Node* root2, int x) { c=0; solve(root1,root2,x); return c; }};"
},
{
"code": null,
"e": 3171,
"s": 3168,
"text": "+1"
},
{
"code": null,
"e": 3190,
"s": 3171,
"text": "raj22202 weeks ago"
},
{
"code": null,
"e": 3259,
"s": 3190,
"text": "// Java Sloution with O(n) time complexity and O(n) Space Complexity"
},
{
"code": null,
"e": 3947,
"s": 3261,
"text": "class Solution{public static int countPairs(Node root1, Node root2, int x){ ArrayList<Integer> in1 = new ArrayList<>(); ArrayList<Integer> in2 = new ArrayList<>(); inOrder(root1, in1); inOrder(root2, in2); int i = 0; int j = in2.size()-1; int count = 0; while(i < in1.size() && j >= 0) { int sum = in1.get(i) + in2.get(j) ; if(sum == x) { count++; i++; j--; } else if(sum < x) { i++; } else { j--; } } return count; }public static void inOrder(Node root, ArrayList<Integer> in){ if(root == null) { return; } inOrder(root.left, in); in.add(root.data); inOrder(root.right, in);}}"
},
{
"code": null,
"e": 3950,
"s": 3947,
"text": "+1"
},
{
"code": null,
"e": 3972,
"s": 3950,
"text": "sgupta95191 month ago"
},
{
"code": null,
"e": 4392,
"s": 3972,
"text": "class Solution\n{\npublic static int countPairs(Node root1, Node root2, int x)\n{\n // Code here\n if(root1==null)\n return 0;\n return chec(root2,x-root1.data)+countPairs(root1.left,root2,x)+countPairs(root1.right,root2,x);\n}\nstatic int chec(Node root2, int x)\n{\n if(root2==null)\n return 0;\n if(root2.data==x)\n return 1;\n if(root2.data<x)\n return chec(root2.right,x);\n return chec(root2.left,x);\n \n}\n}"
},
{
"code": null,
"e": 4394,
"s": 4392,
"text": "0"
},
{
"code": null,
"e": 4418,
"s": 4394,
"text": "ahmadsahil261 month ago"
},
{
"code": null,
"e": 5183,
"s": 4418,
"text": "class Solution{ public static void inorder(Node root,ArrayList<Integer> list){ if(root==null) return; inorder(root.left,list); list.add(root.data); inorder(root.right,list); } public static int countPairs(Node root1, Node root2, int x){ // Code here ArrayList<Integer> first = new ArrayList<>(); ArrayList<Integer> second = new ArrayList<>(); inorder(root1,first); inorder(root2,second); int i = 0; int j = second.size()-1; int count = 0; while(i<first.size()&&j>=0){ int a = first.get(i); int b = second.get(j); if(a+b==x){ count++; i++; j--; } else if(a+b<x){ i++; }else j--; } return count; }}"
},
{
"code": null,
"e": 5185,
"s": 5183,
"text": "0"
},
{
"code": null,
"e": 5216,
"s": 5185,
"text": "milindprajapatmst191 month ago"
},
{
"code": null,
"e": 5860,
"s": 5216,
"text": "Linear Space and Complexity.\n\nconst int N = 1e6;\nint _hash[N + 1];\nclass Solution {\npublic:\n void inorder(Node* root, int x, int k, int& cnt) {\n if (!root)\n return;\n inorder(root->left, x, k, cnt);\n if (k && x - root->data > 0 && x - root->data <= N)\n cnt += _hash[x - root->data];\n else if (!k)\n _hash[root->data]++;\n inorder(root->right, x, k, cnt);\n }\n int countPairs(Node* root1, Node* root2, int x) {\n memset(_hash, 0, sizeof(_hash));\n int cnt = 0;\n inorder(root1, x, 0, cnt);\n inorder(root2, x, 1, cnt);\n return cnt;\n }\n};"
},
{
"code": null,
"e": 5863,
"s": 5860,
"text": "+1"
},
{
"code": null,
"e": 5884,
"s": 5863,
"text": "sfazal0001 month ago"
},
{
"code": null,
"e": 5893,
"s": 5884,
"text": "int cnt;"
},
{
"code": null,
"e": 6193,
"s": 5893,
"text": "bool pairs(node* root1 , int k){ if(!root1) return false; if(k == root1->data) return true; bool x = false; bool y = false; if(k< root1->data) { x = pairs(root1->left, k); } else if(k> root1->data) { y = pairs(root1->right ,k); } return x or y;}"
},
{
"code": null,
"e": 6416,
"s": 6195,
"text": "void solve(node* root , node* root1 , int k){ if(!root and root1) return ; solve(root->left, root1,k); if(pairs(root1, k-root->data)) { cnt++; } solve(root->right, root1,k);} "
},
{
"code": null,
"e": 6549,
"s": 6418,
"text": "int countPairs(node* root, node* root1, int k){ if(!root) return 0; cnt =0; solve(root, root1,k); return cnt;} "
},
{
"code": null,
"e": 6552,
"s": 6549,
"text": "+1"
},
{
"code": null,
"e": 6576,
"s": 6552,
"text": "golaravi5552 months ago"
},
{
"code": null,
"e": 7063,
"s": 6576,
"text": " void inorder(Node *root,vector<int>&v){ if(!root)return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } int countPairs(Node* root1, Node* root2, int x) { vector<int>v1,v2; inorder(root1,v1); inorder(root2,v2); unordered_set<int> s(v1.begin(),v1.end()); int ct = 0; for(int i = 0; i < v2.size(); i++){ if(s.find(x - v2[i]) != s.end()) ct++; } return ct; }"
},
{
"code": null,
"e": 7065,
"s": 7063,
"text": "0"
},
{
"code": null,
"e": 7090,
"s": 7065,
"text": "sanketbhagat2 months ago"
},
{
"code": null,
"e": 7110,
"s": 7090,
"text": "SMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 7601,
"s": 7110,
"text": "class Solution{\n \n static void inorder(Node root,Set<Integer> set){\n if(root==null) return;\n inorder(root.left,set);\n set.add(root.data);\n inorder(root.right,set);\n }\n \n\tpublic static int countPairs(Node root1, Node root2, int x){\n\t\t// Code here\n\t\tSet<Integer> set1 = new HashSet();\n\t\tinorder(root1,set1);\n\t\tSet<Integer> set2 = new HashSet<>();\n\t\tinorder(root2,set2);\n\t\tint ans = 0;\n\t\tfor(int i: set1) if(set2.contains(x-i)) ans++;\n\t\treturn ans;\n\t}\n}"
},
{
"code": null,
"e": 7747,
"s": 7601,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7783,
"s": 7747,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7793,
"s": 7783,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7803,
"s": 7793,
"text": "\nContest\n"
},
{
"code": null,
"e": 7866,
"s": 7803,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8014,
"s": 7866,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8222,
"s": 8014,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8328,
"s": 8222,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java program to find whether the given string is empty or null
|
The isEmpty() method of the String class returns true if the length of the current string is 0.
import java.util.Scanner;
public class StringEmptyOrNull {
public static void main(String[] args) {
System.out.println("Enter a string value ::");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
if(str.isEmpty()&& str==null ){
System.out.println("Given string is empty or null");
}else{
System.out.println("Given string is not empty or null");
}
}
}
Enter a string value ::
Hi welcome to tutorialspoint
Given string is not empty or null
Enter a string value ::
Given string is empty or null
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "The isEmpty() method of the String class returns true if the length of the current string is 0."
},
{
"code": null,
"e": 1587,
"s": 1158,
"text": "import java.util.Scanner;\npublic class StringEmptyOrNull {\n public static void main(String[] args) {\n System.out.println(\"Enter a string value ::\");\n Scanner sc = new Scanner(System.in);\n String str = sc.nextLine();\n\n if(str.isEmpty()&& str==null ){\n System.out.println(\"Given string is empty or null\");\n }else{\n System.out.println(\"Given string is not empty or null\");\n }\n }\n}\n"
},
{
"code": null,
"e": 1674,
"s": 1587,
"text": "Enter a string value ::\nHi welcome to tutorialspoint\nGiven string is not empty or null"
},
{
"code": null,
"e": 1728,
"s": 1674,
"text": "Enter a string value ::\nGiven string is empty or null"
}
] |
How do I load an image by URL on iOS device using Swift?
|
To load an image in iOS using swift we’ll make use of simple data Task session. The image needs to be loaded in background because it may be of any size and we don’t want it to stop our main view’s operations.
Let’s see this with help of an example. Create an empty project and add an empty Image view.
Create its outlet and then we’ll write the code to get image from an URL. This is how our application looks at the moment.
Now, let’s add code to get image from an URL.
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL) {
getData(from: url) {
data, response, error in
guard let data = data, error == nil else {
return
}
DispatchQueue.main.async() {
self.image = UIImage(data: data)
}
}
}
When we run this code, it will download image from the URL, we can create an image object and initialize our imgView with the new object.
But let’s create an extension of this method and use.
extension UIImageView {
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL) {
getData(from: url) {
data, response, error in
guard let data = data, error == nil else {
return
}
DispatchQueue.main.async() {
self.image = UIImage(data: data)
}
}
}
}
Now, In our viewDidLoad (or any other place you like) add the following code.
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681")
self.imgView.downloadImage(from: url!)
}
When we run this code on our device, we get the following result.
|
[
{
"code": null,
"e": 1272,
"s": 1062,
"text": "To load an image in iOS using swift we’ll make use of simple data Task session. The image needs to be loaded in background because it may be of any size and we don’t want it to stop our main view’s operations."
},
{
"code": null,
"e": 1365,
"s": 1272,
"text": "Let’s see this with help of an example. Create an empty project and add an empty Image view."
},
{
"code": null,
"e": 1488,
"s": 1365,
"text": "Create its outlet and then we’ll write the code to get image from an URL. This is how our application looks at the moment."
},
{
"code": null,
"e": 1534,
"s": 1488,
"text": "Now, let’s add code to get image from an URL."
},
{
"code": null,
"e": 1961,
"s": 1534,
"text": "func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {\n URLSession.shared.dataTask(with: url, completionHandler: completion).resume()\n}\nfunc downloadImage(from url: URL) {\n getData(from: url) {\n data, response, error in\n guard let data = data, error == nil else {\n return\n }\n DispatchQueue.main.async() {\n self.image = UIImage(data: data)\n }\n }\n}"
},
{
"code": null,
"e": 2099,
"s": 1961,
"text": "When we run this code, it will download image from the URL, we can create an image object and initialize our imgView with the new object."
},
{
"code": null,
"e": 2153,
"s": 2099,
"text": "But let’s create an extension of this method and use."
},
{
"code": null,
"e": 2649,
"s": 2153,
"text": "extension UIImageView {\n func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {\n URLSession.shared.dataTask(with: url, completionHandler: completion).resume()\n }\n func downloadImage(from url: URL) {\n getData(from: url) {\n data, response, error in\n guard let data = data, error == nil else {\n return\n }\n DispatchQueue.main.async() {\n self.image = UIImage(data: data)\n }\n }\n }\n}"
},
{
"code": null,
"e": 2727,
"s": 2649,
"text": "Now, In our viewDidLoad (or any other place you like) add the following code."
},
{
"code": null,
"e": 2962,
"s": 2727,
"text": "override func viewDidLoad() {\n super.viewDidLoad()\n let url = URL(string: \"https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681\")\n self.imgView.downloadImage(from: url!)\n}"
},
{
"code": null,
"e": 3028,
"s": 2962,
"text": "When we run this code on our device, we get the following result."
}
] |
How to create full width container in bootstrap5? - GeeksforGeeks
|
10 Sep, 2020
Bootstrap containers are content holders that are used to align, add margins and padding to your content. Bootstrap has three different container classes, namely:
.container
.container-fluid
.container-{breakpoint}
Width of a container varies in accordance with its class. We can create a full width container in Bootstrap5 using “.container-fluid” class. It sets the container width equal to 100% in all screen sizes. This means the container spans the entire width of the viewport.
Syntax:
<div class= ".container-fluid">
...
</div>
Example:
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <style> .gfg { background-color: green; color: white; text-align: center; } </style> </head> <body> <div class="container-fluid gfg"> <h2>GeeksforGeeks</h2> </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.
Bootstrap-Misc
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to change the background color of the active nav-item?
How to Use Bootstrap with React?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 25186,
"s": 25158,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 25351,
"s": 25186,
"text": "Bootstrap containers are content holders that are used to align, add margins and padding to your content. Bootstrap has three different container classes, namely: "
},
{
"code": null,
"e": 25362,
"s": 25351,
"text": ".container"
},
{
"code": null,
"e": 25379,
"s": 25362,
"text": ".container-fluid"
},
{
"code": null,
"e": 25403,
"s": 25379,
"text": ".container-{breakpoint}"
},
{
"code": null,
"e": 25672,
"s": 25403,
"text": "Width of a container varies in accordance with its class. We can create a full width container in Bootstrap5 using “.container-fluid” class. It sets the container width equal to 100% in all screen sizes. This means the container spans the entire width of the viewport."
},
{
"code": null,
"e": 25680,
"s": 25672,
"text": "Syntax:"
},
{
"code": null,
"e": 25728,
"s": 25680,
"text": "<div class= \".container-fluid\">\n ...\n</div> \n"
},
{
"code": null,
"e": 25737,
"s": 25728,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <style> .gfg { background-color: green; color: white; text-align: center; } </style> </head> <body> <div class=\"container-fluid gfg\"> <h2>GeeksforGeeks</h2> </div> </body></html>",
"e": 26334,
"s": 25737,
"text": null
},
{
"code": null,
"e": 26342,
"s": 26334,
"text": "Output:"
},
{
"code": null,
"e": 26479,
"s": 26342,
"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": 26494,
"s": 26479,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 26504,
"s": 26494,
"text": "Bootstrap"
},
{
"code": null,
"e": 26509,
"s": 26504,
"text": "HTML"
},
{
"code": null,
"e": 26526,
"s": 26509,
"text": "Web Technologies"
},
{
"code": null,
"e": 26531,
"s": 26526,
"text": "HTML"
},
{
"code": null,
"e": 26629,
"s": 26531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26670,
"s": 26629,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 26711,
"s": 26670,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 26774,
"s": 26711,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 26833,
"s": 26774,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 26866,
"s": 26833,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 26916,
"s": 26866,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26978,
"s": 26916,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27038,
"s": 26978,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27086,
"s": 27038,
"text": "How to update Node.js and NPM to next version ?"
}
] |
VB.Net - ScrollBar Control
|
The ScrollBar controls display vertical and horizontal scroll bars on the form. This is used for navigating through large amount of information. There are two types of scroll bar controls: HScrollBar for horizontal scroll bars and VScrollBar for vertical scroll bars. These are used independently from each other.
Let's click on HScrollBar control and VScrollBar control from the Toolbox and place them on the form.
The following are some of the commonly used properties of the ScrollBar control −
AutoSize
Gets or sets a value indicating whether the ScrollBar is automatically resized to fit its contents.
BackColor
Gets or sets the background color for the control.
ForeColor
Gets or sets the foreground color of the scroll bar control.
ImeMode
Gets or sets the Input Method Editor (IME) mode supported by this control.
LargeChange
Gets or sets a value to be added to or subtracted from the Value property when the scroll box is moved a large distance.
Maximum
Gets or sets the upper limit of values of the scrollable range.
Minimum
Gets or sets the lower limit of values of the scrollable range.
SmallChange
Gets or sets the value to be added to or subtracted from the Value property when the scroll box is moved a small distance.
Value
Gets or sets a numeric value that represents the current position of the scroll box on the scroll bar control.
The following are some of the commonly used methods of the ScrollBar control −
OnClick
Generates the Click event.
Select
Activates the control.
The following are some of the commonly used events of the ScrollBar control −
Click
Occurs when the control is clicked.
DoubleClick
Occurs when the user double-clicks the control.
Scroll
Occurs when the control is moved.
ValueChanged
Occurs when the Value property changes, either by handling the Scroll event or programmatically.
In this example, let us create two scroll bars at runtime. Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'create two scroll bars
Dim hs As HScrollBar
Dim vs As VScrollBar
hs = New HScrollBar()
vs = New VScrollBar()
'set properties
hs.Location = New Point(10, 200)
hs.Size = New Size(175, 15)
hs.Value = 50
vs.Location = New Point(200, 30)
vs.Size = New Size(15, 175)
hs.Value = 50
'adding the scroll bars to the form
Me.Controls.Add(hs)
Me.Controls.Add(vs)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2614,
"s": 2300,
"text": "The ScrollBar controls display vertical and horizontal scroll bars on the form. This is used for navigating through large amount of information. There are two types of scroll bar controls: HScrollBar for horizontal scroll bars and VScrollBar for vertical scroll bars. These are used independently from each other."
},
{
"code": null,
"e": 2716,
"s": 2614,
"text": "Let's click on HScrollBar control and VScrollBar control from the Toolbox and place them on the form."
},
{
"code": null,
"e": 2798,
"s": 2716,
"text": "The following are some of the commonly used properties of the ScrollBar control −"
},
{
"code": null,
"e": 2807,
"s": 2798,
"text": "AutoSize"
},
{
"code": null,
"e": 2907,
"s": 2807,
"text": "Gets or sets a value indicating whether the ScrollBar is automatically resized to fit its contents."
},
{
"code": null,
"e": 2917,
"s": 2907,
"text": "BackColor"
},
{
"code": null,
"e": 2968,
"s": 2917,
"text": "Gets or sets the background color for the control."
},
{
"code": null,
"e": 2978,
"s": 2968,
"text": "ForeColor"
},
{
"code": null,
"e": 3039,
"s": 2978,
"text": "Gets or sets the foreground color of the scroll bar control."
},
{
"code": null,
"e": 3047,
"s": 3039,
"text": "ImeMode"
},
{
"code": null,
"e": 3122,
"s": 3047,
"text": "Gets or sets the Input Method Editor (IME) mode supported by this control."
},
{
"code": null,
"e": 3134,
"s": 3122,
"text": "LargeChange"
},
{
"code": null,
"e": 3255,
"s": 3134,
"text": "Gets or sets a value to be added to or subtracted from the Value property when the scroll box is moved a large distance."
},
{
"code": null,
"e": 3263,
"s": 3255,
"text": "Maximum"
},
{
"code": null,
"e": 3327,
"s": 3263,
"text": "Gets or sets the upper limit of values of the scrollable range."
},
{
"code": null,
"e": 3335,
"s": 3327,
"text": "Minimum"
},
{
"code": null,
"e": 3399,
"s": 3335,
"text": "Gets or sets the lower limit of values of the scrollable range."
},
{
"code": null,
"e": 3411,
"s": 3399,
"text": "SmallChange"
},
{
"code": null,
"e": 3534,
"s": 3411,
"text": "Gets or sets the value to be added to or subtracted from the Value property when the scroll box is moved a small distance."
},
{
"code": null,
"e": 3540,
"s": 3534,
"text": "Value"
},
{
"code": null,
"e": 3651,
"s": 3540,
"text": "Gets or sets a numeric value that represents the current position of the scroll box on the scroll bar control."
},
{
"code": null,
"e": 3730,
"s": 3651,
"text": "The following are some of the commonly used methods of the ScrollBar control −"
},
{
"code": null,
"e": 3738,
"s": 3730,
"text": "OnClick"
},
{
"code": null,
"e": 3765,
"s": 3738,
"text": "Generates the Click event."
},
{
"code": null,
"e": 3772,
"s": 3765,
"text": "Select"
},
{
"code": null,
"e": 3795,
"s": 3772,
"text": "Activates the control."
},
{
"code": null,
"e": 3873,
"s": 3795,
"text": "The following are some of the commonly used events of the ScrollBar control −"
},
{
"code": null,
"e": 3879,
"s": 3873,
"text": "Click"
},
{
"code": null,
"e": 3915,
"s": 3879,
"text": "Occurs when the control is clicked."
},
{
"code": null,
"e": 3927,
"s": 3915,
"text": "DoubleClick"
},
{
"code": null,
"e": 3975,
"s": 3927,
"text": "Occurs when the user double-clicks the control."
},
{
"code": null,
"e": 3982,
"s": 3975,
"text": "Scroll"
},
{
"code": null,
"e": 4016,
"s": 3982,
"text": "Occurs when the control is moved."
},
{
"code": null,
"e": 4029,
"s": 4016,
"text": "ValueChanged"
},
{
"code": null,
"e": 4127,
"s": 4029,
"text": "Occurs when the Value property changes, either by handling the Scroll event or programmatically. "
},
{
"code": null,
"e": 4263,
"s": 4127,
"text": "In this example, let us create two scroll bars at runtime. Let's double click on the Form and put the follow code in the opened window."
},
{
"code": null,
"e": 4939,
"s": 4263,
"text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) _\n Handles MyBase.Load\n \n 'create two scroll bars\n Dim hs As HScrollBar\n Dim vs As VScrollBar\n hs = New HScrollBar()\n vs = New VScrollBar()\n \n 'set properties\n hs.Location = New Point(10, 200)\n hs.Size = New Size(175, 15)\n hs.Value = 50\n vs.Location = New Point(200, 30)\n vs.Size = New Size(15, 175)\n hs.Value = 50\n \n 'adding the scroll bars to the form\n Me.Controls.Add(hs)\n Me.Controls.Add(vs)\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\nEnd Class"
},
{
"code": null,
"e": 5085,
"s": 4939,
"text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −"
},
{
"code": null,
"e": 5118,
"s": 5085,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5135,
"s": 5118,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5170,
"s": 5135,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5185,
"s": 5170,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5220,
"s": 5185,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5235,
"s": 5220,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5268,
"s": 5235,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5283,
"s": 5268,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5290,
"s": 5283,
"text": " Print"
},
{
"code": null,
"e": 5301,
"s": 5290,
"text": " Add Notes"
}
] |
Java program to check occurence of each character in String
|
In order to find occurrence of each character in a string we can use Map utility of Java.In Map, a key could not be duplicate so make each character of the string as the key of Map and provide an initial value corresponding to each key as 1 if this character does not insert in the map before. Now when a character repeats during insertion as key in Map increase its value by one. Continue this for each character until all characters of string get inserted.
public class occurenceOfCharacter {
public static void main(String[] args) {
String str = "SSDRRRTTYYTYTR";
HashMap <Character, Integer> hMap = new HashMap<>();
for (int i = str.length() - 1; i > = 0; i--) {
if (hMap.containsKey(str.charAt(i))) {
int count = hMap.get(str.charAt(i));
hMap.put(str.charAt(i), ++count);
} else {
hMap.put(str.charAt(i),1);
}
}
System.out.println(hMap);
}
}
{D=1, T=4, S=2, R=4, Y=3}
|
[
{
"code": null,
"e": 1521,
"s": 1062,
"text": "In order to find occurrence of each character in a string we can use Map utility of Java.In Map, a key could not be duplicate so make each character of the string as the key of Map and provide an initial value corresponding to each key as 1 if this character does not insert in the map before. Now when a character repeats during insertion as key in Map increase its value by one. Continue this for each character until all characters of string get inserted."
},
{
"code": null,
"e": 2008,
"s": 1521,
"text": "public class occurenceOfCharacter {\n public static void main(String[] args) {\n String str = \"SSDRRRTTYYTYTR\";\n HashMap <Character, Integer> hMap = new HashMap<>();\n for (int i = str.length() - 1; i > = 0; i--) {\n if (hMap.containsKey(str.charAt(i))) {\n int count = hMap.get(str.charAt(i));\n hMap.put(str.charAt(i), ++count);\n } else {\n hMap.put(str.charAt(i),1);\n }\n }\n System.out.println(hMap);\n }\n}"
},
{
"code": null,
"e": 2034,
"s": 2008,
"text": "{D=1, T=4, S=2, R=4, Y=3}"
}
] |
C program for DFA accepting all strings over w ∈(a,b)* containing “aba” as a substring
|
Design a DFA for the language L={w1abaw2 | w1,w2 Є(a,b)*}, which means the DFA accepts all strings which contain “aba” as a substring.
The strings that are accepted by language L= {aba,aabaa, aabab, babab, ababa, .......}
Step 1 − Transition diagram for minimal string (starting string) −
If w1 and w2 are null then the string it generates is “aba” because w1, w2 ε(a,b)*
q0 is the initial state and q3 is the final state.
Step 2 − The final DFA for the given language is as follows −
qo is the initial state q0 on ‘a’ goes to q1 and on ‘b’ goes to q0, according to DFA each state has to generate a transition on both inputs.
qo is the initial state q0 on ‘a’ goes to q1 and on ‘b’ goes to q0, according to DFA each state has to generate a transition on both inputs.
q1 on ‘a’ goes to q1 and on ‘b’ goes to q2, we have to keep in mind according to the given language we need to generate a substring “aba”.
q1 on ‘a’ goes to q1 and on ‘b’ goes to q2, we have to keep in mind according to the given language we need to generate a substring “aba”.
q2 on ‘a’ goes on q3 on ‘b’ goes to q0 state.
q2 on ‘a’ goes on q3 on ‘b’ goes to q0 state.
q3 which is the final state, on input ‘a’ and ‘b’ goes to q3 only.
q3 which is the final state, on input ‘a’ and ‘b’ goes to q3 only.
Let’s see the transition table as follows −
Following is the C program for construction of DFA accepting all strings over w ε(a,b)* which contains “aba” as a substring -
Live Demo
#include <stdio.h>
#include <string.h>
void checkDFA(char s[] ) {
// storing initial state
int initialState = 0;
//assign initial state to previous state.
int previousState = initialState;
int finalState;
for(int i = 0; i < strlen(s); i++) {
if((previousState == 0 && s[i] == 'a') || (previousState == 1 && s[i] == 'a')) {
finalState = 1;
}
if((previousState == 0 && s[i] == 'b') || (previousState == 2 && s[i] == 'b')) {
finalState = 0;
}
if(previousState == 1 && s[i] == 'b') {
finalState = 2;
}
if((previousState == 2 && s[i] == 'a') || (previousState == 3)) {
finalState = 3;
}
previousState = finalState;
}
if(finalState == 3) {
printf("given string is Accepted");
}
else
{
printf("given string is Not Accepted");
}
}
int main() {
// Given string
char s[40];
printf("implementation of DFA which having a sub string 'aba':\n enter a string:");
scanf("%s",s);
checkDFA(s);
return 0;
}
The output is as follows −
Run 1:
implementation of DFA which having a sub string 'aba':
enter a string:aba
given string is Accepted.
Run 2:
implementation of DFA which having a sub string 'aba':
enter a string:abba
given string is Not Accepted.
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Design a DFA for the language L={w1abaw2 | w1,w2 Є(a,b)*}, which means the DFA accepts all strings which contain “aba” as a substring."
},
{
"code": null,
"e": 1284,
"s": 1197,
"text": "The strings that are accepted by language L= {aba,aabaa, aabab, babab, ababa, .......}"
},
{
"code": null,
"e": 1351,
"s": 1284,
"text": "Step 1 − Transition diagram for minimal string (starting string) −"
},
{
"code": null,
"e": 1434,
"s": 1351,
"text": "If w1 and w2 are null then the string it generates is “aba” because w1, w2 ε(a,b)*"
},
{
"code": null,
"e": 1485,
"s": 1434,
"text": "q0 is the initial state and q3 is the final state."
},
{
"code": null,
"e": 1547,
"s": 1485,
"text": "Step 2 − The final DFA for the given language is as follows −"
},
{
"code": null,
"e": 1688,
"s": 1547,
"text": "qo is the initial state q0 on ‘a’ goes to q1 and on ‘b’ goes to q0, according to DFA each state has to generate a transition on both inputs."
},
{
"code": null,
"e": 1829,
"s": 1688,
"text": "qo is the initial state q0 on ‘a’ goes to q1 and on ‘b’ goes to q0, according to DFA each state has to generate a transition on both inputs."
},
{
"code": null,
"e": 1968,
"s": 1829,
"text": "q1 on ‘a’ goes to q1 and on ‘b’ goes to q2, we have to keep in mind according to the given language we need to generate a substring “aba”."
},
{
"code": null,
"e": 2107,
"s": 1968,
"text": "q1 on ‘a’ goes to q1 and on ‘b’ goes to q2, we have to keep in mind according to the given language we need to generate a substring “aba”."
},
{
"code": null,
"e": 2153,
"s": 2107,
"text": "q2 on ‘a’ goes on q3 on ‘b’ goes to q0 state."
},
{
"code": null,
"e": 2199,
"s": 2153,
"text": "q2 on ‘a’ goes on q3 on ‘b’ goes to q0 state."
},
{
"code": null,
"e": 2266,
"s": 2199,
"text": "q3 which is the final state, on input ‘a’ and ‘b’ goes to q3 only."
},
{
"code": null,
"e": 2333,
"s": 2266,
"text": "q3 which is the final state, on input ‘a’ and ‘b’ goes to q3 only."
},
{
"code": null,
"e": 2377,
"s": 2333,
"text": "Let’s see the transition table as follows −"
},
{
"code": null,
"e": 2503,
"s": 2377,
"text": "Following is the C program for construction of DFA accepting all strings over w ε(a,b)* which contains “aba” as a substring -"
},
{
"code": null,
"e": 2514,
"s": 2503,
"text": " Live Demo"
},
{
"code": null,
"e": 3561,
"s": 2514,
"text": "#include <stdio.h>\n#include <string.h>\nvoid checkDFA(char s[] ) {\n // storing initial state\n int initialState = 0;\n //assign initial state to previous state.\n int previousState = initialState;\n int finalState;\n for(int i = 0; i < strlen(s); i++) {\n if((previousState == 0 && s[i] == 'a') || (previousState == 1 && s[i] == 'a')) {\n finalState = 1;\n }\n if((previousState == 0 && s[i] == 'b') || (previousState == 2 && s[i] == 'b')) {\n finalState = 0;\n }\n if(previousState == 1 && s[i] == 'b') {\n finalState = 2;\n }\n if((previousState == 2 && s[i] == 'a') || (previousState == 3)) {\n finalState = 3;\n }\n previousState = finalState;\n }\n if(finalState == 3) {\n printf(\"given string is Accepted\");\n }\n else\n {\n printf(\"given string is Not Accepted\");\n }\n}\nint main() {\n // Given string\n char s[40];\n printf(\"implementation of DFA which having a sub string 'aba':\\n enter a string:\");\n scanf(\"%s\",s);\n checkDFA(s);\n return 0;\n}"
},
{
"code": null,
"e": 3588,
"s": 3561,
"text": "The output is as follows −"
},
{
"code": null,
"e": 3807,
"s": 3588,
"text": "Run 1:\nimplementation of DFA which having a sub string 'aba':\nenter a string:aba\ngiven string is Accepted.\nRun 2:\nimplementation of DFA which having a sub string 'aba':\nenter a string:abba\ngiven string is Not Accepted."
}
] |
While loop- printTable - Java | Practice | GeeksforGeeks
|
While loop is another loop like for loop but unlike for loop it only checks for one condition.
Here, we will use a while loop and print a number n's table in reverse order.
Example 1:
Input:
1
Output:
10 9 8 7 6 5 4 3 2 1
Example 2:
Input:
2
Output:
20 18 16 14 12 10 8 6 4 2
User Task:
Your task is to complete the provided function and print the table in reverse order (with space between the values).
NOTE: As the code is checked against multiple test cases, the new line is necessary after every execution and the template code has taken care of that.
Constraints:
1 <= n<= 1000
0
arpandutta5033 weeks ago
Int I= 0;
While (i<11){
System .Out.println(I);
}
+1
shrutidhongade161 month ago
class Geeks {
static void printTable (int n)
{
int multiplier=10;
while(multiplier>0)
{
System.out.print(n * multiplier + " ");
multiplier -= 1;
//Your code here
}
System.out.println();
}
}
0
janmejayy2 months ago
static void printTable (int n) { for(int i=10;i>0;i--){ System.out.print(n*i+" "); } System.out.println(); }
0
piyushchpkumar2 months ago
JAVA SOLUTION
static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(multiplier*n+ " "); multiplier--; } System.out.println(); }
0
mdsaif04052 months ago
class Geeks {
static void printTable (int n)
{
int multiplier=10;
while(multiplier>0)
{
System.out.print(n*multiplier + " ");
multiplier--;
}
System.out.println();
}
}
0
mdsaif0405
This comment was deleted.
0
sdsapkale4 months ago
class Geeks { static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(multiplier*n+" "); multiplier--; } System.out.println(); }
}
0
badgujarsachin834 months ago
static void printTable (int n)
{
int multiplier=10;
while(multiplier>0)
{
//Your code here
System.out.print(n*multiplier+" ");
}
System.out.println();
}
-1
rawalaashi017 months ago
class Geeks { static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(n*multiplier +" "); //return(n*multiplier); multiplier--; }System.out.println();
}
}
0
garvitsingh14017 months ago
TIme - 0.2
class Geeks { static void printTable (int n) { int multiplier=10; int j=n*10; while(multiplier>0) { System.out.printf("%d ",j); j=j-n; multiplier--; } System.out.println(); }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 321,
"s": 226,
"text": "While loop is another loop like for loop but unlike for loop it only checks for one condition."
},
{
"code": null,
"e": 399,
"s": 321,
"text": "Here, we will use a while loop and print a number n's table in reverse order."
},
{
"code": null,
"e": 410,
"s": 399,
"text": "Example 1:"
},
{
"code": null,
"e": 450,
"s": 410,
"text": "Input:\n1\n\nOutput:\n10 9 8 7 6 5 4 3 2 1\n"
},
{
"code": null,
"e": 461,
"s": 450,
"text": "Example 2:"
},
{
"code": null,
"e": 505,
"s": 461,
"text": "Input:\n2\n\nOutput:\n20 18 16 14 12 10 8 6 4 2"
},
{
"code": null,
"e": 786,
"s": 505,
"text": "User Task: \nYour task is to complete the provided function and print the table in reverse order (with space between the values).\nNOTE: As the code is checked against multiple test cases, the new line is necessary after every execution and the template code has taken care of that."
},
{
"code": null,
"e": 813,
"s": 786,
"text": "Constraints:\n1 <= n<= 1000"
},
{
"code": null,
"e": 815,
"s": 813,
"text": "0"
},
{
"code": null,
"e": 840,
"s": 815,
"text": "arpandutta5033 weeks ago"
},
{
"code": null,
"e": 850,
"s": 840,
"text": "Int I= 0;"
},
{
"code": null,
"e": 864,
"s": 850,
"text": "While (i<11){"
},
{
"code": null,
"e": 888,
"s": 864,
"text": "System .Out.println(I);"
},
{
"code": null,
"e": 890,
"s": 888,
"text": "}"
},
{
"code": null,
"e": 893,
"s": 890,
"text": "+1"
},
{
"code": null,
"e": 921,
"s": 893,
"text": "shrutidhongade161 month ago"
},
{
"code": null,
"e": 1222,
"s": 921,
"text": "class Geeks {\n\t static void printTable (int n) \n\t {\n int multiplier=10;\n while(multiplier>0)\n {\n System.out.print(n * multiplier + \" \");\n multiplier -= 1;\n //Your code here\n }\n System.out.println();\n\t }\n\n}"
},
{
"code": null,
"e": 1224,
"s": 1222,
"text": "0"
},
{
"code": null,
"e": 1246,
"s": 1224,
"text": "janmejayy2 months ago"
},
{
"code": null,
"e": 1407,
"s": 1246,
"text": " static void printTable (int n) { for(int i=10;i>0;i--){ System.out.print(n*i+\" \"); } System.out.println(); }"
},
{
"code": null,
"e": 1409,
"s": 1407,
"text": "0"
},
{
"code": null,
"e": 1436,
"s": 1409,
"text": "piyushchpkumar2 months ago"
},
{
"code": null,
"e": 1450,
"s": 1436,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 1710,
"s": 1452,
"text": " static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(multiplier*n+ \" \"); multiplier--; } System.out.println(); }"
},
{
"code": null,
"e": 1712,
"s": 1710,
"text": "0"
},
{
"code": null,
"e": 1735,
"s": 1712,
"text": "mdsaif04052 months ago"
},
{
"code": null,
"e": 2004,
"s": 1735,
"text": "class Geeks {\n\t static void printTable (int n) \n\t {\n int multiplier=10;\n while(multiplier>0)\n {\n System.out.print(n*multiplier + \" \"); \n multiplier--;\n }\n System.out.println();\n\t }\n\n}"
},
{
"code": null,
"e": 2006,
"s": 2004,
"text": "0"
},
{
"code": null,
"e": 2017,
"s": 2006,
"text": "mdsaif0405"
},
{
"code": null,
"e": 2043,
"s": 2017,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2045,
"s": 2043,
"text": "0"
},
{
"code": null,
"e": 2067,
"s": 2045,
"text": "sdsapkale4 months ago"
},
{
"code": null,
"e": 2351,
"s": 2067,
"text": "class Geeks { static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(multiplier*n+\" \"); multiplier--; } System.out.println(); }"
},
{
"code": null,
"e": 2353,
"s": 2351,
"text": "}"
},
{
"code": null,
"e": 2355,
"s": 2353,
"text": "0"
},
{
"code": null,
"e": 2384,
"s": 2355,
"text": "badgujarsachin834 months ago"
},
{
"code": null,
"e": 2630,
"s": 2384,
"text": " static void printTable (int n) \n\t {\n int multiplier=10;\n while(multiplier>0)\n {\n //Your code here\n System.out.print(n*multiplier+\" \");\n }\n System.out.println();\n\t }"
},
{
"code": null,
"e": 2633,
"s": 2630,
"text": "-1"
},
{
"code": null,
"e": 2658,
"s": 2633,
"text": "rawalaashi017 months ago"
},
{
"code": null,
"e": 2942,
"s": 2658,
"text": "class Geeks { static void printTable (int n) { int multiplier=10; while(multiplier>0) { //Your code here System.out.print(n*multiplier +\" \"); //return(n*multiplier); multiplier--; }System.out.println();"
},
{
"code": null,
"e": 2945,
"s": 2942,
"text": " }"
},
{
"code": null,
"e": 2947,
"s": 2945,
"text": "}"
},
{
"code": null,
"e": 2949,
"s": 2947,
"text": "0"
},
{
"code": null,
"e": 2977,
"s": 2949,
"text": "garvitsingh14017 months ago"
},
{
"code": null,
"e": 2989,
"s": 2977,
"text": "TIme - 0.2 "
},
{
"code": null,
"e": 3264,
"s": 2991,
"text": "class Geeks { static void printTable (int n) { int multiplier=10; int j=n*10; while(multiplier>0) { System.out.printf(\"%d \",j); j=j-n; multiplier--; } System.out.println(); }"
},
{
"code": null,
"e": 3266,
"s": 3264,
"text": "}"
},
{
"code": null,
"e": 3412,
"s": 3266,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3448,
"s": 3412,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3458,
"s": 3448,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3468,
"s": 3458,
"text": "\nContest\n"
},
{
"code": null,
"e": 3531,
"s": 3468,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3679,
"s": 3531,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3887,
"s": 3679,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3993,
"s": 3887,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to get current date/time in milli seconds in Java?
|
The getTime() method of the Date class retrieves and returns the epoch time (number of milliseconds from Jan 1st 1970 00:00:00 GMT0.
Live Demo
import java.util.Date;
public class Sample {
public static void main(String args[]){
//Instantiating the Date class
Date date = new Date();
long msec = date.getTime();
System.out.println("Milli Seconds: "+msec);
}
}
Milli Seconds: 1605160094688
Milli Seconds: 1605160094688
The getTimeInMillis() method of the calendar class retrieves and returns the time in milli seconds from the epochepoch time (Jan 1st 1970 00:00:00 GMT).
Live Demo
import java.util.Calendar;
public class Sample {
public static void main(String args[]){
//Creating the Calendar object
Calendar cal = Calendar.getInstance();
long msec = cal.getTimeInMillis();
System.out.println("Milli Seconds: "+msec);
}
}
Milli Seconds: 1605160934357
Milli Seconds: 1605160934357
The toEpochMilli() method of the Instant class returns the milliseconds from the epoch.
Live Demo
import java.time.Instant;
import java.time.ZonedDateTime;
public class Sample {
public static void main(String args[]){
//Creating the ZonedDateTime object
ZonedDateTime obj = ZonedDateTime.now();
Instant instant = obj.toInstant();
long msec = instant.toEpochMilli();
System.out.println("Milli Seconds: "+msec);
}
}
Milli Seconds: 1605162474464
Milli Seconds: 1605162474464
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "The getTime() method of the Date class retrieves and returns the epoch time (number of milliseconds from Jan 1st 1970 00:00:00 GMT0."
},
{
"code": null,
"e": 1205,
"s": 1195,
"text": "Live Demo"
},
{
"code": null,
"e": 1453,
"s": 1205,
"text": "import java.util.Date;\npublic class Sample {\n public static void main(String args[]){ \n //Instantiating the Date class\n Date date = new Date();\n long msec = date.getTime();\n System.out.println(\"Milli Seconds: \"+msec);\n }\n}"
},
{
"code": null,
"e": 1482,
"s": 1453,
"text": "Milli Seconds: 1605160094688"
},
{
"code": null,
"e": 1511,
"s": 1482,
"text": "Milli Seconds: 1605160094688"
},
{
"code": null,
"e": 1664,
"s": 1511,
"text": "The getTimeInMillis() method of the calendar class retrieves and returns the time in milli seconds from the epochepoch time (Jan 1st 1970 00:00:00 GMT)."
},
{
"code": null,
"e": 1674,
"s": 1664,
"text": "Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1674,
"text": "import java.util.Calendar;\npublic class Sample {\n public static void main(String args[]){ \n //Creating the Calendar object\n Calendar cal = Calendar.getInstance();\n long msec = cal.getTimeInMillis();\n System.out.println(\"Milli Seconds: \"+msec);\n }\n}"
},
{
"code": null,
"e": 1977,
"s": 1948,
"text": "Milli Seconds: 1605160934357"
},
{
"code": null,
"e": 2006,
"s": 1977,
"text": "Milli Seconds: 1605160934357"
},
{
"code": null,
"e": 2095,
"s": 2006,
"text": "The toEpochMilli() method of the Instant class returns the milliseconds from the epoch."
},
{
"code": null,
"e": 2105,
"s": 2095,
"text": "Live Demo"
},
{
"code": null,
"e": 2459,
"s": 2105,
"text": "import java.time.Instant;\nimport java.time.ZonedDateTime;\npublic class Sample {\n public static void main(String args[]){ \n //Creating the ZonedDateTime object\n ZonedDateTime obj = ZonedDateTime.now();\n Instant instant = obj.toInstant();\n long msec = instant.toEpochMilli();\n System.out.println(\"Milli Seconds: \"+msec);\n }\n}"
},
{
"code": null,
"e": 2488,
"s": 2459,
"text": "Milli Seconds: 1605162474464"
},
{
"code": null,
"e": 2517,
"s": 2488,
"text": "Milli Seconds: 1605162474464"
}
] |
Android - Data Access Object in Room Database - GeeksforGeeks
|
03 Jan, 2022
Data Access Objects, or DAOs, are used in Room to access your application’s persisted data. When compared to query builders or direct queries, they are a better and more modular way to access your database. You should also make a note that a DAO need not be only a class. If it’s an abstract class, it can have a function Object() { [native code] } that only accepts a RoomDatabase as a parameter. At compile time, Room creates each DAO implementation. DAO allows you to perform a variety of operations such as inserting, updating, deleting, and running raw queries. You can also easily incorporate LiveData, RxJava Observables, and Kotlin Coroutines into DAOs.
Room generates an implementation that inserts all parameters into the database in a single transaction when you annotate a DAO method with @Insert.
Kotlin
@Daointerface gfgDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertCourses(vararg course: Course) @Insert fun insertAndroid(course1: Course, course2: Course) @Insert fun insertDataStructures(course: Course, prices: List<Course>)}
The onConflict annotation parameter indicates what to do if a conflict occurs during insertion. It can be any of the following values:
OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction.OnConflictStrategy.ROLLBACK: To undo a transaction.OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed.OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed.OnConflictStrategy.NONE: To disregard the conflict.
OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction.
OnConflictStrategy.ROLLBACK: To undo a transaction.
OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed.
OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed.
OnConflictStrategy.NONE: To disregard the conflict.
Note: ROLLBACK and FAIL strategies are no longer supported. Instead, use ABORT.
Kotlin
@Daointerface CourseDAO { @Update(onConflict = OnConflictStrategy.REPLACE) fun updateCourses(vararg courses: Course) @Update fun update(courses: Course)}
When you create a DAO method and annotate it with @Delete, Room generates an implementation that deletes a set of entities from the database, as specified by the parameters. It searches for entities to delete using the primary keys.
Kotlin
@Daointerface CoursesDao { @Delete fun removeCourses(vararg courses: Courses)}
The main annotation used in DAO classes is @Query. It enables you to read and write data from a database. Because each @Query method is validated at compile-time, if there is a problem with the query, a compilation error occurs rather than a runtime failure. Room also verifies the query’s return value, so that if the name of a field in the returned object does not match the corresponding column names in the query response, Room notifies you in one of two ways: It issues a warning if only a subset of the field names matches. If no field names match, it returns an error.
Kotlin
@Daointerface CoursesDao { @Query("SELECT * FROM courses") fun loadCourses(): Array<Courses>}
Parameters passed to DAO methods can be used in queries written with the @Query annotation.
Kotlin
@Daointerface CoursesDao { @Query("SELECT * FROM courses WHERE price BETWEEN :minPrice AND :maxPrice") fun loadAllCourses(minPrices: Int, maxPrices: Int): Array<Course> @Query("SELECT * FROM courses WHERE first_course LIKE :search " + "OR last_course LIKE :search") fun findCourses(search: String): List<Courses>}
In-Room, you can also return subsets of columns from a query.
Kotlin
data class coursesTuple( @CourseName(name = "first_course") val first_course: String?, @CourseName(name = "last_course") val last_course: String?)@Daointerface courseDao { @Query("SELECT first_name, last_name FROM course") fun loadCourses(): List<CourseTuple>}
Some of your queries may necessitate access to multiple tables in order to calculate the result. Room allows you to write any query, including table joins. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room looks for invalidation in all tables referenced in the query.
Kotlin
@Daointerface UserDAO { @Query( "SELECT * FROM users " + "INNER JOIN loan ON loan.book_id = course.id " + "INNER JOIN user ON user.id = loan.course " + "WHERE course.name LIKE :courseName" ) fun fingCourseTakenBy(courseName: String): List<Course>}
The room supports a wide range of query method return types, including specialized return types for interoperability with specific frameworks or APIs. Query methods can return LiveData, Observable, and Flow objects. You can also create a DAO method suspend function. Separate articles are dedicated to each of these topics.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to View and Locate SQLite Database in Android Studio?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Image to Drawable Folder in Android Studio?
How to Retrieve Data from the Firebase Realtime Database in Android?
How to Change the Background Color After Clicking the Button in Android?
GridView in Android with Example
|
[
{
"code": null,
"e": 24633,
"s": 24605,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 25295,
"s": 24633,
"text": "Data Access Objects, or DAOs, are used in Room to access your application’s persisted data. When compared to query builders or direct queries, they are a better and more modular way to access your database. You should also make a note that a DAO need not be only a class. If it’s an abstract class, it can have a function Object() { [native code] } that only accepts a RoomDatabase as a parameter. At compile time, Room creates each DAO implementation. DAO allows you to perform a variety of operations such as inserting, updating, deleting, and running raw queries. You can also easily incorporate LiveData, RxJava Observables, and Kotlin Coroutines into DAOs."
},
{
"code": null,
"e": 25443,
"s": 25295,
"text": "Room generates an implementation that inserts all parameters into the database in a single transaction when you annotate a DAO method with @Insert."
},
{
"code": null,
"e": 25450,
"s": 25443,
"text": "Kotlin"
},
{
"code": "@Daointerface gfgDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertCourses(vararg course: Course) @Insert fun insertAndroid(course1: Course, course2: Course) @Insert fun insertDataStructures(course: Course, prices: List<Course>)}",
"e": 25713,
"s": 25450,
"text": null
},
{
"code": null,
"e": 25848,
"s": 25713,
"text": "The onConflict annotation parameter indicates what to do if a conflict occurs during insertion. It can be any of the following values:"
},
{
"code": null,
"e": 26201,
"s": 25848,
"text": "OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction.OnConflictStrategy.ROLLBACK: To undo a transaction.OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed.OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed.OnConflictStrategy.NONE: To disregard the conflict."
},
{
"code": null,
"e": 26283,
"s": 26201,
"text": "OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction."
},
{
"code": null,
"e": 26335,
"s": 26283,
"text": "OnConflictStrategy.ROLLBACK: To undo a transaction."
},
{
"code": null,
"e": 26421,
"s": 26335,
"text": "OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed."
},
{
"code": null,
"e": 26506,
"s": 26421,
"text": "OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed."
},
{
"code": null,
"e": 26558,
"s": 26506,
"text": "OnConflictStrategy.NONE: To disregard the conflict."
},
{
"code": null,
"e": 26638,
"s": 26558,
"text": "Note: ROLLBACK and FAIL strategies are no longer supported. Instead, use ABORT."
},
{
"code": null,
"e": 26645,
"s": 26638,
"text": "Kotlin"
},
{
"code": "@Daointerface CourseDAO { @Update(onConflict = OnConflictStrategy.REPLACE) fun updateCourses(vararg courses: Course) @Update fun update(courses: Course)}",
"e": 26813,
"s": 26645,
"text": null
},
{
"code": null,
"e": 27046,
"s": 26813,
"text": "When you create a DAO method and annotate it with @Delete, Room generates an implementation that deletes a set of entities from the database, as specified by the parameters. It searches for entities to delete using the primary keys."
},
{
"code": null,
"e": 27053,
"s": 27046,
"text": "Kotlin"
},
{
"code": "@Daointerface CoursesDao { @Delete fun removeCourses(vararg courses: Courses)}",
"e": 27138,
"s": 27053,
"text": null
},
{
"code": null,
"e": 27714,
"s": 27138,
"text": "The main annotation used in DAO classes is @Query. It enables you to read and write data from a database. Because each @Query method is validated at compile-time, if there is a problem with the query, a compilation error occurs rather than a runtime failure. Room also verifies the query’s return value, so that if the name of a field in the returned object does not match the corresponding column names in the query response, Room notifies you in one of two ways: It issues a warning if only a subset of the field names matches. If no field names match, it returns an error."
},
{
"code": null,
"e": 27721,
"s": 27714,
"text": "Kotlin"
},
{
"code": "@Daointerface CoursesDao { @Query(\"SELECT * FROM courses\") fun loadCourses(): Array<Courses>}",
"e": 27821,
"s": 27721,
"text": null
},
{
"code": null,
"e": 27913,
"s": 27821,
"text": "Parameters passed to DAO methods can be used in queries written with the @Query annotation."
},
{
"code": null,
"e": 27920,
"s": 27913,
"text": "Kotlin"
},
{
"code": "@Daointerface CoursesDao { @Query(\"SELECT * FROM courses WHERE price BETWEEN :minPrice AND :maxPrice\") fun loadAllCourses(minPrices: Int, maxPrices: Int): Array<Course> @Query(\"SELECT * FROM courses WHERE first_course LIKE :search \" + \"OR last_course LIKE :search\") fun findCourses(search: String): List<Courses>}",
"e": 28258,
"s": 27920,
"text": null
},
{
"code": null,
"e": 28320,
"s": 28258,
"text": "In-Room, you can also return subsets of columns from a query."
},
{
"code": null,
"e": 28327,
"s": 28320,
"text": "Kotlin"
},
{
"code": "data class coursesTuple( @CourseName(name = \"first_course\") val first_course: String?, @CourseName(name = \"last_course\") val last_course: String?)@Daointerface courseDao { @Query(\"SELECT first_name, last_name FROM course\") fun loadCourses(): List<CourseTuple>}",
"e": 28600,
"s": 28327,
"text": null
},
{
"code": null,
"e": 28910,
"s": 28600,
"text": "Some of your queries may necessitate access to multiple tables in order to calculate the result. Room allows you to write any query, including table joins. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room looks for invalidation in all tables referenced in the query."
},
{
"code": null,
"e": 28917,
"s": 28910,
"text": "Kotlin"
},
{
"code": "@Daointerface UserDAO { @Query( \"SELECT * FROM users \" + \"INNER JOIN loan ON loan.book_id = course.id \" + \"INNER JOIN user ON user.id = loan.course \" + \"WHERE course.name LIKE :courseName\" ) fun fingCourseTakenBy(courseName: String): List<Course>}",
"e": 29202,
"s": 28917,
"text": null
},
{
"code": null,
"e": 29526,
"s": 29202,
"text": "The room supports a wide range of query method return types, including specialized return types for interoperability with specific frameworks or APIs. Query methods can return LiveData, Observable, and Flow objects. You can also create a DAO method suspend function. Separate articles are dedicated to each of these topics."
},
{
"code": null,
"e": 29533,
"s": 29526,
"text": "Picked"
},
{
"code": null,
"e": 29541,
"s": 29533,
"text": "Android"
},
{
"code": null,
"e": 29549,
"s": 29541,
"text": "Android"
},
{
"code": null,
"e": 29647,
"s": 29549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29656,
"s": 29647,
"text": "Comments"
},
{
"code": null,
"e": 29669,
"s": 29656,
"text": "Old Comments"
},
{
"code": null,
"e": 29708,
"s": 29669,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29758,
"s": 29708,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29816,
"s": 29758,
"text": "How to View and Locate SQLite Database in Android Studio?"
},
{
"code": null,
"e": 29854,
"s": 29816,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29905,
"s": 29854,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29947,
"s": 29905,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30002,
"s": 29947,
"text": "How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 30071,
"s": 30002,
"text": "How to Retrieve Data from the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 30144,
"s": 30071,
"text": "How to Change the Background Color After Clicking the Button in Android?"
}
] |
SEO - Relevant Filenames
|
One of the simplest methods to improve your search engine optimization is to look at the way you name your files. Before writing this tutorial, we did a lot of research on file-names and found that search engines like Google give too much importance to file names. You should think what you want put in your web page and then give a relevant file name to this page.
Just try giving any keyword in Google search engine and you will find file names highlighted with the keyword you have given. It proves that your file name should have appropriate keywords.
The filename should preferably be short and descriptive.
The filename should preferably be short and descriptive.
It is always good to use same keywords in a filename as well as in page title.
It is always good to use same keywords in a filename as well as in page title.
Do not use filenames such as service.htm or job.htm as they are generic. Use actual service name in your file name such as computer-repairing.htm.
Do not use filenames such as service.htm or job.htm as they are generic. Use actual service name in your file name such as computer-repairing.htm.
Do not use more than 3-4 words in file names.
Do not use more than 3-4 words in file names.
Separate the keywords with hyphens rather than underscores.
Separate the keywords with hyphens rather than underscores.
Try to use 2 keywords if possible.
Try to use 2 keywords if possible.
Listed below are some filenames which would be ideal from the users' point of view as well as SEO.
slazenger-brand-balls.html
wimbledon-brand-balls.html
wilson-brand-balls.html
Notice that the keywords are separated by hyphens rather than underscores. Google sees good filenames as follows:
seo-relevant-filename as seo relevant filename(good)
Filenames with underscores are not a good option.
seo_relevant_filename as seorelevantfilename (not good)
You should notice that .html, .htm, .php and any other extension do NOTHING for your visitors, and they are simply a means of offloading some of the work of configuring your webserver properly onto your visitor's. In effect, you are asking your site visitors to tell your webserver HOW to produce the page, not which one?
Many Web masters think that it is a good idea to use filename without using extension. It may help you, but not a whole lot.
From Search Engine Optimization point of view, URL sub-directory name hardly matters. You can try giving any keyword in any search, and you will not find any sub-directory name matching with your keywords. But from the user's point of view, you should keep an abbreviated sub-directory name.
Keep the following points in mind before naming your files:
Keep the web page filename short, simple, descriptive, and relevant to the page content.
Keep the web page filename short, simple, descriptive, and relevant to the page content.
Try to use a maximum of 3-4 keywords in your filename, and these keywords should appear on your web page title as well.
Try to use a maximum of 3-4 keywords in your filename, and these keywords should appear on your web page title as well.
Separate all keywords with hyphen rather than with underscore.
Separate all keywords with hyphen rather than with underscore.
Keep your sub-directories name as short as possible.
Keep your sub-directories name as short as possible.
Restrict the file size to less than 101K because Google chops almost everything above that.
Restrict the file size to less than 101K because Google chops almost everything above that.
33 Lectures
4 hours
Asif Hussain
33 Lectures
2.5 hours
Sasha Miller
20 Lectures
3 hours
Sasha Miller
38 Lectures
3 hours
Sasha Miller
15 Lectures
1 hours
Zach Miller
22 Lectures
1.5 hours
Zach Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2291,
"s": 1925,
"text": "One of the simplest methods to improve your search engine optimization is to look at the way you name your files. Before writing this tutorial, we did a lot of research on file-names and found that search engines like Google give too much importance to file names. You should think what you want put in your web page and then give a relevant file name to this page."
},
{
"code": null,
"e": 2481,
"s": 2291,
"text": "Just try giving any keyword in Google search engine and you will find file names highlighted with the keyword you have given. It proves that your file name should have appropriate keywords."
},
{
"code": null,
"e": 2538,
"s": 2481,
"text": "The filename should preferably be short and descriptive."
},
{
"code": null,
"e": 2595,
"s": 2538,
"text": "The filename should preferably be short and descriptive."
},
{
"code": null,
"e": 2674,
"s": 2595,
"text": "It is always good to use same keywords in a filename as well as in page title."
},
{
"code": null,
"e": 2753,
"s": 2674,
"text": "It is always good to use same keywords in a filename as well as in page title."
},
{
"code": null,
"e": 2900,
"s": 2753,
"text": "Do not use filenames such as service.htm or job.htm as they are generic. Use actual service name in your file name such as computer-repairing.htm."
},
{
"code": null,
"e": 3047,
"s": 2900,
"text": "Do not use filenames such as service.htm or job.htm as they are generic. Use actual service name in your file name such as computer-repairing.htm."
},
{
"code": null,
"e": 3093,
"s": 3047,
"text": "Do not use more than 3-4 words in file names."
},
{
"code": null,
"e": 3139,
"s": 3093,
"text": "Do not use more than 3-4 words in file names."
},
{
"code": null,
"e": 3199,
"s": 3139,
"text": "Separate the keywords with hyphens rather than underscores."
},
{
"code": null,
"e": 3259,
"s": 3199,
"text": "Separate the keywords with hyphens rather than underscores."
},
{
"code": null,
"e": 3294,
"s": 3259,
"text": "Try to use 2 keywords if possible."
},
{
"code": null,
"e": 3329,
"s": 3294,
"text": "Try to use 2 keywords if possible."
},
{
"code": null,
"e": 3428,
"s": 3329,
"text": "Listed below are some filenames which would be ideal from the users' point of view as well as SEO."
},
{
"code": null,
"e": 3506,
"s": 3428,
"text": "slazenger-brand-balls.html\nwimbledon-brand-balls.html\nwilson-brand-balls.html"
},
{
"code": null,
"e": 3620,
"s": 3506,
"text": "Notice that the keywords are separated by hyphens rather than underscores. Google sees good filenames as follows:"
},
{
"code": null,
"e": 3673,
"s": 3620,
"text": "seo-relevant-filename as seo relevant filename(good)"
},
{
"code": null,
"e": 3723,
"s": 3673,
"text": "Filenames with underscores are not a good option."
},
{
"code": null,
"e": 3779,
"s": 3723,
"text": "seo_relevant_filename as seorelevantfilename (not good)"
},
{
"code": null,
"e": 4102,
"s": 3779,
"text": "You should notice that .html, .htm, .php and any other extension do NOTHING for your visitors, and they are simply a means of offloading some of the work of configuring your webserver properly onto your visitor's. In effect, you are asking your site visitors to tell your webserver HOW to produce the page, not which one?"
},
{
"code": null,
"e": 4227,
"s": 4102,
"text": "Many Web masters think that it is a good idea to use filename without using extension. It may help you, but not a whole lot."
},
{
"code": null,
"e": 4519,
"s": 4227,
"text": "From Search Engine Optimization point of view, URL sub-directory name hardly matters. You can try giving any keyword in any search, and you will not find any sub-directory name matching with your keywords. But from the user's point of view, you should keep an abbreviated sub-directory name."
},
{
"code": null,
"e": 4579,
"s": 4519,
"text": "Keep the following points in mind before naming your files:"
},
{
"code": null,
"e": 4668,
"s": 4579,
"text": "Keep the web page filename short, simple, descriptive, and relevant to the page content."
},
{
"code": null,
"e": 4757,
"s": 4668,
"text": "Keep the web page filename short, simple, descriptive, and relevant to the page content."
},
{
"code": null,
"e": 4877,
"s": 4757,
"text": "Try to use a maximum of 3-4 keywords in your filename, and these keywords should appear on your web page title as well."
},
{
"code": null,
"e": 4997,
"s": 4877,
"text": "Try to use a maximum of 3-4 keywords in your filename, and these keywords should appear on your web page title as well."
},
{
"code": null,
"e": 5060,
"s": 4997,
"text": "Separate all keywords with hyphen rather than with underscore."
},
{
"code": null,
"e": 5123,
"s": 5060,
"text": "Separate all keywords with hyphen rather than with underscore."
},
{
"code": null,
"e": 5176,
"s": 5123,
"text": "Keep your sub-directories name as short as possible."
},
{
"code": null,
"e": 5229,
"s": 5176,
"text": "Keep your sub-directories name as short as possible."
},
{
"code": null,
"e": 5321,
"s": 5229,
"text": "Restrict the file size to less than 101K because Google chops almost everything above that."
},
{
"code": null,
"e": 5413,
"s": 5321,
"text": "Restrict the file size to less than 101K because Google chops almost everything above that."
},
{
"code": null,
"e": 5446,
"s": 5413,
"text": "\n 33 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5460,
"s": 5446,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5495,
"s": 5460,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5509,
"s": 5495,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5542,
"s": 5509,
"text": "\n 20 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5556,
"s": 5542,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5589,
"s": 5556,
"text": "\n 38 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5603,
"s": 5589,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5636,
"s": 5603,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5649,
"s": 5636,
"text": " Zach Miller"
},
{
"code": null,
"e": 5684,
"s": 5649,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5697,
"s": 5684,
"text": " Zach Miller"
},
{
"code": null,
"e": 5704,
"s": 5697,
"text": " Print"
},
{
"code": null,
"e": 5715,
"s": 5704,
"text": " Add Notes"
}
] |
Python Pandas - Merging/Joining
|
Pandas has full-featured, high performance in-memory join operations idiomatically very similar to relational databases like SQL.
Pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects −
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True)
Here, we have used the following parameters −
left − A DataFrame object.
left − A DataFrame object.
right − Another DataFrame object.
right − Another DataFrame object.
on − Columns (names) to join on. Must be found in both the left and right DataFrame
objects.
on − Columns (names) to join on. Must be found in both the left and right DataFrame
objects.
left_on − Columns from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame.
left_on − Columns from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame.
right_on − Columns from the right DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame.
right_on − Columns from the right DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame.
left_index − If True, use the index (row labels) from the left DataFrame as its join key(s). In case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame.
left_index − If True, use the index (row labels) from the left DataFrame as its join key(s). In case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame.
right_index − Same usage as left_index for the right DataFrame.
right_index − Same usage as left_index for the right DataFrame.
how − One of 'left', 'right', 'outer', 'inner'. Defaults to inner. Each method has been described below.
how − One of 'left', 'right', 'outer', 'inner'. Defaults to inner. Each method has been described below.
sort − Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting to False will improve the performance substantially in many cases.
sort − Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting to False will improve the performance substantially in many cases.
Let us now create two different DataFrames and perform the merging operations on it.
# import the pandas library
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame(
{'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print left
print right
Its output is as follows −
Name id subject_id
0 Alex 1 sub1
1 Amy 2 sub2
2 Allen 3 sub4
3 Alice 4 sub6
4 Ayoung 5 sub5
Name id subject_id
0 Billy 1 sub2
1 Brian 2 sub4
2 Bran 3 sub3
3 Bryce 4 sub6
4 Betty 5 sub5
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left,right,on='id')
Its output is as follows −
Name_x id subject_id_x Name_y subject_id_y
0 Alex 1 sub1 Billy sub2
1 Amy 2 sub2 Brian sub4
2 Allen 3 sub4 Bran sub3
3 Alice 4 sub6 Bryce sub6
4 Ayoung 5 sub5 Betty sub5
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left,right,on=['id','subject_id'])
Its output is as follows −
Name_x id subject_id Name_y
0 Alice 4 sub6 Bryce
1 Ayoung 5 sub5 Betty
The how argument to merge specifies how to determine which keys are to be included in the resulting table. If a key combination does not appear in either the left or the right tables, the values in the joined table will be NA.
Here is a summary of the how options and their SQL equivalent names −
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left, right, on='subject_id', how='left')
Its output is as follows −
Name_x id_x subject_id Name_y id_y
0 Alex 1 sub1 NaN NaN
1 Amy 2 sub2 Billy 1.0
2 Allen 3 sub4 Brian 2.0
3 Alice 4 sub6 Bryce 4.0
4 Ayoung 5 sub5 Betty 5.0
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left, right, on='subject_id', how='right')
Its output is as follows −
Name_x id_x subject_id Name_y id_y
0 Amy 2.0 sub2 Billy 1
1 Allen 3.0 sub4 Brian 2
2 Alice 4.0 sub6 Bryce 4
3 Ayoung 5.0 sub5 Betty 5
4 NaN NaN sub3 Bran 3
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left, right, how='outer', on='subject_id')
Its output is as follows −
Name_x id_x subject_id Name_y id_y
0 Alex 1.0 sub1 NaN NaN
1 Amy 2.0 sub2 Billy 1.0
2 Allen 3.0 sub4 Brian 2.0
3 Alice 4.0 sub6 Bryce 4.0
4 Ayoung 5.0 sub5 Betty 5.0
5 NaN NaN sub3 Bran 3.0
Joining will be performed on index. Join operation honors the object on which it is called.
So, a.join(b) is not equal to b.join(a).
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print pd.merge(left, right, on='subject_id', how='inner')
Its output is as follows −
Name_x id_x subject_id Name_y id_y
0 Amy 2 sub2 Billy 1
1 Allen 3 sub4 Brian 2
2 Alice 4 sub6 Bryce 4
3 Ayoung 5 sub5 Betty 5
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2573,
"s": 2443,
"text": "Pandas has full-featured, high performance in-memory join operations idiomatically very similar to relational databases like SQL."
},
{
"code": null,
"e": 2704,
"s": 2573,
"text": "Pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects −"
},
{
"code": null,
"e": 2826,
"s": 2704,
"text": "pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,\nleft_index=False, right_index=False, sort=True)\n"
},
{
"code": null,
"e": 2872,
"s": 2826,
"text": "Here, we have used the following parameters −"
},
{
"code": null,
"e": 2899,
"s": 2872,
"text": "left − A DataFrame object."
},
{
"code": null,
"e": 2926,
"s": 2899,
"text": "left − A DataFrame object."
},
{
"code": null,
"e": 2960,
"s": 2926,
"text": "right − Another DataFrame object."
},
{
"code": null,
"e": 2994,
"s": 2960,
"text": "right − Another DataFrame object."
},
{
"code": null,
"e": 3087,
"s": 2994,
"text": "on − Columns (names) to join on. Must be found in both the left and right DataFrame\nobjects."
},
{
"code": null,
"e": 3180,
"s": 3087,
"text": "on − Columns (names) to join on. Must be found in both the left and right DataFrame\nobjects."
},
{
"code": null,
"e": 3325,
"s": 3180,
"text": "left_on − Columns from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame."
},
{
"code": null,
"e": 3470,
"s": 3325,
"text": "left_on − Columns from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame."
},
{
"code": null,
"e": 3617,
"s": 3470,
"text": "right_on − Columns from the right DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame."
},
{
"code": null,
"e": 3764,
"s": 3617,
"text": "right_on − Columns from the right DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame."
},
{
"code": null,
"e": 3996,
"s": 3764,
"text": "left_index − If True, use the index (row labels) from the left DataFrame as its join key(s). In case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame."
},
{
"code": null,
"e": 4228,
"s": 3996,
"text": "left_index − If True, use the index (row labels) from the left DataFrame as its join key(s). In case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame."
},
{
"code": null,
"e": 4292,
"s": 4228,
"text": "right_index − Same usage as left_index for the right DataFrame."
},
{
"code": null,
"e": 4356,
"s": 4292,
"text": "right_index − Same usage as left_index for the right DataFrame."
},
{
"code": null,
"e": 4461,
"s": 4356,
"text": "how − One of 'left', 'right', 'outer', 'inner'. Defaults to inner. Each method has been described below."
},
{
"code": null,
"e": 4566,
"s": 4461,
"text": "how − One of 'left', 'right', 'outer', 'inner'. Defaults to inner. Each method has been described below."
},
{
"code": null,
"e": 4735,
"s": 4566,
"text": "sort − Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting to False will improve the performance substantially in many cases."
},
{
"code": null,
"e": 4904,
"s": 4735,
"text": "sort − Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting to False will improve the performance substantially in many cases."
},
{
"code": null,
"e": 4989,
"s": 4904,
"text": "Let us now create two different DataFrames and perform the merging operations on it."
},
{
"code": null,
"e": 5370,
"s": 4989,
"text": "# import the pandas library\nimport pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame(\n {'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint left\nprint right"
},
{
"code": null,
"e": 5397,
"s": 5370,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5711,
"s": 5397,
"text": " Name id subject_id\n0 Alex 1 sub1\n1 Amy 2 sub2\n2 Allen 3 sub4\n3 Alice 4 sub6\n4 Ayoung 5 sub5\n\n Name id subject_id\n0 Billy 1 sub2\n1 Brian 2 sub4\n2 Bran 3 sub3\n3 Bryce 4 sub6\n4 Betty 5 sub5\n"
},
{
"code": null,
"e": 6074,
"s": 5711,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n\t'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left,right,on='id')"
},
{
"code": null,
"e": 6101,
"s": 6074,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6420,
"s": 6101,
"text": " Name_x id subject_id_x Name_y subject_id_y\n0 Alex 1 sub1 Billy sub2\n1 Amy 2 sub2 Brian sub4\n2 Allen 3 sub4 Bran sub3\n3 Alice 4 sub6 Bryce sub6\n4 Ayoung 5 sub5 Betty sub5\n"
},
{
"code": null,
"e": 6798,
"s": 6420,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n\t'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left,right,on=['id','subject_id'])"
},
{
"code": null,
"e": 6825,
"s": 6798,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6940,
"s": 6825,
"text": " Name_x id subject_id Name_y\n0 Alice 4 sub6 Bryce\n1 Ayoung 5 sub5 Betty\n"
},
{
"code": null,
"e": 7167,
"s": 6940,
"text": "The how argument to merge specifies how to determine which keys are to be included in the resulting table. If a key combination does not appear in either the left or the right tables, the values in the joined table will be NA."
},
{
"code": null,
"e": 7237,
"s": 7167,
"text": "Here is a summary of the how options and their SQL equivalent names −"
},
{
"code": null,
"e": 7624,
"s": 7237,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left, right, on='subject_id', how='left')"
},
{
"code": null,
"e": 7651,
"s": 7624,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7934,
"s": 7651,
"text": " Name_x id_x subject_id Name_y id_y\n0 Alex 1 sub1 NaN NaN\n1 Amy 2 sub2 Billy 1.0\n2 Allen 3 sub4 Brian 2.0\n3 Alice 4 sub6 Bryce 4.0\n4 Ayoung 5 sub5 Betty 5.0\n"
},
{
"code": null,
"e": 8322,
"s": 7934,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left, right, on='subject_id', how='right')"
},
{
"code": null,
"e": 8349,
"s": 8322,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 8626,
"s": 8349,
"text": " Name_x id_x subject_id Name_y id_y\n0 Amy 2.0 sub2 Billy 1\n1 Allen 3.0 sub4 Brian 2\n2 Alice 4.0 sub6 Bryce 4\n3 Ayoung 5.0 sub5 Betty 5\n4 NaN NaN sub3 Bran 3\n"
},
{
"code": null,
"e": 9014,
"s": 8626,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left, right, how='outer', on='subject_id')"
},
{
"code": null,
"e": 9041,
"s": 9014,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 9364,
"s": 9041,
"text": " Name_x id_x subject_id Name_y id_y\n0 Alex 1.0 sub1 NaN NaN\n1 Amy 2.0 sub2 Billy 1.0\n2 Allen 3.0 sub4 Brian 2.0\n3 Alice 4.0 sub6 Bryce 4.0\n4 Ayoung 5.0 sub5 Betty 5.0\n5 NaN NaN sub3 Bran 3.0\n"
},
{
"code": null,
"e": 9497,
"s": 9364,
"text": "Joining will be performed on index. Join operation honors the object on which it is called.\nSo, a.join(b) is not equal to b.join(a)."
},
{
"code": null,
"e": 9885,
"s": 9497,
"text": "import pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint pd.merge(left, right, on='subject_id', how='inner')"
},
{
"code": null,
"e": 9912,
"s": 9885,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 10148,
"s": 9912,
"text": " Name_x id_x subject_id Name_y id_y\n0 Amy 2 sub2 Billy 1\n1 Allen 3 sub4 Brian 2\n2 Alice 4 sub6 Bryce 4\n3 Ayoung 5 sub5 Betty 5\n"
},
{
"code": null,
"e": 10185,
"s": 10148,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 10201,
"s": 10185,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10234,
"s": 10201,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10253,
"s": 10234,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10288,
"s": 10253,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 10310,
"s": 10288,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 10344,
"s": 10310,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 10372,
"s": 10344,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10407,
"s": 10372,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 10421,
"s": 10407,
"text": " Lets Kode It"
},
{
"code": null,
"e": 10454,
"s": 10421,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10471,
"s": 10454,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10478,
"s": 10471,
"text": " Print"
},
{
"code": null,
"e": 10489,
"s": 10478,
"text": " Add Notes"
}
] |
Add list elements with a multi-list based on index in Python
|
Lists can be nested. Which means we have smaller lists as elements inside a bigger list. In this article we solve the challenge of adding the elements of a simple list to the elements of a nested list. If the length of the lists are different then the length of the smaller list becomes the maximum length of the resulting list.
Below are the various methods to accomplish this.
In this method, we take the length of the smaller list and loop through the elements of this list adding it to the elements of the bigger list. Here we use the append function to append each element into the result list.
Live Demo
simple_list = [25, 35, 45, 55, 65]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15],[5,6]]
result_list = []
for n in range(len(simple_list)):
var = []
for m in nested_list[n]:
var.append(m + simple_list[n])
result_list.append(var)
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)
Running the above code gives us the following result −
The first list : [25, 35, 45, 55, 65]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15], [5, 6]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]
The enumerate() function takes a collection like list or tuple and returns it as an enumerate object. In this approach we first create an outer for loop having the enumerate function to get each element of the nested list and then add them to the respective elements in the simple list through an inner for loop.
Live Demo
simple_list = [25, 35, 45, 55, 65,25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []
# using enumerate
result_list = [[val + simple_list[p] for val in q] for p, q in enumerate(nested_list)]
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)
Running the above code gives us the following result −
The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]
In this approach we repeat the above program but using zip () instead of enumerate. The zip() takes in both the lists as its input.
Live Demo
simple_list = [25, 35, 45, 55, 65,25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []
result_list = [[w + u for w in v ]for u, v in zip(simple_list, nested_list)]
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)
Running the above code gives us the following result −
The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]
|
[
{
"code": null,
"e": 1391,
"s": 1062,
"text": "Lists can be nested. Which means we have smaller lists as elements inside a bigger list. In this article we solve the challenge of adding the elements of a simple list to the elements of a nested list. If the length of the lists are different then the length of the smaller list becomes the maximum length of the resulting list."
},
{
"code": null,
"e": 1441,
"s": 1391,
"text": "Below are the various methods to accomplish this."
},
{
"code": null,
"e": 1662,
"s": 1441,
"text": "In this method, we take the length of the smaller list and loop through the elements of this list adding it to the elements of the bigger list. Here we use the append function to append each element into the result list."
},
{
"code": null,
"e": 1673,
"s": 1662,
"text": " Live Demo"
},
{
"code": null,
"e": 2033,
"s": 1673,
"text": "simple_list = [25, 35, 45, 55, 65]\nnested_list = [[5,10], [10], [5,15], [25], [5,10,15],[5,6]]\nresult_list = []\n\nfor n in range(len(simple_list)):\n var = []\n for m in nested_list[n]:\n var.append(m + simple_list[n])\n result_list.append(var)\nprint(\"The first list :\", simple_list)\nprint(\"The nested list :\", nested_list)\nprint(\"Result :\",result_list)"
},
{
"code": null,
"e": 2088,
"s": 2033,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2252,
"s": 2088,
"text": "The first list : [25, 35, 45, 55, 65]\nThe nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15], [5, 6]]\nResult : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]"
},
{
"code": null,
"e": 2565,
"s": 2252,
"text": "The enumerate() function takes a collection like list or tuple and returns it as an enumerate object. In this approach we first create an outer for loop having the enumerate function to get each element of the nested list and then add them to the respective elements in the simple list through an inner for loop."
},
{
"code": null,
"e": 2576,
"s": 2565,
"text": " Live Demo"
},
{
"code": null,
"e": 2900,
"s": 2576,
"text": "simple_list = [25, 35, 45, 55, 65,25]\nnested_list = [[5,10], [10], [5,15], [25], [5,10,15]]\nresult_list = []\n\n# using enumerate\nresult_list = [[val + simple_list[p] for val in q] for p, q in enumerate(nested_list)]\nprint(\"The first list :\", simple_list)\nprint(\"The nested list :\", nested_list)\nprint(\"Result :\",result_list)"
},
{
"code": null,
"e": 2955,
"s": 2900,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3115,
"s": 2955,
"text": "The first list : [25, 35, 45, 55, 65, 25]\nThe nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]\nResult : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]"
},
{
"code": null,
"e": 3247,
"s": 3115,
"text": "In this approach we repeat the above program but using zip () instead of enumerate. The zip() takes in both the lists as its input."
},
{
"code": null,
"e": 3258,
"s": 3247,
"text": " Live Demo"
},
{
"code": null,
"e": 3555,
"s": 3258,
"text": "simple_list = [25, 35, 45, 55, 65,25]\nnested_list = [[5,10], [10], [5,15], [25], [5,10,15]]\nresult_list = []\n\nresult_list = [[w + u for w in v ]for u, v in zip(simple_list, nested_list)]\n\nprint(\"The first list :\", simple_list)\nprint(\"The nested list :\", nested_list)\nprint(\"Result :\",result_list)"
},
{
"code": null,
"e": 3610,
"s": 3555,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3770,
"s": 3610,
"text": "The first list : [25, 35, 45, 55, 65, 25]\nThe nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]\nResult : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.