title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
NHibernate - Profiler | In this chapter, we will be understanding how all the records from the database are retrieved, updated, created, and deleted and how exactly these queries are performed?
To understand all these, we can simply add an option into our configuration, which logs the SQL in the console. Here is the simple statement that will log the SQL query −
x.LogSqlInConsole = true;
Now, we have two records in our student table in the NHibernateDemoDB database. Let’s retrieve all the records from the database as shown in the following code.
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Linq;
using System.Reflection;
namespace NHibernateDemoApp {
class Program {
static void Main(string[] args) {
var cfg = new Configuration();
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source +
Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
TrustServerCertificate + ApplicationIntent + MultiSubnetFailover";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
x.LogSqlInConsole = true;
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sefact = cfg.BuildSessionFactory();
using (var session = sefact.OpenSession()) {
using (var tx = session.BeginTransaction()) {
Console.WriteLine("\nFetch the complete list again\n");
var students = session.CreateCriteria<Student>().List<Student>();
foreach (var student in students) {
Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName,
student.LastName);
}
tx.Commit();
}
Console.ReadLine();
}
}
}
}
So let's go ahead and run this application again, and you will see the following output −
NHibernate: SELECT this_.ID as ID0_0_, this_.LastName as LastName0_0_,
this_.FirstMidName as FirstMid3_0_0_ FROM Student this_
Fetch the complete list again
3 Allan Bommer
4 Jerry Lewis
As you can see, the select clause being sent to the database, it is actually like clause which will retrieve the ID, FirstMidName and LastName. So all this is being sent to the database and processed there rather than having a lot of records brought back to your server and processed on the server side.
Another way to look at these results is to use NHibernate Profiler. NHibernate Profiler is a commercial tool, but is it very useful for working with NHibernate applications. You can easily install the NHibernate Profiler into your application from NuGet.
Let’s go to the NuGet Manager console from the Tools menu by selecting the NuGet Package Manager → Package Manager Console. It will open the Package Manager Console window. Enter the following command and press enter.
PM> install-package NHibernateProfiler
It will install all the required binaries for the NHibernate Profiler, once it is successfully installed you will see the following message.
You will also see that the NHibernate Profiler is launched, once it is installed. It will require a license to use it, but for demo purposes, we can use the 30-days trial version of NHibernate Profiler.
Now, NHibernate Profiler is optimized to work with web applications and you will see that it has added App_Start folder in the solution explorer. To keep all these simple, delete the App_Start folder and also you will observe that one statement is added at the start of the Main method in Program class.
App_Start.NHibernateProfilerBootstrapper.PreStart();
Remove this statement as well and just add a simple call NHibernateProfiler.Initialize as shown in the following code.
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Linq;
using System.Reflection;
namespace NHibernateDemoApp {
class Program {
static void Main(string[] args) {
NHibernateProfiler.Initialize();
var cfg = new Configuration();
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source +
Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
TrustServerCertificate + ApplicationIntent + MultiSubnetFailover";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
x.LogSqlInConsole = true;
});
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sefact = cfg.BuildSessionFactory();
using (var session = sefact.OpenSession()) {
using (var tx = session.BeginTransaction()){
var students = session.CreateCriteria<Student>().List<Student>();
Console.WriteLine("\nFetch the complete list again\n");
foreach (var student in students) {
Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName,
student.LastName);
}
tx.Commit();
}
Console.ReadLine();
}
}
}
}
Now when you run the application, it's going to send data over to the NHibernate Profiler application.
You can see here, we've got a nice display that shows that we've started the transaction, what the SQL is doing to the database in a nice format.
So this is very useful for determining what exactly is happening inside of your NHibernate application. It becomes incredibly useful once the application gets to a certain level of complexity, where you need something more like a SQL Profiler, but with the knowledge of NHibernate.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2503,
"s": 2333,
"text": "In this chapter, we will be understanding how all the records from the database are retrieved, updated, created, and deleted and how exactly these queries are performed?"
},
{
"code": null,
"e": 2674,
"s": 2503,
"text": "To understand all these, we can simply add an option into our configuration, which logs the SQL in the console. Here is the simple statement that will log the SQL query −"
},
{
"code": null,
"e": 2701,
"s": 2674,
"text": "x.LogSqlInConsole = true;\n"
},
{
"code": null,
"e": 2862,
"s": 2701,
"text": "Now, we have two records in our student table in the NHibernateDemoDB database. Let’s retrieve all the records from the database as shown in the following code."
},
{
"code": null,
"e": 4641,
"s": 2862,
"text": "using NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\n\nnamespace NHibernateDemoApp { \n\n class Program { \n \n static void Main(string[] args) { \n var cfg = new Configuration();\n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\t\t\t\n \n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\"; \n \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n }); \n \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory();\n \n using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()) { \n Console.WriteLine(\"\\nFetch the complete list again\\n\");\n var students = session.CreateCriteria<Student>().List<Student>(); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, student.FirstMidName,\n student.LastName); \n } \n \n tx.Commit(); \n } \n\t\t\t\t\n Console.ReadLine(); \n } \n } \n } \n}"
},
{
"code": null,
"e": 4731,
"s": 4641,
"text": "So let's go ahead and run this application again, and you will see the following output −"
},
{
"code": null,
"e": 4923,
"s": 4731,
"text": "NHibernate: SELECT this_.ID as ID0_0_, this_.LastName as LastName0_0_,\n this_.FirstMidName as FirstMid3_0_0_ FROM Student this_\n\nFetch the complete list again\n\n3 Allan Bommer\n4 Jerry Lewis\n"
},
{
"code": null,
"e": 5227,
"s": 4923,
"text": "As you can see, the select clause being sent to the database, it is actually like clause which will retrieve the ID, FirstMidName and LastName. So all this is being sent to the database and processed there rather than having a lot of records brought back to your server and processed on the server side."
},
{
"code": null,
"e": 5482,
"s": 5227,
"text": "Another way to look at these results is to use NHibernate Profiler. NHibernate Profiler is a commercial tool, but is it very useful for working with NHibernate applications. You can easily install the NHibernate Profiler into your application from NuGet."
},
{
"code": null,
"e": 5700,
"s": 5482,
"text": "Let’s go to the NuGet Manager console from the Tools menu by selecting the NuGet Package Manager → Package Manager Console. It will open the Package Manager Console window. Enter the following command and press enter."
},
{
"code": null,
"e": 5740,
"s": 5700,
"text": "PM> install-package NHibernateProfiler\n"
},
{
"code": null,
"e": 5881,
"s": 5740,
"text": "It will install all the required binaries for the NHibernate Profiler, once it is successfully installed you will see the following message."
},
{
"code": null,
"e": 6084,
"s": 5881,
"text": "You will also see that the NHibernate Profiler is launched, once it is installed. It will require a license to use it, but for demo purposes, we can use the 30-days trial version of NHibernate Profiler."
},
{
"code": null,
"e": 6388,
"s": 6084,
"text": "Now, NHibernate Profiler is optimized to work with web applications and you will see that it has added App_Start folder in the solution explorer. To keep all these simple, delete the App_Start folder and also you will observe that one statement is added at the start of the Main method in Program class."
},
{
"code": null,
"e": 6442,
"s": 6388,
"text": "App_Start.NHibernateProfilerBootstrapper.PreStart();\n"
},
{
"code": null,
"e": 6561,
"s": 6442,
"text": "Remove this statement as well and just add a simple call NHibernateProfiler.Initialize as shown in the following code."
},
{
"code": null,
"e": 8432,
"s": 6561,
"text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\n\nnamespace NHibernateDemoApp { \n \n class Program { \n\t\n static void Main(string[] args) { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration();\n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\t\t\t\n \n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\";\n\t\t\t\t\n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n }); \n\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n \n using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()){ \n var students = session.CreateCriteria<Student>().List<Student>(); \n Console.WriteLine(\"\\nFetch the complete list again\\n\");\n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2}\", student.ID, student.FirstMidName,\n student.LastName); \n } \n\t\t\t\t\t\n tx.Commit(); \n } \n\t\t\t\t\n Console.ReadLine(); \n } \n } \n \n }\n}"
},
{
"code": null,
"e": 8535,
"s": 8432,
"text": "Now when you run the application, it's going to send data over to the NHibernate Profiler application."
},
{
"code": null,
"e": 8681,
"s": 8535,
"text": "You can see here, we've got a nice display that shows that we've started the transaction, what the SQL is doing to the database in a nice format."
},
{
"code": null,
"e": 8963,
"s": 8681,
"text": "So this is very useful for determining what exactly is happening inside of your NHibernate application. It becomes incredibly useful once the application gets to a certain level of complexity, where you need something more like a SQL Profiler, but with the knowledge of NHibernate."
},
{
"code": null,
"e": 8970,
"s": 8963,
"text": " Print"
},
{
"code": null,
"e": 8981,
"s": 8970,
"text": " Add Notes"
}
] |
wxPython - Drag & Drop | Provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another just by dragging it with the mouse and dropping on another window.
Drag and drop operation involves the following steps −
Declare a drop target
Create data object
Create wx.DropSource
Execute drag operation
Cancel or accept drop
In wxPython, there are two predefined drop targets −
wx.TextDropTarget
wx.FileDropTarget
Many wxPython widgets support drag and drop activity. Source control must have dragging enabled, whereas target control must be in a position to accept (or reject) drag.
Source Data that the user is dragging is placed on the the target object. OnDropText() of target object consumes the data. If so desired, data from the source object can be deleted.
In the following example, two ListCrl objects are placed horizontally in a Box Sizer. List on the left is populated with a languages[] data. It is designated as the source of drag. One on the right is the target.
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET','C#']
self.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
self.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
for lang in languages:
self.lst1.InsertStringItem(0,lang)
The second list control is empty and is an argument for object of TextDropTarget class.
class MyTextDropTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object
def OnDropText(self, x, y, data):
self.object.InsertStringItem(0, data)
OnDropText() method adds source data in the target list control.
Drag operation is initialized by the event binder.
wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)
OnDragInit() function puts drag data on the target and deletes from the source.
def OnDragInit(self, event):
text = self.lst1.GetItemText(event.GetIndex())
tobj = wx.PyTextDataObject(text)
src = wx.DropSource(self.lst1)
src.SetData(tobj)
src.DoDragDrop(True)
self.lst1.DeleteItem(event.GetIndex())
The complete code is as follows −
import wx
class MyTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object
def OnDropText(self, x, y, data):
self.object.InsertStringItem(0, data)
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (-1,300))
panel = wx.Panel(self)
box = wx.BoxSizer(wx.HORIZONTAL)
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript',
'PHP', 'VB.NET','C#']
self.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
self.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST)
for lang in languages:
self.lst1.InsertStringItem(0,lang)
dt = MyTarget(self.lst2)
self.lst2.SetDropTarget(dt)
wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)
box.Add(self.lst1,0,wx.EXPAND)
box.Add(self.lst2, 1, wx.EXPAND)
panel.SetSizer(box)
panel.Fit()
self.Centre()
self.Show(True)
def OnDragInit(self, event):
text = self.lst1.GetItemText(event.GetIndex())
tobj = wx.PyTextDataObject(text)
src = wx.DropSource(self.lst1)
src.SetData(tobj)
src.DoDragDrop(True)
self.lst1.DeleteItem(event.GetIndex())
ex = wx.App()
Mywin(None,'Drag&Drop Demo')
ex.MainLoop()
The above code produces the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2116,
"s": 1882,
"text": "Provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another just by dragging it with the mouse and dropping on another window."
},
{
"code": null,
"e": 2171,
"s": 2116,
"text": "Drag and drop operation involves the following steps −"
},
{
"code": null,
"e": 2193,
"s": 2171,
"text": "Declare a drop target"
},
{
"code": null,
"e": 2212,
"s": 2193,
"text": "Create data object"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Create wx.DropSource"
},
{
"code": null,
"e": 2256,
"s": 2233,
"text": "Execute drag operation"
},
{
"code": null,
"e": 2278,
"s": 2256,
"text": "Cancel or accept drop"
},
{
"code": null,
"e": 2331,
"s": 2278,
"text": "In wxPython, there are two predefined drop targets −"
},
{
"code": null,
"e": 2349,
"s": 2331,
"text": "wx.TextDropTarget"
},
{
"code": null,
"e": 2367,
"s": 2349,
"text": "wx.FileDropTarget"
},
{
"code": null,
"e": 2537,
"s": 2367,
"text": "Many wxPython widgets support drag and drop activity. Source control must have dragging enabled, whereas target control must be in a position to accept (or reject) drag."
},
{
"code": null,
"e": 2719,
"s": 2537,
"text": "Source Data that the user is dragging is placed on the the target object. OnDropText() of target object consumes the data. If so desired, data from the source object can be deleted."
},
{
"code": null,
"e": 2932,
"s": 2719,
"text": "In the following example, two ListCrl objects are placed horizontally in a Box Sizer. List on the left is populated with a languages[] data. It is designated as the source of drag. One on the right is the target."
},
{
"code": null,
"e": 3201,
"s": 2932,
"text": "languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET','C#'] \nself.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST) \nself.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST) \n\n for lang in languages: \n self.lst1.InsertStringItem(0,lang)"
},
{
"code": null,
"e": 3289,
"s": 3201,
"text": "The second list control is empty and is an argument for object of TextDropTarget class."
},
{
"code": null,
"e": 3516,
"s": 3289,
"text": "class MyTextDropTarget(wx.TextDropTarget):\n def __init__(self, object): \n wx.TextDropTarget.__init__(self) \n self.object = object\n\t\t\n def OnDropText(self, x, y, data): \n self.object.InsertStringItem(0, data)"
},
{
"code": null,
"e": 3581,
"s": 3516,
"text": "OnDropText() method adds source data in the target list control."
},
{
"code": null,
"e": 3632,
"s": 3581,
"text": "Drag operation is initialized by the event binder."
},
{
"code": null,
"e": 3698,
"s": 3632,
"text": "wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)\n"
},
{
"code": null,
"e": 3778,
"s": 3698,
"text": "OnDragInit() function puts drag data on the target and deletes from the source."
},
{
"code": null,
"e": 4020,
"s": 3778,
"text": "def OnDragInit(self, event): \n text = self.lst1.GetItemText(event.GetIndex()) \n tobj = wx.PyTextDataObject(text) \n src = wx.DropSource(self.lst1) \n src.SetData(tobj) \n src.DoDragDrop(True) \n self.lst1.DeleteItem(event.GetIndex())"
},
{
"code": null,
"e": 4054,
"s": 4020,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 5478,
"s": 4054,
"text": "import wx\n \nclass MyTarget(wx.TextDropTarget): \n def __init__(self, object): \n wx.TextDropTarget.__init__(self) \n self.object = object \n\t\t\n def OnDropText(self, x, y, data): \n self.object.InsertStringItem(0, data) \n\t\t\nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (-1,300)) \n panel = wx.Panel(self) \n box = wx.BoxSizer(wx.HORIZONTAL) \n languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript',\n 'PHP', 'VB.NET','C#']\n\t\t\t\n self.lst1 = wx.ListCtrl(panel, -1, style = wx.LC_LIST) \n self.lst2 = wx.ListCtrl(panel, -1, style = wx.LC_LIST) \n for lang in languages: \n self.lst1.InsertStringItem(0,lang) \n \n dt = MyTarget(self.lst2) \n self.lst2.SetDropTarget(dt) \n wx.EVT_LIST_BEGIN_DRAG(self, self.lst1.GetId(), self.OnDragInit)\n\t\t\n box.Add(self.lst1,0,wx.EXPAND) \n box.Add(self.lst2, 1, wx.EXPAND) \n\t\t\n panel.SetSizer(box) \n panel.Fit() \n self.Centre() \n self.Show(True) \n \n def OnDragInit(self, event): \n text = self.lst1.GetItemText(event.GetIndex()) \n tobj = wx.PyTextDataObject(text) \n src = wx.DropSource(self.lst1) \n src.SetData(tobj) \n src.DoDragDrop(True) \n self.lst1.DeleteItem(event.GetIndex()) \n\t\t\nex = wx.App() \nMywin(None,'Drag&Drop Demo') \nex.MainLoop()"
},
{
"code": null,
"e": 5525,
"s": 5478,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5532,
"s": 5525,
"text": " Print"
},
{
"code": null,
"e": 5543,
"s": 5532,
"text": " Add Notes"
}
] |
Minimum Cost Path with Left, Right, Bottom and Up moves allowed - GeeksforGeeks | 05 May, 2022
Given a two dimensional grid, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.Note : It is assumed that negative cost cycles do not exist in input matrix.This problem is extension of below problem.Min Cost Path with right and bottom moves allowed.In previous problem only going right and bottom was allowed but in this problem we are allowed to go bottom, up, right and left i.e. in all 4 direction.Examples:
A cost grid is given in below diagram, minimum
cost to reach bottom right from top left
is 327 (= 31 + 10 + 13 + 47 + 65 + 12 + 18 +
6 + 33 + 11 + 20 + 41 + 20)
The chosen least cost path is shown in green.
It is not possible to solve this problem using dynamic programming similar to previous problem because here current state depends not only on right and bottom cells but also on left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of grid represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph from these cells instead we will use matrix as it is in our dijkstra’s algorithm. In below code Dijkstra’ algorithm’s implementation is used. The code implemented below is changed to cope with matrix represented implicit graph. Please also see use of dx and dy arrays in below code, these arrays are taken for simplifying the process of visiting neighbor vertices of each cell.
C++
Java
Python3
Javascript
// C++ program to get least cost path in a grid from// top-left to bottom-right#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 5 // structure for information of each cellstruct cell{ int x, y; int distance; cell(int x, int y, int distance) : x(x), y(y), distance(distance) {}}; // Utility method for comparing two cellsbool operator<(const cell& a, const cell& b){ if (a.distance == b.distance) { if (a.x != b.x) return (a.x < b.x); else return (a.y < b.y); } return (a.distance < b.distance);} // Utility method to check whether a point is// inside the grid or notbool isInsideGrid(int i, int j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method returns minimum cost to reach bottom// right from top leftint shortest(int grid[ROW][COL], int row, int col){ int dis[row][col]; // initializing distance array by INT_MAX for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) dis[i][j] = INT_MAX; // direction arrays for simplification of getting // neighbour int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; set<cell> st; // insert (0, 0) cell with 0 distance st.insert(cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (!st.empty()) { // get the cell with minimum distance and delete // it from the set cell k = *st.begin(); st.erase(st.begin()); // looping through all neighbours for (int i = 0; i < 4; i++) { int x = k.x + dx[i]; int y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, then // update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // If cell is already there in set, then // remove its previous entry if (dis[x][y] != INT_MAX) st.erase(st.find(cell(x, y, dis[x][y]))); // update the distance and insert new updated // cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.insert(cell(x, y, dis[x][y])); } } } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << " "; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1];} // Driver code to test above methodsint main(){ int grid[ROW][COL] = { 31, 100, 65, 12, 18, 10, 13, 47, 157, 6, 100, 113, 174, 11, 33, 88, 124, 41, 20, 140, 99, 32, 111, 41, 20 }; cout << shortest(grid, ROW, COL) << endl; return 0;}
// Java program to get least cost path// in a grid from top-left to bottom-rightimport java.io.*;import java.util.*; class GFG{ static int[] dx = { -1, 0, 1, 0 };static int[] dy = { 0, 1, 0, -1 };static int ROW = 5;static int COL = 5; // Custom class for representing// row-index, column-index &// distance of each cellstatic class Cell{ int x; int y; int distance; Cell(int x, int y, int distance) { this.x = x; this.y = y; this.distance = distance; }} // Custom comparator for inserting cells// into Priority Queuestatic class distanceComparator implements Comparator<Cell>{ public int compare(Cell a, Cell b) { if (a.distance < b.distance) { return -1; } else if (a.distance > b.distance) { return 1; } else {return 0;} }} // Utility method to check whether current// cell is inside grid or notstatic boolean isInsideGrid(int i, int j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method to return shortest path from// top-corner to bottom-corner in 2D gridstatic int shortestPath(int[][] grid, int row, int col){ int[][] dist = new int[row][col]; // Initializing distance array by INT_MAX for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { dist[i][j] = Integer.MAX_VALUE; } } // Initialized source distance as // initial grid position value dist[0][0] = grid[0][0]; PriorityQueue<Cell> pq = new PriorityQueue<Cell>( row * col, new distanceComparator()); // Insert source cell to priority queue pq.add(new Cell(0, 0, dist[0][0])); while (!pq.isEmpty()) { Cell curr = pq.poll(); for(int i = 0; i < 4; i++) { int rows = curr.x + dx[i]; int cols = curr.y + dy[i]; if (isInsideGrid(rows, cols)) { if (dist[rows][cols] > dist[curr.x][curr.y] + grid[rows][cols]) { // If Cell is already been reached once, // remove it from priority queue if (dist[rows][cols] != Integer.MAX_VALUE) { Cell adj = new Cell(rows, cols, dist[rows][cols]); pq.remove(adj); } // Insert cell with updated distance dist[rows][cols] = dist[curr.x][curr.y] + grid[rows][cols]; pq.add(new Cell(rows, cols, dist[rows][cols])); } } } } return dist[row - 1][col - 1];} // Driver codepublic static void main(String[] args)throws IOException{ int[][] grid = { { 31, 100, 65, 12, 18 }, { 10, 13, 47, 157, 6 }, { 100, 113, 174, 11, 33 }, { 88, 124, 41, 20, 140 }, { 99, 32, 111, 41, 20 } }; System.out.println(shortestPath(grid, ROW, COL));}} // This code is contributed by jigyansu
# Python program to get least cost path in a grid from# top-left to bottom-rightfrom functools import cmp_to_key ROW = 5COL = 5 def mycmp(a,b): if (a.distance == b.distance): if (a.x != b.x): return (a.x - b.x) else: return (a.y - b.y) return (a.distance - b.distance) # structure for information of each cellclass cell: def __init__(self,x, y, distance): self.x = x self.y = y self.distance = distance # Utility method to check whether a point is# inside the grid or notdef isInsideGrid(i, j): return (i >= 0 and i < ROW and j >= 0 and j < COL) # Method returns minimum cost to reach bottom# right from top leftdef shortest(grid, row, col): dis = [[0 for i in range(col)]for j in range(row)] # initializing distance array by INT_MAX for i in range(row): for j in range(col): dis[i][j] = 1000000000 # direction arrays for simplification of getting # neighbour dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] st = [] # insert (0, 0) cell with 0 distance st.append(cell(0, 0, 0)) # initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0] # loop for standard dijkstra's algorithm while (len(st)!=0): # get the cell with minimum distance and delete # it from the set k = st[0] st = st[1:] # looping through all neighbours for i in range(4): x = k.x + dx[i] y = k.y + dy[i] # if not inside boundary, ignore them if (isInsideGrid(x, y) == 0): continue # If distance from current cell is smaller, then # update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]): # update the distance and insert new updated # cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y] st.append(cell(x, y, dis[x][y])) st.sort(key=cmp_to_key(mycmp)) # uncomment below code to print distance # of each cell from (0, 0) # for i in range(row): # for j in range(col): # print(dis[i][j] ,end= " ") # print() # dis[row - 1][col - 1] will represent final # distance of bottom right cell from top left cell return dis[row - 1][col - 1] # Driver code to test above methods grid = [[31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140],[99, 32, 111, 41, 20]]print(shortest(grid, ROW, COL)) # This code is contributed by shinjanpatra
<script> // Javascript program to get least cost path in a grid from// top-left to bottom-rightvar ROW = 5var COL = 5 // structure for information of each cellclass cell{ constructor(x, y, distance) { this.x = x; this.y = y; this.distance = distance; }}; // Utility method to check whether a point is// inside the grid or notfunction isInsideGrid(i, j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method returns minimum cost to reach bottom// right from top leftfunction shortest(grid, row, col){ var dis = Array.from(Array(row), ()=>Array(col).fill(0)); // initializing distance array by INT_MAX for (var i = 0; i < row; i++) for (var j = 0; j < col; j++) dis[i][j] = 1000000000; // direction arrays for simplification of getting // neighbour var dx = [-1, 0, 1, 0]; var dy = [0, 1, 0, -1]; var st = []; // insert (0, 0) cell with 0 distance st.push(new cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (st.length!=0) { // get the cell with minimum distance and delete // it from the set var k = st[0]; st.shift(); // looping through all neighbours for (var i = 0; i < 4; i++) { var x = k.x + dx[i]; var y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, then // update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // update the distance and insert new updated // cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.push(new cell(x, y, dis[x][y])); } } st.sort((a,b)=>{ if (a.distance == b.distance) { if (a.x != b.x) return (a.x - b.x); else return (a.y - b.y); } return (a.distance - b.distance); }); } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << " "; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1];} // Driver code to test above methodsvar grid =[ [31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140], [99, 32, 111, 41, 20]];document.write(shortest(grid, ROW, COL)); // This code is contributed by rutvik_56. </script>
Output:
327
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
jigyansu
azmuth13
rutvik_56
shinjanpatra
MakeMyTrip
Shortest Path
STL
Dynamic Programming
Graph
Greedy
Matrix
MakeMyTrip
Dynamic Programming
Greedy
Matrix
Graph
Shortest Path
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Overlapping Subproblems Property in Dynamic Programming | DP-1
Find minimum number of coins that make a given value
Tabulation vs Memoization
Longest Common Substring | DP-29
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 | [
{
"code": null,
"e": 25969,
"s": 25941,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26529,
"s": 25969,
"text": "Given a two dimensional grid, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.Note : It is assumed that negative cost cycles do not exist in input matrix.This problem is extension of below problem.Min Cost Path with right and bottom moves allowed.In previous problem only going right and bottom was allowed but in this problem we are allowed to go bottom, up, right and left i.e. in all 4 direction.Examples:"
},
{
"code": null,
"e": 26740,
"s": 26529,
"text": "A cost grid is given in below diagram, minimum \ncost to reach bottom right from top left \nis 327 (= 31 + 10 + 13 + 47 + 65 + 12 + 18 + \n6 + 33 + 11 + 20 + 41 + 20)\n\nThe chosen least cost path is shown in green."
},
{
"code": null,
"e": 27476,
"s": 26740,
"text": "It is not possible to solve this problem using dynamic programming similar to previous problem because here current state depends not only on right and bottom cells but also on left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of grid represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph from these cells instead we will use matrix as it is in our dijkstra’s algorithm. In below code Dijkstra’ algorithm’s implementation is used. The code implemented below is changed to cope with matrix represented implicit graph. Please also see use of dx and dy arrays in below code, these arrays are taken for simplifying the process of visiting neighbor vertices of each cell."
},
{
"code": null,
"e": 27480,
"s": 27476,
"text": "C++"
},
{
"code": null,
"e": 27485,
"s": 27480,
"text": "Java"
},
{
"code": null,
"e": 27493,
"s": 27485,
"text": "Python3"
},
{
"code": null,
"e": 27504,
"s": 27493,
"text": "Javascript"
},
{
"code": "// C++ program to get least cost path in a grid from// top-left to bottom-right#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 5 // structure for information of each cellstruct cell{ int x, y; int distance; cell(int x, int y, int distance) : x(x), y(y), distance(distance) {}}; // Utility method for comparing two cellsbool operator<(const cell& a, const cell& b){ if (a.distance == b.distance) { if (a.x != b.x) return (a.x < b.x); else return (a.y < b.y); } return (a.distance < b.distance);} // Utility method to check whether a point is// inside the grid or notbool isInsideGrid(int i, int j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method returns minimum cost to reach bottom// right from top leftint shortest(int grid[ROW][COL], int row, int col){ int dis[row][col]; // initializing distance array by INT_MAX for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) dis[i][j] = INT_MAX; // direction arrays for simplification of getting // neighbour int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; set<cell> st; // insert (0, 0) cell with 0 distance st.insert(cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (!st.empty()) { // get the cell with minimum distance and delete // it from the set cell k = *st.begin(); st.erase(st.begin()); // looping through all neighbours for (int i = 0; i < 4; i++) { int x = k.x + dx[i]; int y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, then // update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // If cell is already there in set, then // remove its previous entry if (dis[x][y] != INT_MAX) st.erase(st.find(cell(x, y, dis[x][y]))); // update the distance and insert new updated // cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.insert(cell(x, y, dis[x][y])); } } } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << \" \"; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1];} // Driver code to test above methodsint main(){ int grid[ROW][COL] = { 31, 100, 65, 12, 18, 10, 13, 47, 157, 6, 100, 113, 174, 11, 33, 88, 124, 41, 20, 140, 99, 32, 111, 41, 20 }; cout << shortest(grid, ROW, COL) << endl; return 0;}",
"e": 30543,
"s": 27504,
"text": null
},
{
"code": "// Java program to get least cost path// in a grid from top-left to bottom-rightimport java.io.*;import java.util.*; class GFG{ static int[] dx = { -1, 0, 1, 0 };static int[] dy = { 0, 1, 0, -1 };static int ROW = 5;static int COL = 5; // Custom class for representing// row-index, column-index &// distance of each cellstatic class Cell{ int x; int y; int distance; Cell(int x, int y, int distance) { this.x = x; this.y = y; this.distance = distance; }} // Custom comparator for inserting cells// into Priority Queuestatic class distanceComparator implements Comparator<Cell>{ public int compare(Cell a, Cell b) { if (a.distance < b.distance) { return -1; } else if (a.distance > b.distance) { return 1; } else {return 0;} }} // Utility method to check whether current// cell is inside grid or notstatic boolean isInsideGrid(int i, int j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method to return shortest path from// top-corner to bottom-corner in 2D gridstatic int shortestPath(int[][] grid, int row, int col){ int[][] dist = new int[row][col]; // Initializing distance array by INT_MAX for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { dist[i][j] = Integer.MAX_VALUE; } } // Initialized source distance as // initial grid position value dist[0][0] = grid[0][0]; PriorityQueue<Cell> pq = new PriorityQueue<Cell>( row * col, new distanceComparator()); // Insert source cell to priority queue pq.add(new Cell(0, 0, dist[0][0])); while (!pq.isEmpty()) { Cell curr = pq.poll(); for(int i = 0; i < 4; i++) { int rows = curr.x + dx[i]; int cols = curr.y + dy[i]; if (isInsideGrid(rows, cols)) { if (dist[rows][cols] > dist[curr.x][curr.y] + grid[rows][cols]) { // If Cell is already been reached once, // remove it from priority queue if (dist[rows][cols] != Integer.MAX_VALUE) { Cell adj = new Cell(rows, cols, dist[rows][cols]); pq.remove(adj); } // Insert cell with updated distance dist[rows][cols] = dist[curr.x][curr.y] + grid[rows][cols]; pq.add(new Cell(rows, cols, dist[rows][cols])); } } } } return dist[row - 1][col - 1];} // Driver codepublic static void main(String[] args)throws IOException{ int[][] grid = { { 31, 100, 65, 12, 18 }, { 10, 13, 47, 157, 6 }, { 100, 113, 174, 11, 33 }, { 88, 124, 41, 20, 140 }, { 99, 32, 111, 41, 20 } }; System.out.println(shortestPath(grid, ROW, COL));}} // This code is contributed by jigyansu",
"e": 33929,
"s": 30543,
"text": null
},
{
"code": "# Python program to get least cost path in a grid from# top-left to bottom-rightfrom functools import cmp_to_key ROW = 5COL = 5 def mycmp(a,b): if (a.distance == b.distance): if (a.x != b.x): return (a.x - b.x) else: return (a.y - b.y) return (a.distance - b.distance) # structure for information of each cellclass cell: def __init__(self,x, y, distance): self.x = x self.y = y self.distance = distance # Utility method to check whether a point is# inside the grid or notdef isInsideGrid(i, j): return (i >= 0 and i < ROW and j >= 0 and j < COL) # Method returns minimum cost to reach bottom# right from top leftdef shortest(grid, row, col): dis = [[0 for i in range(col)]for j in range(row)] # initializing distance array by INT_MAX for i in range(row): for j in range(col): dis[i][j] = 1000000000 # direction arrays for simplification of getting # neighbour dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] st = [] # insert (0, 0) cell with 0 distance st.append(cell(0, 0, 0)) # initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0] # loop for standard dijkstra's algorithm while (len(st)!=0): # get the cell with minimum distance and delete # it from the set k = st[0] st = st[1:] # looping through all neighbours for i in range(4): x = k.x + dx[i] y = k.y + dy[i] # if not inside boundary, ignore them if (isInsideGrid(x, y) == 0): continue # If distance from current cell is smaller, then # update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]): # update the distance and insert new updated # cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y] st.append(cell(x, y, dis[x][y])) st.sort(key=cmp_to_key(mycmp)) # uncomment below code to print distance # of each cell from (0, 0) # for i in range(row): # for j in range(col): # print(dis[i][j] ,end= \" \") # print() # dis[row - 1][col - 1] will represent final # distance of bottom right cell from top left cell return dis[row - 1][col - 1] # Driver code to test above methods grid = [[31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140],[99, 32, 111, 41, 20]]print(shortest(grid, ROW, COL)) # This code is contributed by shinjanpatra",
"e": 36480,
"s": 33929,
"text": null
},
{
"code": "<script> // Javascript program to get least cost path in a grid from// top-left to bottom-rightvar ROW = 5var COL = 5 // structure for information of each cellclass cell{ constructor(x, y, distance) { this.x = x; this.y = y; this.distance = distance; }}; // Utility method to check whether a point is// inside the grid or notfunction isInsideGrid(i, j){ return (i >= 0 && i < ROW && j >= 0 && j < COL);} // Method returns minimum cost to reach bottom// right from top leftfunction shortest(grid, row, col){ var dis = Array.from(Array(row), ()=>Array(col).fill(0)); // initializing distance array by INT_MAX for (var i = 0; i < row; i++) for (var j = 0; j < col; j++) dis[i][j] = 1000000000; // direction arrays for simplification of getting // neighbour var dx = [-1, 0, 1, 0]; var dy = [0, 1, 0, -1]; var st = []; // insert (0, 0) cell with 0 distance st.push(new cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (st.length!=0) { // get the cell with minimum distance and delete // it from the set var k = st[0]; st.shift(); // looping through all neighbours for (var i = 0; i < 4; i++) { var x = k.x + dx[i]; var y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, then // update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // update the distance and insert new updated // cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.push(new cell(x, y, dis[x][y])); } } st.sort((a,b)=>{ if (a.distance == b.distance) { if (a.x != b.x) return (a.x - b.x); else return (a.y - b.y); } return (a.distance - b.distance); }); } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << \" \"; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1];} // Driver code to test above methodsvar grid =[ [31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140], [99, 32, 111, 41, 20]];document.write(shortest(grid, ROW, COL)); // This code is contributed by rutvik_56. </script>",
"e": 39236,
"s": 36480,
"text": null
},
{
"code": null,
"e": 39244,
"s": 39236,
"text": "Output:"
},
{
"code": null,
"e": 39248,
"s": 39244,
"text": "327"
},
{
"code": null,
"e": 39677,
"s": 39248,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39690,
"s": 39677,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 39699,
"s": 39690,
"text": "jigyansu"
},
{
"code": null,
"e": 39708,
"s": 39699,
"text": "azmuth13"
},
{
"code": null,
"e": 39718,
"s": 39708,
"text": "rutvik_56"
},
{
"code": null,
"e": 39731,
"s": 39718,
"text": "shinjanpatra"
},
{
"code": null,
"e": 39742,
"s": 39731,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 39756,
"s": 39742,
"text": "Shortest Path"
},
{
"code": null,
"e": 39760,
"s": 39756,
"text": "STL"
},
{
"code": null,
"e": 39780,
"s": 39760,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39786,
"s": 39780,
"text": "Graph"
},
{
"code": null,
"e": 39793,
"s": 39786,
"text": "Greedy"
},
{
"code": null,
"e": 39800,
"s": 39793,
"text": "Matrix"
},
{
"code": null,
"e": 39811,
"s": 39800,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 39831,
"s": 39811,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39838,
"s": 39831,
"text": "Greedy"
},
{
"code": null,
"e": 39845,
"s": 39838,
"text": "Matrix"
},
{
"code": null,
"e": 39851,
"s": 39845,
"text": "Graph"
},
{
"code": null,
"e": 39865,
"s": 39851,
"text": "Shortest Path"
},
{
"code": null,
"e": 39869,
"s": 39865,
"text": "STL"
},
{
"code": null,
"e": 39967,
"s": 39869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40035,
"s": 39967,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 40098,
"s": 40035,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 40151,
"s": 40098,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 40177,
"s": 40151,
"text": "Tabulation vs Memoization"
},
{
"code": null,
"e": 40210,
"s": 40177,
"text": "Longest Common Substring | DP-29"
},
{
"code": null,
"e": 40250,
"s": 40210,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 40301,
"s": 40250,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 40339,
"s": 40301,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 40397,
"s": 40339,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
CSS | Shadow Effect - GeeksforGeeks | 04 Dec, 2018
The shadow effect property in CSS is used to add text and images shadow in HTML document.
Text Shadow: The CSS text-shadow property is used to display the text with shadow. This property holds the pixel length, breadth, and width of the shadow and the color of the shadow.
Syntax:
Text-shadow: 3px 3px 3px green;
Example:
<!DOCTYPE html><html> <head> <title>text-shadow property</title> <style> h1 { color: green; text-shadow: 3px 3px 3px lightgreen; } </style> </head> <body> <h1>Geeks For Geeks | A computer Science portal for Geeks</h1> </body></html>
Output:
TextBox Shadow: The CSS boxShadow property applies shadow to the text box. This property hold the pixel length, breadth, and width of the shadow and the color of the shadow.
Syntax:
boxShadow: 3px 3px 3px green;
Example:
<!DOCTYPE html><html> <head> <title>box shadow property</title> <style> #Gfg { width: 220px; height: 50px; background-color: green; color: white; } </style> <script> // function that show Shadow Effect. function Shadow() { document.getElementById("Gfg").style.boxShadow = "5px 5px 5px gray"; } </script> </head> <body> <button onclick = "Shadow()">Click to see Shadow</button> <div id = "Gfg"> <h1>GeeksforGeeks</h1> </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.
CSS-Advanced
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 update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 29291,
"s": 29263,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 29381,
"s": 29291,
"text": "The shadow effect property in CSS is used to add text and images shadow in HTML document."
},
{
"code": null,
"e": 29564,
"s": 29381,
"text": "Text Shadow: The CSS text-shadow property is used to display the text with shadow. This property holds the pixel length, breadth, and width of the shadow and the color of the shadow."
},
{
"code": null,
"e": 29572,
"s": 29564,
"text": "Syntax:"
},
{
"code": null,
"e": 29604,
"s": 29572,
"text": "Text-shadow: 3px 3px 3px green;"
},
{
"code": null,
"e": 29613,
"s": 29604,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>text-shadow property</title> <style> h1 { color: green; text-shadow: 3px 3px 3px lightgreen; } </style> </head> <body> <h1>Geeks For Geeks | A computer Science portal for Geeks</h1> </body></html> ",
"e": 29958,
"s": 29613,
"text": null
},
{
"code": null,
"e": 29966,
"s": 29958,
"text": "Output:"
},
{
"code": null,
"e": 30140,
"s": 29966,
"text": "TextBox Shadow: The CSS boxShadow property applies shadow to the text box. This property hold the pixel length, breadth, and width of the shadow and the color of the shadow."
},
{
"code": null,
"e": 30148,
"s": 30140,
"text": "Syntax:"
},
{
"code": null,
"e": 30178,
"s": 30148,
"text": "boxShadow: 3px 3px 3px green;"
},
{
"code": null,
"e": 30187,
"s": 30178,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>box shadow property</title> <style> #Gfg { width: 220px; height: 50px; background-color: green; color: white; } </style> <script> // function that show Shadow Effect. function Shadow() { document.getElementById(\"Gfg\").style.boxShadow = \"5px 5px 5px gray\"; } </script> </head> <body> <button onclick = \"Shadow()\">Click to see Shadow</button> <div id = \"Gfg\"> <h1>GeeksforGeeks</h1> </div> </body></html>",
"e": 30928,
"s": 30187,
"text": null
},
{
"code": null,
"e": 30936,
"s": 30928,
"text": "Output:"
},
{
"code": null,
"e": 31073,
"s": 30936,
"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": 31086,
"s": 31073,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 31090,
"s": 31086,
"text": "CSS"
},
{
"code": null,
"e": 31095,
"s": 31090,
"text": "HTML"
},
{
"code": null,
"e": 31112,
"s": 31095,
"text": "Web Technologies"
},
{
"code": null,
"e": 31117,
"s": 31112,
"text": "HTML"
},
{
"code": null,
"e": 31215,
"s": 31117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31277,
"s": 31215,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31327,
"s": 31277,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31375,
"s": 31327,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31433,
"s": 31375,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31488,
"s": 31433,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 31550,
"s": 31488,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31600,
"s": 31550,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31648,
"s": 31600,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31708,
"s": 31648,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Find shortest unique prefix for every word in a given list | Set 2 (Using Sorting) - GeeksforGeeks | 08 Feb, 2022
Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is a prefix of another. Output the shortest unique prefixes in sorted order.
Input : {"zebra", "dog", "duck", "dove"}
Output : z, dog, dov, du
Explanation: dog => dog
dove = dov
duck = du
z => zebra
Input: {"geeksgeeks", "geeksquiz", "geeksforgeeks"}
Output: geeksf, geeksg, geeksq
We have discussed a Trie based approach in the below post. Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)In this post, a sorting based approach is discussed. On comparing the string with 2 other most similar strings in the array, we can find its shortest unique prefix. For example, if we sort the array {“zebra”, “dog”, “duck”, “dove”}, we get {“dog”, “dove”, “duck”, “zebra”}. The shortest unique prefix for the string “dove” can be found as: Compare “dove” to “dog” –> unique prefix for dove is “dov” Compare “dove” to “duck” –> unique prefix for dove is “do” Now, the shortest unique prefix for “dove” is the one with greater length between “dov” and “do”. So, it is “dov”. The shortest unique prefix for the first and last string can be found by comparing them with only 1 most similar neighbor on right and left, respectively.
We can sort the array of strings and keep on doing this for every string of the array.
C++
Java
Python3
C#
// C++ program to print shortest unique prefixes// for every word.#include <bits/stdc++.h>using namespace std; vector<string> uniquePrefix(vector<string> &a){ int size = a.size(); /* create an array to store the results */ vector<string> res(size); /* sort the array of strings */ sort(a.begin(), a.end()); /* compare the first string with its only right neighbor */ int j = 0; while (j < min(a[0].length() - 1, a[1].length() - 1)) { if (a[0][j] == a[1][j]) j++; else break; } int ind = 0; res[ind++] = a[0].substr(0, j + 1); /* Store the unique prefix of a[1] from its left neighbor */ string temp_prefix = a[1].substr(0, j + 1); for (int i = 1; i < size - 1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < min(a[i].length() - 1, a[i + 1].length() - 1)) { if (a[i][j] == a[i + 1][j]) j++; else break; } string new_prefix = a[i].substr(0, j + 1); /* compare the new prefix with previous prefix */ if (temp_prefix.length() > new_prefix.length()) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i + 1].substr(0, j + 1); } /* compute the unique prefix for the last string in sorted array */ j = 0; string sec_last = a[size - 2]; string last = a[size - 1]; while (j < min(sec_last.length() - 1, last.length() - 1)) { if (sec_last[j] == last[j]) j++; else break; } res[ind] = last.substr(0, j + 1); return res;} // Driver Codeint main(){ vector<string> input = {"zebra", "dog", "duck", "dove"}; vector<string> output = uniquePrefix(input); cout << "The shortest unique prefixes in sorted order are : \n"; for (auto i : output) cout << i << ' '; return 0;} // This code is contributed by// sanjeev2552
// Java program to print shortest unique prefixes// for every word.import java.io.*;import java.util.*; class GFG{ public String[] uniquePrefix(String[] a) { int size = a.length; /* create an array to store the results */ String[] res = new String[size]; /* sort the array of strings */ Arrays.sort(a); /* compare the first string with its only right neighbor */ int j = 0; while (j < Math.min(a[0].length()-1, a[1].length()-1)) { if (a[0].charAt(j)==a[1].charAt(j)) j++; else break; } int ind = 0; res[ind++] = a[0].substring(0, j+1); /* Store the unique prefix of a[1] from its left neighbor */ String temp_prefix = a[1].substring(0, j+1); for (int i = 1; i < size-1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < Math.min( a[i].length()-1, a[i+1].length()-1 )) { if (a[i].charAt(j) == a[i+1].charAt(j)) j++; else break; } String new_prefix = a[i].substring(0, j+1); /* compare the new prefix with previous prefix */ if (temp_prefix.length() > new_prefix.length() ) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i+1].substring(0, j+1); } /* compute the unique prefix for the last string in sorted array */ j = 0; String sec_last = a[size-2] ; String last = a[size-1]; while (j < Math.min( sec_last.length()-1, last.length()-1)) { if (sec_last.charAt(j) == last.charAt(j)) j++; else break; } res[ind] = last.substring(0, j+1); return res; } /* Driver Function to test other function */ public static void main(String[] args) { GFG gfg = new GFG(); String[] input = {"zebra", "dog", "duck", "dove"}; String[] output = gfg.uniquePrefix(input); System.out.println( "The shortest unique prefixes" + " in sorted order are :"); for (int i=0; i < output.length; i++) System.out.print( output[i] + " "); }}
# Python3 program to print shortest unique prefixes# for every word.def uniquePrefix(a): size = len(a) # Create an array to store the results res = [0] * (size) # Sort the array of strings */ a = sorted(a) # Compare the first with its only right # neighbor j = 0 while (j < min(len(a[0]) - 1, len(a[1]) - 1)): if (a[0][j] == a[1][j]): j += 1 else: break ind = 0 res[ind] = a[0][0:j + 1] ind += 1 # Store the unique prefix of a[1] # from its left neighbor temp_prefix = a[1][0:j + 1] for i in range(1, size - 1): # Compute common prefix of a[i] unique from # its right neighbor j = 0 while (j < min(len(a[i]) - 1, len(a[i + 1]) - 1)): if (a[i][j] == a[i + 1][j]): j += 1 else: break new_prefix = a[i][0:j + 1] # Compare the new prefix with previous prefix if (len(temp_prefix) > len(new_prefix)): res[ind] = temp_prefix ind += 1 else: res[ind] = new_prefix ind += 1 # Store the prefix of a[i+1] unique from its # left neighbour temp_prefix = a[i + 1][0:j + 1] # Compute the unique prefix for the last # in sorted array j = 0 sec_last = a[size - 2] last = a[size - 1] while (j < min(len(sec_last) - 1, len(last) - 1)): if (sec_last[j] == last[j]): j += 1 else: break res[ind] = last[0:j + 1] return res # Driver Codeif __name__ == '__main__': input = [ "zebra", "dog", "duck", "dove" ] output = uniquePrefix(input) print("The shortest unique prefixes " + "in sorted order are : ") for i in output: print(i, end = " ") # This code is contributed by mohit kumar 29
// C# program to print shortest unique prefixes// for every word.using System; class GFG{ public String[] uniquePrefix(String[] a) { int size = a.Length; /* create an array to store the results */ String[] res = new String[size]; /* sort the array of strings */ Array.Sort(a); /* compare the first string with its only right neighbor */ int j = 0; while (j < Math.Min(a[0].Length - 1, a[1].Length - 1)) { if (a[0][j] == a[1][j]) j++; else break; } int ind = 0; res[ind++] = a[0].Substring(0, j + 1); /* Store the unique prefix of a[1] from its left neighbor */ String temp_prefix = a[1].Substring(0, j + 1); for (int i = 1; i < size - 1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < Math.Min( a[i].Length - 1, a[i + 1].Length - 1 )) { if (a[i][j] == a[i + 1][j]) j++; else break; } String new_prefix = a[i].Substring(0, j+1); /* compare the new prefix with previous prefix */ if (temp_prefix.Length > new_prefix.Length ) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i+1].Substring(0, j+1); } /* compute the unique prefix for the last string in sorted array */ j = 0; String sec_last = a[size-2] ; String last = a[size-1]; while (j < Math.Min( sec_last.Length-1, last.Length-1)) { if (sec_last[j] == last[j]) j++; else break; } res[ind] = last.Substring(0, j+1); return res; } /* Driver code */ public static void Main(String[] args) { GFG gfg = new GFG(); String[] input = {"zebra", "dog", "duck", "dove"}; String[] output = gfg.uniquePrefix(input); Console.WriteLine( "The shortest unique prefixes" + " in sorted order are :"); for (int i = 0; i < output.Length; i++) Console.Write( output[i] + " "); }} // This code is contributed by Princi Singh
Output:
The shortest unique prefixes in sorted order are :
dog dov du z
Another Python approach:If we want to output the prefixes as the order of strings in the input array, we can store the string and its corresponding index in the hashmap. While adding the prefix to the result array, we can get the index of the corresponding string from the hashmap and add the prefix to that index.
Python3
#Python program to print shortest unique prefix for every word in a list a=['dogs','dove','duck','zebra']r=[]j=0while(j<min(len(a[0]),len(a[1]))): if(a[0][j]==a[1][j]): j+=1 else: break i=0r.append(a[0][0:j+1])x=a[1][0:j+1] for i in range(1,len(a)-1): j=0 while(j<min(len(a[i]),len(a[i+1]))): if a[i][j]==a[i+1][j]: j+=1 else: break y=a[i][0:j+1] if(len(x)>len(y)): r.append(x) else: r.append(y) x=a[i+1][0:j+1] j=0l=a[len(a)-2]k=a[len(a)-1] while(j<min(len(l),len(k))): if ( l[j]==k[j]): j+=1 else: break r.append(k[0:j+1])print("The shortest unique prefixes are :")for i in range(0,len(r)): print(r[i],end=' ') #This code is contributed by Saahith Reddy
Output:
The shortest unique prefixes are :
dog dov du z
For a more efficient solution, we can use Trie as discussed in this post.This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
princi singh
sanjeev2552
reddysaahithm
mohit kumar 29
simmytarika5
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
C++ Program for QuickSort
Stability in sorting algorithms
Quick Sort vs Merge Sort
Sorting in Java
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 25321,
"s": 25293,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 25520,
"s": 25321,
"text": "Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is a prefix of another. Output the shortest unique prefixes in sorted order."
},
{
"code": null,
"e": 25770,
"s": 25520,
"text": "Input : {\"zebra\", \"dog\", \"duck\", \"dove\"}\nOutput : z, dog, dov, du\nExplanation: dog => dog\n dove = dov \n duck = du\n z => zebra \n\nInput: {\"geeksgeeks\", \"geeksquiz\", \"geeksforgeeks\"}\nOutput: geeksf, geeksg, geeksq"
},
{
"code": null,
"e": 26637,
"s": 25770,
"text": "We have discussed a Trie based approach in the below post. Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)In this post, a sorting based approach is discussed. On comparing the string with 2 other most similar strings in the array, we can find its shortest unique prefix. For example, if we sort the array {“zebra”, “dog”, “duck”, “dove”}, we get {“dog”, “dove”, “duck”, “zebra”}. The shortest unique prefix for the string “dove” can be found as: Compare “dove” to “dog” –> unique prefix for dove is “dov” Compare “dove” to “duck” –> unique prefix for dove is “do” Now, the shortest unique prefix for “dove” is the one with greater length between “dov” and “do”. So, it is “dov”. The shortest unique prefix for the first and last string can be found by comparing them with only 1 most similar neighbor on right and left, respectively. "
},
{
"code": null,
"e": 26726,
"s": 26637,
"text": "We can sort the array of strings and keep on doing this for every string of the array. "
},
{
"code": null,
"e": 26730,
"s": 26726,
"text": "C++"
},
{
"code": null,
"e": 26735,
"s": 26730,
"text": "Java"
},
{
"code": null,
"e": 26743,
"s": 26735,
"text": "Python3"
},
{
"code": null,
"e": 26746,
"s": 26743,
"text": "C#"
},
{
"code": "// C++ program to print shortest unique prefixes// for every word.#include <bits/stdc++.h>using namespace std; vector<string> uniquePrefix(vector<string> &a){ int size = a.size(); /* create an array to store the results */ vector<string> res(size); /* sort the array of strings */ sort(a.begin(), a.end()); /* compare the first string with its only right neighbor */ int j = 0; while (j < min(a[0].length() - 1, a[1].length() - 1)) { if (a[0][j] == a[1][j]) j++; else break; } int ind = 0; res[ind++] = a[0].substr(0, j + 1); /* Store the unique prefix of a[1] from its left neighbor */ string temp_prefix = a[1].substr(0, j + 1); for (int i = 1; i < size - 1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < min(a[i].length() - 1, a[i + 1].length() - 1)) { if (a[i][j] == a[i + 1][j]) j++; else break; } string new_prefix = a[i].substr(0, j + 1); /* compare the new prefix with previous prefix */ if (temp_prefix.length() > new_prefix.length()) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i + 1].substr(0, j + 1); } /* compute the unique prefix for the last string in sorted array */ j = 0; string sec_last = a[size - 2]; string last = a[size - 1]; while (j < min(sec_last.length() - 1, last.length() - 1)) { if (sec_last[j] == last[j]) j++; else break; } res[ind] = last.substr(0, j + 1); return res;} // Driver Codeint main(){ vector<string> input = {\"zebra\", \"dog\", \"duck\", \"dove\"}; vector<string> output = uniquePrefix(input); cout << \"The shortest unique prefixes in sorted order are : \\n\"; for (auto i : output) cout << i << ' '; return 0;} // This code is contributed by// sanjeev2552",
"e": 28831,
"s": 26746,
"text": null
},
{
"code": "// Java program to print shortest unique prefixes// for every word.import java.io.*;import java.util.*; class GFG{ public String[] uniquePrefix(String[] a) { int size = a.length; /* create an array to store the results */ String[] res = new String[size]; /* sort the array of strings */ Arrays.sort(a); /* compare the first string with its only right neighbor */ int j = 0; while (j < Math.min(a[0].length()-1, a[1].length()-1)) { if (a[0].charAt(j)==a[1].charAt(j)) j++; else break; } int ind = 0; res[ind++] = a[0].substring(0, j+1); /* Store the unique prefix of a[1] from its left neighbor */ String temp_prefix = a[1].substring(0, j+1); for (int i = 1; i < size-1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < Math.min( a[i].length()-1, a[i+1].length()-1 )) { if (a[i].charAt(j) == a[i+1].charAt(j)) j++; else break; } String new_prefix = a[i].substring(0, j+1); /* compare the new prefix with previous prefix */ if (temp_prefix.length() > new_prefix.length() ) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i+1].substring(0, j+1); } /* compute the unique prefix for the last string in sorted array */ j = 0; String sec_last = a[size-2] ; String last = a[size-1]; while (j < Math.min( sec_last.length()-1, last.length()-1)) { if (sec_last.charAt(j) == last.charAt(j)) j++; else break; } res[ind] = last.substring(0, j+1); return res; } /* Driver Function to test other function */ public static void main(String[] args) { GFG gfg = new GFG(); String[] input = {\"zebra\", \"dog\", \"duck\", \"dove\"}; String[] output = gfg.uniquePrefix(input); System.out.println( \"The shortest unique prefixes\" + \" in sorted order are :\"); for (int i=0; i < output.length; i++) System.out.print( output[i] + \" \"); }}",
"e": 31334,
"s": 28831,
"text": null
},
{
"code": "# Python3 program to print shortest unique prefixes# for every word.def uniquePrefix(a): size = len(a) # Create an array to store the results res = [0] * (size) # Sort the array of strings */ a = sorted(a) # Compare the first with its only right # neighbor j = 0 while (j < min(len(a[0]) - 1, len(a[1]) - 1)): if (a[0][j] == a[1][j]): j += 1 else: break ind = 0 res[ind] = a[0][0:j + 1] ind += 1 # Store the unique prefix of a[1] # from its left neighbor temp_prefix = a[1][0:j + 1] for i in range(1, size - 1): # Compute common prefix of a[i] unique from # its right neighbor j = 0 while (j < min(len(a[i]) - 1, len(a[i + 1]) - 1)): if (a[i][j] == a[i + 1][j]): j += 1 else: break new_prefix = a[i][0:j + 1] # Compare the new prefix with previous prefix if (len(temp_prefix) > len(new_prefix)): res[ind] = temp_prefix ind += 1 else: res[ind] = new_prefix ind += 1 # Store the prefix of a[i+1] unique from its # left neighbour temp_prefix = a[i + 1][0:j + 1] # Compute the unique prefix for the last # in sorted array j = 0 sec_last = a[size - 2] last = a[size - 1] while (j < min(len(sec_last) - 1, len(last) - 1)): if (sec_last[j] == last[j]): j += 1 else: break res[ind] = last[0:j + 1] return res # Driver Codeif __name__ == '__main__': input = [ \"zebra\", \"dog\", \"duck\", \"dove\" ] output = uniquePrefix(input) print(\"The shortest unique prefixes \" + \"in sorted order are : \") for i in output: print(i, end = \" \") # This code is contributed by mohit kumar 29",
"e": 33194,
"s": 31334,
"text": null
},
{
"code": "// C# program to print shortest unique prefixes// for every word.using System; class GFG{ public String[] uniquePrefix(String[] a) { int size = a.Length; /* create an array to store the results */ String[] res = new String[size]; /* sort the array of strings */ Array.Sort(a); /* compare the first string with its only right neighbor */ int j = 0; while (j < Math.Min(a[0].Length - 1, a[1].Length - 1)) { if (a[0][j] == a[1][j]) j++; else break; } int ind = 0; res[ind++] = a[0].Substring(0, j + 1); /* Store the unique prefix of a[1] from its left neighbor */ String temp_prefix = a[1].Substring(0, j + 1); for (int i = 1; i < size - 1; i++) { /* compute common prefix of a[i] unique from its right neighbor */ j = 0; while (j < Math.Min( a[i].Length - 1, a[i + 1].Length - 1 )) { if (a[i][j] == a[i + 1][j]) j++; else break; } String new_prefix = a[i].Substring(0, j+1); /* compare the new prefix with previous prefix */ if (temp_prefix.Length > new_prefix.Length ) res[ind++] = temp_prefix; else res[ind++] = new_prefix; /* store the prefix of a[i+1] unique from its left neighbour */ temp_prefix = a[i+1].Substring(0, j+1); } /* compute the unique prefix for the last string in sorted array */ j = 0; String sec_last = a[size-2] ; String last = a[size-1]; while (j < Math.Min( sec_last.Length-1, last.Length-1)) { if (sec_last[j] == last[j]) j++; else break; } res[ind] = last.Substring(0, j+1); return res; } /* Driver code */ public static void Main(String[] args) { GFG gfg = new GFG(); String[] input = {\"zebra\", \"dog\", \"duck\", \"dove\"}; String[] output = gfg.uniquePrefix(input); Console.WriteLine( \"The shortest unique prefixes\" + \" in sorted order are :\"); for (int i = 0; i < output.Length; i++) Console.Write( output[i] + \" \"); }} // This code is contributed by Princi Singh",
"e": 35637,
"s": 33194,
"text": null
},
{
"code": null,
"e": 35646,
"s": 35637,
"text": "Output: "
},
{
"code": null,
"e": 35711,
"s": 35646,
"text": "The shortest unique prefixes in sorted order are :\ndog dov du z "
},
{
"code": null,
"e": 36026,
"s": 35711,
"text": "Another Python approach:If we want to output the prefixes as the order of strings in the input array, we can store the string and its corresponding index in the hashmap. While adding the prefix to the result array, we can get the index of the corresponding string from the hashmap and add the prefix to that index."
},
{
"code": null,
"e": 36034,
"s": 36026,
"text": "Python3"
},
{
"code": "#Python program to print shortest unique prefix for every word in a list a=['dogs','dove','duck','zebra']r=[]j=0while(j<min(len(a[0]),len(a[1]))): if(a[0][j]==a[1][j]): j+=1 else: break i=0r.append(a[0][0:j+1])x=a[1][0:j+1] for i in range(1,len(a)-1): j=0 while(j<min(len(a[i]),len(a[i+1]))): if a[i][j]==a[i+1][j]: j+=1 else: break y=a[i][0:j+1] if(len(x)>len(y)): r.append(x) else: r.append(y) x=a[i+1][0:j+1] j=0l=a[len(a)-2]k=a[len(a)-1] while(j<min(len(l),len(k))): if ( l[j]==k[j]): j+=1 else: break r.append(k[0:j+1])print(\"The shortest unique prefixes are :\")for i in range(0,len(r)): print(r[i],end=' ') #This code is contributed by Saahith Reddy",
"e": 36815,
"s": 36034,
"text": null
},
{
"code": null,
"e": 36824,
"s": 36815,
"text": "Output: "
},
{
"code": null,
"e": 36872,
"s": 36824,
"text": "The shortest unique prefixes are :\ndog dov du z"
},
{
"code": null,
"e": 37367,
"s": 36872,
"text": "For a more efficient solution, we can use Trie as discussed in this post.This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37380,
"s": 37367,
"text": "princi singh"
},
{
"code": null,
"e": 37392,
"s": 37380,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37406,
"s": 37392,
"text": "reddysaahithm"
},
{
"code": null,
"e": 37421,
"s": 37406,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37434,
"s": 37421,
"text": "simmytarika5"
},
{
"code": null,
"e": 37442,
"s": 37434,
"text": "Sorting"
},
{
"code": null,
"e": 37450,
"s": 37442,
"text": "Strings"
},
{
"code": null,
"e": 37458,
"s": 37450,
"text": "Strings"
},
{
"code": null,
"e": 37466,
"s": 37458,
"text": "Sorting"
},
{
"code": null,
"e": 37564,
"s": 37466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37595,
"s": 37564,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 37621,
"s": 37595,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 37653,
"s": 37621,
"text": "Stability in sorting algorithms"
},
{
"code": null,
"e": 37678,
"s": 37653,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 37694,
"s": 37678,
"text": "Sorting in Java"
},
{
"code": null,
"e": 37740,
"s": 37694,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 37765,
"s": 37740,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37825,
"s": 37765,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37840,
"s": 37825,
"text": "C++ Data Types"
}
] |
N Queen Problem | Backtracking-3 - GeeksforGeeks | 12 May, 2022
We have discussed Knight’s tour and Rat in a Maze problems in Set 1 and Set 2 respectively. Let us discuss N Queen as another example problem that can be solved using Backtracking. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem.
The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the output matrix for above 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
Naive Algorithm Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints.
while there are untried configurations
{
generate the next configuration
if queens don't attack in this configuration then
{
print this configuration;
}
}
Backtracking Algorithm The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.
1) Start in the leftmost column
2) If all queens are placed
return true
3) Try all rows in the current column.
Do following for every tried row.
a) If the queen can be placed safely in this row
then mark this [row, column] as part of the
solution and recursively check if placing
queen here leads to a solution.
b) If placing the queen in [row, column] leads to
a solution then return true.
c) If placing queen doesn't lead to a solution then
unmark this [row, column] (Backtrack) and go to
step (a) to try other rows.
4) If all rows have been tried and nothing worked,
return false to trigger backtracking.
Implementation of Backtracking solution
C++
C
Java
Python3
C#
Javascript
/* C++ program to solve N Queen Problem using backtracking */ #include <bits/stdc++.h>#define N 4using namespace std; /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << " " << board[i][j] << " "; printf("\n"); }} /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout << "Solution does not exist"; return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
/* C program to solve N Queen Problem using backtracking */#define N 4#include <stdbool.h>#include <stdio.h> /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("\n"); }} /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { printf("Solution does not exist"); return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
/* Java program to solve N Queen Problem using backtracking */public class NQueenProblem { final int N = 4; /* A utility function to print solution */ void printSolution(int board[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + board[i][j] + " "); System.out.println(); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placeed in columns from 0 to col -1. So we need to check only left side for attacking queens */ boolean isSafe(int board[][], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ boolean solveNQUtil(int board[][], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveNQ() { int board[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { System.out.print("Solution does not exist"); return false; } printSolution(board); return true; } // driver program to test above function public static void main(String args[]) { NQueenProblem Queen = new NQueenProblem(); Queen.solveNQ(); }}// This code is contributed by Abhishek Shankhadhar
# Python3 program to solve N Queen# Problem using backtrackingglobal NN = 4 def printSolution(board): for i in range(N): for j in range(N): print (board[i][j], end = " ") print() # A utility function to check if a queen can# be placed on board[row][col]. Note that this# function is called when "col" queens are# already placed in columns from 0 to col -1.# So we need to check only left side for# attacking queensdef isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): # base case: If all queens are placed # then return true if col >= N: return True # Consider this column and try placing # this queen in all rows one by one for i in range(N): if isSafe(board, i, col): # Place this queen in board[i][col] board[i][col] = 1 # recur to place rest of the queens if solveNQUtil(board, col + 1) == True: return True # If placing queen in board[i][col # doesn't lead to a solution, then # queen from board[i][col] board[i][col] = 0 # if the queen can not be placed in any row in # this column col then return false return False # This function solves the N Queen problem using# Backtracking. It mainly uses solveNQUtil() to# solve the problem. It returns false if queens# cannot be placed, otherwise return true and# placement of queens in the form of 1s.# note that there may be more than one# solutions, this function prints one of the# feasible solutions.def solveNQ(): board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solveNQUtil(board, 0) == False: print ("Solution does not exist") return False printSolution(board) return True # Driver CodesolveNQ() # This code is contributed by Divyanshu Mehta
// C# program to solve N Queen Problem// using backtrackingusing System; class GFG{ readonly int N = 4; /* A utility function to print solution */ void printSolution(int [,]board) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(" " + board[i, j] + " "); Console.WriteLine(); } } /* A utility function to check if a queen can be placed on board[row,col]. Note that this function is called when "col" queens are already placeed in columns from 0 to col -1. So we need to check only left side for attacking queens */ bool isSafe(int [,]board, int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row,i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i,j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i, j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int [,]board, int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i,col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i,col] */ board[i, col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i,col] doesn't lead to a solution then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int [,]board = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { Console.Write("Solution does not exist"); return false; } printSolution(board); return true; } // Driver Code public static void Main(String []args) { GFG Queen = new GFG(); Queen.solveNQ(); }} // This code is contributed by Princi Singh
<script>// JavaScript program to solve N Queen// Problem using backtrackingconst N = 4 function printSolution(board){ for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) { document.write(board[i][j], " ") } document.write("</br>") }} // A utility function to check if a queen can// be placed on board[row][col]. Note that this// function is called when "col" queens are// already placed in columns from 0 to col -1.// So we need to check only left side for// attacking queensfunction isSafe(board, row, col){ // Check this row on left side for(let i = 0; i < col; i++){ if(board[row][i] == 1) return false } // Check upper diagonal on left side for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false // Check lower diagonal on left side for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false return true} function solveNQUtil(board, col){ // base case: If all queens are placed // then return true if(col >= N) return true // Consider this column and try placing // this queen in all rows one by one for(let i=0;i<N;i++){ if(isSafe(board, i, col)==true){ // Place this queen in board[i][col] board[i][col] = 1 // recur to place rest of the queens if(solveNQUtil(board, col + 1) == true) return true // If placing queen in board[i][col // doesn't lead to a solution, then // queen from board[i][col] board[i][col] = 0 } } // if the queen can not be placed in any row in // this column col then return false return false} // This function solves the N Queen problem using// Backtracking. It mainly uses solveNQUtil() to// solve the problem. It returns false if queens// cannot be placed, otherwise return true and// placement of queens in the form of 1s.// note that there may be more than one// solutions, this function prints one of the// feasible solutions.function solveNQ(){ let board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if(solveNQUtil(board, 0) == false){ document.write("Solution does not exist") return false } printSolution(board) return true} // Driver CodesolveNQ() // This code is contributed by shinjanpatra </script>
Output: The 1 values indicate placements of queens
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Optimization in is_safe() function The idea is not to check every element in right and left diagonal instead use property of diagonals: 1.The sum of i and j is constant and unique for each right diagonal where i is the row of element and j is the column of element. 2.The difference of i and j is constant and unique for each left diagonal where i and j are row and column of element respectively.Implementation of Backtracking solution(with optimization)
C++
C
Java
Python3
C#
Javascript
/* C++ program to solve N Queen Problem using backtracking */#include<bits/stdc++.h>using namespace std;#define N 4/* ld is an array where its indices indicate row-col+N-1 (N-1) is for shifting the difference to store negative indices */int ld[30] = { 0 };/* rd is an array where its indices indicate row+col and used to check whether a queen can be placed on right diagonal or not*/int rd[30] = { 0 };/*column array where its indices indicates column and used to check whether a queen can be placed in that row or not*/int cl[30] = { 0 };/* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<" "<< board[i][j]<<" "; cout<<endl; }} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout<<"Solution does not exist"; return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
/* C program to solve N Queen Problem usingbacktracking */#define N 4#include <stdbool.h>#include <stdio.h> /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("\n"); }} /* A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when "col" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve NQueen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { printf("Solution does not exist"); return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
/* Java program to solve N Queen Problemusing backtracking */import java.util.*; class GFG{static int N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */static int []ld = new int[30]; /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/static int []rd = new int[30]; /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/static int []cl = new int[30]; /* A utility function to print solution */static void printSolution(int board[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.printf(" %d ", board[i][j]); System.out.printf("\n"); }} /* A recursive utility function to solve NQueen problem */static boolean solveNQUtil(int board[][], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/static boolean solveNQ(){ int board[][] = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { System.out.printf("Solution does not exist"); return false; } printSolution(board); return true;} // Driver Codepublic static void main(String[] args){ solveNQ();}} // This code is contributed by Princi Singh
""" Python3 program to solve N Queen Problem usingbacktracking """N = 4 """ ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices """ld = [0] * 30 """ rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not"""rd = [0] * 30 """column array where its indices indicates column andused to check whether a queen can be placed in that row or not"""cl = [0] * 30 """ A utility function to print solution """def printSolution(board): for i in range(N): for j in range(N): print(board[i][j], end = " ") print() """ A recursive utility function to solve NQueen problem """def solveNQUtil(board, col): """ base case: If all queens are placed then return True """ if (col >= N): return True """ Consider this column and try placing this queen in all rows one by one """ for i in range(N): """ Check if the queen can be placed on board[i][col] """ """ A check if a queen can be placed on board[row][col]. We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively""" if ((ld[i - col + N - 1] != 1 and rd[i + col] != 1) and cl[i] != 1): """ Place this queen in board[i][col] """ board[i][col] = 1 ld[i - col + N - 1] = rd[i + col] = cl[i] = 1 """ recur to place rest of the queens """ if (solveNQUtil(board, col + 1)): return True """ If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] """ board[i][col] = 0 # BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0 """ If the queen cannot be placed in any row in this column col then return False """ return False """ This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns False if queenscannot be placed, otherwise, return True andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions."""def solveNQ(): board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] if (solveNQUtil(board, 0) == False): printf("Solution does not exist") return False printSolution(board) return True # Driver CodesolveNQ() # This code is contributed by SHUBHAMSINGH10
/* C# program to solve N Queen Problemusing backtracking */using System; class GFG{static int N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */static int []ld = new int[30]; /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/static int []rd = new int[30]; /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/static int []cl = new int[30]; /* A utility function to print solution */static void printSolution(int [,]board){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(" {0} ", board[i, j]); Console.Write("\n"); }} /* A recursive utility function to solve NQueen problem */static bool solveNQUtil(int [,]board, int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i,col] */ /* A check if a queen can be placed on board[row,col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i,col] */ board[i, col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i,col] doesn't lead to a solution, then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/static bool solveNQ(){ int [,]board = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { Console.Write("Solution does not exist"); return false; } printSolution(board); return true;} // Driver Codepublic static void Main(String[] args){ solveNQ();}} // This code is contributed by Rajput-Ji
<script> // JavaScript code to implement the approach let N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */let ld = new Array(30); /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/let rd = new Array(30); /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/let cl = new Array(30); /* A utility function to prlet solution */function prletSolution( board){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(board[i][j] + " "); document.write("<br/>"); }} /* A recursive utility function to solve NQueen problem */function solveNQUtil(board, col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (let i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprlets placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prlets one of thefeasible solutions.*/function solveNQ(){ let board = [[ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ]]; if (solveNQUtil(board, 0) == false) { document.write("Solution does not exist"); return false; } prletSolution(board); return true;} // Driver code solveNQ(); // This code is contributed by sanjoy_62.</script>
Output: The 1 values indicate placements of queens
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Printing all solutions in N-Queen Problem
YouTubeGeeksforGeeks507K subscribersN Queen Problem | Backtracking | 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 / 5:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0DeznFqrgAI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Sources: http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf http://en.literateprograms.org/Eight_queens_puzzle_%28C%29 http://en.wikipedia.org/wiki/Eight_queens_puzzlePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AniruddhaPandey
Parimal7
harminder3027
SHUBHAMSINGH10
princi singh
Rajput-Ji
clintra
as5853535
meena13091999
shinjanpatra
adityakumar129
sanjoy_62
Accolite
Amazon
Amdocs
chessboard-problems
MAQ Software
Twitter
Visa
Backtracking
Accolite
Amazon
Visa
MAQ Software
Amdocs
Twitter
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Backtracking | Introduction
Print all paths from a given source to a destination
Printing all solutions in N-Queen Problem
Backtracking to find all subsets
Combinational Sum
Print all permutations of a string in Java
8 queen problem
Travelling Salesman Problem implementation using BackTracking
Count all possible paths between two vertices | [
{
"code": null,
"e": 35839,
"s": 35811,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 36194,
"s": 35839,
"text": "We have discussed Knight’s tour and Rat in a Maze problems in Set 1 and Set 2 respectively. Let us discuss N Queen as another example problem that can be solved using Backtracking. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. "
},
{
"code": null,
"e": 36359,
"s": 36194,
"text": "The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the output matrix for above 4 queen solution. "
},
{
"code": null,
"e": 36483,
"s": 36359,
"text": " { 0, 1, 0, 0}\n { 0, 0, 0, 1}\n { 1, 0, 0, 0}\n { 0, 0, 1, 0}"
},
{
"code": null,
"e": 36622,
"s": 36485,
"text": "Naive Algorithm Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints. "
},
{
"code": null,
"e": 36795,
"s": 36622,
"text": "while there are untried configurations\n{\n generate the next configuration\n if queens don't attack in this configuration then\n {\n print this configuration;\n }\n}"
},
{
"code": null,
"e": 37201,
"s": 36795,
"text": "Backtracking Algorithm The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false. "
},
{
"code": null,
"e": 37877,
"s": 37201,
"text": "1) Start in the leftmost column\n2) If all queens are placed\n return true\n3) Try all rows in the current column. \n Do following for every tried row.\n a) If the queen can be placed safely in this row \n then mark this [row, column] as part of the \n solution and recursively check if placing\n queen here leads to a solution.\n b) If placing the queen in [row, column] leads to\n a solution then return true.\n c) If placing queen doesn't lead to a solution then\n unmark this [row, column] (Backtrack) and go to \n step (a) to try other rows.\n4) If all rows have been tried and nothing worked,\n return false to trigger backtracking."
},
{
"code": null,
"e": 37919,
"s": 37877,
"text": "Implementation of Backtracking solution "
},
{
"code": null,
"e": 37923,
"s": 37919,
"text": "C++"
},
{
"code": null,
"e": 37925,
"s": 37923,
"text": "C"
},
{
"code": null,
"e": 37930,
"s": 37925,
"text": "Java"
},
{
"code": null,
"e": 37938,
"s": 37930,
"text": "Python3"
},
{
"code": null,
"e": 37941,
"s": 37938,
"text": "C#"
},
{
"code": null,
"e": 37952,
"s": 37941,
"text": "Javascript"
},
{
"code": "/* C++ program to solve N Queen Problem using backtracking */ #include <bits/stdc++.h>#define N 4using namespace std; /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << \" \" << board[i][j] << \" \"; printf(\"\\n\"); }} /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when \"col\" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout << \"Solution does not exist\"; return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 40808,
"s": 37952,
"text": null
},
{
"code": "/* C program to solve N Queen Problem using backtracking */#define N 4#include <stdbool.h>#include <stdio.h> /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\" %d \", board[i][j]); printf(\"\\n\"); }} /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when \"col\" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { printf(\"Solution does not exist\"); return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 43649,
"s": 40808,
"text": null
},
{
"code": "/* Java program to solve N Queen Problem using backtracking */public class NQueenProblem { final int N = 4; /* A utility function to print solution */ void printSolution(int board[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(\" \" + board[i][j] + \" \"); System.out.println(); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when \"col\" queens are already placeed in columns from 0 to col -1. So we need to check only left side for attacking queens */ boolean isSafe(int board[][], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ boolean solveNQUtil(int board[][], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveNQ() { int board[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { System.out.print(\"Solution does not exist\"); return false; } printSolution(board); return true; } // driver program to test above function public static void main(String args[]) { NQueenProblem Queen = new NQueenProblem(); Queen.solveNQ(); }}// This code is contributed by Abhishek Shankhadhar",
"e": 46981,
"s": 43649,
"text": null
},
{
"code": "# Python3 program to solve N Queen# Problem using backtrackingglobal NN = 4 def printSolution(board): for i in range(N): for j in range(N): print (board[i][j], end = \" \") print() # A utility function to check if a queen can# be placed on board[row][col]. Note that this# function is called when \"col\" queens are# already placed in columns from 0 to col -1.# So we need to check only left side for# attacking queensdef isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): # base case: If all queens are placed # then return true if col >= N: return True # Consider this column and try placing # this queen in all rows one by one for i in range(N): if isSafe(board, i, col): # Place this queen in board[i][col] board[i][col] = 1 # recur to place rest of the queens if solveNQUtil(board, col + 1) == True: return True # If placing queen in board[i][col # doesn't lead to a solution, then # queen from board[i][col] board[i][col] = 0 # if the queen can not be placed in any row in # this column col then return false return False # This function solves the N Queen problem using# Backtracking. It mainly uses solveNQUtil() to# solve the problem. It returns false if queens# cannot be placed, otherwise return true and# placement of queens in the form of 1s.# note that there may be more than one# solutions, this function prints one of the# feasible solutions.def solveNQ(): board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solveNQUtil(board, 0) == False: print (\"Solution does not exist\") return False printSolution(board) return True # Driver CodesolveNQ() # This code is contributed by Divyanshu Mehta",
"e": 49334,
"s": 46981,
"text": null
},
{
"code": "// C# program to solve N Queen Problem// using backtrackingusing System; class GFG{ readonly int N = 4; /* A utility function to print solution */ void printSolution(int [,]board) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(\" \" + board[i, j] + \" \"); Console.WriteLine(); } } /* A utility function to check if a queen can be placed on board[row,col]. Note that this function is called when \"col\" queens are already placeed in columns from 0 to col -1. So we need to check only left side for attacking queens */ bool isSafe(int [,]board, int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row,i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i,j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i, j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int [,]board, int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i,col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i,col] */ board[i, col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1) == true) return true; /* If placing queen in board[i,col] doesn't lead to a solution then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK } } /* If the queen can not be placed in any row in this column col, then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil () to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int [,]board = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { Console.Write(\"Solution does not exist\"); return false; } printSolution(board); return true; } // Driver Code public static void Main(String []args) { GFG Queen = new GFG(); Queen.solveNQ(); }} // This code is contributed by Princi Singh",
"e": 52587,
"s": 49334,
"text": null
},
{
"code": "<script>// JavaScript program to solve N Queen// Problem using backtrackingconst N = 4 function printSolution(board){ for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) { document.write(board[i][j], \" \") } document.write(\"</br>\") }} // A utility function to check if a queen can// be placed on board[row][col]. Note that this// function is called when \"col\" queens are// already placed in columns from 0 to col -1.// So we need to check only left side for// attacking queensfunction isSafe(board, row, col){ // Check this row on left side for(let i = 0; i < col; i++){ if(board[row][i] == 1) return false } // Check upper diagonal on left side for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false // Check lower diagonal on left side for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false return true} function solveNQUtil(board, col){ // base case: If all queens are placed // then return true if(col >= N) return true // Consider this column and try placing // this queen in all rows one by one for(let i=0;i<N;i++){ if(isSafe(board, i, col)==true){ // Place this queen in board[i][col] board[i][col] = 1 // recur to place rest of the queens if(solveNQUtil(board, col + 1) == true) return true // If placing queen in board[i][col // doesn't lead to a solution, then // queen from board[i][col] board[i][col] = 0 } } // if the queen can not be placed in any row in // this column col then return false return false} // This function solves the N Queen problem using// Backtracking. It mainly uses solveNQUtil() to// solve the problem. It returns false if queens// cannot be placed, otherwise return true and// placement of queens in the form of 1s.// note that there may be more than one// solutions, this function prints one of the// feasible solutions.function solveNQ(){ let board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if(solveNQUtil(board, 0) == false){ document.write(\"Solution does not exist\") return false } printSolution(board) return true} // Driver CodesolveNQ() // This code is contributed by shinjanpatra </script>",
"e": 55073,
"s": 52587,
"text": null
},
{
"code": null,
"e": 55126,
"s": 55073,
"text": "Output: The 1 values indicate placements of queens "
},
{
"code": null,
"e": 55178,
"s": 55126,
"text": " 0 0 1 0 \n 1 0 0 0 \n 0 0 0 1 \n 0 1 0 0 "
},
{
"code": null,
"e": 55636,
"s": 55178,
"text": "Optimization in is_safe() function The idea is not to check every element in right and left diagonal instead use property of diagonals: 1.The sum of i and j is constant and unique for each right diagonal where i is the row of element and j is the column of element. 2.The difference of i and j is constant and unique for each left diagonal where i and j are row and column of element respectively.Implementation of Backtracking solution(with optimization) "
},
{
"code": null,
"e": 55640,
"s": 55636,
"text": "C++"
},
{
"code": null,
"e": 55642,
"s": 55640,
"text": "C"
},
{
"code": null,
"e": 55647,
"s": 55642,
"text": "Java"
},
{
"code": null,
"e": 55655,
"s": 55647,
"text": "Python3"
},
{
"code": null,
"e": 55658,
"s": 55655,
"text": "C#"
},
{
"code": null,
"e": 55669,
"s": 55658,
"text": "Javascript"
},
{
"code": "/* C++ program to solve N Queen Problem using backtracking */#include<bits/stdc++.h>using namespace std;#define N 4/* ld is an array where its indices indicate row-col+N-1 (N-1) is for shifting the difference to store negative indices */int ld[30] = { 0 };/* rd is an array where its indices indicate row+col and used to check whether a queen can be placed on right diagonal or not*/int rd[30] = { 0 };/*column array where its indices indicates column and used to check whether a queen can be placed in that row or not*/int cl[30] = { 0 };/* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<\" \"<< board[i][j]<<\" \"; cout<<endl; }} /* A recursive utility function to solve N Queen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout<<\"Solution does not exist\"; return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 58585,
"s": 55669,
"text": null
},
{
"code": "/* C program to solve N Queen Problem usingbacktracking */#define N 4#include <stdbool.h>#include <stdio.h> /* A utility function to print solution */void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\" %d \", board[i][j]); printf(\"\\n\"); }} /* A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when \"col\" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens */bool isSafe(int board[N][N], int row, int col){ int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve NQueen problem */bool solveNQUtil(int board[N][N], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/bool solveNQ(){ int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { printf(\"Solution does not exist\"); return false; } printSolution(board); return true;} // driver program to test above functionint main(){ solveNQ(); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 61369,
"s": 58585,
"text": null
},
{
"code": "/* Java program to solve N Queen Problemusing backtracking */import java.util.*; class GFG{static int N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */static int []ld = new int[30]; /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/static int []rd = new int[30]; /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/static int []cl = new int[30]; /* A utility function to print solution */static void printSolution(int board[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.printf(\" %d \", board[i][j]); System.out.printf(\"\\n\"); }} /* A recursive utility function to solve NQueen problem */static boolean solveNQUtil(int board[][], int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/static boolean solveNQ(){ int board[][] = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { System.out.printf(\"Solution does not exist\"); return false; } printSolution(board); return true;} // Driver Codepublic static void main(String[] args){ solveNQ();}} // This code is contributed by Princi Singh",
"e": 64330,
"s": 61369,
"text": null
},
{
"code": "\"\"\" Python3 program to solve N Queen Problem usingbacktracking \"\"\"N = 4 \"\"\" ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices \"\"\"ld = [0] * 30 \"\"\" rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not\"\"\"rd = [0] * 30 \"\"\"column array where its indices indicates column andused to check whether a queen can be placed in that row or not\"\"\"cl = [0] * 30 \"\"\" A utility function to print solution \"\"\"def printSolution(board): for i in range(N): for j in range(N): print(board[i][j], end = \" \") print() \"\"\" A recursive utility function to solve NQueen problem \"\"\"def solveNQUtil(board, col): \"\"\" base case: If all queens are placed then return True \"\"\" if (col >= N): return True \"\"\" Consider this column and try placing this queen in all rows one by one \"\"\" for i in range(N): \"\"\" Check if the queen can be placed on board[i][col] \"\"\" \"\"\" A check if a queen can be placed on board[row][col]. We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively\"\"\" if ((ld[i - col + N - 1] != 1 and rd[i + col] != 1) and cl[i] != 1): \"\"\" Place this queen in board[i][col] \"\"\" board[i][col] = 1 ld[i - col + N - 1] = rd[i + col] = cl[i] = 1 \"\"\" recur to place rest of the queens \"\"\" if (solveNQUtil(board, col + 1)): return True \"\"\" If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] \"\"\" board[i][col] = 0 # BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0 \"\"\" If the queen cannot be placed in any row in this column col then return False \"\"\" return False \"\"\" This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns False if queenscannot be placed, otherwise, return True andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.\"\"\"def solveNQ(): board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] if (solveNQUtil(board, 0) == False): printf(\"Solution does not exist\") return False printSolution(board) return True # Driver CodesolveNQ() # This code is contributed by SHUBHAMSINGH10",
"e": 67028,
"s": 64330,
"text": null
},
{
"code": "/* C# program to solve N Queen Problemusing backtracking */using System; class GFG{static int N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */static int []ld = new int[30]; /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/static int []rd = new int[30]; /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/static int []cl = new int[30]; /* A utility function to print solution */static void printSolution(int [,]board){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(\" {0} \", board[i, j]); Console.Write(\"\\n\"); }} /* A recursive utility function to solve NQueen problem */static bool solveNQUtil(int [,]board, int col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i,col] */ /* A check if a queen can be placed on board[row,col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i,col] */ board[i, col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i,col] doesn't lead to a solution, then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/static bool solveNQ(){ int [,]board = {{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }}; if (solveNQUtil(board, 0) == false) { Console.Write(\"Solution does not exist\"); return false; } printSolution(board); return true;} // Driver Codepublic static void Main(String[] args){ solveNQ();}} // This code is contributed by Rajput-Ji",
"e": 69955,
"s": 67028,
"text": null
},
{
"code": "<script> // JavaScript code to implement the approach let N = 4; /* ld is an array where its indices indicate row-col+N-1(N-1) is for shifting the difference to store negativeindices */let ld = new Array(30); /* rd is an array where its indices indicate row+coland used to check whether a queen can be placed onright diagonal or not*/let rd = new Array(30); /*column array where its indices indicates column andused to check whether a queen can be placed in that row or not*/let cl = new Array(30); /* A utility function to prlet solution */function prletSolution( board){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(board[i][j] + \" \"); document.write(\"<br/>\"); }} /* A recursive utility function to solve NQueen problem */function solveNQUtil(board, col){ /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (let i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false;}/* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise, return true andprlets placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prlets one of thefeasible solutions.*/function solveNQ(){ let board = [[ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ]]; if (solveNQUtil(board, 0) == false) { document.write(\"Solution does not exist\"); return false; } prletSolution(board); return true;} // Driver code solveNQ(); // This code is contributed by sanjoy_62.</script>",
"e": 72787,
"s": 69955,
"text": null
},
{
"code": null,
"e": 72840,
"s": 72787,
"text": "Output: The 1 values indicate placements of queens "
},
{
"code": null,
"e": 72892,
"s": 72840,
"text": " 0 0 1 0 \n 1 0 0 0 \n 0 0 0 1 \n 0 1 0 0 "
},
{
"code": null,
"e": 72935,
"s": 72892,
"text": "Printing all solutions in N-Queen Problem "
},
{
"code": null,
"e": 73764,
"s": 72935,
"text": "YouTubeGeeksforGeeks507K subscribersN Queen Problem | Backtracking | 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 / 5:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0DeznFqrgAI\" 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": 74081,
"s": 73764,
"text": "Sources: http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf http://en.literateprograms.org/Eight_queens_puzzle_%28C%29 http://en.wikipedia.org/wiki/Eight_queens_puzzlePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 74097,
"s": 74081,
"text": "AniruddhaPandey"
},
{
"code": null,
"e": 74106,
"s": 74097,
"text": "Parimal7"
},
{
"code": null,
"e": 74120,
"s": 74106,
"text": "harminder3027"
},
{
"code": null,
"e": 74135,
"s": 74120,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 74148,
"s": 74135,
"text": "princi singh"
},
{
"code": null,
"e": 74158,
"s": 74148,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 74166,
"s": 74158,
"text": "clintra"
},
{
"code": null,
"e": 74176,
"s": 74166,
"text": "as5853535"
},
{
"code": null,
"e": 74190,
"s": 74176,
"text": "meena13091999"
},
{
"code": null,
"e": 74203,
"s": 74190,
"text": "shinjanpatra"
},
{
"code": null,
"e": 74218,
"s": 74203,
"text": "adityakumar129"
},
{
"code": null,
"e": 74228,
"s": 74218,
"text": "sanjoy_62"
},
{
"code": null,
"e": 74237,
"s": 74228,
"text": "Accolite"
},
{
"code": null,
"e": 74244,
"s": 74237,
"text": "Amazon"
},
{
"code": null,
"e": 74251,
"s": 74244,
"text": "Amdocs"
},
{
"code": null,
"e": 74271,
"s": 74251,
"text": "chessboard-problems"
},
{
"code": null,
"e": 74284,
"s": 74271,
"text": "MAQ Software"
},
{
"code": null,
"e": 74292,
"s": 74284,
"text": "Twitter"
},
{
"code": null,
"e": 74297,
"s": 74292,
"text": "Visa"
},
{
"code": null,
"e": 74310,
"s": 74297,
"text": "Backtracking"
},
{
"code": null,
"e": 74319,
"s": 74310,
"text": "Accolite"
},
{
"code": null,
"e": 74326,
"s": 74319,
"text": "Amazon"
},
{
"code": null,
"e": 74331,
"s": 74326,
"text": "Visa"
},
{
"code": null,
"e": 74344,
"s": 74331,
"text": "MAQ Software"
},
{
"code": null,
"e": 74351,
"s": 74344,
"text": "Amdocs"
},
{
"code": null,
"e": 74359,
"s": 74351,
"text": "Twitter"
},
{
"code": null,
"e": 74372,
"s": 74359,
"text": "Backtracking"
},
{
"code": null,
"e": 74470,
"s": 74372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 74555,
"s": 74470,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 74583,
"s": 74555,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 74636,
"s": 74583,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 74678,
"s": 74636,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 74711,
"s": 74678,
"text": "Backtracking to find all subsets"
},
{
"code": null,
"e": 74729,
"s": 74711,
"text": "Combinational Sum"
},
{
"code": null,
"e": 74772,
"s": 74729,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 74788,
"s": 74772,
"text": "8 queen problem"
},
{
"code": null,
"e": 74850,
"s": 74788,
"text": "Travelling Salesman Problem implementation using BackTracking"
}
] |
Range Minimum Query (Square Root Decomposition and Sparse Table) - GeeksforGeeks | 24 Aug, 2021
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Example:
Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18};
query[] = [0, 4], [4, 7], [7, 8]
Output: Minimum of [0, 4] is 0
Minimum of [4, 7] is 3
Minimum of [7, 8] is 12
A simple solution is to run a loop from L to R and find the minimum element in the given range. This solution takes O(n) time to query in the worst case.Another approach is to use Segment tree. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree. Segment tree allows updates also in O(Log n) time.
How to optimize query time when there are no update operations and there are many range minimum queries?Below are different methods.
Method 1 (Simple Solution) A Simple Solution is to create a 2D array lookup[][] where an entry lookup[i][j] stores the minimum value in range arr[i..j]. The minimum of a given range can now be calculated in O(1) time.
C++
Java
Python3
C#
Javascript
// C++ program to do range// minimum query in O(1) time with// O(n*n) extra space and O(n*n)// preprocessing time.#include <bits/stdc++.h>using namespace std;#define MAX 500 // lookup[i][j] is going to store// index of minimum value in// arr[i..j]int lookup[MAX][MAX]; // Structure to represent a query rangestruct Query { int L, R;}; // Fills lookup array lookup[n][n]// for all possible values// of query rangesvoid preprocess(int arr[], int n){ // Initialize lookup[][] for the // intervals with length 1 for (int i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum // of arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; }} // Prints minimum of given m// query ranges in arr[0..n-1]void RMQ(int arr[], int n, Query q[], int m){ // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range cout << "Minimum of [" << L << ", " << R << "] is " << arr[lookup[L][R]] << endl; }} // Driver codeint main(){ int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 4 }, { 4, 7 }, { 7, 8 } }; int m = sizeof(q) / sizeof(q[0]); RMQ(a, n, q, m); return 0;}
// Java program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing time.import java.util.*; class GFG { static int MAX = 500; // lookup[i][j] is going to store index of // minimum value in arr[i..j] static int[][] lookup = new int[MAX][MAX]; // Structure to represent a query range static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[n][n] for // all possible values of query ranges static void preprocess(int arr[], int n) { // Initialize lookup[][] for // the intervals with length 1 for (int i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; } } // Prints minimum of given m query // ranges in arr[0..n-1] static void RMQ(int arr[], int n, Query q[], int m) { // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range System.out.println("Minimum of [" + L + ", " + R + "] is " + arr[lookup[L][R]]); } } // Driver Code public static void main(String[] args) { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.length; Query q[] = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.length; RMQ(a, n, q, m); }} // This code is contributed by 29AjayKumar
# Python3 program to do range# minimum query in O(1) time with# O(n*n) extra space and O(n*n)# preprocessing time.MAX = 500 # lookup[i][j] is going to store# index of minimum value in# arr[i..j]lookup = [[0 for j in range(MAX)] for i in range(MAX)] # Structure to represent# a query rangeclass Query: def __init__(self, L, R): self.L = L self.R = R # Fills lookup array lookup[n][n]# for all possible values# of query rangesdef preprocess(arr, n): # Initialize lookup[][] for the # intervals with length 1 for i in range(n): lookup[i][i] = i; # Fill rest of the entries in # bottom up manner for i in range(n): for j in range(i + 1, n): # To find minimum of [0,4], # we compare minimum # of arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]): lookup[i][j] = lookup[i][j - 1]; else: lookup[i][j] = j; # Prints minimum of given m# query ranges in arr[0..n-1]def RMQ(arr, n, q, m): # Fill lookup table for # all possible input queries preprocess(arr, n); # One by one compute sum of # all queries for i in range(m): # Left and right boundaries # of current range L = q[i].L R = q[i].R; # Print sum of current query range print("Minimum of [" + str(L) + ", " + str(R) + "] is " + str(arr[lookup[L][R]])) # Driver codeif __name__ == "__main__": a = [7, 2, 3, 0, 5, 10, 3, 12, 18] n = len(a) q = [Query(0, 4), Query(4, 7), Query(7, 8)] m = len(q) RMQ(a, n, q, m); # This code is contributed by Rutvik_56
// C# program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing time.using System; class GFG { static int MAX = 500; // lookup[i][j] is going to store index of // minimum value in arr[i..j] static int[, ] lookup = new int[MAX, MAX]; // Structure to represent a query range public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[n][n] for // all possible values of query ranges static void preprocess(int[] arr, int n) { // Initialize lookup[][] for // the intervals with length 1 for (int i = 0; i < n; i++) lookup[i, i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i, j - 1]] < arr[j]) lookup[i, j] = lookup[i, j - 1]; else lookup[i, j] = j; } } // Prints minimum of given m query // ranges in arr[0..n-1] static void RMQ(int[] arr, int n, Query[] q, int m) { // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range Console.WriteLine("Minimum of [" + L + ", " + R + "] is " + arr[lookup[L, R]]); } } // Driver Code public static void Main(String[] args) { int[] a = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.Length; Query[] q = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.Length; RMQ(a, n, q, m); }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing timelet MAX = 500; // lookup[i][j] is going to store index of// minimum value in arr[i..j]let lookup = new Array(MAX);for(let i = 0; i < MAX; i++){ lookup[i] = new Array(MAX); for(let j = 0; j < MAX; j++) lookup[i][j] = 0;} // Structure to represent a query rangeclass Query{ constructor(L, R) { this.L = L; this.R = R; }} // Fills lookup array lookup[n][n] for // all possible values of query rangesfunction preprocess(arr, n){ // Initialize lookup[][] for // the intervals with length 1 for (let i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; }} // Prints minimum of given m query// ranges in arr[0..n-1]function RMQ(arr,n,q,m){ // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (let i = 0; i < m; i++) { // Left and right boundaries // of current range let L = q[i].L, R = q[i].R; // Print sum of current query range document.write("Minimum of [" + L + ", " + R + "] is " + arr[lookup[L][R]]+"<br>"); }} // Driver Codelet a=[7, 2, 3, 0, 5, 10, 3, 12, 18];let n = a.length;let q = [ new Query(0, 4), new Query(4, 7),new Query(7, 8) ];let m = q.length;RMQ(a, n, q, m); // This code is contributed by avanitrachhadiya2155</script>
Output:
Minimum of [0, 4] is 0
Minimum of [4, 7] is 3
Minimum of [7, 8] is 12
This approach supports queries in O(1), but preprocessing takes O(n2) time. Also, this approach needs O(n2) extra space which may become huge for large input arrays.
Method 2 (Square Root Decomposition) We can use Square Root Decompositions to reduce space required in the above method.Preprocessing: 1) Divide the range [0, n-1] into different blocks of √n each. 2) Compute the minimum of every block of size √n and store the results.Preprocessing takes O(√n * √n) = O(n) time and O(√n) space.
Query: 1) To query a range [L, R], we take a minimum of all blocks that lie in this range. For left and right corner blocks which may partially overlap with the given range, we linearly scan them to find the minimum. The time complexity of the query is O(√n). Note that we have a minimum of the middle block directly accessible and there can be at most O(√n) middle blocks. There can be at most two corner blocks that we may have to scan, so we may have to scan 2*O(√n) elements of corner blocks. Therefore, the overall time complexity is O(√n).Refer to Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction) for details.
Method 3 (Sparse Table Algorithm) The above solution requires only O(√n) space but takes O(√n) time to query. The sparse table method supports query time O(1) with extra space O(n Log n).The idea is to precompute a minimum of all subarrays of size 2j where j varies from 0 to Log n. Like method 1, we make a lookup table. Here lookup[i][j] contains a minimum of range starting from i and of size 2j. For example lookup[0][3] contains a minimum of range [0, 7] (starting with 0 and of size 23)
Preprocessing: How to fill this lookup table? The idea is simple, fill in a bottom-up manner using previously computed values. For example, to find a minimum of range [0, 7], we can use a minimum of the following two. a) Minimum of range [0, 3] b) Minimum of range [4, 7]Based on the above example, below is the formula,
// If arr[lookup[0][2]] <= arr[lookup[4][2]],
// then lookup[0][3] = lookup[0][2]
If arr[lookup[i][j-1]] <= arr[lookup[i+2j-1][j-1]]
lookup[i][j] = lookup[i][j-1]
// If arr[lookup[0][2]] > arr[lookup[4][2]],
// then lookup[0][3] = lookup[4][2]
Else
lookup[i][j] = lookup[i+2j-1][j-1]
Query: For any arbitrary range [l, R], we need to use ranges that are in powers of 2. The idea is to use the closest power of 2. We always need to do at most one comparison (compare a minimum of two ranges which are powers of 2). One range starts with L and ends with “L + closest-power-of-2”. The other range ends at R and starts with “R – same-closest-power-of-2 + 1”. For example, if the given range is (2, 10), we compare a minimum of two ranges (2, 9) and (3, 10). Based on the above example, below is the formula,
// For (2,10), j = floor(Log2(10-2+1)) = 3
j = floor(Log(R-L+1))
// If arr[lookup[0][3]] <= arr[lookup[3][3]],
// then RMQ(2,10) = lookup[0][3]
If arr[lookup[L][j]] <= arr[lookup[R-(int)pow(2,j)+1][j]]
RMQ(L, R) = lookup[L][j]
// If arr[lookup[0][3]] > arr[lookup[3][3]],
// then RMQ(2,10) = lookup[3][3]
Else
RMQ(L, R) = lookup[R-(int)pow(2,j)+1][j]
Since we do only one comparison, the time complexity of the query is O(1).
Below is the implementation of the above idea.
C++
Java
Python3
C#
// C++ program to do range minimum// query in O(1) time with// O(n Log n) extra space and// O(n Log n) preprocessing time#include <bits/stdc++.h>using namespace std;#define MAX 500 // lookup[i][j] is going to// store index of minimum value in// arr[i..j]. Ideally lookup// table size should not be fixed// and should be determined using// n Log n. It is kept// constant to keep code simple.int lookup[MAX][MAX]; // Structure to represent a query rangestruct Query { int L, R;}; // Fills lookup array// lookup[][] in bottom up manner.void preprocess(int arr[], int n){ // Initialize M for the // intervals with length 1 for (int i = 0; i < n; i++) lookup[i][0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size // 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we // compare arr[lookup[0][3]] // and arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))][j - 1]]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } }} // Returns minimum of arr[L..R]int query(int arr[], int L, int R){ // For [2,10], j = 3 int j = (int)log2(R - L + 1); // For [2,10], we compare arr[lookup[0][3]] and // arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]) return arr[lookup[L][j]]; else return arr[lookup[R - (1 << j) + 1][j]];} // Prints minimum of given// m query ranges in arr[0..n-1]void RMQ(int arr[], int n, Query q[], int m){ // Fills table lookup[n][Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range cout << "Minimum of [" << L << ", " << R << "] is " << query(arr, L, R) << endl; }} // Driver codeint main(){ int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 4 }, { 4, 7 }, { 7, 8 } }; int m = sizeof(q) / sizeof(q[0]); RMQ(a, n, q, m); return 0;}
// Java program to do range minimum query// in O(1) time with O(n Log n) extra space// and O(n Log n) preprocessing timeimport java.util.*; class GFG { static int MAX = 500; // lookup[i][j] is going to store index // of minimum value in arr[i..j]. // Ideally lookup table size should not be fixed // and should be determined using n Log n. // It is kept constant to keep code simple. static int[][] lookup = new int[MAX][MAX]; // Structure to represent a query range static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[][] // in bottom up manner. static void preprocess(int arr[], int n) { // Initialize M for the intervals // with length 1 for (int i = 0; i < n; i++) lookup[i][0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we compare // arr[lookup[0][3]] // and arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))] [j - 1]]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } } } // Returns minimum of arr[L..R] static int query(int arr[], int L, int R) { // For [2,10], j = 3 int j = (int)Math.log(R - L + 1); // For [2,10], we compare // arr[lookup[0][3]] // and arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]) return arr[lookup[L][j]]; else return arr[lookup[R - (1 << j) + 1][j]]; } // Prints minimum of given m // query ranges in arr[0..n-1] static void RMQ(int arr[], int n, Query q[], int m) { // Fills table lookup[n][Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range System.out.println("Minimum of [" + L + ", " + R + "] is " + query(arr, L, R)); } } // Driver Code public static void main(String[] args) { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.length; Query q[] = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.length; RMQ(a, n, q, m); }} // This code is contributed by Rajput-Ji
# Python3 program to do range minimum query# in O(1) time with O(n Log n) extra space# and O(n Log n) preprocessing timefrom math import log2 MAX = 500 # lookup[i][j] is going to store index of# minimum value in arr[i..j].# Ideally lookup table size should# not be fixed and should be determined# using n Log n. It is kept constant# to keep code simple.lookup = [[0 for i in range(500)] for j in range(500)] # Structure to represent a query range class Query: def __init__(self, l, r): self.L = l self.R = r # Fills lookup array lookup[][]# in bottom up manner. def preprocess(arr: list, n: int): global lookup # Initialize M for the # intervals with length 1 for i in range(n): lookup[i][0] = i # Compute values from # smaller to bigger intervals j = 1 while (1 << j) <= n: # Compute minimum value for # all intervals with size 2^j i = 0 while i + (1 << j) - 1 < n: # For arr[2][10], we compare # arr[lookup[0][3]] and # arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))][j - 1]]): lookup[i][j] = lookup[i][j - 1] else: lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1] i += 1 j += 1 # Returns minimum of arr[L..R] def query(arr: list, L: int, R: int) -> int: global lookup # For [2,10], j = 3 j = int(log2(R - L + 1)) # For [2,10], we compare # arr[lookup[0][3]] and # arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]): return arr[lookup[L][j]] else: return arr[lookup[R - (1 << j) + 1][j]] # Prints minimum of given# m query ranges in arr[0..n-1] def RMQ(arr: list, n: int, q: list, m: int): # Fills table lookup[n][Log n] preprocess(arr, n) # One by one compute sum of all queries for i in range(m): # Left and right boundaries # of current range L = q[i].L R = q[i].R # Print sum of current query range print("Minimum of [%d, %d] is %d" % (L, R, query(arr, L, R))) # Driver Codeif __name__ == "__main__": a = [7, 2, 3, 0, 5, 10, 3, 12, 18] n = len(a) q = [Query(0, 4), Query(4, 7), Query(7, 8)] m = len(q) RMQ(a, n, q, m) # This code is contributed by# sanjeev2552
// C# program to do range minimum query// in O(1) time with O(n Log n) extra space// and O(n Log n) preprocessing timeusing System; class GFG { static int MAX = 500; // lookup[i,j] is going to store index // of minimum value in arr[i..j]. // Ideally lookup table size should not be fixed // and should be determined using n Log n. // It is kept constant to keep code simple. static int[, ] lookup = new int[MAX, MAX]; // Structure to represent a query range public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[,] // in bottom up manner. static void preprocess(int[] arr, int n) { // Initialize M for the intervals // with length 1 for (int i = 0; i < n; i++) lookup[i, 0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2,10], we compare // arr[lookup[0,3]] and arr[lookup[3,3]] if (arr[lookup[i, j - 1]] < arr[lookup[i + (1 << (j - 1)), j - 1]]) lookup[i, j] = lookup[i, j - 1]; else lookup[i, j] = lookup[i + (1 << (j - 1)), j - 1]; } } } // Returns minimum of arr[L..R] static int query(int[] arr, int L, int R) { // For [2,10], j = 3 int j = (int)Math.Log(R - L + 1); // For [2,10], we compare arr[lookup[0,3]] // and arr[lookup[3,3]], if (arr[lookup[L, j]] <= arr[lookup[R - (1 << j) + 1, j]]) return arr[lookup[L, j]]; else return arr[lookup[R - (1 << j) + 1, j]]; } // Prints minimum of given m // query ranges in arr[0..n-1] static void RMQ(int[] arr, int n, Query[] q, int m) { // Fills table lookup[n,Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right // boundaries of current range int L = q[i].L, R = q[i].R; // Print sum of current query range Console.WriteLine("Minimum of [" + L + ", " + R + "] is " + query(arr, L, R)); } } // Driver Code public static void Main(String[] args) { int[] a = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.Length; Query[] q = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.Length; RMQ(a, n, q, m); }} // This code is contributed by Princi Singh
Minimum of [0, 4] is 0
Minimum of [4, 7] is 3
Minimum of [7, 8] is 12
So sparse table method supports query operation in O(1) time with O(n Log n) preprocessing time and O(n Log n) space.This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
costom
29AjayKumar
princiraj1992
Rajput-Ji
princi singh
sanjeev2552
udbhav99
rutvik_56
avanitrachhadiya2155
array-range-queries
Segment-Tree
Advanced Data Structure
Competitive Programming
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Ordered Set and GNU C++ PBDS
Red-Black Tree | Set 2 (Insert)
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming | [
{
"code": null,
"e": 25917,
"s": 25889,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 26144,
"s": 25917,
"text": "We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Example: "
},
{
"code": null,
"e": 26330,
"s": 26144,
"text": "Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18};\n query[] = [0, 4], [4, 7], [7, 8]\n\nOutput: Minimum of [0, 4] is 0\n Minimum of [4, 7] is 3\n Minimum of [7, 8] is 12"
},
{
"code": null,
"e": 26730,
"s": 26330,
"text": "A simple solution is to run a loop from L to R and find the minimum element in the given range. This solution takes O(n) time to query in the worst case.Another approach is to use Segment tree. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree. Segment tree allows updates also in O(Log n) time. "
},
{
"code": null,
"e": 26863,
"s": 26730,
"text": "How to optimize query time when there are no update operations and there are many range minimum queries?Below are different methods."
},
{
"code": null,
"e": 27082,
"s": 26863,
"text": "Method 1 (Simple Solution) A Simple Solution is to create a 2D array lookup[][] where an entry lookup[i][j] stores the minimum value in range arr[i..j]. The minimum of a given range can now be calculated in O(1) time. "
},
{
"code": null,
"e": 27086,
"s": 27082,
"text": "C++"
},
{
"code": null,
"e": 27091,
"s": 27086,
"text": "Java"
},
{
"code": null,
"e": 27099,
"s": 27091,
"text": "Python3"
},
{
"code": null,
"e": 27102,
"s": 27099,
"text": "C#"
},
{
"code": null,
"e": 27113,
"s": 27102,
"text": "Javascript"
},
{
"code": "// C++ program to do range// minimum query in O(1) time with// O(n*n) extra space and O(n*n)// preprocessing time.#include <bits/stdc++.h>using namespace std;#define MAX 500 // lookup[i][j] is going to store// index of minimum value in// arr[i..j]int lookup[MAX][MAX]; // Structure to represent a query rangestruct Query { int L, R;}; // Fills lookup array lookup[n][n]// for all possible values// of query rangesvoid preprocess(int arr[], int n){ // Initialize lookup[][] for the // intervals with length 1 for (int i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum // of arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; }} // Prints minimum of given m// query ranges in arr[0..n-1]void RMQ(int arr[], int n, Query q[], int m){ // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range cout << \"Minimum of [\" << L << \", \" << R << \"] is \" << arr[lookup[L][R]] << endl; }} // Driver codeint main(){ int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 4 }, { 4, 7 }, { 7, 8 } }; int m = sizeof(q) / sizeof(q[0]); RMQ(a, n, q, m); return 0;}",
"e": 28842,
"s": 27113,
"text": null
},
{
"code": "// Java program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing time.import java.util.*; class GFG { static int MAX = 500; // lookup[i][j] is going to store index of // minimum value in arr[i..j] static int[][] lookup = new int[MAX][MAX]; // Structure to represent a query range static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[n][n] for // all possible values of query ranges static void preprocess(int arr[], int n) { // Initialize lookup[][] for // the intervals with length 1 for (int i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; } } // Prints minimum of given m query // ranges in arr[0..n-1] static void RMQ(int arr[], int n, Query q[], int m) { // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range System.out.println(\"Minimum of [\" + L + \", \" + R + \"] is \" + arr[lookup[L][R]]); } } // Driver Code public static void main(String[] args) { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.length; Query q[] = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.length; RMQ(a, n, q, m); }} // This code is contributed by 29AjayKumar",
"e": 31012,
"s": 28842,
"text": null
},
{
"code": "# Python3 program to do range# minimum query in O(1) time with# O(n*n) extra space and O(n*n)# preprocessing time.MAX = 500 # lookup[i][j] is going to store# index of minimum value in# arr[i..j]lookup = [[0 for j in range(MAX)] for i in range(MAX)] # Structure to represent# a query rangeclass Query: def __init__(self, L, R): self.L = L self.R = R # Fills lookup array lookup[n][n]# for all possible values# of query rangesdef preprocess(arr, n): # Initialize lookup[][] for the # intervals with length 1 for i in range(n): lookup[i][i] = i; # Fill rest of the entries in # bottom up manner for i in range(n): for j in range(i + 1, n): # To find minimum of [0,4], # we compare minimum # of arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]): lookup[i][j] = lookup[i][j - 1]; else: lookup[i][j] = j; # Prints minimum of given m# query ranges in arr[0..n-1]def RMQ(arr, n, q, m): # Fill lookup table for # all possible input queries preprocess(arr, n); # One by one compute sum of # all queries for i in range(m): # Left and right boundaries # of current range L = q[i].L R = q[i].R; # Print sum of current query range print(\"Minimum of [\" + str(L) + \", \" + str(R) + \"] is \" + str(arr[lookup[L][R]])) # Driver codeif __name__ == \"__main__\": a = [7, 2, 3, 0, 5, 10, 3, 12, 18] n = len(a) q = [Query(0, 4), Query(4, 7), Query(7, 8)] m = len(q) RMQ(a, n, q, m); # This code is contributed by Rutvik_56",
"e": 32746,
"s": 31012,
"text": null
},
{
"code": "// C# program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing time.using System; class GFG { static int MAX = 500; // lookup[i][j] is going to store index of // minimum value in arr[i..j] static int[, ] lookup = new int[MAX, MAX]; // Structure to represent a query range public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[n][n] for // all possible values of query ranges static void preprocess(int[] arr, int n) { // Initialize lookup[][] for // the intervals with length 1 for (int i = 0; i < n; i++) lookup[i, i] = i; // Fill rest of the entries in bottom up manner for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i, j - 1]] < arr[j]) lookup[i, j] = lookup[i, j - 1]; else lookup[i, j] = j; } } // Prints minimum of given m query // ranges in arr[0..n-1] static void RMQ(int[] arr, int n, Query[] q, int m) { // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range Console.WriteLine(\"Minimum of [\" + L + \", \" + R + \"] is \" + arr[lookup[L, R]]); } } // Driver Code public static void Main(String[] args) { int[] a = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.Length; Query[] q = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.Length; RMQ(a, n, q, m); }} // This code is contributed by PrinciRaj1992",
"e": 34921,
"s": 32746,
"text": null
},
{
"code": "<script>// Javascript program to do range minimum query// in O(1) time with O(n*n) extra space// and O(n*n) preprocessing timelet MAX = 500; // lookup[i][j] is going to store index of// minimum value in arr[i..j]let lookup = new Array(MAX);for(let i = 0; i < MAX; i++){ lookup[i] = new Array(MAX); for(let j = 0; j < MAX; j++) lookup[i][j] = 0;} // Structure to represent a query rangeclass Query{ constructor(L, R) { this.L = L; this.R = R; }} // Fills lookup array lookup[n][n] for // all possible values of query rangesfunction preprocess(arr, n){ // Initialize lookup[][] for // the intervals with length 1 for (let i = 0; i < n; i++) lookup[i][i] = i; // Fill rest of the entries in bottom up manner for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) // To find minimum of [0,4], // we compare minimum of // arr[lookup[0][3]] with arr[4]. if (arr[lookup[i][j - 1]] < arr[j]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = j; }} // Prints minimum of given m query// ranges in arr[0..n-1]function RMQ(arr,n,q,m){ // Fill lookup table for // all possible input queries preprocess(arr, n); // One by one compute sum of all queries for (let i = 0; i < m; i++) { // Left and right boundaries // of current range let L = q[i].L, R = q[i].R; // Print sum of current query range document.write(\"Minimum of [\" + L + \", \" + R + \"] is \" + arr[lookup[L][R]]+\"<br>\"); }} // Driver Codelet a=[7, 2, 3, 0, 5, 10, 3, 12, 18];let n = a.length;let q = [ new Query(0, 4), new Query(4, 7),new Query(7, 8) ];let m = q.length;RMQ(a, n, q, m); // This code is contributed by avanitrachhadiya2155</script>",
"e": 36919,
"s": 34921,
"text": null
},
{
"code": null,
"e": 36928,
"s": 36919,
"text": "Output: "
},
{
"code": null,
"e": 36998,
"s": 36928,
"text": "Minimum of [0, 4] is 0\nMinimum of [4, 7] is 3\nMinimum of [7, 8] is 12"
},
{
"code": null,
"e": 37164,
"s": 36998,
"text": "This approach supports queries in O(1), but preprocessing takes O(n2) time. Also, this approach needs O(n2) extra space which may become huge for large input arrays."
},
{
"code": null,
"e": 37494,
"s": 37164,
"text": "Method 2 (Square Root Decomposition) We can use Square Root Decompositions to reduce space required in the above method.Preprocessing: 1) Divide the range [0, n-1] into different blocks of √n each. 2) Compute the minimum of every block of size √n and store the results.Preprocessing takes O(√n * √n) = O(n) time and O(√n) space. "
},
{
"code": null,
"e": 38130,
"s": 37494,
"text": "Query: 1) To query a range [L, R], we take a minimum of all blocks that lie in this range. For left and right corner blocks which may partially overlap with the given range, we linearly scan them to find the minimum. The time complexity of the query is O(√n). Note that we have a minimum of the middle block directly accessible and there can be at most O(√n) middle blocks. There can be at most two corner blocks that we may have to scan, so we may have to scan 2*O(√n) elements of corner blocks. Therefore, the overall time complexity is O(√n).Refer to Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction) for details."
},
{
"code": null,
"e": 38623,
"s": 38130,
"text": "Method 3 (Sparse Table Algorithm) The above solution requires only O(√n) space but takes O(√n) time to query. The sparse table method supports query time O(1) with extra space O(n Log n).The idea is to precompute a minimum of all subarrays of size 2j where j varies from 0 to Log n. Like method 1, we make a lookup table. Here lookup[i][j] contains a minimum of range starting from i and of size 2j. For example lookup[0][3] contains a minimum of range [0, 7] (starting with 0 and of size 23)"
},
{
"code": null,
"e": 38945,
"s": 38623,
"text": "Preprocessing: How to fill this lookup table? The idea is simple, fill in a bottom-up manner using previously computed values. For example, to find a minimum of range [0, 7], we can use a minimum of the following two. a) Minimum of range [0, 3] b) Minimum of range [4, 7]Based on the above example, below is the formula, "
},
{
"code": null,
"e": 39242,
"s": 38945,
"text": "// If arr[lookup[0][2]] <= arr[lookup[4][2]], \n// then lookup[0][3] = lookup[0][2]\nIf arr[lookup[i][j-1]] <= arr[lookup[i+2j-1][j-1]]\n lookup[i][j] = lookup[i][j-1]\n\n// If arr[lookup[0][2]] > arr[lookup[4][2]], \n// then lookup[0][3] = lookup[4][2]\nElse \n lookup[i][j] = lookup[i+2j-1][j-1] "
},
{
"code": null,
"e": 39763,
"s": 39242,
"text": "Query: For any arbitrary range [l, R], we need to use ranges that are in powers of 2. The idea is to use the closest power of 2. We always need to do at most one comparison (compare a minimum of two ranges which are powers of 2). One range starts with L and ends with “L + closest-power-of-2”. The other range ends at R and starts with “R – same-closest-power-of-2 + 1”. For example, if the given range is (2, 10), we compare a minimum of two ranges (2, 9) and (3, 10). Based on the above example, below is the formula, "
},
{
"code": null,
"e": 40127,
"s": 39763,
"text": "// For (2,10), j = floor(Log2(10-2+1)) = 3\nj = floor(Log(R-L+1))\n\n// If arr[lookup[0][3]] <= arr[lookup[3][3]], \n// then RMQ(2,10) = lookup[0][3]\nIf arr[lookup[L][j]] <= arr[lookup[R-(int)pow(2,j)+1][j]]\n RMQ(L, R) = lookup[L][j]\n\n// If arr[lookup[0][3]] > arr[lookup[3][3]], \n// then RMQ(2,10) = lookup[3][3]\nElse \n RMQ(L, R) = lookup[R-(int)pow(2,j)+1][j]"
},
{
"code": null,
"e": 40202,
"s": 40127,
"text": "Since we do only one comparison, the time complexity of the query is O(1)."
},
{
"code": null,
"e": 40250,
"s": 40202,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 40254,
"s": 40250,
"text": "C++"
},
{
"code": null,
"e": 40259,
"s": 40254,
"text": "Java"
},
{
"code": null,
"e": 40267,
"s": 40259,
"text": "Python3"
},
{
"code": null,
"e": 40270,
"s": 40267,
"text": "C#"
},
{
"code": "// C++ program to do range minimum// query in O(1) time with// O(n Log n) extra space and// O(n Log n) preprocessing time#include <bits/stdc++.h>using namespace std;#define MAX 500 // lookup[i][j] is going to// store index of minimum value in// arr[i..j]. Ideally lookup// table size should not be fixed// and should be determined using// n Log n. It is kept// constant to keep code simple.int lookup[MAX][MAX]; // Structure to represent a query rangestruct Query { int L, R;}; // Fills lookup array// lookup[][] in bottom up manner.void preprocess(int arr[], int n){ // Initialize M for the // intervals with length 1 for (int i = 0; i < n; i++) lookup[i][0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size // 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we // compare arr[lookup[0][3]] // and arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))][j - 1]]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } }} // Returns minimum of arr[L..R]int query(int arr[], int L, int R){ // For [2,10], j = 3 int j = (int)log2(R - L + 1); // For [2,10], we compare arr[lookup[0][3]] and // arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]) return arr[lookup[L][j]]; else return arr[lookup[R - (1 << j) + 1][j]];} // Prints minimum of given// m query ranges in arr[0..n-1]void RMQ(int arr[], int n, Query q[], int m){ // Fills table lookup[n][Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range cout << \"Minimum of [\" << L << \", \" << R << \"] is \" << query(arr, L, R) << endl; }} // Driver codeint main(){ int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 4 }, { 4, 7 }, { 7, 8 } }; int m = sizeof(q) / sizeof(q[0]); RMQ(a, n, q, m); return 0;}",
"e": 42664,
"s": 40270,
"text": null
},
{
"code": "// Java program to do range minimum query// in O(1) time with O(n Log n) extra space// and O(n Log n) preprocessing timeimport java.util.*; class GFG { static int MAX = 500; // lookup[i][j] is going to store index // of minimum value in arr[i..j]. // Ideally lookup table size should not be fixed // and should be determined using n Log n. // It is kept constant to keep code simple. static int[][] lookup = new int[MAX][MAX]; // Structure to represent a query range static class Query { int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[][] // in bottom up manner. static void preprocess(int arr[], int n) { // Initialize M for the intervals // with length 1 for (int i = 0; i < n; i++) lookup[i][0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we compare // arr[lookup[0][3]] // and arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))] [j - 1]]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } } } // Returns minimum of arr[L..R] static int query(int arr[], int L, int R) { // For [2,10], j = 3 int j = (int)Math.log(R - L + 1); // For [2,10], we compare // arr[lookup[0][3]] // and arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]) return arr[lookup[L][j]]; else return arr[lookup[R - (1 << j) + 1][j]]; } // Prints minimum of given m // query ranges in arr[0..n-1] static void RMQ(int arr[], int n, Query q[], int m) { // Fills table lookup[n][Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries // of current range int L = q[i].L, R = q[i].R; // Print sum of current query range System.out.println(\"Minimum of [\" + L + \", \" + R + \"] is \" + query(arr, L, R)); } } // Driver Code public static void main(String[] args) { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.length; Query q[] = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.length; RMQ(a, n, q, m); }} // This code is contributed by Rajput-Ji",
"e": 45753,
"s": 42664,
"text": null
},
{
"code": "# Python3 program to do range minimum query# in O(1) time with O(n Log n) extra space# and O(n Log n) preprocessing timefrom math import log2 MAX = 500 # lookup[i][j] is going to store index of# minimum value in arr[i..j].# Ideally lookup table size should# not be fixed and should be determined# using n Log n. It is kept constant# to keep code simple.lookup = [[0 for i in range(500)] for j in range(500)] # Structure to represent a query range class Query: def __init__(self, l, r): self.L = l self.R = r # Fills lookup array lookup[][]# in bottom up manner. def preprocess(arr: list, n: int): global lookup # Initialize M for the # intervals with length 1 for i in range(n): lookup[i][0] = i # Compute values from # smaller to bigger intervals j = 1 while (1 << j) <= n: # Compute minimum value for # all intervals with size 2^j i = 0 while i + (1 << j) - 1 < n: # For arr[2][10], we compare # arr[lookup[0][3]] and # arr[lookup[3][3]] if (arr[lookup[i][j - 1]] < arr[lookup[i + (1 << (j - 1))][j - 1]]): lookup[i][j] = lookup[i][j - 1] else: lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1] i += 1 j += 1 # Returns minimum of arr[L..R] def query(arr: list, L: int, R: int) -> int: global lookup # For [2,10], j = 3 j = int(log2(R - L + 1)) # For [2,10], we compare # arr[lookup[0][3]] and # arr[lookup[3][3]], if (arr[lookup[L][j]] <= arr[lookup[R - (1 << j) + 1][j]]): return arr[lookup[L][j]] else: return arr[lookup[R - (1 << j) + 1][j]] # Prints minimum of given# m query ranges in arr[0..n-1] def RMQ(arr: list, n: int, q: list, m: int): # Fills table lookup[n][Log n] preprocess(arr, n) # One by one compute sum of all queries for i in range(m): # Left and right boundaries # of current range L = q[i].L R = q[i].R # Print sum of current query range print(\"Minimum of [%d, %d] is %d\" % (L, R, query(arr, L, R))) # Driver Codeif __name__ == \"__main__\": a = [7, 2, 3, 0, 5, 10, 3, 12, 18] n = len(a) q = [Query(0, 4), Query(4, 7), Query(7, 8)] m = len(q) RMQ(a, n, q, m) # This code is contributed by# sanjeev2552",
"e": 48176,
"s": 45753,
"text": null
},
{
"code": "// C# program to do range minimum query// in O(1) time with O(n Log n) extra space// and O(n Log n) preprocessing timeusing System; class GFG { static int MAX = 500; // lookup[i,j] is going to store index // of minimum value in arr[i..j]. // Ideally lookup table size should not be fixed // and should be determined using n Log n. // It is kept constant to keep code simple. static int[, ] lookup = new int[MAX, MAX]; // Structure to represent a query range public class Query { public int L, R; public Query(int L, int R) { this.L = L; this.R = R; } }; // Fills lookup array lookup[,] // in bottom up manner. static void preprocess(int[] arr, int n) { // Initialize M for the intervals // with length 1 for (int i = 0; i < n; i++) lookup[i, 0] = i; // Compute values from smaller // to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for // all intervals with size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2,10], we compare // arr[lookup[0,3]] and arr[lookup[3,3]] if (arr[lookup[i, j - 1]] < arr[lookup[i + (1 << (j - 1)), j - 1]]) lookup[i, j] = lookup[i, j - 1]; else lookup[i, j] = lookup[i + (1 << (j - 1)), j - 1]; } } } // Returns minimum of arr[L..R] static int query(int[] arr, int L, int R) { // For [2,10], j = 3 int j = (int)Math.Log(R - L + 1); // For [2,10], we compare arr[lookup[0,3]] // and arr[lookup[3,3]], if (arr[lookup[L, j]] <= arr[lookup[R - (1 << j) + 1, j]]) return arr[lookup[L, j]]; else return arr[lookup[R - (1 << j) + 1, j]]; } // Prints minimum of given m // query ranges in arr[0..n-1] static void RMQ(int[] arr, int n, Query[] q, int m) { // Fills table lookup[n,Log n] preprocess(arr, n); // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right // boundaries of current range int L = q[i].L, R = q[i].R; // Print sum of current query range Console.WriteLine(\"Minimum of [\" + L + \", \" + R + \"] is \" + query(arr, L, R)); } } // Driver Code public static void Main(String[] args) { int[] a = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.Length; Query[] q = { new Query(0, 4), new Query(4, 7), new Query(7, 8) }; int m = q.Length; RMQ(a, n, q, m); }} // This code is contributed by Princi Singh",
"e": 51137,
"s": 48176,
"text": null
},
{
"code": null,
"e": 51207,
"s": 51137,
"text": "Minimum of [0, 4] is 0\nMinimum of [4, 7] is 3\nMinimum of [7, 8] is 12"
},
{
"code": null,
"e": 51493,
"s": 51207,
"text": "So sparse table method supports query operation in O(1) time with O(n Log n) preprocessing time and O(n Log n) space.This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 51500,
"s": 51493,
"text": "costom"
},
{
"code": null,
"e": 51512,
"s": 51500,
"text": "29AjayKumar"
},
{
"code": null,
"e": 51526,
"s": 51512,
"text": "princiraj1992"
},
{
"code": null,
"e": 51536,
"s": 51526,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 51549,
"s": 51536,
"text": "princi singh"
},
{
"code": null,
"e": 51561,
"s": 51549,
"text": "sanjeev2552"
},
{
"code": null,
"e": 51570,
"s": 51561,
"text": "udbhav99"
},
{
"code": null,
"e": 51580,
"s": 51570,
"text": "rutvik_56"
},
{
"code": null,
"e": 51601,
"s": 51580,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 51621,
"s": 51601,
"text": "array-range-queries"
},
{
"code": null,
"e": 51634,
"s": 51621,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51658,
"s": 51634,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 51682,
"s": 51658,
"text": "Competitive Programming"
},
{
"code": null,
"e": 51695,
"s": 51682,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51793,
"s": 51695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51827,
"s": 51793,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 51867,
"s": 51827,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 51895,
"s": 51867,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 51924,
"s": 51895,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 51956,
"s": 51924,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 51999,
"s": 51956,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 52042,
"s": 51999,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 52083,
"s": 52042,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 52161,
"s": 52083,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
numpy.left_shift() in Python - GeeksforGeeks | 28 Nov, 2018
numpy.left_shift() function is used to Shift the bits of an integer to the left.
The bits are shifted to the left by appending arr2 0s(zeroes) at the right of arr1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying arr1 by 2**arr2. For example, if the number is 5 and we want to 2 bit left shift then after left shift 2 bit the result will be 5*(2^2) = 20
Syntax : numpy.left_shift(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘left_shift’)
Parameters :arr1 : array_like of integer typearr2 : array_like of integer typeNumber of zeros to append to arr1.The value of arr2 should be positive integer.
out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : array of integer type.Return arr1 with bits shifted arr2 times to the left. This is a scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# left_shift() function import numpy as geekin_num = 5bit_shift = 2 print ("Input number : ", in_num)print ("Number of bit shift : ", bit_shift ) out_num = geek.left_shift(in_num, bit_shift) print ("After left shifting 2 bit : ", out_num)
Output :
Input number : 5
Number of bit shift : 2
After left shifting 2 bit : 20
Code #2 :
# Python program explaining# left_shift() function import numpy as geek in_arr = [2, 8, 15]bit_shift =[3, 4, 5] print ("Input array : ", in_arr) print ("Number of bit shift : ", bit_shift) out_arr = geek.left_shift(in_arr, bit_shift) print ("Output array after left shifting: ", out_arr)
Output :
Input array : [2, 8, 15]
Number of bit shift : [3, 4, 5]
Output array after left shifting: [ 16 128 480]
Python numpy-Binary Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 25618,
"s": 25537,
"text": "numpy.left_shift() function is used to Shift the bits of an integer to the left."
},
{
"code": null,
"e": 25953,
"s": 25618,
"text": "The bits are shifted to the left by appending arr2 0s(zeroes) at the right of arr1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying arr1 by 2**arr2. For example, if the number is 5 and we want to 2 bit left shift then after left shift 2 bit the result will be 5*(2^2) = 20"
},
{
"code": null,
"e": 26083,
"s": 25953,
"text": "Syntax : numpy.left_shift(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘left_shift’)"
},
{
"code": null,
"e": 26241,
"s": 26083,
"text": "Parameters :arr1 : array_like of integer typearr2 : array_like of integer typeNumber of zeros to append to arr1.The value of arr2 should be positive integer."
},
{
"code": null,
"e": 26447,
"s": 26241,
"text": "out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned."
},
{
"code": null,
"e": 26592,
"s": 26447,
"text": "**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function."
},
{
"code": null,
"e": 26759,
"s": 26592,
"text": "where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone."
},
{
"code": null,
"e": 26896,
"s": 26759,
"text": "Return : array of integer type.Return arr1 with bits shifted arr2 times to the left. This is a scalar if both arr1 and arr2 are scalars."
},
{
"code": null,
"e": 26914,
"s": 26896,
"text": "Code #1 : Working"
},
{
"code": "# Python program explaining# left_shift() function import numpy as geekin_num = 5bit_shift = 2 print (\"Input number : \", in_num)print (\"Number of bit shift : \", bit_shift ) out_num = geek.left_shift(in_num, bit_shift) print (\"After left shifting 2 bit : \", out_num) ",
"e": 27189,
"s": 26914,
"text": null
},
{
"code": null,
"e": 27198,
"s": 27189,
"text": "Output :"
},
{
"code": null,
"e": 27276,
"s": 27198,
"text": "Input number : 5\nNumber of bit shift : 2\nAfter left shifting 2 bit : 20\n"
},
{
"code": null,
"e": 27287,
"s": 27276,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# left_shift() function import numpy as geek in_arr = [2, 8, 15]bit_shift =[3, 4, 5] print (\"Input array : \", in_arr) print (\"Number of bit shift : \", bit_shift) out_arr = geek.left_shift(in_arr, bit_shift) print (\"Output array after left shifting: \", out_arr) ",
"e": 27583,
"s": 27287,
"text": null
},
{
"code": null,
"e": 27592,
"s": 27583,
"text": "Output :"
},
{
"code": null,
"e": 27701,
"s": 27592,
"text": "Input array : [2, 8, 15]\nNumber of bit shift : [3, 4, 5]\nOutput array after left shifting: [ 16 128 480]\n"
},
{
"code": null,
"e": 27733,
"s": 27703,
"text": "Python numpy-Binary Operation"
},
{
"code": null,
"e": 27746,
"s": 27733,
"text": "Python-numpy"
},
{
"code": null,
"e": 27753,
"s": 27746,
"text": "Python"
},
{
"code": null,
"e": 27851,
"s": 27753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27883,
"s": 27851,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27925,
"s": 27883,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27967,
"s": 27925,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28023,
"s": 27967,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28050,
"s": 28023,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28089,
"s": 28050,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28120,
"s": 28089,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28142,
"s": 28120,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28171,
"s": 28142,
"text": "Create a directory in Python"
}
] |
Bottomsheet in Flutter - GeeksforGeeks | 22 Mar, 2021
We can create bottomsheet in flutter. Basically, we have two types of bottomsheets in material design: Persistent and Modal. Bottomsheets are used when we want to perform actions. There are basically two types of Bottomsheets: Persistent and Modal. Persistent bottomsheet do not hide the screen content and focus on both sides. But Modal bottomsheet focuses more on bottomsheet rather than the main screen content. When the persistent button is tapped then the page will be pushed and the Persistent bottomsheet will be displayed. While in the case of a Modal bottomsheet, rather than a page push, bottomsheet will be displayed on the same page and is less complex than the persistent bottomsheet. We can use either of the bottomsheet as per our requirement.
Persistent: It is visible even when the user uses the other parts of the app.
Modal: It prevents the user from using other parts of the app.
Let’s understand these with the help of examples:
BottomSheet({Key key,
AnimationController animationController,
bool enableDrag: true,
BottomSheetDragStartHandler onDragStart,
BottomSheetDragEndHandler onDragEnd,
Color backgroundColor,
double elevation,
ShapeBorder shape,
Clip clipBehavior,
@required VoidCallback onClosing,
@required WidgetBuilder builder})
main.dart
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'BottomSheet', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage>{ final _scaffoldKey =new GlobalKey<ScaffoldState>(); VoidCallback _showPersBottomSheetCallBack; @override void initState(){ super.initState(); _showPersBottomSheetCallBack=_showPersistentBottomSheet; } void _showPersistentBottomSheet(){ setState(() { _showPersBottomSheetCallBack=null; }); _scaffoldKey.currentState.showBottomSheet((context){ return new Container( height: 200.0, color: Colors.green, child: new Center( child: new Text("Persistent BottomSheet",textScaleFactor: 2, style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold)), ), ); }).closed.whenComplete((){ if(mounted){ setState(() { _showPersBottomSheetCallBack=_showPersistentBottomSheet; }); } }); } void _showModalSheet(){ showModalBottomSheet( context: context, builder: (builder){ return new Container( height: 200.0, color: Colors.green, child: new Center( child: new Text(" Modal BottomSheet",textScaleFactor: 2, style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold)), ), ); } ); } @override Widget build(BuildContext context) { return new Scaffold( key:_scaffoldKey, appBar: new AppBar( title: new Text("Bottomsheet"), backgroundColor: Colors.green, actions: <Widget>[ Text("GFG",textScaleFactor: 2,) ], ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new RaisedButton( color: Colors.red, onPressed: _showPersBottomSheetCallBack, child: new Text("Persistent", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), ), new Padding( padding: const EdgeInsets.only(top: 10.0), ), new RaisedButton( color: Colors.red, onPressed: _showModalSheet, child: new Text("Model", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), ) ], ), ), backgroundColor: Colors.lightBlue[100], ); }}
Output:
When the above code is executed, the output is shown below:
When the Persistent button is tapped, a persistent bottomsheet will be displayed. In this persistent bottomsheet, the main screen content is equally focused as the bottomsheet content. When the persistent button is tapped then the page will be pushed and the Persistent bottomsheet will be displayed. When the Modal button is tapped, the modal bottomsheet will be displayed. In the Modal bottomsheet, rather than a page push, bottomsheet will be displayed on the same page and is less complex than the persistent bottomsheet.
Flutter
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Dialogs | [
{
"code": null,
"e": 25261,
"s": 25233,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 26020,
"s": 25261,
"text": "We can create bottomsheet in flutter. Basically, we have two types of bottomsheets in material design: Persistent and Modal. Bottomsheets are used when we want to perform actions. There are basically two types of Bottomsheets: Persistent and Modal. Persistent bottomsheet do not hide the screen content and focus on both sides. But Modal bottomsheet focuses more on bottomsheet rather than the main screen content. When the persistent button is tapped then the page will be pushed and the Persistent bottomsheet will be displayed. While in the case of a Modal bottomsheet, rather than a page push, bottomsheet will be displayed on the same page and is less complex than the persistent bottomsheet. We can use either of the bottomsheet as per our requirement."
},
{
"code": null,
"e": 26098,
"s": 26020,
"text": "Persistent: It is visible even when the user uses the other parts of the app."
},
{
"code": null,
"e": 26161,
"s": 26098,
"text": "Modal: It prevents the user from using other parts of the app."
},
{
"code": null,
"e": 26211,
"s": 26161,
"text": "Let’s understand these with the help of examples:"
},
{
"code": null,
"e": 26532,
"s": 26211,
"text": "BottomSheet({Key key, \nAnimationController animationController, \nbool enableDrag: true, \nBottomSheetDragStartHandler onDragStart, \nBottomSheetDragEndHandler onDragEnd, \nColor backgroundColor, \ndouble elevation, \nShapeBorder shape, \nClip clipBehavior, \n@required VoidCallback onClosing, \n@required WidgetBuilder builder})"
},
{
"code": null,
"e": 26542,
"s": 26532,
"text": "main.dart"
},
{
"code": null,
"e": 26547,
"s": 26542,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'BottomSheet', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage>{ final _scaffoldKey =new GlobalKey<ScaffoldState>(); VoidCallback _showPersBottomSheetCallBack; @override void initState(){ super.initState(); _showPersBottomSheetCallBack=_showPersistentBottomSheet; } void _showPersistentBottomSheet(){ setState(() { _showPersBottomSheetCallBack=null; }); _scaffoldKey.currentState.showBottomSheet((context){ return new Container( height: 200.0, color: Colors.green, child: new Center( child: new Text(\"Persistent BottomSheet\",textScaleFactor: 2, style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold)), ), ); }).closed.whenComplete((){ if(mounted){ setState(() { _showPersBottomSheetCallBack=_showPersistentBottomSheet; }); } }); } void _showModalSheet(){ showModalBottomSheet( context: context, builder: (builder){ return new Container( height: 200.0, color: Colors.green, child: new Center( child: new Text(\" Modal BottomSheet\",textScaleFactor: 2, style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold)), ), ); } ); } @override Widget build(BuildContext context) { return new Scaffold( key:_scaffoldKey, appBar: new AppBar( title: new Text(\"Bottomsheet\"), backgroundColor: Colors.green, actions: <Widget>[ Text(\"GFG\",textScaleFactor: 2,) ], ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new RaisedButton( color: Colors.red, onPressed: _showPersBottomSheetCallBack, child: new Text(\"Persistent\", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), ), new Padding( padding: const EdgeInsets.only(top: 10.0), ), new RaisedButton( color: Colors.red, onPressed: _showModalSheet, child: new Text(\"Model\", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), ) ], ), ), backgroundColor: Colors.lightBlue[100], ); }}",
"e": 29420,
"s": 26547,
"text": null
},
{
"code": null,
"e": 29428,
"s": 29420,
"text": "Output:"
},
{
"code": null,
"e": 29488,
"s": 29428,
"text": "When the above code is executed, the output is shown below:"
},
{
"code": null,
"e": 30014,
"s": 29488,
"text": "When the Persistent button is tapped, a persistent bottomsheet will be displayed. In this persistent bottomsheet, the main screen content is equally focused as the bottomsheet content. When the persistent button is tapped then the page will be pushed and the Persistent bottomsheet will be displayed. When the Modal button is tapped, the modal bottomsheet will be displayed. In the Modal bottomsheet, rather than a page push, bottomsheet will be displayed on the same page and is less complex than the persistent bottomsheet."
},
{
"code": null,
"e": 30022,
"s": 30014,
"text": "Flutter"
},
{
"code": null,
"e": 30038,
"s": 30022,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 30043,
"s": 30038,
"text": "Dart"
},
{
"code": null,
"e": 30051,
"s": 30043,
"text": "Flutter"
},
{
"code": null,
"e": 30149,
"s": 30051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30188,
"s": 30149,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30214,
"s": 30188,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 30240,
"s": 30214,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 30263,
"s": 30240,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 30308,
"s": 30263,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 30347,
"s": 30308,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30364,
"s": 30347,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 30390,
"s": 30364,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 30413,
"s": 30390,
"text": "Flutter - Stack Widget"
}
] |
Changing the Replication Factor in Cassandra - GeeksforGeeks | 28 Apr, 2020
In this article, we are going to discuss how we can change the replication factor in both simple and network topology replication strategy. For better understanding please refer Replication Strategy in Cassandra article.
Altering a Keyspace:To change the replication factor you can execute the Altering a keyspace statement where you can change the replication factor for Simple Strategy and NetworkTopology Strategy.
For example:Changing the Replication Factor for SimpleStrategy:If you want to change the replication factor of a keyspace, you can do it by executing the ALTER KEYSPACE command, which has the following syntax:
Syntax:
ALTER KEYSPACE "KeySpace Name"
WITH replication = {'class': 'Strategy name',
'replication_factor' : 'No.Of replicas'};
first, you can create any keyspace and then you can change the replication factor or if you have existing keyspace then you can change in the same way.
Example: Creating a WFH keyspace.
CREATE KEYSPACE WFH WITH replication =
{
'class': 'SimpleStrategy',
'replication_factor': '2'
}
AND durable_writes = true;
Now, here you can change the replication factor for the same.
cassandra@cqlsh> ALTER KEYSPACE WFH
... WITH replication =
... {
... 'class': 'SimpleStrategy',
... 'replication_factor': '3'
... }
... AND durable_writes = true;
Now, to verify the result you can execute the following CQL query.
cassandra@cqlsh> describe WFH;
Output:
CREATE KEYSPACE wfh
WITH
replication =
{
'class': 'SimpleStrategy',
'replication_factor': '3'
}
AND durable_writes = true;
In Cassandra, You set the replication strategy at the keyspace level when creating the keyspace or later by modifying the keyspace.
Changing the Replication Factor for NetworkTopologyStrategy:In this case, you can consider an existing keyspace that you want to change the Replication Factor for NetworkTopologyStrategy.
Example: Existing keyspace : app_datayou can see the description of app_data keyspace by executing the following CQL query.
cassandra@cqlsh> describe app_data;
Output:
CREATE KEYSPACE app_data
WITH replication =
{'class': 'NetworkTopologyStrategy',
'datacenter1': '3',
'datacenter2': '2'}
AND durable_writes = true;
Now, if we want to change the replication factor for datacenter2 from 2 to 3 then you can execute the following CQL query given below.
cassandra@cqlsh> ALTER KEYSPACE app_data
... WITH replication =
... {
... 'class': 'NetworkTopologyStrategy',
... 'datacenter1': '3',
... 'datacenter2': '3'
... }
... AND durable_writes = true;
Now, to verify the result then you can execute the following CQL query.
cassandra@cqlsh> describe app_data;
Output:
CREATE KEYSPACE app_data
WITH replication =
{
'class': 'NetworkTopologyStrategy',
'datacenter1': '3',
'datacenter2': '3'
}
AND durable_writes = true;
In Cassandra, You can’t alter the name of a keyspace.
It is always a good practice after changing the replication factor or any modification you can execute the repair command.
You can execute the following CQL query for full repair.nodetool repair -full
nodetool repair -full
NoSQL
DBMS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Introduction of B-Tree
SQL Trigger | Student Database
CTE in SQL
Difference between Clustered and Non-clustered index
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 25441,
"s": 25413,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 25662,
"s": 25441,
"text": "In this article, we are going to discuss how we can change the replication factor in both simple and network topology replication strategy. For better understanding please refer Replication Strategy in Cassandra article."
},
{
"code": null,
"e": 25859,
"s": 25662,
"text": "Altering a Keyspace:To change the replication factor you can execute the Altering a keyspace statement where you can change the replication factor for Simple Strategy and NetworkTopology Strategy."
},
{
"code": null,
"e": 26069,
"s": 25859,
"text": "For example:Changing the Replication Factor for SimpleStrategy:If you want to change the replication factor of a keyspace, you can do it by executing the ALTER KEYSPACE command, which has the following syntax:"
},
{
"code": null,
"e": 26220,
"s": 26069,
"text": "Syntax:\n \nALTER KEYSPACE \"KeySpace Name\"\nWITH replication = {'class': 'Strategy name', \n 'replication_factor' : 'No.Of replicas'}; "
},
{
"code": null,
"e": 26372,
"s": 26220,
"text": "first, you can create any keyspace and then you can change the replication factor or if you have existing keyspace then you can change in the same way."
},
{
"code": null,
"e": 26406,
"s": 26372,
"text": "Example: Creating a WFH keyspace."
},
{
"code": null,
"e": 26591,
"s": 26406,
"text": "CREATE KEYSPACE WFH WITH replication =\n {\n 'class': 'SimpleStrategy',\n 'replication_factor': '2'\n }\n AND durable_writes = true;\n"
},
{
"code": null,
"e": 26653,
"s": 26591,
"text": "Now, here you can change the replication factor for the same."
},
{
"code": null,
"e": 26907,
"s": 26653,
"text": "cassandra@cqlsh> ALTER KEYSPACE WFH\n ... WITH replication =\n ... {\n ... 'class': 'SimpleStrategy',\n ... 'replication_factor': '3'\n ... }\n ... AND durable_writes = true;\n"
},
{
"code": null,
"e": 26974,
"s": 26907,
"text": "Now, to verify the result you can execute the following CQL query."
},
{
"code": null,
"e": 27006,
"s": 26974,
"text": "cassandra@cqlsh> describe WFH;\n"
},
{
"code": null,
"e": 27014,
"s": 27006,
"text": "Output:"
},
{
"code": null,
"e": 27144,
"s": 27014,
"text": "CREATE KEYSPACE wfh \nWITH \nreplication = \n{\n'class': 'SimpleStrategy', \n'replication_factor': '3'\n} \nAND durable_writes = true;\n"
},
{
"code": null,
"e": 27276,
"s": 27144,
"text": "In Cassandra, You set the replication strategy at the keyspace level when creating the keyspace or later by modifying the keyspace."
},
{
"code": null,
"e": 27464,
"s": 27276,
"text": "Changing the Replication Factor for NetworkTopologyStrategy:In this case, you can consider an existing keyspace that you want to change the Replication Factor for NetworkTopologyStrategy."
},
{
"code": null,
"e": 27588,
"s": 27464,
"text": "Example: Existing keyspace : app_datayou can see the description of app_data keyspace by executing the following CQL query."
},
{
"code": null,
"e": 27625,
"s": 27588,
"text": "cassandra@cqlsh> describe app_data;\n"
},
{
"code": null,
"e": 27633,
"s": 27625,
"text": "Output:"
},
{
"code": null,
"e": 27788,
"s": 27633,
"text": "CREATE KEYSPACE app_data \nWITH replication = \n{'class': 'NetworkTopologyStrategy', \n'datacenter1': '3', \n'datacenter2': '2'} \nAND durable_writes = true;\n"
},
{
"code": null,
"e": 27923,
"s": 27788,
"text": "Now, if we want to change the replication factor for datacenter2 from 2 to 3 then you can execute the following CQL query given below."
},
{
"code": null,
"e": 28193,
"s": 27923,
"text": "cassandra@cqlsh> ALTER KEYSPACE app_data\n ... WITH replication =\n ... {\n ... 'class': 'NetworkTopologyStrategy',\n ... 'datacenter1': '3',\n ... 'datacenter2': '3'\n ... }\n ... AND durable_writes = true;\n"
},
{
"code": null,
"e": 28265,
"s": 28193,
"text": "Now, to verify the result then you can execute the following CQL query."
},
{
"code": null,
"e": 28302,
"s": 28265,
"text": "cassandra@cqlsh> describe app_data;\n"
},
{
"code": null,
"e": 28310,
"s": 28302,
"text": "Output:"
},
{
"code": null,
"e": 28467,
"s": 28310,
"text": "CREATE KEYSPACE app_data \nWITH replication = \n{\n'class': 'NetworkTopologyStrategy', \n'datacenter1': '3', \n'datacenter2': '3'\n} \nAND durable_writes = true;\n"
},
{
"code": null,
"e": 28521,
"s": 28467,
"text": "In Cassandra, You can’t alter the name of a keyspace."
},
{
"code": null,
"e": 28644,
"s": 28521,
"text": "It is always a good practice after changing the replication factor or any modification you can execute the repair command."
},
{
"code": null,
"e": 28723,
"s": 28644,
"text": "You can execute the following CQL query for full repair.nodetool repair -full\n"
},
{
"code": null,
"e": 28746,
"s": 28723,
"text": "nodetool repair -full\n"
},
{
"code": null,
"e": 28752,
"s": 28746,
"text": "NoSQL"
},
{
"code": null,
"e": 28757,
"s": 28752,
"text": "DBMS"
},
{
"code": null,
"e": 28773,
"s": 28757,
"text": "Write From Home"
},
{
"code": null,
"e": 28778,
"s": 28773,
"text": "DBMS"
},
{
"code": null,
"e": 28876,
"s": 28778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28900,
"s": 28876,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 28923,
"s": 28900,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 28954,
"s": 28923,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 28965,
"s": 28954,
"text": "CTE in SQL"
},
{
"code": null,
"e": 29018,
"s": 28965,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 29054,
"s": 29018,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29090,
"s": 29054,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 29106,
"s": 29090,
"text": "Python infinity"
},
{
"code": null,
"e": 29167,
"s": 29106,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Traverse graph in lexicographical order of nodes using DFS - GeeksforGeeks | 20 Jul, 2021
Given a graph, G consisting of N nodes, a source S, and an array Edges[][2] of type {u, v} that denotes that there is an undirected edge between node u and v, the task is to traverse the graph in lexicographical order using DFS.
Examples:
Input: N = 10, M = 10, S = ‘a’, Edges[][2] = { { ‘a’, ‘y’ }, { ‘a’, ‘z’ }, { ‘a’, ‘p’ }, { ‘p’, ‘c’ }, { ‘p’, ‘b’ }, { ‘y’, ‘m’ }, { ‘y’, ‘l’ }, { ‘z’, ‘h’ }, { ‘z’, ‘g’ }, { ‘z’, ‘i’ } } Output: a p b c y l m z g h i
Explanation: For the first level visit the node and print it:
Similarly visited the second level node p which is lexicographical smallest as:
Similarly visited the third level for node p in lexicographical order as:
Now the final traversal is shown in the below image and labelled as increasing order of number:
Input: N = 6, S = ‘a’, Edges[][2] = { { ‘a’, ‘e’ }, { ‘a’, ‘d’ }, { ‘e’, ‘b’ }, { ‘e’, ‘c’ }, { ‘d’, ‘f’ }, { ‘d’, ‘g’ } } Output: a d f g e b c
Approach: Follow the steps below to solve the problem:
Initialize a map, say G to store all the adjacent nodes of a node according to lexicographical order of the nodes.
Initialize a map, say vis to check if a node is already traversed or not.
Traverse the Edges[][2] array and store all the adjacent nodes of each node of the graph in G.
Finally, traverse the graph using DFS and print the visited nodes of the graph.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to traverse the graph in// lexicographical order using DFSvoid LexiDFS(map<char, set<char> >& G, char S, map<char, bool>& vis){ // Mark S as visited nodes vis[S] = true; // Print value of visited nodes cout << S << " "; // Traverse all adjacent nodes of S for (auto i = G[S].begin(); i != G[S].end(); i++) { // If i is not visited if (!vis[*i]) { // Traverse all the nodes // which is connected to i LexiDFS(G, *i, vis); } }} // Utility Function to traverse graph// in lexicographical order of nodesvoid CreateGraph(int N, int M, int S, char Edges[][2]){ // Store all the adjacent nodes // of each node of a graph map<char, set<char> > G; // Traverse Edges[][2] array for (int i = 0; i < M; i++) { // Add the edges G[Edges[i][0]].insert( Edges[i][1]); } // Check if a node is already // visited or not map<char, bool> vis; // Function Call LexiDFS(G, S, vis);} // Driver Codeint main(){ int N = 10, M = 10, S = 'a'; char Edges[M][2] = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', 'b' }, { 'y', 'm' }, { 'y', 'l' }, { 'z', 'h' }, { 'z', 'g' }, { 'z', 'i' } }; // Function Call CreateGraph(N, M, S, Edges); return 0;}
// Java program for above approachimport java.util.*; class Graph{ // Function to traverse the graph in// lexicographical order using DFSstatic void LexiDFS(HashMap<Character, Set<Character>> G, char S, HashMap<Character, Boolean> vis){ // Mark S as visited nodes vis.put(S, true); // Print value of visited nodes System.out.print(S + " "); // Traverse all adjacent nodes of S if (G.containsKey(S)) { for(char i : G.get(S)) { // If i is not visited if (!vis.containsKey(i) || !vis.get(i)) { // Traverse all the nodes // which is connected to i LexiDFS(G, i, vis); } } }} // Utility Function to traverse graph// in lexicographical order of nodesstatic void CreateGraph(int N, int M, char S, char[][] Edges){ // Store all the adjacent nodes // of each node of a graph HashMap<Character, Set<Character>> G = new HashMap<>(); // Traverse Edges[][2] array for(int i = 0; i < M; i++) { if (G.containsKey(Edges[i][0])) { Set<Character> temp = G.get(Edges[i][0]); temp.add(Edges[i][1]); G.put(Edges[i][0], temp); } else { Set<Character> temp = new HashSet<>(); temp.add(Edges[i][1]); G.put(Edges[i][0], temp); } } // Check if a node is already visited or not HashMap<Character, Boolean> vis = new HashMap<>(); LexiDFS(G, S, vis);} // Driver codepublic static void main(String[] args){ int N = 10, M = 10; char S = 'a'; char[][] Edges = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', 'b' }, { 'y', 'm' }, { 'y', 'l' }, { 'z', 'h' }, { 'z', 'g' }, { 'z', 'i' } }; // Function Call CreateGraph(N, M, S, Edges);}} // This code is contributed by hritikrommie
# Python3 program for the above approachG = [[] for i in range(300)]vis = [0 for i in range(300)] # Function to traverse the graph in# lexicographical order using DFSdef LexiDFS(S): global G, vis # Mark S as visited nodes vis[ord(S)] = 1 # Prvalue of visited nodes print (S,end=" ") # Traverse all adjacent nodes of S for i in G[ord(S)]: # If i is not visited if (not vis[i]): # Traverse all the nodes # which is connected to i LexiDFS(chr(i)) # Utility Function to traverse graph# in lexicographical order of nodesdef CreateGraph(N, M, S, Edges): global G # Store all the adjacent nodes # of each node of a graph # Traverse Edges[][2] array for i in Edges: # Add the edges G[ord(i[0])].append(ord(i[1])) G[ord(i[0])] = sorted(G[ord(i[0])]) # Function Call LexiDFS(S) # Driver Codeif __name__ == '__main__': N = 10 M = 10 S = 'a' Edges=[ ['a', 'y' ],[ 'a', 'z' ], [ 'a', 'p' ],[ 'p', 'c' ], [ 'p', 'b' ],[ 'y', 'm' ], [ 'y', 'l' ],[ 'z', 'h' ], [ 'z', 'g' ],[ 'z', 'i' ] ] # Function Call CreateGraph(N, M, S, Edges); # This code is contributed by mohitkumar29.
<script> // JavaScript program for the above approach let G = new Array(300).fill(0).map(() => [])let vis = new Array(300).fill(0) // Function to traverse the graph in// lexicographical order using DFSfunction LexiDFS(S) { // Mark S as visited nodes vis[S.charCodeAt(0)] = 1 // Prvalue of visited nodes document.write(S + " ") // Traverse all adjacent nodes of S for (let i of G[S.charCodeAt(0)]) { // If i is not visited if (!vis[i]) { // Traverse all the nodes // which is connected to i LexiDFS(String.fromCharCode(i)) } }} // Utility Function to traverse graph// in lexicographical order of nodesfunction CreateGraph(N, M, S, Edges) { // Store all the adjacent nodes // of each node of a graph // Traverse Edges[][2] array for (let i of Edges) { // Add the edges G[i[0].charCodeAt(0)].push(i[1].charCodeAt(0)) G[i[0].charCodeAt(0)] = G[i[0].charCodeAt(0)].sort((a, b) => a - b) } // Function Call LexiDFS(S)} // Driver Codelet N = 10let M = 10let S = 'a'let Edges = [['a', 'y'], ['a', 'z'],['a', 'p'], ['p', 'c'],['p', 'b'], ['y', 'm'],['y', 'l'], ['z', 'h'],['z', 'g'], ['z', 'i']] // Function CallCreateGraph(N, M, S, Edges); // This code is contributed by _saurabh_jaiswal </script>
a p b c y l m z g h i
Time Complexity: O(N * log(N)) Auxiliary Space: O(N)
mohit kumar 29
_saurabh_jaiswal
hritikrommie
DFS
Graph Traversals
lexicographic-ordering
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hamiltonian Cycle | Backtracking-6
Longest Path in a Directed Acyclic Graph
Best First Search (Informed Search)
Dijkstra's Shortest Path Algorithm using priority_queue of STL
Graph Coloring | Set 2 (Greedy Algorithm)
Maximum Bipartite Matching
Kahn's algorithm for Topological Sorting
Graph Coloring | Set 1 (Introduction and Applications)
Find if there is a path between two vertices in a directed graph
Find minimum s-t cut in a flow network | [
{
"code": null,
"e": 26453,
"s": 26425,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 26682,
"s": 26453,
"text": "Given a graph, G consisting of N nodes, a source S, and an array Edges[][2] of type {u, v} that denotes that there is an undirected edge between node u and v, the task is to traverse the graph in lexicographical order using DFS."
},
{
"code": null,
"e": 26692,
"s": 26682,
"text": "Examples:"
},
{
"code": null,
"e": 26910,
"s": 26692,
"text": "Input: N = 10, M = 10, S = ‘a’, Edges[][2] = { { ‘a’, ‘y’ }, { ‘a’, ‘z’ }, { ‘a’, ‘p’ }, { ‘p’, ‘c’ }, { ‘p’, ‘b’ }, { ‘y’, ‘m’ }, { ‘y’, ‘l’ }, { ‘z’, ‘h’ }, { ‘z’, ‘g’ }, { ‘z’, ‘i’ } } Output: a p b c y l m z g h i"
},
{
"code": null,
"e": 26974,
"s": 26910,
"text": "Explanation: For the first level visit the node and print it: "
},
{
"code": null,
"e": 27056,
"s": 26974,
"text": "Similarly visited the second level node p which is lexicographical smallest as: "
},
{
"code": null,
"e": 27132,
"s": 27056,
"text": "Similarly visited the third level for node p in lexicographical order as: "
},
{
"code": null,
"e": 27230,
"s": 27132,
"text": "Now the final traversal is shown in the below image and labelled as increasing order of number: "
},
{
"code": null,
"e": 27377,
"s": 27232,
"text": "Input: N = 6, S = ‘a’, Edges[][2] = { { ‘a’, ‘e’ }, { ‘a’, ‘d’ }, { ‘e’, ‘b’ }, { ‘e’, ‘c’ }, { ‘d’, ‘f’ }, { ‘d’, ‘g’ } } Output: a d f g e b c"
},
{
"code": null,
"e": 27434,
"s": 27379,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27549,
"s": 27434,
"text": "Initialize a map, say G to store all the adjacent nodes of a node according to lexicographical order of the nodes."
},
{
"code": null,
"e": 27623,
"s": 27549,
"text": "Initialize a map, say vis to check if a node is already traversed or not."
},
{
"code": null,
"e": 27718,
"s": 27623,
"text": "Traverse the Edges[][2] array and store all the adjacent nodes of each node of the graph in G."
},
{
"code": null,
"e": 27798,
"s": 27718,
"text": "Finally, traverse the graph using DFS and print the visited nodes of the graph."
},
{
"code": null,
"e": 27849,
"s": 27798,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27853,
"s": 27849,
"text": "C++"
},
{
"code": null,
"e": 27858,
"s": 27853,
"text": "Java"
},
{
"code": null,
"e": 27866,
"s": 27858,
"text": "Python3"
},
{
"code": null,
"e": 27877,
"s": 27866,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to traverse the graph in// lexicographical order using DFSvoid LexiDFS(map<char, set<char> >& G, char S, map<char, bool>& vis){ // Mark S as visited nodes vis[S] = true; // Print value of visited nodes cout << S << \" \"; // Traverse all adjacent nodes of S for (auto i = G[S].begin(); i != G[S].end(); i++) { // If i is not visited if (!vis[*i]) { // Traverse all the nodes // which is connected to i LexiDFS(G, *i, vis); } }} // Utility Function to traverse graph// in lexicographical order of nodesvoid CreateGraph(int N, int M, int S, char Edges[][2]){ // Store all the adjacent nodes // of each node of a graph map<char, set<char> > G; // Traverse Edges[][2] array for (int i = 0; i < M; i++) { // Add the edges G[Edges[i][0]].insert( Edges[i][1]); } // Check if a node is already // visited or not map<char, bool> vis; // Function Call LexiDFS(G, S, vis);} // Driver Codeint main(){ int N = 10, M = 10, S = 'a'; char Edges[M][2] = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', 'b' }, { 'y', 'm' }, { 'y', 'l' }, { 'z', 'h' }, { 'z', 'g' }, { 'z', 'i' } }; // Function Call CreateGraph(N, M, S, Edges); return 0;}",
"e": 29353,
"s": 27877,
"text": null
},
{
"code": "// Java program for above approachimport java.util.*; class Graph{ // Function to traverse the graph in// lexicographical order using DFSstatic void LexiDFS(HashMap<Character, Set<Character>> G, char S, HashMap<Character, Boolean> vis){ // Mark S as visited nodes vis.put(S, true); // Print value of visited nodes System.out.print(S + \" \"); // Traverse all adjacent nodes of S if (G.containsKey(S)) { for(char i : G.get(S)) { // If i is not visited if (!vis.containsKey(i) || !vis.get(i)) { // Traverse all the nodes // which is connected to i LexiDFS(G, i, vis); } } }} // Utility Function to traverse graph// in lexicographical order of nodesstatic void CreateGraph(int N, int M, char S, char[][] Edges){ // Store all the adjacent nodes // of each node of a graph HashMap<Character, Set<Character>> G = new HashMap<>(); // Traverse Edges[][2] array for(int i = 0; i < M; i++) { if (G.containsKey(Edges[i][0])) { Set<Character> temp = G.get(Edges[i][0]); temp.add(Edges[i][1]); G.put(Edges[i][0], temp); } else { Set<Character> temp = new HashSet<>(); temp.add(Edges[i][1]); G.put(Edges[i][0], temp); } } // Check if a node is already visited or not HashMap<Character, Boolean> vis = new HashMap<>(); LexiDFS(G, S, vis);} // Driver codepublic static void main(String[] args){ int N = 10, M = 10; char S = 'a'; char[][] Edges = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', 'b' }, { 'y', 'm' }, { 'y', 'l' }, { 'z', 'h' }, { 'z', 'g' }, { 'z', 'i' } }; // Function Call CreateGraph(N, M, S, Edges);}} // This code is contributed by hritikrommie",
"e": 31377,
"s": 29353,
"text": null
},
{
"code": "# Python3 program for the above approachG = [[] for i in range(300)]vis = [0 for i in range(300)] # Function to traverse the graph in# lexicographical order using DFSdef LexiDFS(S): global G, vis # Mark S as visited nodes vis[ord(S)] = 1 # Prvalue of visited nodes print (S,end=\" \") # Traverse all adjacent nodes of S for i in G[ord(S)]: # If i is not visited if (not vis[i]): # Traverse all the nodes # which is connected to i LexiDFS(chr(i)) # Utility Function to traverse graph# in lexicographical order of nodesdef CreateGraph(N, M, S, Edges): global G # Store all the adjacent nodes # of each node of a graph # Traverse Edges[][2] array for i in Edges: # Add the edges G[ord(i[0])].append(ord(i[1])) G[ord(i[0])] = sorted(G[ord(i[0])]) # Function Call LexiDFS(S) # Driver Codeif __name__ == '__main__': N = 10 M = 10 S = 'a' Edges=[ ['a', 'y' ],[ 'a', 'z' ], [ 'a', 'p' ],[ 'p', 'c' ], [ 'p', 'b' ],[ 'y', 'm' ], [ 'y', 'l' ],[ 'z', 'h' ], [ 'z', 'g' ],[ 'z', 'i' ] ] # Function Call CreateGraph(N, M, S, Edges); # This code is contributed by mohitkumar29.",
"e": 32618,
"s": 31377,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach let G = new Array(300).fill(0).map(() => [])let vis = new Array(300).fill(0) // Function to traverse the graph in// lexicographical order using DFSfunction LexiDFS(S) { // Mark S as visited nodes vis[S.charCodeAt(0)] = 1 // Prvalue of visited nodes document.write(S + \" \") // Traverse all adjacent nodes of S for (let i of G[S.charCodeAt(0)]) { // If i is not visited if (!vis[i]) { // Traverse all the nodes // which is connected to i LexiDFS(String.fromCharCode(i)) } }} // Utility Function to traverse graph// in lexicographical order of nodesfunction CreateGraph(N, M, S, Edges) { // Store all the adjacent nodes // of each node of a graph // Traverse Edges[][2] array for (let i of Edges) { // Add the edges G[i[0].charCodeAt(0)].push(i[1].charCodeAt(0)) G[i[0].charCodeAt(0)] = G[i[0].charCodeAt(0)].sort((a, b) => a - b) } // Function Call LexiDFS(S)} // Driver Codelet N = 10let M = 10let S = 'a'let Edges = [['a', 'y'], ['a', 'z'],['a', 'p'], ['p', 'c'],['p', 'b'], ['y', 'm'],['y', 'l'], ['z', 'h'],['z', 'g'], ['z', 'i']] // Function CallCreateGraph(N, M, S, Edges); // This code is contributed by _saurabh_jaiswal </script>",
"e": 33946,
"s": 32618,
"text": null
},
{
"code": null,
"e": 33968,
"s": 33946,
"text": "a p b c y l m z g h i"
},
{
"code": null,
"e": 34023,
"s": 33970,
"text": "Time Complexity: O(N * log(N)) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34038,
"s": 34023,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34055,
"s": 34038,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34068,
"s": 34055,
"text": "hritikrommie"
},
{
"code": null,
"e": 34072,
"s": 34068,
"text": "DFS"
},
{
"code": null,
"e": 34089,
"s": 34072,
"text": "Graph Traversals"
},
{
"code": null,
"e": 34112,
"s": 34089,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 34118,
"s": 34112,
"text": "Graph"
},
{
"code": null,
"e": 34122,
"s": 34118,
"text": "DFS"
},
{
"code": null,
"e": 34128,
"s": 34122,
"text": "Graph"
},
{
"code": null,
"e": 34226,
"s": 34128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34261,
"s": 34226,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 34302,
"s": 34261,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 34338,
"s": 34302,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 34401,
"s": 34338,
"text": "Dijkstra's Shortest Path Algorithm using priority_queue of STL"
},
{
"code": null,
"e": 34443,
"s": 34401,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 34470,
"s": 34443,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 34511,
"s": 34470,
"text": "Kahn's algorithm for Topological Sorting"
},
{
"code": null,
"e": 34566,
"s": 34511,
"text": "Graph Coloring | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 34631,
"s": 34566,
"text": "Find if there is a path between two vertices in a directed graph"
}
] |
When to use self over $this in PHP ? - GeeksforGeeks | 29 Jun, 2021
The self and this are two different operators which are used to represent current class and current object respectively. self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.self operator: self operator represents the current class and thus is used to access class variables or static variables because these members belongs to a class rather than the object of that class. Syntax:
self::$static_member
Example 1: This is the basic example which shows the use of self operator.
php
<?php class GFG { private static $static_member = "GeeksForGeeks"; function __construct() { echo self::$static_member; // Accessing static variable }} new GFG();?>
Output:
GeeksForGeeks
Example 2: This example is a demo of exploiting polymorphic behavior in php using self.
php
<?php class GFG { function print() { echo 'Parent Class'; } function bar() { self::print(); }} class Child extends GFG { function print() { echo 'Child Class'; }} $parent = new Child();$parent->bar();?>
Output:
Parent Class:
Here the parent class method runs because the self operator represents the class, thus we see that the main class method is the method of the parent class only. $this operator: $this, as the ‘$’ sign suggest, is an object. $this represents the current object of a class. It is used to access non-static members of a class. Syntax:
$that->$non_static_member;
Example 1: This is the basic example which shows the use of $this operator.
php
<?phpclass GFG { private $non_static_member = "GeeksForGeeks"; function __construct() { echo $this->$non_static_member; // accessing non-static variable }} new GFG();?>
Output:
GeeksForGeeks
Example 2: This example is a demo of polymorphic behavior in php using self.
php
<?php class GFG { function print() { echo 'Parent Class'; } function bar() { $this->print(); }} class Child extends GFG { function print() { echo 'Child Class'; }} $parent = new Child();$parent->bar();?>
Output:
Child Class
Here, there is no reference to any class and the object which is pointing the child class is calling the method defined in the child class. This is an example of dynamic polymorphism in PHP.
sweetyty
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP? | [
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 26727,
"s": 26095,
"text": "The self and this are two different operators which are used to represent current class and current object respectively. self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.self operator: self operator represents the current class and thus is used to access class variables or static variables because these members belongs to a class rather than the object of that class. Syntax: "
},
{
"code": null,
"e": 26748,
"s": 26727,
"text": "self::$static_member"
},
{
"code": null,
"e": 26825,
"s": 26748,
"text": "Example 1: This is the basic example which shows the use of self operator. "
},
{
"code": null,
"e": 26829,
"s": 26825,
"text": "php"
},
{
"code": "<?php class GFG { private static $static_member = \"GeeksForGeeks\"; function __construct() { echo self::$static_member; // Accessing static variable }} new GFG();?>",
"e": 27017,
"s": 26829,
"text": null
},
{
"code": null,
"e": 27027,
"s": 27017,
"text": "Output: "
},
{
"code": null,
"e": 27041,
"s": 27027,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 27131,
"s": 27041,
"text": "Example 2: This example is a demo of exploiting polymorphic behavior in php using self. "
},
{
"code": null,
"e": 27135,
"s": 27131,
"text": "php"
},
{
"code": "<?php class GFG { function print() { echo 'Parent Class'; } function bar() { self::print(); }} class Child extends GFG { function print() { echo 'Child Class'; }} $parent = new Child();$parent->bar();?>",
"e": 27378,
"s": 27135,
"text": null
},
{
"code": null,
"e": 27387,
"s": 27378,
"text": "Output: "
},
{
"code": null,
"e": 27401,
"s": 27387,
"text": "Parent Class:"
},
{
"code": null,
"e": 27734,
"s": 27401,
"text": "Here the parent class method runs because the self operator represents the class, thus we see that the main class method is the method of the parent class only. $this operator: $this, as the ‘$’ sign suggest, is an object. $this represents the current object of a class. It is used to access non-static members of a class. Syntax: "
},
{
"code": null,
"e": 27761,
"s": 27734,
"text": "$that->$non_static_member;"
},
{
"code": null,
"e": 27838,
"s": 27761,
"text": "Example 1: This is the basic example which shows the use of $this operator. "
},
{
"code": null,
"e": 27842,
"s": 27838,
"text": "php"
},
{
"code": "<?phpclass GFG { private $non_static_member = \"GeeksForGeeks\"; function __construct() { echo $this->$non_static_member; // accessing non-static variable }} new GFG();?>",
"e": 28035,
"s": 27842,
"text": null
},
{
"code": null,
"e": 28045,
"s": 28035,
"text": "Output: "
},
{
"code": null,
"e": 28059,
"s": 28045,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 28138,
"s": 28059,
"text": "Example 2: This example is a demo of polymorphic behavior in php using self. "
},
{
"code": null,
"e": 28142,
"s": 28138,
"text": "php"
},
{
"code": "<?php class GFG { function print() { echo 'Parent Class'; } function bar() { $this->print(); }} class Child extends GFG { function print() { echo 'Child Class'; }} $parent = new Child();$parent->bar();?>",
"e": 28386,
"s": 28142,
"text": null
},
{
"code": null,
"e": 28396,
"s": 28386,
"text": "Output: "
},
{
"code": null,
"e": 28408,
"s": 28396,
"text": "Child Class"
},
{
"code": null,
"e": 28601,
"s": 28408,
"text": "Here, there is no reference to any class and the object which is pointing the child class is calling the method defined in the child class. This is an example of dynamic polymorphism in PHP. "
},
{
"code": null,
"e": 28610,
"s": 28601,
"text": "sweetyty"
},
{
"code": null,
"e": 28617,
"s": 28610,
"text": "Picked"
},
{
"code": null,
"e": 28621,
"s": 28617,
"text": "PHP"
},
{
"code": null,
"e": 28634,
"s": 28621,
"text": "PHP Programs"
},
{
"code": null,
"e": 28651,
"s": 28634,
"text": "Web Technologies"
},
{
"code": null,
"e": 28678,
"s": 28651,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28682,
"s": 28678,
"text": "PHP"
},
{
"code": null,
"e": 28780,
"s": 28682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28820,
"s": 28780,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28865,
"s": 28820,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28907,
"s": 28865,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 28959,
"s": 28907,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28992,
"s": 28959,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 29032,
"s": 28992,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29084,
"s": 29032,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 29126,
"s": 29084,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 29178,
"s": 29126,
"text": "Split a comma delimited string into an array in PHP"
}
] |
How to create a Color-Box App using ReactJS? - GeeksforGeeks | 30 Sep, 2020
Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its previous color value.
We create three components ‘App’ and ‘BoxContainer’ and ‘Box’. The app component renders a single BoxContainer component only. There is no actual logic put inside the App component. BoxContainer component contains all the behind logics. It has a default prop ‘num’ that accounts for a number of different color boxes shows to the screen. It is a stateful component and has a single state that contains an array of RGB color values. We map over each color of state ‘colors’ and for each color, we render a ‘Box’ component. The box component is responsible to show each individual boxes with their proper color set in the background of the box. The Box component sets a click event handler to each box component and when the user clicks on any box, some logic is executed that changes the color of that box. BoxContainer component uses the props system to communicate with the Box component.
Example:
index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js : App component renders single BoxContainer component onlyJavascriptJavascriptimport React from 'react';import BoxContainer from './BoxContainer' function App() { return ( <div className="App"> <BoxContainer /> </div> );} export default App;
App.js : App component renders single BoxContainer component only
Javascript
import React from 'react';import BoxContainer from './BoxContainer' function App() { return ( <div className="App"> <BoxContainer /> </div> );} export default App;
BoxContainer.js : It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of RGB color values. number of colors(number of color boxes want to render by when the application starts) set as default props. We map over each color of state colors and for each color, we render a ‘Box’ component. BoxConatiner component also contains a method changeColor that is responsible to change the color of the box, each time a box is clicked. It generates a new random color until the new color value is not equal to the previous color of the box and updates the state colors by inserting that new color in place of the previous color value.JavascriptJavascriptimport React,{ Component } from 'react'import './BoxContainer.css'import Box from './Box'import { rgbValue, generateColors } from './helpers' class BoxContainer extends Component{ // Number of color boxes want shows by default static defaultProps = { num : 18 } constructor(props){ super(props) this.state = { // Color state contains array of rgb color values colors : generateColors(this.props.num) } this.changeColor = this.changeColor.bind(this) } changeColor(c){ // Create new random rgb color let newColor do{ newColor = `rgb( ${rgbValue()}, ${rgbValue()}, ${rgbValue()} )` // If new rgb color is equal to previous // color of the box then again create new // rgb color value }while(newColor === c) // Change colors array state by inserting // new color value in place of previous color this.setState(st => ({ colors : st.colors.map(color => { if(color !== c) return color return newColor }) })) } render(){ return( <div className='BoxContainer'> {this.state.colors.map(color => ( // For each color make a box component <Box color={color} changeColor={this.changeColor}/> ))} </div> ) }} export default BoxContainer
BoxContainer.js : It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of RGB color values. number of colors(number of color boxes want to render by when the application starts) set as default props. We map over each color of state colors and for each color, we render a ‘Box’ component. BoxConatiner component also contains a method changeColor that is responsible to change the color of the box, each time a box is clicked. It generates a new random color until the new color value is not equal to the previous color of the box and updates the state colors by inserting that new color in place of the previous color value.
Javascript
import React,{ Component } from 'react'import './BoxContainer.css'import Box from './Box'import { rgbValue, generateColors } from './helpers' class BoxContainer extends Component{ // Number of color boxes want shows by default static defaultProps = { num : 18 } constructor(props){ super(props) this.state = { // Color state contains array of rgb color values colors : generateColors(this.props.num) } this.changeColor = this.changeColor.bind(this) } changeColor(c){ // Create new random rgb color let newColor do{ newColor = `rgb( ${rgbValue()}, ${rgbValue()}, ${rgbValue()} )` // If new rgb color is equal to previous // color of the box then again create new // rgb color value }while(newColor === c) // Change colors array state by inserting // new color value in place of previous color this.setState(st => ({ colors : st.colors.map(color => { if(color !== c) return color return newColor }) })) } render(){ return( <div className='BoxContainer'> {this.state.colors.map(color => ( // For each color make a box component <Box color={color} changeColor={this.changeColor}/> ))} </div> ) }} export default BoxContainer
Coin.js : It is responsible to show each box with its proper color set in the background. It also set a click handler to each div component and executes a callback each time user clicks on the box. The click handler callback in return calls the changeColor method of the BoxContainer component passing the current color of the box. BoxContainer component communicates with the Coin component using the props system.JavascriptJavascriptimport React,{ Component } from 'react' class Box extends Component{ constructor(props){ super(props) this.handleChangeColor = this.handleChangeColor.bind(this) } // Handler callback handleChangeColor(){ // Call parent component cahngeColor method passing the // color value of div this.props.changeColor(this.props.color) } render(){ // Create a div component and assign the given / color value by BoxContainer component as its // background color return <div // Set click handler to the div and pass a callback onClick={this.handleChangeColor} style={{backgroundColor:this.props.color, width:'13em', height:'13em'}} /> }} export default Box
Coin.js : It is responsible to show each box with its proper color set in the background. It also set a click handler to each div component and executes a callback each time user clicks on the box. The click handler callback in return calls the changeColor method of the BoxContainer component passing the current color of the box. BoxContainer component communicates with the Coin component using the props system.
Javascript
import React,{ Component } from 'react' class Box extends Component{ constructor(props){ super(props) this.handleChangeColor = this.handleChangeColor.bind(this) } // Handler callback handleChangeColor(){ // Call parent component cahngeColor method passing the // color value of div this.props.changeColor(this.props.color) } render(){ // Create a div component and assign the given / color value by BoxContainer component as its // background color return <div // Set click handler to the div and pass a callback onClick={this.handleChangeColor} style={{backgroundColor:this.props.color, width:'13em', height:'13em'}} /> }} export default Box
helper.js : It creates and returns some helper function that is used in our main components.JavascriptJavascript// Method return a random number from 0 to 255 const rgbValue = () => { return Math.floor(Math.random() * 256)} // Method generates an array of rgb colorsconst generateColors = (num) => { let colors = [] for(let i=0; i<num; i++){ const red = rgbValue() const blue = rgbValue() const green = rgbValue() colors.push(`rgb(${red},${blue},${green})`) } return colors} export { rgbValue, generateColors }
helper.js : It creates and returns some helper function that is used in our main components.
Javascript
// Method return a random number from 0 to 255 const rgbValue = () => { return Math.floor(Math.random() * 256)} // Method generates an array of rgb colorsconst generateColors = (num) => { let colors = [] for(let i=0; i<num; i++){ const red = rgbValue() const blue = rgbValue() const green = rgbValue() colors.push(`rgb(${red},${blue},${green})`) } return colors} export { rgbValue, generateColors }
BoxContainer.css :CSSCSS.BoxContainer{ display:flex; flex-wrap:wrap; justify-content: center; align-items: center; flex:1}
BoxContainer.css :
CSS
.BoxContainer{ display:flex; flex-wrap:wrap; justify-content: center; align-items: center; flex:1}
Output :
Color Box
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 28387,
"s": 28359,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 28705,
"s": 28387,
"text": "Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its previous color value."
},
{
"code": null,
"e": 29597,
"s": 28705,
"text": "We create three components ‘App’ and ‘BoxContainer’ and ‘Box’. The app component renders a single BoxContainer component only. There is no actual logic put inside the App component. BoxContainer component contains all the behind logics. It has a default prop ‘num’ that accounts for a number of different color boxes shows to the screen. It is a stateful component and has a single state that contains an array of RGB color values. We map over each color of state ‘colors’ and for each color, we render a ‘Box’ component. The box component is responsible to show each individual boxes with their proper color set in the background of the box. The Box component sets a click event handler to each box component and when the user clicks on any box, some logic is executed that changes the color of that box. BoxContainer component uses the props system to communicate with the Box component."
},
{
"code": null,
"e": 29606,
"s": 29597,
"text": "Example:"
},
{
"code": null,
"e": 29775,
"s": 29606,
"text": "index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))"
},
{
"code": null,
"e": 29785,
"s": 29775,
"text": "index.js:"
},
{
"code": null,
"e": 29796,
"s": 29785,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 29936,
"s": 29796,
"text": null
},
{
"code": null,
"e": 30202,
"s": 29936,
"text": "App.js : App component renders single BoxContainer component onlyJavascriptJavascriptimport React from 'react';import BoxContainer from './BoxContainer' function App() { return ( <div className=\"App\"> <BoxContainer /> </div> );} export default App;"
},
{
"code": null,
"e": 30270,
"s": 30202,
"text": "App.js : App component renders single BoxContainer component only"
},
{
"code": null,
"e": 30281,
"s": 30270,
"text": "Javascript"
},
{
"code": "import React from 'react';import BoxContainer from './BoxContainer' function App() { return ( <div className=\"App\"> <BoxContainer /> </div> );} export default App;",
"e": 30460,
"s": 30281,
"text": null
},
{
"code": null,
"e": 32498,
"s": 30460,
"text": "BoxContainer.js : It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of RGB color values. number of colors(number of color boxes want to render by when the application starts) set as default props. We map over each color of state colors and for each color, we render a ‘Box’ component. BoxConatiner component also contains a method changeColor that is responsible to change the color of the box, each time a box is clicked. It generates a new random color until the new color value is not equal to the previous color of the box and updates the state colors by inserting that new color in place of the previous color value.JavascriptJavascriptimport React,{ Component } from 'react'import './BoxContainer.css'import Box from './Box'import { rgbValue, generateColors } from './helpers' class BoxContainer extends Component{ // Number of color boxes want shows by default static defaultProps = { num : 18 } constructor(props){ super(props) this.state = { // Color state contains array of rgb color values colors : generateColors(this.props.num) } this.changeColor = this.changeColor.bind(this) } changeColor(c){ // Create new random rgb color let newColor do{ newColor = `rgb( ${rgbValue()}, ${rgbValue()}, ${rgbValue()} )` // If new rgb color is equal to previous // color of the box then again create new // rgb color value }while(newColor === c) // Change colors array state by inserting // new color value in place of previous color this.setState(st => ({ colors : st.colors.map(color => { if(color !== c) return color return newColor }) })) } render(){ return( <div className='BoxContainer'> {this.state.colors.map(color => ( // For each color make a box component <Box color={color} changeColor={this.changeColor}/> ))} </div> ) }} export default BoxContainer"
},
{
"code": null,
"e": 33184,
"s": 32498,
"text": "BoxContainer.js : It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of RGB color values. number of colors(number of color boxes want to render by when the application starts) set as default props. We map over each color of state colors and for each color, we render a ‘Box’ component. BoxConatiner component also contains a method changeColor that is responsible to change the color of the box, each time a box is clicked. It generates a new random color until the new color value is not equal to the previous color of the box and updates the state colors by inserting that new color in place of the previous color value."
},
{
"code": null,
"e": 33195,
"s": 33184,
"text": "Javascript"
},
{
"code": "import React,{ Component } from 'react'import './BoxContainer.css'import Box from './Box'import { rgbValue, generateColors } from './helpers' class BoxContainer extends Component{ // Number of color boxes want shows by default static defaultProps = { num : 18 } constructor(props){ super(props) this.state = { // Color state contains array of rgb color values colors : generateColors(this.props.num) } this.changeColor = this.changeColor.bind(this) } changeColor(c){ // Create new random rgb color let newColor do{ newColor = `rgb( ${rgbValue()}, ${rgbValue()}, ${rgbValue()} )` // If new rgb color is equal to previous // color of the box then again create new // rgb color value }while(newColor === c) // Change colors array state by inserting // new color value in place of previous color this.setState(st => ({ colors : st.colors.map(color => { if(color !== c) return color return newColor }) })) } render(){ return( <div className='BoxContainer'> {this.state.colors.map(color => ( // For each color make a box component <Box color={color} changeColor={this.changeColor}/> ))} </div> ) }} export default BoxContainer",
"e": 34528,
"s": 33195,
"text": null
},
{
"code": null,
"e": 35698,
"s": 34528,
"text": "Coin.js : It is responsible to show each box with its proper color set in the background. It also set a click handler to each div component and executes a callback each time user clicks on the box. The click handler callback in return calls the changeColor method of the BoxContainer component passing the current color of the box. BoxContainer component communicates with the Coin component using the props system.JavascriptJavascriptimport React,{ Component } from 'react' class Box extends Component{ constructor(props){ super(props) this.handleChangeColor = this.handleChangeColor.bind(this) } // Handler callback handleChangeColor(){ // Call parent component cahngeColor method passing the // color value of div this.props.changeColor(this.props.color) } render(){ // Create a div component and assign the given / color value by BoxContainer component as its // background color return <div // Set click handler to the div and pass a callback onClick={this.handleChangeColor} style={{backgroundColor:this.props.color, width:'13em', height:'13em'}} /> }} export default Box"
},
{
"code": null,
"e": 36114,
"s": 35698,
"text": "Coin.js : It is responsible to show each box with its proper color set in the background. It also set a click handler to each div component and executes a callback each time user clicks on the box. The click handler callback in return calls the changeColor method of the BoxContainer component passing the current color of the box. BoxContainer component communicates with the Coin component using the props system."
},
{
"code": null,
"e": 36125,
"s": 36114,
"text": "Javascript"
},
{
"code": "import React,{ Component } from 'react' class Box extends Component{ constructor(props){ super(props) this.handleChangeColor = this.handleChangeColor.bind(this) } // Handler callback handleChangeColor(){ // Call parent component cahngeColor method passing the // color value of div this.props.changeColor(this.props.color) } render(){ // Create a div component and assign the given / color value by BoxContainer component as its // background color return <div // Set click handler to the div and pass a callback onClick={this.handleChangeColor} style={{backgroundColor:this.props.color, width:'13em', height:'13em'}} /> }} export default Box",
"e": 36860,
"s": 36125,
"text": null
},
{
"code": null,
"e": 37394,
"s": 36860,
"text": "helper.js : It creates and returns some helper function that is used in our main components.JavascriptJavascript// Method return a random number from 0 to 255 const rgbValue = () => { return Math.floor(Math.random() * 256)} // Method generates an array of rgb colorsconst generateColors = (num) => { let colors = [] for(let i=0; i<num; i++){ const red = rgbValue() const blue = rgbValue() const green = rgbValue() colors.push(`rgb(${red},${blue},${green})`) } return colors} export { rgbValue, generateColors }"
},
{
"code": null,
"e": 37487,
"s": 37394,
"text": "helper.js : It creates and returns some helper function that is used in our main components."
},
{
"code": null,
"e": 37498,
"s": 37487,
"text": "Javascript"
},
{
"code": "// Method return a random number from 0 to 255 const rgbValue = () => { return Math.floor(Math.random() * 256)} // Method generates an array of rgb colorsconst generateColors = (num) => { let colors = [] for(let i=0; i<num; i++){ const red = rgbValue() const blue = rgbValue() const green = rgbValue() colors.push(`rgb(${red},${blue},${green})`) } return colors} export { rgbValue, generateColors }",
"e": 37920,
"s": 37498,
"text": null
},
{
"code": null,
"e": 38048,
"s": 37920,
"text": "BoxContainer.css :CSSCSS.BoxContainer{ display:flex; flex-wrap:wrap; justify-content: center; align-items: center; flex:1}"
},
{
"code": null,
"e": 38067,
"s": 38048,
"text": "BoxContainer.css :"
},
{
"code": null,
"e": 38071,
"s": 38067,
"text": "CSS"
},
{
"code": ".BoxContainer{ display:flex; flex-wrap:wrap; justify-content: center; align-items: center; flex:1}",
"e": 38175,
"s": 38071,
"text": null
},
{
"code": null,
"e": 38184,
"s": 38175,
"text": "Output :"
},
{
"code": null,
"e": 38194,
"s": 38184,
"text": "Color Box"
},
{
"code": null,
"e": 38203,
"s": 38194,
"text": "react-js"
},
{
"code": null,
"e": 38220,
"s": 38203,
"text": "Web Technologies"
},
{
"code": null,
"e": 38318,
"s": 38220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38358,
"s": 38318,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 38391,
"s": 38358,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 38436,
"s": 38391,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38479,
"s": 38436,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 38529,
"s": 38479,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38590,
"s": 38529,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 38652,
"s": 38590,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 38710,
"s": 38652,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 38743,
"s": 38710,
"text": "Node.js fs.readFileSync() Method"
}
] |
How to remove specific elements from a NumPy array ? - GeeksforGeeks | 21 Apr, 2021
In this article, we will discuss how to remove specific element from the NumPy Array. The delete() method will be used to do the same.
Syntax:
numpy.delete(array_name,index_value)
Where array_name is the name of the array to be deleted and index-value is the index of the element to be deleted.
For example, we are having an array with 5 elements,
array1=[1,2,3,4,5]
The indexing starts from 0 to n-1. If we want to delete 2, then 2 element index is 1. So, we can specify
np.delete(array1,1)
If we want to delete multiple elements i.e. 1,2,3,4,5 at a time, you can specify all index elements in a list.
np.delete(array1,[0,1,2,3,4])
Below are some examples where we remove specific elements in a NumPy array.
Example 1:
Program to create an array with 5 elements and delete 1st element.
Python3
# import numpy as npimport numpy as np # create an array with 5 elementsa = np.array([1, 2, 3, 4, 5]) # display aprint(a) # delete 1 st elementprint("remaining elements after deleting 1st element ", np.delete(a, 0))
Output:
[1 2 3 4 5]
remaining elements after deleting 1st element [2 3 4 5]
Example 2:
Program to create an array with 5 elements and delete 1st and last element.
Python3
# import numpy as npimport numpy as np # create an array with 5 # elementsa = np.array([1, 2, 3, 4, 5]) # display aprint(a) # delete 1 st elementprint("remaining elements after deleting 1st and last element ", np.delete(a, [0, 4]))
Output:
[1 2 3 4 5]
remaining elements after deleting 1st and last element [2 3 4]
Example 3:
Deleting 4th element.
Python3
#import numpy as npimport numpy as np # create an array with 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # display aprint(a) # delete 4 th elementprint("remaining elements after deleting 4th element ", np.delete(a, 3))
Output:
[ 1 2 3 4 5 6 7 8 9 10]
remaining elements after deleting 4th element [ 1 2 3 5 6 7 8 9 10]
Picked
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25690,
"s": 25555,
"text": "In this article, we will discuss how to remove specific element from the NumPy Array. The delete() method will be used to do the same."
},
{
"code": null,
"e": 25698,
"s": 25690,
"text": "Syntax:"
},
{
"code": null,
"e": 25735,
"s": 25698,
"text": "numpy.delete(array_name,index_value)"
},
{
"code": null,
"e": 25850,
"s": 25735,
"text": "Where array_name is the name of the array to be deleted and index-value is the index of the element to be deleted."
},
{
"code": null,
"e": 25904,
"s": 25850,
"text": "For example, we are having an array with 5 elements, "
},
{
"code": null,
"e": 25923,
"s": 25904,
"text": "array1=[1,2,3,4,5]"
},
{
"code": null,
"e": 26029,
"s": 25923,
"text": "The indexing starts from 0 to n-1. If we want to delete 2, then 2 element index is 1. So, we can specify "
},
{
"code": null,
"e": 26049,
"s": 26029,
"text": "np.delete(array1,1)"
},
{
"code": null,
"e": 26160,
"s": 26049,
"text": "If we want to delete multiple elements i.e. 1,2,3,4,5 at a time, you can specify all index elements in a list."
},
{
"code": null,
"e": 26190,
"s": 26160,
"text": "np.delete(array1,[0,1,2,3,4])"
},
{
"code": null,
"e": 26267,
"s": 26190,
"text": "Below are some examples where we remove specific elements in a NumPy array. "
},
{
"code": null,
"e": 26278,
"s": 26267,
"text": "Example 1:"
},
{
"code": null,
"e": 26345,
"s": 26278,
"text": "Program to create an array with 5 elements and delete 1st element."
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Python3"
},
{
"code": "# import numpy as npimport numpy as np # create an array with 5 elementsa = np.array([1, 2, 3, 4, 5]) # display aprint(a) # delete 1 st elementprint(\"remaining elements after deleting 1st element \", np.delete(a, 0))",
"e": 26577,
"s": 26353,
"text": null
},
{
"code": null,
"e": 26585,
"s": 26577,
"text": "Output:"
},
{
"code": null,
"e": 26654,
"s": 26585,
"text": "[1 2 3 4 5]\nremaining elements after deleting 1st element [2 3 4 5]"
},
{
"code": null,
"e": 26665,
"s": 26654,
"text": "Example 2:"
},
{
"code": null,
"e": 26741,
"s": 26665,
"text": "Program to create an array with 5 elements and delete 1st and last element."
},
{
"code": null,
"e": 26749,
"s": 26741,
"text": "Python3"
},
{
"code": "# import numpy as npimport numpy as np # create an array with 5 # elementsa = np.array([1, 2, 3, 4, 5]) # display aprint(a) # delete 1 st elementprint(\"remaining elements after deleting 1st and last element \", np.delete(a, [0, 4]))",
"e": 26989,
"s": 26749,
"text": null
},
{
"code": null,
"e": 26997,
"s": 26989,
"text": "Output:"
},
{
"code": null,
"e": 27073,
"s": 26997,
"text": "[1 2 3 4 5]\nremaining elements after deleting 1st and last element [2 3 4]"
},
{
"code": null,
"e": 27084,
"s": 27073,
"text": "Example 3:"
},
{
"code": null,
"e": 27106,
"s": 27084,
"text": "Deleting 4th element."
},
{
"code": null,
"e": 27114,
"s": 27106,
"text": "Python3"
},
{
"code": "#import numpy as npimport numpy as np # create an array with 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # display aprint(a) # delete 4 th elementprint(\"remaining elements after deleting 4th element \", np.delete(a, 3))",
"e": 27356,
"s": 27114,
"text": null
},
{
"code": null,
"e": 27364,
"s": 27356,
"text": "Output:"
},
{
"code": null,
"e": 27396,
"s": 27364,
"text": "[ 1 2 3 4 5 6 7 8 9 10]"
},
{
"code": null,
"e": 27472,
"s": 27396,
"text": "remaining elements after deleting 4th element [ 1 2 3 5 6 7 8 9 10]"
},
{
"code": null,
"e": 27479,
"s": 27472,
"text": "Picked"
},
{
"code": null,
"e": 27501,
"s": 27479,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 27514,
"s": 27501,
"text": "Python-numpy"
},
{
"code": null,
"e": 27521,
"s": 27514,
"text": "Python"
},
{
"code": null,
"e": 27619,
"s": 27521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27651,
"s": 27619,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27693,
"s": 27651,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27735,
"s": 27693,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27791,
"s": 27735,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27818,
"s": 27791,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27849,
"s": 27818,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27888,
"s": 27849,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27917,
"s": 27888,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27939,
"s": 27917,
"text": "Defaultdict in Python"
}
] |
Python - Flatten tuple of List to tuple - GeeksforGeeks | 22 Jun, 2020
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have lists as its constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple = ([5], [6], [3], [8])Output : (5, 6, 3, 8)
Input : test_tuple = ([5, 7, 8])Output : (5, 7, 8)
Method #1 : Using sum() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum(), passing empty list as its argument.
# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using sum() + tuple() # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3]) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Flatten tuple of List to tuple# Using sum() + tuple()res = tuple(sum(test_tuple, [])) # printing result print("The flattened tuple : " + str(res))
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Method #2 : Using tuple() + chain.from_iterable()The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable() and conversion to tuple using tuple().
# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()from itertools import chain # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3]) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()res = tuple(chain.from_iterable(test_tuple)) # printing result print("The flattened tuple : " + str(res))
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26103,
"s": 26075,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 26407,
"s": 26103,
"text": "Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have lists as its constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26470,
"s": 26407,
"text": "Input : test_tuple = ([5], [6], [3], [8])Output : (5, 6, 3, 8)"
},
{
"code": null,
"e": 26521,
"s": 26470,
"text": "Input : test_tuple = ([5, 7, 8])Output : (5, 7, 8)"
},
{
"code": null,
"e": 26716,
"s": 26521,
"text": "Method #1 : Using sum() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum(), passing empty list as its argument."
},
{
"code": "# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using sum() + tuple() # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3]) # printing original tupleprint(\"The original tuple : \" + str(test_tuple)) # Flatten tuple of List to tuple# Using sum() + tuple()res = tuple(sum(test_tuple, [])) # printing result print(\"The flattened tuple : \" + str(res))",
"e": 27101,
"s": 26716,
"text": null
},
{
"code": null,
"e": 27195,
"s": 27101,
"text": "The original tuple : ([5, 6], [6, 7, 8, 9], [3])\nThe flattened tuple : (5, 6, 6, 7, 8, 9, 3)\n"
},
{
"code": null,
"e": 27416,
"s": 27197,
"text": "Method #2 : Using tuple() + chain.from_iterable()The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable() and conversion to tuple using tuple()."
},
{
"code": "# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()from itertools import chain # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3]) # printing original tupleprint(\"The original tuple : \" + str(test_tuple)) # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()res = tuple(chain.from_iterable(test_tuple)) # printing result print(\"The flattened tuple : \" + str(res))",
"e": 27872,
"s": 27416,
"text": null
},
{
"code": null,
"e": 27966,
"s": 27872,
"text": "The original tuple : ([5, 6], [6, 7, 8, 9], [3])\nThe flattened tuple : (5, 6, 6, 7, 8, 9, 3)\n"
},
{
"code": null,
"e": 27988,
"s": 27966,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27995,
"s": 27988,
"text": "Python"
},
{
"code": null,
"e": 28011,
"s": 27995,
"text": "Python Programs"
},
{
"code": null,
"e": 28109,
"s": 28011,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28127,
"s": 28109,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28159,
"s": 28127,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28181,
"s": 28159,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28223,
"s": 28181,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28253,
"s": 28223,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28296,
"s": 28253,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28318,
"s": 28296,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28357,
"s": 28318,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28403,
"s": 28357,
"text": "Python | Split string into list of characters"
}
] |
if command in linux with examples - GeeksforGeeks | 22 May, 2019
if is a command in Linux which is used to execute commands based on conditions. The ‘if COMMANDS‘ list is executed. If its status is zero, then the ‘then COMMANDS‘ list is executed. Otherwise, each ‘elif COMMANDS‘ list is executed in turn, and if its exit status is zero, the corresponding ‘then COMMANDS‘ list is executed and the if command completes. Otherwise, the ‘else COMMANDS‘ list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true.
Syntax:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Example:
Options:
help if : It displays help information.
linux-command
Linux-misc-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
scp command in Linux with Examples | [
{
"code": null,
"e": 25879,
"s": 25851,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 26419,
"s": 25879,
"text": "if is a command in Linux which is used to execute commands based on conditions. The ‘if COMMANDS‘ list is executed. If its status is zero, then the ‘then COMMANDS‘ list is executed. Otherwise, each ‘elif COMMANDS‘ list is executed in turn, and if its exit status is zero, the corresponding ‘then COMMANDS‘ list is executed and the if command completes. Otherwise, the ‘else COMMANDS‘ list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true."
},
{
"code": null,
"e": 26427,
"s": 26419,
"text": "Syntax:"
},
{
"code": null,
"e": 26518,
"s": 26427,
"text": "if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi"
},
{
"code": null,
"e": 26527,
"s": 26518,
"text": "Example:"
},
{
"code": null,
"e": 26536,
"s": 26527,
"text": "Options:"
},
{
"code": null,
"e": 26576,
"s": 26536,
"text": "help if : It displays help information."
},
{
"code": null,
"e": 26590,
"s": 26576,
"text": "linux-command"
},
{
"code": null,
"e": 26610,
"s": 26590,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 26621,
"s": 26610,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26640,
"s": 26621,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26738,
"s": 26640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26773,
"s": 26738,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26806,
"s": 26773,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 26842,
"s": 26806,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 26880,
"s": 26842,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26916,
"s": 26880,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26951,
"s": 26916,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26988,
"s": 26951,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 27024,
"s": 26988,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 27043,
"s": 27024,
"text": "Compiling with g++"
}
] |
K-th Smallest Element in an Unsorted Array using Priority Queue - GeeksforGeeks | 22 Jul, 2021
Given an array arr[] consisting of N integers and an integer K, the task is to find the Kth smallest element in the array using Priority Queue.
Examples:
Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 2Output: 5Explanation: In the given array, the 2nd smallest element is 5. Therefore, the required output is 5.
Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 5Output: 20Explanation: In the given array, the 5th smallest element is 20. Therefore, the required output is 20.
Approach: The idea is to use PriorityQueue Collection in Java or priority_queue STL library to implement Max_Heap to find the Kth smallest array element. Follow the steps below to solve the problem:
Implement Max Heap using a priority_queue.Push first K array elements into the priority_queue.From there on, after every insertion of an array element, pop the element at the top of the priority_queue.After complete traversal of the array, print the element at the top of the priority queue as the required answer.
Implement Max Heap using a priority_queue.
Push first K array elements into the priority_queue.
From there on, after every insertion of an array element, pop the element at the top of the priority_queue.
After complete traversal of the array, print the element at the top of the priority queue as the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find kth smallest array elementvoid kthSmallest(vector<int>& v, int N, int K){ // Implement Max Heap using // a Priority Queue priority_queue<int> heap1; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.push(v[i]); // If size of the priority // queue exceeds k if (heap1.size() > K) { heap1.pop(); } } // Print the k-th smallest element cout << heap1.top() << endl;} // Driver codeint main(){ // Given array vector<int> vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.size(); // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N); return 0;}
// Java program for the above approachimport java.util.*;class CustomComparator implements Comparator<Integer> { @Override public int compare(Integer number1, Integer number2) { int value = number1.compareTo(number2); // elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } }}class GFG{ // Function to find kth smallest array elementstatic void kthSmallest(int []v, int N, int K){ // Implement Max Heap using // a Priority Queue PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>(new CustomComparator()); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.add(v[i]); // If size of the priority // queue exceeds k if (heap1.size() > K) { heap1.remove(); } } // Print the k-th smallest element System.out.print(heap1.peek() +"\n");} // Driver codepublic static void main(String[] args){ // Given array int []vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.length; // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find kth smallest array elementdef kthSmallest(v, N, K): # Implement Max Heap using # a Priority Queue heap1 = [] for i in range(N): # Insert elements into # the priority queue heap1.append(v[i]) # If size of the priority # queue exceeds k if (len(heap1) > K): heap1.sort() heap1.reverse() del heap1[0] # Print the k-th smallest element heap1.sort() heap1.reverse() print(heap1[0]) # Driver code # Given arrayvec = [ 5, 20, 10, 7, 1 ] # Size of arrayN = len(vec) # Given KK = 2 # Function CallkthSmallest(vec, N, K % N) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find kth smallest array elementstatic void kthSmallest(int []v, int N, int K){ // Implement Max Heap using // a Priority Queue List<int> heap1 = new List<int>(); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.Add(v[i]); // If size of the priority // queue exceeds k if (heap1.Count > K) { heap1.Sort(); heap1.Reverse(); heap1.RemoveAt(0); } } heap1.Sort(); heap1.Reverse(); // Print the k-th smallest element Console.WriteLine(heap1[0]);} // Driver codepublic static void Main(String[] args){ // Given array int []vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.Length; // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N);}} // This code is contributed by gauravrajput1
<script>// Javascript program for the above approach // Function to find kth smallest array elementfunction kthSmallest(v,N,K){ let heap1 = []; for (let i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.push(v[i]); // If size of the priority // queue exceeds k if (heap1.length > K) { heap1.sort(function(a,b){ return a-b; }); heap1.reverse(); heap1.shift(); } } heap1.sort(function(a,b){ return a-b; }); heap1.reverse(); // Print the k-th smallest element document.write(heap1[0] +"<br>");} // Driver code// Given arraylet vec=[5, 20, 10, 7, 1 ];// Size of arraylet N = vec.length; // Given Klet K = 2; // Function CallkthSmallest(vec, N, K % N); // This code is contributed by patel2127</script>
5
Time Complexity: O(N LogK)Auxiliary Space: O(K), since the priority queue ay any time holds at max k elements.
amit143katiyar
GauravRajput1
divyeshrabadiya07
patel2127
ruhelaa48
cpp-priority-queue
cpp-vector
Heap Sort
Arrays
Heap
Queue
Sorting
Arrays
Sorting
Queue
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
Building Heap from Array
Insertion and Deletion in Heaps | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 26209,
"s": 26065,
"text": "Given an array arr[] consisting of N integers and an integer K, the task is to find the Kth smallest element in the array using Priority Queue."
},
{
"code": null,
"e": 26219,
"s": 26209,
"text": "Examples:"
},
{
"code": null,
"e": 26375,
"s": 26219,
"text": "Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 2Output: 5Explanation: In the given array, the 2nd smallest element is 5. Therefore, the required output is 5."
},
{
"code": null,
"e": 26534,
"s": 26375,
"text": "Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 5Output: 20Explanation: In the given array, the 5th smallest element is 20. Therefore, the required output is 20."
},
{
"code": null,
"e": 26733,
"s": 26534,
"text": "Approach: The idea is to use PriorityQueue Collection in Java or priority_queue STL library to implement Max_Heap to find the Kth smallest array element. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27048,
"s": 26733,
"text": "Implement Max Heap using a priority_queue.Push first K array elements into the priority_queue.From there on, after every insertion of an array element, pop the element at the top of the priority_queue.After complete traversal of the array, print the element at the top of the priority queue as the required answer."
},
{
"code": null,
"e": 27091,
"s": 27048,
"text": "Implement Max Heap using a priority_queue."
},
{
"code": null,
"e": 27144,
"s": 27091,
"text": "Push first K array elements into the priority_queue."
},
{
"code": null,
"e": 27252,
"s": 27144,
"text": "From there on, after every insertion of an array element, pop the element at the top of the priority_queue."
},
{
"code": null,
"e": 27366,
"s": 27252,
"text": "After complete traversal of the array, print the element at the top of the priority queue as the required answer."
},
{
"code": null,
"e": 27417,
"s": 27366,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27421,
"s": 27417,
"text": "C++"
},
{
"code": null,
"e": 27426,
"s": 27421,
"text": "Java"
},
{
"code": null,
"e": 27434,
"s": 27426,
"text": "Python3"
},
{
"code": null,
"e": 27437,
"s": 27434,
"text": "C#"
},
{
"code": null,
"e": 27448,
"s": 27437,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find kth smallest array elementvoid kthSmallest(vector<int>& v, int N, int K){ // Implement Max Heap using // a Priority Queue priority_queue<int> heap1; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.push(v[i]); // If size of the priority // queue exceeds k if (heap1.size() > K) { heap1.pop(); } } // Print the k-th smallest element cout << heap1.top() << endl;} // Driver codeint main(){ // Given array vector<int> vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.size(); // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N); return 0;}",
"e": 28257,
"s": 27448,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class CustomComparator implements Comparator<Integer> { @Override public int compare(Integer number1, Integer number2) { int value = number1.compareTo(number2); // elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } }}class GFG{ // Function to find kth smallest array elementstatic void kthSmallest(int []v, int N, int K){ // Implement Max Heap using // a Priority Queue PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>(new CustomComparator()); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.add(v[i]); // If size of the priority // queue exceeds k if (heap1.size() > K) { heap1.remove(); } } // Print the k-th smallest element System.out.print(heap1.peek() +\"\\n\");} // Driver codepublic static void main(String[] args){ // Given array int []vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.length; // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N);}} // This code is contributed by Amit Katiyar",
"e": 29564,
"s": 28257,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find kth smallest array elementdef kthSmallest(v, N, K): # Implement Max Heap using # a Priority Queue heap1 = [] for i in range(N): # Insert elements into # the priority queue heap1.append(v[i]) # If size of the priority # queue exceeds k if (len(heap1) > K): heap1.sort() heap1.reverse() del heap1[0] # Print the k-th smallest element heap1.sort() heap1.reverse() print(heap1[0]) # Driver code # Given arrayvec = [ 5, 20, 10, 7, 1 ] # Size of arrayN = len(vec) # Given KK = 2 # Function CallkthSmallest(vec, N, K % N) # This code is contributed by divyeshrabadiya07",
"e": 30306,
"s": 29564,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find kth smallest array elementstatic void kthSmallest(int []v, int N, int K){ // Implement Max Heap using // a Priority Queue List<int> heap1 = new List<int>(); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.Add(v[i]); // If size of the priority // queue exceeds k if (heap1.Count > K) { heap1.Sort(); heap1.Reverse(); heap1.RemoveAt(0); } } heap1.Sort(); heap1.Reverse(); // Print the k-th smallest element Console.WriteLine(heap1[0]);} // Driver codepublic static void Main(String[] args){ // Given array int []vec = { 5, 20, 10, 7, 1 }; // Size of array int N = vec.Length; // Given K int K = 2; // Function Call kthSmallest(vec, N, K % N);}} // This code is contributed by gauravrajput1",
"e": 31294,
"s": 30306,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find kth smallest array elementfunction kthSmallest(v,N,K){ let heap1 = []; for (let i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.push(v[i]); // If size of the priority // queue exceeds k if (heap1.length > K) { heap1.sort(function(a,b){ return a-b; }); heap1.reverse(); heap1.shift(); } } heap1.sort(function(a,b){ return a-b; }); heap1.reverse(); // Print the k-th smallest element document.write(heap1[0] +\"<br>\");} // Driver code// Given arraylet vec=[5, 20, 10, 7, 1 ];// Size of arraylet N = vec.length; // Given Klet K = 2; // Function CallkthSmallest(vec, N, K % N); // This code is contributed by patel2127</script>",
"e": 32198,
"s": 31294,
"text": null
},
{
"code": null,
"e": 32200,
"s": 32198,
"text": "5"
},
{
"code": null,
"e": 32313,
"s": 32202,
"text": "Time Complexity: O(N LogK)Auxiliary Space: O(K), since the priority queue ay any time holds at max k elements."
},
{
"code": null,
"e": 32328,
"s": 32313,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32342,
"s": 32328,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32360,
"s": 32342,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32370,
"s": 32360,
"text": "patel2127"
},
{
"code": null,
"e": 32380,
"s": 32370,
"text": "ruhelaa48"
},
{
"code": null,
"e": 32399,
"s": 32380,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 32410,
"s": 32399,
"text": "cpp-vector"
},
{
"code": null,
"e": 32420,
"s": 32410,
"text": "Heap Sort"
},
{
"code": null,
"e": 32427,
"s": 32420,
"text": "Arrays"
},
{
"code": null,
"e": 32432,
"s": 32427,
"text": "Heap"
},
{
"code": null,
"e": 32438,
"s": 32432,
"text": "Queue"
},
{
"code": null,
"e": 32446,
"s": 32438,
"text": "Sorting"
},
{
"code": null,
"e": 32453,
"s": 32446,
"text": "Arrays"
},
{
"code": null,
"e": 32461,
"s": 32453,
"text": "Sorting"
},
{
"code": null,
"e": 32467,
"s": 32461,
"text": "Queue"
},
{
"code": null,
"e": 32472,
"s": 32467,
"text": "Heap"
},
{
"code": null,
"e": 32570,
"s": 32472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32597,
"s": 32570,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32628,
"s": 32597,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32653,
"s": 32628,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32691,
"s": 32653,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32712,
"s": 32691,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32721,
"s": 32712,
"text": "HeapSort"
},
{
"code": null,
"e": 32733,
"s": 32721,
"text": "Binary Heap"
},
{
"code": null,
"e": 32764,
"s": 32733,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 32789,
"s": 32764,
"text": "Building Heap from Array"
}
] |
HTML Editors - GeeksforGeeks | 24 Mar, 2022
HTML text editors are used to create and modify web pages. HTML codes can be written in any text editors including the notepad. One just needs to write HTML in any text editor and save the file with an extension “.html”. Some of the popular HTML text editors are given below:
Notepad
Notepad++
Sublime Text 3
Atom
GeeksforGeeks IDE
Notepad: Notepad is a simple text editor. It is an inbuilt desktop application available in Windows OS.
Bracket: Bracket is an open-source software primarily used for Web development. It provides live HTML, CSS, JavaScript editing functionality.
Sublime Text 3: Sublime is a cross platform code editor tool. It supports all markup languages.
Atom: Atom is an open source code editor tool for MAC, Linux and Windows.
Steps to write HTML code in Editor:
Open any of the text editors of your choice. Here we are using the notepad text editor.Create new file: File->New File or Ctrl+N.Write HTML code in text editor.Save the file with a suitable name of your choice and .html extension.Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”).
Open any of the text editors of your choice. Here we are using the notepad text editor.
Create new file: File->New File or Ctrl+N.
Write HTML code in text editor.
Save the file with a suitable name of your choice and .html extension.
Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”).
GeeksforGeeks IDE: It is an online code editor to test the code. It provides the shareable link to share code with others.
<html> <head> <title>HTML Text Editor</title> <style> h1 { color:#009900; } </style> </head> <body> <h1>GeeksforGeeks</h1> </body></html>
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 31645,
"s": 31617,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 31921,
"s": 31645,
"text": "HTML text editors are used to create and modify web pages. HTML codes can be written in any text editors including the notepad. One just needs to write HTML in any text editor and save the file with an extension “.html”. Some of the popular HTML text editors are given below:"
},
{
"code": null,
"e": 31929,
"s": 31921,
"text": "Notepad"
},
{
"code": null,
"e": 31939,
"s": 31929,
"text": "Notepad++"
},
{
"code": null,
"e": 31954,
"s": 31939,
"text": "Sublime Text 3"
},
{
"code": null,
"e": 31959,
"s": 31954,
"text": "Atom"
},
{
"code": null,
"e": 31977,
"s": 31959,
"text": "GeeksforGeeks IDE"
},
{
"code": null,
"e": 32081,
"s": 31977,
"text": "Notepad: Notepad is a simple text editor. It is an inbuilt desktop application available in Windows OS."
},
{
"code": null,
"e": 32223,
"s": 32081,
"text": "Bracket: Bracket is an open-source software primarily used for Web development. It provides live HTML, CSS, JavaScript editing functionality."
},
{
"code": null,
"e": 32319,
"s": 32223,
"text": "Sublime Text 3: Sublime is a cross platform code editor tool. It supports all markup languages."
},
{
"code": null,
"e": 32393,
"s": 32319,
"text": "Atom: Atom is an open source code editor tool for MAC, Linux and Windows."
},
{
"code": null,
"e": 32429,
"s": 32393,
"text": "Steps to write HTML code in Editor:"
},
{
"code": null,
"e": 32779,
"s": 32429,
"text": "Open any of the text editors of your choice. Here we are using the notepad text editor.Create new file: File->New File or Ctrl+N.Write HTML code in text editor.Save the file with a suitable name of your choice and .html extension.Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”)."
},
{
"code": null,
"e": 32867,
"s": 32779,
"text": "Open any of the text editors of your choice. Here we are using the notepad text editor."
},
{
"code": null,
"e": 32910,
"s": 32867,
"text": "Create new file: File->New File or Ctrl+N."
},
{
"code": null,
"e": 32942,
"s": 32910,
"text": "Write HTML code in text editor."
},
{
"code": null,
"e": 33013,
"s": 32942,
"text": "Save the file with a suitable name of your choice and .html extension."
},
{
"code": null,
"e": 33133,
"s": 33013,
"text": "Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”)."
},
{
"code": null,
"e": 33256,
"s": 33133,
"text": "GeeksforGeeks IDE: It is an online code editor to test the code. It provides the shareable link to share code with others."
},
{
"code": "<html> <head> <title>HTML Text Editor</title> <style> h1 { color:#009900; } </style> </head> <body> <h1>GeeksforGeeks</h1> </body></html>",
"e": 33431,
"s": 33256,
"text": null
},
{
"code": null,
"e": 33568,
"s": 33431,
"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": 33575,
"s": 33568,
"text": "Picked"
},
{
"code": null,
"e": 33580,
"s": 33575,
"text": "HTML"
},
{
"code": null,
"e": 33597,
"s": 33580,
"text": "Web Technologies"
},
{
"code": null,
"e": 33602,
"s": 33597,
"text": "HTML"
},
{
"code": null,
"e": 33700,
"s": 33602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33750,
"s": 33700,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33812,
"s": 33750,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33860,
"s": 33812,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 33920,
"s": 33860,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33973,
"s": 33920,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 34013,
"s": 33973,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34046,
"s": 34013,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34091,
"s": 34046,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34134,
"s": 34091,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference between PC relative and Base register Addressing Modes - GeeksforGeeks | 10 Apr, 2020
Prerequisite – Addressing Modes
1. PC relative addressing mode:PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.
EA = PC + Address field value
PC = PC + Relative value
2. Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control. In this mode effective address is obtained by adding base register value to address field value.
EA = Base register + Address field value
PC = Base register + Relative value
Difference between PC Relative And Base Register Addressing modes:
Picked
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 26025,
"s": 25997,
"text": "\n10 Apr, 2020"
},
{
"code": null,
"e": 26057,
"s": 26025,
"text": "Prerequisite – Addressing Modes"
},
{
"code": null,
"e": 26245,
"s": 26057,
"text": "1. PC relative addressing mode:PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC."
},
{
"code": null,
"e": 26301,
"s": 26245,
"text": "EA = PC + Address field value\nPC = PC + Relative value "
},
{
"code": null,
"e": 26517,
"s": 26301,
"text": "2. Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control. In this mode effective address is obtained by adding base register value to address field value."
},
{
"code": null,
"e": 26595,
"s": 26517,
"text": "EA = Base register + Address field value\nPC = Base register + Relative value "
},
{
"code": null,
"e": 26662,
"s": 26595,
"text": "Difference between PC Relative And Base Register Addressing modes:"
},
{
"code": null,
"e": 26669,
"s": 26662,
"text": "Picked"
},
{
"code": null,
"e": 26706,
"s": 26669,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 26725,
"s": 26706,
"text": "Difference Between"
},
{
"code": null,
"e": 26733,
"s": 26725,
"text": "GATE CS"
},
{
"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": 26893,
"s": 26831,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 26984,
"s": 26893,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 27020,
"s": 26984,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27055,
"s": 27020,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 27082,
"s": 27055,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 27113,
"s": 27082,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27153,
"s": 27113,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27185,
"s": 27153,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27246,
"s": 27185,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Polymorphism in Java - GeeksforGeeks | 14 Dec, 2021
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
Real-life Illustration: Polymorphism
A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism. Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.
Types of polymorphism
In Java polymorphism is mainly divided into two types:
Compile-time Polymorphism
Runtime Polymorphism
Type 1: Compile-time polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading: When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in the number of arguments or/and a change in the type of arguments.
Example 1
Java
// Java Program for Method overloading// By using Different Types of Arguments // Class 1// Helper classclass Helper { // Method with 2 integer parameters static int Multiply(int a, int b) { // Returns product of integer numbers return a * b; } // Method 2 // With same name but with 2 double parameters static double Multiply(double a, double b) { // Returns product of double numbers return a * b; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2, 4)); System.out.println(Helper.Multiply(5.5, 6.3)); }}
8
34.65
Example 2
Java
// Java program for Method Overloading// by Using Different Numbers of Arguments // Class 1// Helper classclass Helper { // Method 1 // Multiplication of 2 numbers static int Multiply(int a, int b) { // Return product return a * b; } // Method 2 // // Multiplication of 3 numbers static int Multiply(int a, int b, int c) { // Return product return a * b * c; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2, 4)); System.out.println(Helper.Multiply(2, 7, 3)); }}
8
42
Type 2: Runtime polymorphism
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
Example
Java
// Java Program for Method Overriding // Class 1// Helper classclass Parent { // Method of parent class void Print() { // Print statement System.out.println("parent class"); }} // Class 2// Helper classclass subclass1 extends Parent { // Method void Print() { System.out.println("subclass1"); }} // Class 3// Helper classclass subclass2 extends Parent { // Method void Print() { // Print statement System.out.println("subclass2"); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 Parent a; // Now we will be calling print methods // inside main() method a = new subclass1(); a.Print(); a = new subclass2(); a.Print(); }}
subclass1
subclass2
Output explanation:
Here in this program, When an object of child class is created, then the method inside the child class is called. This is because The method in the parent class is overridden by the child class. Since The method is overridden, This method has more priority than the parent method inside the child class. So, the body inside the child class is executed.
bajracharyakshitij
rocklinglokesh
Java-Object Oriented
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Stream In Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
Initializing a List in Java
Different ways of Reading a text file in Java
Generics in Java | [
{
"code": null,
"e": 30195,
"s": 30167,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 30354,
"s": 30195,
"text": "The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. "
},
{
"code": null,
"e": 30391,
"s": 30354,
"text": "Real-life Illustration: Polymorphism"
},
{
"code": null,
"e": 30954,
"s": 30391,
"text": "A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism. Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms."
},
{
"code": null,
"e": 30976,
"s": 30954,
"text": "Types of polymorphism"
},
{
"code": null,
"e": 31032,
"s": 30976,
"text": "In Java polymorphism is mainly divided into two types: "
},
{
"code": null,
"e": 31058,
"s": 31032,
"text": "Compile-time Polymorphism"
},
{
"code": null,
"e": 31079,
"s": 31058,
"text": "Runtime Polymorphism"
},
{
"code": null,
"e": 31113,
"s": 31079,
"text": "Type 1: Compile-time polymorphism"
},
{
"code": null,
"e": 31242,
"s": 31113,
"text": "It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. "
},
{
"code": null,
"e": 31299,
"s": 31242,
"text": "Note: But Java doesn’t support the Operator Overloading."
},
{
"code": null,
"e": 31552,
"s": 31299,
"text": "Method Overloading: When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in the number of arguments or/and a change in the type of arguments."
},
{
"code": null,
"e": 31563,
"s": 31552,
"text": "Example 1 "
},
{
"code": null,
"e": 31568,
"s": 31563,
"text": "Java"
},
{
"code": "// Java Program for Method overloading// By using Different Types of Arguments // Class 1// Helper classclass Helper { // Method with 2 integer parameters static int Multiply(int a, int b) { // Returns product of integer numbers return a * b; } // Method 2 // With same name but with 2 double parameters static double Multiply(double a, double b) { // Returns product of double numbers return a * b; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2, 4)); System.out.println(Helper.Multiply(5.5, 6.3)); }}",
"e": 32318,
"s": 31568,
"text": null
},
{
"code": null,
"e": 32326,
"s": 32318,
"text": "8\n34.65"
},
{
"code": null,
"e": 32338,
"s": 32328,
"text": "Example 2"
},
{
"code": null,
"e": 32343,
"s": 32338,
"text": "Java"
},
{
"code": "// Java program for Method Overloading// by Using Different Numbers of Arguments // Class 1// Helper classclass Helper { // Method 1 // Multiplication of 2 numbers static int Multiply(int a, int b) { // Return product return a * b; } // Method 2 // // Multiplication of 3 numbers static int Multiply(int a, int b, int c) { // Return product return a * b * c; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Helper.Multiply(2, 4)); System.out.println(Helper.Multiply(2, 7, 3)); }}",
"e": 33053,
"s": 32343,
"text": null
},
{
"code": null,
"e": 33058,
"s": 33053,
"text": "8\n42"
},
{
"code": null,
"e": 33089,
"s": 33060,
"text": "Type 2: Runtime polymorphism"
},
{
"code": null,
"e": 33463,
"s": 33089,
"text": "It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden."
},
{
"code": null,
"e": 33471,
"s": 33463,
"text": "Example"
},
{
"code": null,
"e": 33476,
"s": 33471,
"text": "Java"
},
{
"code": "// Java Program for Method Overriding // Class 1// Helper classclass Parent { // Method of parent class void Print() { // Print statement System.out.println(\"parent class\"); }} // Class 2// Helper classclass subclass1 extends Parent { // Method void Print() { System.out.println(\"subclass1\"); }} // Class 3// Helper classclass subclass2 extends Parent { // Method void Print() { // Print statement System.out.println(\"subclass2\"); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of class 1 Parent a; // Now we will be calling print methods // inside main() method a = new subclass1(); a.Print(); a = new subclass2(); a.Print(); }}",
"e": 34315,
"s": 33476,
"text": null
},
{
"code": null,
"e": 34335,
"s": 34315,
"text": "subclass1\nsubclass2"
},
{
"code": null,
"e": 34358,
"s": 34337,
"text": "Output explanation: "
},
{
"code": null,
"e": 34711,
"s": 34358,
"text": "Here in this program, When an object of child class is created, then the method inside the child class is called. This is because The method in the parent class is overridden by the child class. Since The method is overridden, This method has more priority than the parent method inside the child class. So, the body inside the child class is executed."
},
{
"code": null,
"e": 34730,
"s": 34711,
"text": "bajracharyakshitij"
},
{
"code": null,
"e": 34745,
"s": 34730,
"text": "rocklinglokesh"
},
{
"code": null,
"e": 34766,
"s": 34745,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 34773,
"s": 34766,
"text": "Picked"
},
{
"code": null,
"e": 34778,
"s": 34773,
"text": "Java"
},
{
"code": null,
"e": 34783,
"s": 34778,
"text": "Java"
},
{
"code": null,
"e": 34881,
"s": 34783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34925,
"s": 34881,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34961,
"s": 34925,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 34986,
"s": 34961,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35001,
"s": 34986,
"text": "Stream In Java"
},
{
"code": null,
"e": 35032,
"s": 35001,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 35064,
"s": 35032,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 35088,
"s": 35064,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 35116,
"s": 35088,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 35162,
"s": 35116,
"text": "Different ways of Reading a text file in Java"
}
] |
Count of smaller rectangles that can be placed inside a bigger rectangle - GeeksforGeeks | 20 Apr, 2021
Given four integers L, B, l, and b, where L and B denote the dimensions of a bigger rectangle and l and b denotes the dimension of a smaller rectangle, the task is to count the number of smaller rectangles that can be drawn inside a bigger rectangle. Note: Smaller rectangles can overlap partially.
Examples:
Input: L = 5, B = 3, l = 4, b = 1Output: 6Explanation:There are 6 rectangles of dimension 4 × 1 that can be drawn inside a bigger rectangle of dimension 5 × 3.
Input: L = 3, B = 2, l = 2, b = 1Output: 3Explanation:There are 3 rectangles of dimension 3 × 2 can be drawn inside a bigger rectangle of dimension 2 × 1.
Naive Approach: The idea is to iterate over the length L and breadth B of the bigger rectangle to count the number of smaller rectangles of dimension l x b that can be drawn within the range of bigger rectangle. Print the total count after the traversal. Time Complexity: O(L * B)Auxiliary Space: O(1)
Efficient Approach: The above problem can be solved using Permutation and Combinations. Below are the steps:
The total possible values of the length of smaller rectangle l using the length L is given by (L – l + 1).The total possible values of the breadth of smaller rectangle b using the length B is given by (B – b + 1).Hence, the total number of possible rectangles can be formed is given by:
The total possible values of the length of smaller rectangle l using the length L is given by (L – l + 1).
The total possible values of the breadth of smaller rectangle b using the length B is given by (B – b + 1).
Hence, the total number of possible rectangles can be formed is given by:
(L – l + 1) * (B – b + 1)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count smaller rectangles// within the larger rectangleint No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codeint main(){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call cout << No_of_rectangles(L, B, l, b); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count smaller rectangles// within the larger rectanglestatic int No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codepublic static void main(String[] args){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call System.out.println(No_of_rectangles(L, B, l, b));}} // This code is contributed by jana_sayantan
# Python3 program for the above approach # Function to count smaller rectangles# within the larger rectangledef No_of_rectangles( L, B, l, b): # If the dimension of the smaller # rectangle is greater than the # bigger one if (l > L) or (b > B): return -1; else: # Return the number of smaller # rectangles possible return (L - l + 1) * (B - b + 1); # Driver codeif __name__ == '__main__': # Dimension of bigger rectangle L = 5 B = 3 # Dimension of smaller rectangle l = 4 b = 1 # Function call print(No_of_rectangles(L, B, l, b)) # This code is contributed by jana_sayantan
// C# program for the above approachusing System; class GFG{ // Function to count smaller rectangles// within the larger rectanglestatic int No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codepublic static void Main(String[] args){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call Console.Write(No_of_rectangles(L, B, l, b));}} // This code is contributed by jana_sayantan
<script> // JavaScript implementation of the above approach // Function to count smaller rectangles// within the larger rectanglefunction No_of_rectangles(L, B, l, b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver code // Dimension of bigger rectangle let L = 5, B = 3; // Dimension of smaller rectangle let l = 4, b = 1; // Function call document.write(No_of_rectangles(L, B, l, b)); // This code is contributed by code_hunt.</script>
6
Time Complexity: O(1)Auxiliary Space: O(1)
jana_sayantan
code_hunt
Combinatorial
Geometric
Mathematical
Mathematical
Combinatorial
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Find if two rectangles overlap | [
{
"code": null,
"e": 26697,
"s": 26669,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 26996,
"s": 26697,
"text": "Given four integers L, B, l, and b, where L and B denote the dimensions of a bigger rectangle and l and b denotes the dimension of a smaller rectangle, the task is to count the number of smaller rectangles that can be drawn inside a bigger rectangle. Note: Smaller rectangles can overlap partially."
},
{
"code": null,
"e": 27006,
"s": 26996,
"text": "Examples:"
},
{
"code": null,
"e": 27166,
"s": 27006,
"text": "Input: L = 5, B = 3, l = 4, b = 1Output: 6Explanation:There are 6 rectangles of dimension 4 × 1 that can be drawn inside a bigger rectangle of dimension 5 × 3."
},
{
"code": null,
"e": 27321,
"s": 27166,
"text": "Input: L = 3, B = 2, l = 2, b = 1Output: 3Explanation:There are 3 rectangles of dimension 3 × 2 can be drawn inside a bigger rectangle of dimension 2 × 1."
},
{
"code": null,
"e": 27623,
"s": 27321,
"text": "Naive Approach: The idea is to iterate over the length L and breadth B of the bigger rectangle to count the number of smaller rectangles of dimension l x b that can be drawn within the range of bigger rectangle. Print the total count after the traversal. Time Complexity: O(L * B)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27732,
"s": 27623,
"text": "Efficient Approach: The above problem can be solved using Permutation and Combinations. Below are the steps:"
},
{
"code": null,
"e": 28019,
"s": 27732,
"text": "The total possible values of the length of smaller rectangle l using the length L is given by (L – l + 1).The total possible values of the breadth of smaller rectangle b using the length B is given by (B – b + 1).Hence, the total number of possible rectangles can be formed is given by:"
},
{
"code": null,
"e": 28126,
"s": 28019,
"text": "The total possible values of the length of smaller rectangle l using the length L is given by (L – l + 1)."
},
{
"code": null,
"e": 28234,
"s": 28126,
"text": "The total possible values of the breadth of smaller rectangle b using the length B is given by (B – b + 1)."
},
{
"code": null,
"e": 28308,
"s": 28234,
"text": "Hence, the total number of possible rectangles can be formed is given by:"
},
{
"code": null,
"e": 28337,
"s": 28311,
"text": "(L – l + 1) * (B – b + 1)"
},
{
"code": null,
"e": 28390,
"s": 28339,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28394,
"s": 28390,
"text": "C++"
},
{
"code": null,
"e": 28399,
"s": 28394,
"text": "Java"
},
{
"code": null,
"e": 28407,
"s": 28399,
"text": "Python3"
},
{
"code": null,
"e": 28410,
"s": 28407,
"text": "C#"
},
{
"code": null,
"e": 28421,
"s": 28410,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count smaller rectangles// within the larger rectangleint No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codeint main(){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call cout << No_of_rectangles(L, B, l, b); return 0;}",
"e": 29132,
"s": 28421,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to count smaller rectangles// within the larger rectanglestatic int No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codepublic static void main(String[] args){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call System.out.println(No_of_rectangles(L, B, l, b));}} // This code is contributed by jana_sayantan",
"e": 29940,
"s": 29132,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count smaller rectangles# within the larger rectangledef No_of_rectangles( L, B, l, b): # If the dimension of the smaller # rectangle is greater than the # bigger one if (l > L) or (b > B): return -1; else: # Return the number of smaller # rectangles possible return (L - l + 1) * (B - b + 1); # Driver codeif __name__ == '__main__': # Dimension of bigger rectangle L = 5 B = 3 # Dimension of smaller rectangle l = 4 b = 1 # Function call print(No_of_rectangles(L, B, l, b)) # This code is contributed by jana_sayantan",
"e": 30603,
"s": 29940,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to count smaller rectangles// within the larger rectanglestatic int No_of_rectangles(int L, int B, int l, int b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver Codepublic static void Main(String[] args){ // Dimension of bigger rectangle int L = 5, B = 3; // Dimension of smaller rectangle int l = 4, b = 1; // Function call Console.Write(No_of_rectangles(L, B, l, b));}} // This code is contributed by jana_sayantan",
"e": 31405,
"s": 30603,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // Function to count smaller rectangles// within the larger rectanglefunction No_of_rectangles(L, B, l, b){ // If the dimension of the smaller // rectangle is greater than the // bigger one if ((l > L) || (b > B)) { return -1; } else { // Return the number of smaller // rectangles possible return (L - l + 1) * (B - b + 1); }} // Driver code // Dimension of bigger rectangle let L = 5, B = 3; // Dimension of smaller rectangle let l = 4, b = 1; // Function call document.write(No_of_rectangles(L, B, l, b)); // This code is contributed by code_hunt.</script>",
"e": 32171,
"s": 31405,
"text": null
},
{
"code": null,
"e": 32173,
"s": 32171,
"text": "6"
},
{
"code": null,
"e": 32216,
"s": 32173,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32230,
"s": 32216,
"text": "jana_sayantan"
},
{
"code": null,
"e": 32240,
"s": 32230,
"text": "code_hunt"
},
{
"code": null,
"e": 32254,
"s": 32240,
"text": "Combinatorial"
},
{
"code": null,
"e": 32264,
"s": 32254,
"text": "Geometric"
},
{
"code": null,
"e": 32277,
"s": 32264,
"text": "Mathematical"
},
{
"code": null,
"e": 32290,
"s": 32277,
"text": "Mathematical"
},
{
"code": null,
"e": 32304,
"s": 32290,
"text": "Combinatorial"
},
{
"code": null,
"e": 32314,
"s": 32304,
"text": "Geometric"
},
{
"code": null,
"e": 32412,
"s": 32314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32484,
"s": 32412,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 32547,
"s": 32484,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 32577,
"s": 32547,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 32616,
"s": 32577,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 32694,
"s": 32616,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 32752,
"s": 32694,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 32816,
"s": 32752,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 32865,
"s": 32816,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 32916,
"s": 32865,
"text": "How to check if two given line segments intersect?"
}
] |
How to Use Different Types of Google Maps in Android? - GeeksforGeeks | 04 Feb, 2021
When we use the default application of Google Maps we will get to see different types of Maps present inside this application. We will get to see satellite maps, terrain maps, and many more. We have seen adding Google Maps in the Android application. In this article, we will take a look at the implementation of different types of Google Maps in Android.
We will be building a simple application in which we will be simply displaying a Google map with three buttons and we will change the map with the help of these buttons. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.
Step 2: Generating an API key for using Google Maps
To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY.
Step 3: Working with the activity_maps.xml file
Navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--fragment to display our map--> <fragment xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MapsActivity" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_margin="5dp" android:orientation="horizontal" android:padding="5dp" android:weightSum="3"> <!--button for displaying hybrid map--> <Button android:id="@+id/idBtnHybridMap" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:background="@color/purple_500" android:singleLine="false" android:text="Hybrid \n Map" android:textAllCaps="false" android:textColor="@color/white" /> <!--button for displaying satellite map--> <Button android:id="@+id/idBtnSatelliteMap" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:background="@color/purple_500" android:singleLine="false" android:text="Satellite \n Map" android:textAllCaps="false" android:textColor="@color/white" /> <!--button for displaying terrain map--> <Button android:id="@+id/idBtnTerrainMap" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:background="@color/purple_500" android:singleLine="false" android:text="Terrain \n Map" android:textAllCaps="false" android:textColor="@color/white" /> </LinearLayout> </RelativeLayout>
Step 4: Working with the MapsActivity.java file
Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // below are the latitude and longitude // of delhi locations. LatLng delhi = new LatLng(28.644800, 77.216721); // creating a variable for button. private Button hybridMapBtn, terrainMapBtn, satelliteMapBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initialize our buttons hybridMapBtn = findViewById(R.id.idBtnHybridMap); terrainMapBtn = findViewById(R.id.idBtnTerrainMap); satelliteMapBtn = findViewById(R.id.idBtnSatelliteMap); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); // adding on click listener for our hybrid map button. hybridMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change // the type of map to hybrid. mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); } }); // adding on click listener for our terrain map button. terrainMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change // the type of terrain map. mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); } }); // adding on click listener for our satellite map button. satelliteMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change the // type of satellite map. mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); } }); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // adding marker to each location on google maps mMap.addMarker(new MarkerOptions().position(delhi).title("Marker in Delhi")); // below line is use to move camera. mMap.moveCamera(CameraUpdateFactory.newLatLng(delhi)); }}
Now run your app and see the output of the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 26738,
"s": 26381,
"text": "When we use the default application of Google Maps we will get to see different types of Maps present inside this application. We will get to see satellite maps, terrain maps, and many more. We have seen adding Google Maps in the Android application. In this article, we will take a look at the implementation of different types of Google Maps in Android. "
},
{
"code": null,
"e": 27075,
"s": 26738,
"text": "We will be building a simple application in which we will be simply displaying a Google map with three buttons and we will change the map with the help of these buttons. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 27104,
"s": 27075,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27330,
"s": 27104,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project."
},
{
"code": null,
"e": 27382,
"s": 27330,
"text": "Step 2: Generating an API key for using Google Maps"
},
{
"code": null,
"e": 27740,
"s": 27382,
"text": "To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. "
},
{
"code": null,
"e": 27788,
"s": 27740,
"text": "Step 3: Working with the activity_maps.xml file"
},
{
"code": null,
"e": 27936,
"s": 27788,
"text": "Navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 27940,
"s": 27936,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--fragment to display our map--> <fragment xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/map\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MapsActivity\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_margin=\"5dp\" android:orientation=\"horizontal\" android:padding=\"5dp\" android:weightSum=\"3\"> <!--button for displaying hybrid map--> <Button android:id=\"@+id/idBtnHybridMap\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:layout_weight=\"1\" android:background=\"@color/purple_500\" android:singleLine=\"false\" android:text=\"Hybrid \\n Map\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> <!--button for displaying satellite map--> <Button android:id=\"@+id/idBtnSatelliteMap\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:layout_weight=\"1\" android:background=\"@color/purple_500\" android:singleLine=\"false\" android:text=\"Satellite \\n Map\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> <!--button for displaying terrain map--> <Button android:id=\"@+id/idBtnTerrainMap\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:layout_weight=\"1\" android:background=\"@color/purple_500\" android:singleLine=\"false\" android:text=\"Terrain \\n Map\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> </LinearLayout> </RelativeLayout>",
"e": 30261,
"s": 27940,
"text": null
},
{
"code": null,
"e": 30309,
"s": 30261,
"text": "Step 4: Working with the MapsActivity.java file"
},
{
"code": null,
"e": 30499,
"s": 30309,
"text": "Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30504,
"s": 30499,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // below are the latitude and longitude // of delhi locations. LatLng delhi = new LatLng(28.644800, 77.216721); // creating a variable for button. private Button hybridMapBtn, terrainMapBtn, satelliteMapBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initialize our buttons hybridMapBtn = findViewById(R.id.idBtnHybridMap); terrainMapBtn = findViewById(R.id.idBtnTerrainMap); satelliteMapBtn = findViewById(R.id.idBtnSatelliteMap); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); // adding on click listener for our hybrid map button. hybridMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change // the type of map to hybrid. mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); } }); // adding on click listener for our terrain map button. terrainMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change // the type of terrain map. mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); } }); // adding on click listener for our satellite map button. satelliteMapBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // below line is to change the // type of satellite map. mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); } }); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // adding marker to each location on google maps mMap.addMarker(new MarkerOptions().position(delhi).title(\"Marker in Delhi\")); // below line is use to move camera. mMap.moveCamera(CameraUpdateFactory.newLatLng(delhi)); }}",
"e": 33370,
"s": 30504,
"text": null
},
{
"code": null,
"e": 33419,
"s": 33370,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 33427,
"s": 33419,
"text": "android"
},
{
"code": null,
"e": 33451,
"s": 33427,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33459,
"s": 33451,
"text": "Android"
},
{
"code": null,
"e": 33464,
"s": 33459,
"text": "Java"
},
{
"code": null,
"e": 33483,
"s": 33464,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33488,
"s": 33483,
"text": "Java"
},
{
"code": null,
"e": 33496,
"s": 33488,
"text": "Android"
},
{
"code": null,
"e": 33594,
"s": 33496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33632,
"s": 33594,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 33671,
"s": 33632,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33721,
"s": 33671,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 33772,
"s": 33721,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 33814,
"s": 33772,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33829,
"s": 33814,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33873,
"s": 33829,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33895,
"s": 33873,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33946,
"s": 33895,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
How to Replace Values in a List in Python? - GeeksforGeeks | 22 Nov, 2021
In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in serval ways. Below are the methods to replace values in the list.
Using list indexing
Using for loop
Using while loop
Using lambda function
Using list slicing
We can access items of the list using indexing. This is the simplest and easiest method to replace values in a list in python. If we want to replace the first item of the list we can di using index 0. Here below, the index is an index of the item that we want to replace and the new_value is a value that should replace the old value in the list.
Syntax: l[index]=new_value
Code:
Python3
# Replace Values in a List using indexing # define listl = [ 'Hardik','Rohit', 'Rahul', 'Virat', 'Pant'] # replace first valuel[0] = 'Shardul' # print listprint(l)
Output:
['Shardul', 'Rohit', 'Rahul', 'Virat', 'Pant']
We can use for loop to iterate over the list and replace values in the list. Suppose we want to replace ‘Hardik’ and ‘Pant’ from the list with ‘Shardul’ and ‘Ishan’. We first find values in the list using for loop and if condition and then replace it with the new value.
Python3
# Replace Values in a List using For Loop # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] for i in range(len(l)): # replace hardik with shardul if l[i] == 'Hardik': l[i] = 'Shardul' # replace pant with ishan if l[i] == 'Pant': l[i] = 'Ishan' # print listprint(l)
Output:
['Shardul', 'Rohit', 'Rahul', 'Virat', 'Ishan']
We can also use a while loop to replace values in the list. While loop does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If value matches to value that we want to replace then we replace it with the new value.
Python3
# Replace Values in a List using While Loop # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] i = 0while i < len(l): # replace hardik with shardul if l[i] == 'Hardik': l[i] = 'Shardul' # replace pant with ishan if l[i] == 'Pant': l[i] = 'Ishan' i += 1 # print listprint(l)
Output:
['Shardul', 'Rohit', 'Rahul', 'Virat', 'Ishan']
In this method, we use lambda and map function to replace the value in the list. map() is a built-in function in python to iterate over a list without using any loop statement. A lambda is an anonymous function in python that contains a single line expression. Here we gave one expression as a condition to replace value. Here we replace ‘Pant’ with ‘Ishan’ in the lambda function. Then using the list() function we convert the map object into the list.
Syntax: l=list(map(lambda x: x.replace(‘old_value’,’new_value’),l))
Python3
# Replace Values in a List using Lambda Function # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] # replace Pant with Ishanl = list(map(lambda x: x.replace('Pant', 'Ishan'), l)) # print listprint(l)
Output:
['Hardik', 'Rohit', 'Rahul', 'Virat', 'Ishan']
Python allows us to do slicing inside a list. Slicing enables us to access some parts of the list. We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable ‘i’. Then, we replace that item with a new value using list slicing. Suppose we want to replace ‘Rahul’ with ‘Shikhar’ than we first find the index of ‘Rahul’ and then do list slicing and remove ‘Rahul’ and add ‘Shikhar’ in that place.
Syntax: l=l[:index]+[‘new_value’]+l[index+1:]
Python3
# Replace Values in a List using Slicing # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] # find the index of Rahuli = l.index('Rahul') # replace Rahul with Shikharl = l[:i]+['Shikhar']+l[i+1:] # print listprint(l)
Output:
['Hardik', 'Rohit', 'Shikhar', 'Virat', 'Pant']
Picked
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 25744,
"s": 25555,
"text": "In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in serval ways. Below are the methods to replace values in the list."
},
{
"code": null,
"e": 25764,
"s": 25744,
"text": "Using list indexing"
},
{
"code": null,
"e": 25779,
"s": 25764,
"text": "Using for loop"
},
{
"code": null,
"e": 25796,
"s": 25779,
"text": "Using while loop"
},
{
"code": null,
"e": 25818,
"s": 25796,
"text": "Using lambda function"
},
{
"code": null,
"e": 25837,
"s": 25818,
"text": "Using list slicing"
},
{
"code": null,
"e": 26184,
"s": 25837,
"text": "We can access items of the list using indexing. This is the simplest and easiest method to replace values in a list in python. If we want to replace the first item of the list we can di using index 0. Here below, the index is an index of the item that we want to replace and the new_value is a value that should replace the old value in the list."
},
{
"code": null,
"e": 26212,
"s": 26184,
"text": "Syntax: l[index]=new_value"
},
{
"code": null,
"e": 26218,
"s": 26212,
"text": "Code:"
},
{
"code": null,
"e": 26226,
"s": 26218,
"text": "Python3"
},
{
"code": "# Replace Values in a List using indexing # define listl = [ 'Hardik','Rohit', 'Rahul', 'Virat', 'Pant'] # replace first valuel[0] = 'Shardul' # print listprint(l)",
"e": 26393,
"s": 26226,
"text": null
},
{
"code": null,
"e": 26401,
"s": 26393,
"text": "Output:"
},
{
"code": null,
"e": 26448,
"s": 26401,
"text": "['Shardul', 'Rohit', 'Rahul', 'Virat', 'Pant']"
},
{
"code": null,
"e": 26720,
"s": 26448,
"text": "We can use for loop to iterate over the list and replace values in the list. Suppose we want to replace ‘Hardik’ and ‘Pant’ from the list with ‘Shardul’ and ‘Ishan’. We first find values in the list using for loop and if condition and then replace it with the new value. "
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "Python3"
},
{
"code": "# Replace Values in a List using For Loop # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] for i in range(len(l)): # replace hardik with shardul if l[i] == 'Hardik': l[i] = 'Shardul' # replace pant with ishan if l[i] == 'Pant': l[i] = 'Ishan' # print listprint(l)",
"e": 27039,
"s": 26728,
"text": null
},
{
"code": null,
"e": 27047,
"s": 27039,
"text": "Output:"
},
{
"code": null,
"e": 27095,
"s": 27047,
"text": "['Shardul', 'Rohit', 'Rahul', 'Virat', 'Ishan']"
},
{
"code": null,
"e": 27373,
"s": 27095,
"text": "We can also use a while loop to replace values in the list. While loop does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If value matches to value that we want to replace then we replace it with the new value."
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Python3"
},
{
"code": "# Replace Values in a List using While Loop # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] i = 0while i < len(l): # replace hardik with shardul if l[i] == 'Hardik': l[i] = 'Shardul' # replace pant with ishan if l[i] == 'Pant': l[i] = 'Ishan' i += 1 # print listprint(l)",
"e": 27705,
"s": 27381,
"text": null
},
{
"code": null,
"e": 27713,
"s": 27705,
"text": "Output:"
},
{
"code": null,
"e": 27761,
"s": 27713,
"text": "['Shardul', 'Rohit', 'Rahul', 'Virat', 'Ishan']"
},
{
"code": null,
"e": 28215,
"s": 27761,
"text": "In this method, we use lambda and map function to replace the value in the list. map() is a built-in function in python to iterate over a list without using any loop statement. A lambda is an anonymous function in python that contains a single line expression. Here we gave one expression as a condition to replace value. Here we replace ‘Pant’ with ‘Ishan’ in the lambda function. Then using the list() function we convert the map object into the list."
},
{
"code": null,
"e": 28283,
"s": 28215,
"text": "Syntax: l=list(map(lambda x: x.replace(‘old_value’,’new_value’),l))"
},
{
"code": null,
"e": 28291,
"s": 28283,
"text": "Python3"
},
{
"code": "# Replace Values in a List using Lambda Function # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] # replace Pant with Ishanl = list(map(lambda x: x.replace('Pant', 'Ishan'), l)) # print listprint(l)",
"e": 28507,
"s": 28291,
"text": null
},
{
"code": null,
"e": 28515,
"s": 28507,
"text": "Output:"
},
{
"code": null,
"e": 28562,
"s": 28515,
"text": "['Hardik', 'Rohit', 'Rahul', 'Virat', 'Ishan']"
},
{
"code": null,
"e": 29036,
"s": 28562,
"text": "Python allows us to do slicing inside a list. Slicing enables us to access some parts of the list. We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable ‘i’. Then, we replace that item with a new value using list slicing. Suppose we want to replace ‘Rahul’ with ‘Shikhar’ than we first find the index of ‘Rahul’ and then do list slicing and remove ‘Rahul’ and add ‘Shikhar’ in that place."
},
{
"code": null,
"e": 29082,
"s": 29036,
"text": "Syntax: l=l[:index]+[‘new_value’]+l[index+1:]"
},
{
"code": null,
"e": 29090,
"s": 29082,
"text": "Python3"
},
{
"code": "# Replace Values in a List using Slicing # define listl = ['Hardik', 'Rohit', 'Rahul', 'Virat', 'Pant'] # find the index of Rahuli = l.index('Rahul') # replace Rahul with Shikharl = l[:i]+['Shikhar']+l[i+1:] # print listprint(l)",
"e": 29323,
"s": 29090,
"text": null
},
{
"code": null,
"e": 29331,
"s": 29323,
"text": "Output:"
},
{
"code": null,
"e": 29379,
"s": 29331,
"text": "['Hardik', 'Rohit', 'Shikhar', 'Virat', 'Pant']"
},
{
"code": null,
"e": 29386,
"s": 29379,
"text": "Picked"
},
{
"code": null,
"e": 29398,
"s": 29386,
"text": "python-list"
},
{
"code": null,
"e": 29405,
"s": 29398,
"text": "Python"
},
{
"code": null,
"e": 29417,
"s": 29405,
"text": "python-list"
},
{
"code": null,
"e": 29515,
"s": 29417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29547,
"s": 29515,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29589,
"s": 29547,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29631,
"s": 29589,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29687,
"s": 29631,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29714,
"s": 29687,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29745,
"s": 29714,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29774,
"s": 29745,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29813,
"s": 29774,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29849,
"s": 29813,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Python | Plotting Line charts in excel sheet using XlsxWriter module - GeeksforGeeks | 21 Dec, 2018
Prerequisite: Create and Write on an excel sheet
XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot Line charts using realtime data.
Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Line chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object.
Code : Plot the Line Chart.
For plotting the Line chart on an excel sheet, use add_chart() method with type ‘line’ keyword argument of a workbook object.
# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook('chart_Line.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells # in worksheets using add_format() method . # here we create bold format object . bold = workbook.add_format({'bold': 1}) # create a data list . headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20], ] # Write a row of data starting from 'A1' # with bold format . worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively . worksheet.write_column('A2', data[0]) worksheet.write_column('B2', data[1]) worksheet.write_column('C2', data[2]) # Create a chart object that can be added # to a worksheet using add_chart() method. # here we create a line chart object . chart1 = workbook.add_chart({'type': 'line'}) # Add a data series to a chart # using add_series method. # Configure the first series. # = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7', }) # Configure a second series. # Note use of alternative syntax to define ranges. # [sheetname, first_row, first_col, last_row, last_col]. chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2], }) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis label chart1.set_x_axis({'name': 'Test number'}) # Add y-axis label chart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style. chart1.set_style(11) # add chart to the worksheet with given# offset values at the top-left corner of# a chart is anchored to cell D2 . worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10}) # Finally, close the Excel file # via the close() method. workbook.close()
Output:
Python-excel
Technical Scripter 2018
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python | [
{
"code": null,
"e": 26459,
"s": 26431,
"text": "\n21 Dec, 2018"
},
{
"code": null,
"e": 26508,
"s": 26459,
"text": "Prerequisite: Create and Write on an excel sheet"
},
{
"code": null,
"e": 26724,
"s": 26508,
"text": "XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot Line charts using realtime data."
},
{
"code": null,
"e": 27078,
"s": 26724,
"text": "Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Line chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object."
},
{
"code": null,
"e": 27106,
"s": 27078,
"text": "Code : Plot the Line Chart."
},
{
"code": null,
"e": 27232,
"s": 27106,
"text": "For plotting the Line chart on an excel sheet, use add_chart() method with type ‘line’ keyword argument of a workbook object."
},
{
"code": "# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook('chart_Line.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells # in worksheets using add_format() method . # here we create bold format object . bold = workbook.add_format({'bold': 1}) # create a data list . headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20], ] # Write a row of data starting from 'A1' # with bold format . worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively . worksheet.write_column('A2', data[0]) worksheet.write_column('B2', data[1]) worksheet.write_column('C2', data[2]) # Create a chart object that can be added # to a worksheet using add_chart() method. # here we create a line chart object . chart1 = workbook.add_chart({'type': 'line'}) # Add a data series to a chart # using add_series method. # Configure the first series. # = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7', }) # Configure a second series. # Note use of alternative syntax to define ranges. # [sheetname, first_row, first_col, last_row, last_col]. chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2], }) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis label chart1.set_x_axis({'name': 'Test number'}) # Add y-axis label chart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style. chart1.set_style(11) # add chart to the worksheet with given# offset values at the top-left corner of# a chart is anchored to cell D2 . worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10}) # Finally, close the Excel file # via the close() method. workbook.close() ",
"e": 29613,
"s": 27232,
"text": null
},
{
"code": null,
"e": 29621,
"s": 29613,
"text": "Output:"
},
{
"code": null,
"e": 29634,
"s": 29621,
"text": "Python-excel"
},
{
"code": null,
"e": 29658,
"s": 29634,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29665,
"s": 29658,
"text": "Python"
},
{
"code": null,
"e": 29763,
"s": 29665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29781,
"s": 29763,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29813,
"s": 29781,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29835,
"s": 29813,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29877,
"s": 29835,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29907,
"s": 29877,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29951,
"s": 29907,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29980,
"s": 29951,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30017,
"s": 29980,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30059,
"s": 30017,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
Jackson Annotations - @JsonSetter | @JsonSetter allows a specific method to be marked as setter method.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"rollNo\":1,\"name\":\"Marks\"}";
try {
Student student = mapper.readerFor(Student.class).readValue(jsonString);
System.out.println(student.name);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
public int rollNo;
public String name;
@JsonSetter("name")
public void setTheName(String name) {
this.name = name;
}
}
Marks
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2543,
"s": 2475,
"text": "@JsonSetter allows a specific method to be marked as setter method."
},
{
"code": null,
"e": 3257,
"s": 2543,
"text": "import java.io.IOException; \nimport com.fasterxml.jackson.annotation.JsonSetter; \nimport com.fasterxml.jackson.databind.ObjectMapper; \n\npublic class JacksonTester {\n public static void main(String args[]){ \n ObjectMapper mapper = new ObjectMapper(); \n String jsonString = \"{\\\"rollNo\\\":1,\\\"name\\\":\\\"Marks\\\"}\"; \n\n try { \n Student student = mapper.readerFor(Student.class).readValue(jsonString);\n System.out.println(student.name); \n }\n catch (IOException e) {\n e.printStackTrace(); \n } \n } \n}\nclass Student { \n public int rollNo; \n public String name; \n @JsonSetter(\"name\") \n public void setTheName(String name) { \n this.name = name; \n } \n}"
},
{
"code": null,
"e": 3265,
"s": 3257,
"text": "Marks \n"
},
{
"code": null,
"e": 3272,
"s": 3265,
"text": " Print"
},
{
"code": null,
"e": 3283,
"s": 3272,
"text": " Add Notes"
}
] |
How to deal with ModalDialog using selenium webdriver? | We can deal with modal dialog boxes with Selenium. A modal is just like a window that enforces the user to access it prior to going back to the actual page. It can be an authentication window as well.
Let us work with the below modal dialog −
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ModDialog{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.uitestpractice.com/Students/Switchto");
// identify element and click
WebElement m = driver
.findElement(By.xpath("//button[contains(text(), 'Launch modal')]"));
// identify modal header and obtain text
WebElement m=
driver.findElement(By.xpath("//h4[@class='modal−title']"));
System.out.println("Modal Dialog text: " + m.getText());
// click on OK
WebElement n= driver.findElement(By.xpath("//button[text()='Ok']"));
n.click();
driver.quit();
}
} | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "We can deal with modal dialog boxes with Selenium. A modal is just like a window that enforces the user to access it prior to going back to the actual page. It can be an authentication window as well."
},
{
"code": null,
"e": 1305,
"s": 1263,
"text": "Let us work with the below modal dialog −"
},
{
"code": null,
"e": 2227,
"s": 1305,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class ModDialog{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"http://www.uitestpractice.com/Students/Switchto\");\n // identify element and click\n WebElement m = driver\n .findElement(By.xpath(\"//button[contains(text(), 'Launch modal')]\"));\n // identify modal header and obtain text\n WebElement m=\n driver.findElement(By.xpath(\"//h4[@class='modal−title']\"));\n System.out.println(\"Modal Dialog text: \" + m.getText());\n // click on OK\n WebElement n= driver.findElement(By.xpath(\"//button[text()='Ok']\"));\n n.click();\n driver.quit();\n }\n}"
}
] |
How to find the vowels in a given string using Java? | You can read a character in a String using the charAt() method. To find the vowels in a given String you need to compare every character in it with the vowel letters.
Live Demo
public class FindingVowels {
public static void main(String args[]) {
String str = new String("Hi Welcome to Tutorialspoint");
for(int i=0; i<str.length(); i++) {
if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
System.out.println("Given string contains "+str.charAt(i)+" at the index "+i);
}
}
}
}
Given string contains i at the index 1
Given string contains e at the index 4
Given string contains o at the index 7
Given string contains e at the index 9
Given string contains o at the index 12
Given string contains u at the index 15
Given string contains o at the index 17
Given string contains i at the index 19
Given string contains a at the index 20
Given string contains o at the index 24
Given string contains i at the index 25 | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "You can read a character in a String using the charAt() method. To find the vowels in a given String you need to compare every character in it with the vowel letters."
},
{
"code": null,
"e": 1239,
"s": 1229,
"text": "Live Demo"
},
{
"code": null,
"e": 1665,
"s": 1239,
"text": "public class FindingVowels {\n public static void main(String args[]) {\n\n String str = new String(\"Hi Welcome to Tutorialspoint\");\n for(int i=0; i<str.length(); i++) {\n if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {\n System.out.println(\"Given string contains \"+str.charAt(i)+\" at the index \"+i);\n }\n }\n }\n}"
},
{
"code": null,
"e": 2112,
"s": 1665,
"text": "Given string contains i at the index 1 \nGiven string contains e at the index 4 \nGiven string contains o at the index 7 \nGiven string contains e at the index 9 \nGiven string contains o at the index 12 \nGiven string contains u at the index 15 \nGiven string contains o at the index 17 \nGiven string contains i at the index 19 \nGiven string contains a at the index 20 \nGiven string contains o at the index 24 \nGiven string contains i at the index 25"
}
] |
Line Clipping | Set 1 (Cohen–Sutherland Algorithm) - GeeksforGeeks | 18 Apr, 2022
Given a set of lines and a rectangular area of interest, the task is to remove lines that are outside the area of interest and clip the lines which are partially inside the area.
Input : Rectangular area of interest (Defined by
below four values which are coordinates of
bottom left and top right)
x_min = 4, y_min = 4, x_max = 10, y_max = 8
A set of lines (Defined by two corner coordinates)
line 1 : x1 = 5, y1 = 5, x2 = 7, y2 = 7
Line 2 : x1 = 7, y1 = 9, x2 = 11, y2 = 4
Line 2 : x1 = 1, y1 = 5, x2 = 4, y2 = 1
Output : Line 1 : Accepted from (5, 5) to (7, 7)
Line 2 : Accepted from (7.8, 8) to (10, 5.25)
Line 3 : Rejected
Cohen-Sutherland algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and portions of lines that are inside the given rectangular area.
The algorithm can be outlines as follows:-
Nine regions are created, eight "outside" regions and one
"inside" region.
For a given line extreme point (x, y), we can quickly
find its region's four bit code. Four bit code can
be computed by comparing x and y with four values
(x_min, x_max, y_min and y_max).
If x is less than x_min then bit number 1 is set.
If x is greater than x_max then bit number 2 is set.
If y is less than y_min then bit number 3 is set.
If y is greater than y_max then bit number 4 is set
There are three possible cases for any given line.
Completely inside the given rectangle : Bitwise OR of region of two end points of line is 0 (Both points are inside the rectangle)Completely outside the given rectangle : Both endpoints share at least one outside region which implies that the line does not cross the visible region. (bitwise AND of endpoints != 0).Partially inside the window : Both endpoints are in different regions. In this case, the algorithm finds one of the two points that is outside the rectangular region. The intersection of the line from outside point and rectangular window becomes new corner point and the algorithm repeats
Completely inside the given rectangle : Bitwise OR of region of two end points of line is 0 (Both points are inside the rectangle)
Completely outside the given rectangle : Both endpoints share at least one outside region which implies that the line does not cross the visible region. (bitwise AND of endpoints != 0).
Partially inside the window : Both endpoints are in different regions. In this case, the algorithm finds one of the two points that is outside the rectangular region. The intersection of the line from outside point and rectangular window becomes new corner point and the algorithm repeats
Pseudo Code:
Step 1 : Assign a region code for two endpoints of given line.
Step 2 : If both endpoints have a region code 0000
then given line is completely inside.
Step 3 : Else, perform the logical AND operation for both region codes.
Step 3.1 : If the result is not 0000, then given line is completely
outside.
Step 3.2 : Else line is partially inside.
Step 3.2.1 : Choose an endpoint of the line
that is outside the given rectangle.
Step 3.2.2 : Find the intersection point of the
rectangular boundary (based on region code).
Step 3.2.3 : Replace endpoint with the intersection point
and update the region code.
Step 3.2.4 : Repeat step 2 until we find a clipped line either
trivially accepted or trivially rejected.
Step 4 : Repeat step 1 for other lines
Below is implementation of above steps.
C++
Python3
// C++ program to implement Cohen Sutherland algorithm// for line clipping.#include <iostream>using namespace std; // Defining region codesconst int INSIDE = 0; // 0000const int LEFT = 1; // 0001const int RIGHT = 2; // 0010const int BOTTOM = 4; // 0100const int TOP = 8; // 1000 // Defining x_max, y_max and x_min, y_min for// clipping rectangle. Since diagonal points are// enough to define a rectangleconst int x_max = 10;const int y_max = 8;const int x_min = 4;const int y_min = 4; // Function to compute region code for a point(x, y)int computeCode(double x, double y){ // initialized as being inside int code = INSIDE; if (x < x_min) // to the left of rectangle code |= LEFT; else if (x > x_max) // to the right of rectangle code |= RIGHT; if (y < y_min) // below the rectangle code |= BOTTOM; else if (y > y_max) // above the rectangle code |= TOP; return code;} // Implementing Cohen-Sutherland algorithm// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)void cohenSutherlandClip(double x1, double y1, double x2, double y2){ // Compute region codes for P1, P2 int code1 = computeCode(x1, y1); int code2 = computeCode(x2, y2); // Initialize line as outside the rectangular window bool accept = false; while (true) { if ((code1 == 0) && (code2 == 0)) { // If both endpoints lie within rectangle accept = true; break; } else if (code1 & code2) { // If both endpoints are outside rectangle, // in same region break; } else { // Some segment of line lies within the // rectangle int code_out; double x, y; // At least one endpoint is outside the // rectangle, pick it. if (code1 != 0) code_out = code1; else code_out = code2; // Find intersection point; // using formulas y = y1 + slope * (x - x1), // x = x1 + (1 / slope) * (y - y1) if (code_out & TOP) { // point is above the clip rectangle x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1); y = y_max; } else if (code_out & BOTTOM) { // point is below the rectangle x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1); y = y_min; } else if (code_out & RIGHT) { // point is to the right of rectangle y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1); x = x_max; } else if (code_out & LEFT) { // point is to the left of rectangle y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1); x = x_min; } // Now intersection point x, y is found // We replace point outside rectangle // by intersection point if (code_out == code1) { x1 = x; y1 = y; code1 = computeCode(x1, y1); } else { x2 = x; y2 = y; code2 = computeCode(x2, y2); } } } if (accept) { cout << "Line accepted from " << x1 << ", " << y1 << " to " << x2 << ", " << y2 << endl; // Here the user can add code to display the rectangle // along with the accepted (portion of) lines } else cout << "Line rejected" << endl;} // Driver codeint main(){ // First Line segment // P11 = (5, 5), P12 = (7, 7) cohenSutherlandClip(5, 5, 7, 7); // Second Line segment // P21 = (7, 9), P22 = (11, 4) cohenSutherlandClip(7, 9, 11, 4); // Third Line segment // P31 = (1, 5), P32 = (4, 1) cohenSutherlandClip(1, 5, 4, 1); return 0;}
# Python program to implement Cohen Sutherland algorithm# for line clipping. # Defining region codesINSIDE = 0 # 0000LEFT = 1 # 0001RIGHT = 2 # 0010BOTTOM = 4 # 0100TOP = 8 # 1000 # Defining x_max, y_max and x_min, y_min for rectangle# Since diagonal points are enough to define a rectanglex_max = 10.0y_max = 8.0x_min = 4.0y_min = 4.0 # Function to compute region code for a point(x, y)def computeCode(x, y): code = INSIDE if x < x_min: # to the left of rectangle code |= LEFT else if x > x_max: # to the right of rectangle code |= RIGHT if y < y_min: # below the rectangle code |= BOTTOM else if y > y_max: # above the rectangle code |= TOP return code # Implementing Cohen-Sutherland algorithm# Clipping a line from P1 = (x1, y1) to P2 = (x2, y2)def cohenSutherlandClip(x1, y1, x2, y2): # Compute region codes for P1, P2 code1 = computeCode(x1, y1) code2 = computeCode(x2, y2) accept = False while True: # If both endpoints lie within rectangle if code1 == 0 and code2 == 0: accept = True break # If both endpoints are outside rectangle else if (code1 & code2) != 0: break # Some segment lies within the rectangle else: # Line Needs clipping # At least one of the points is outside, # select it x = 1.0 y = 1.0 if code1 != 0: code_out = code1 else: code_out = code2 # Find intersection point # using formulas y = y1 + slope * (x - x1), # x = x1 + (1 / slope) * (y - y1) if code_out & TOP: # point is above the clip rectangle x = x1 + (x2 - x1) * \ (y_max - y1) / (y2 - y1) y = y_max else if code_out & BOTTOM: # point is below the clip rectangle x = x1 + (x2 - x1) * \ (y_min - y1) / (y2 - y1) y = y_min else if code_out & RIGHT: # point is to the right of the clip rectangle y = y1 + (y2 - y1) * \ (x_max - x1) / (x2 - x1) x = x_max else if code_out & LEFT: # point is to the left of the clip rectangle y = y1 + (y2 - y1) * \ (x_min - x1) / (x2 - x1) x = x_min # Now intersection point x, y is found # We replace point outside clipping rectangle # by intersection point if code_out == code1: x1 = x y1 = y code1 = computeCode(x1, y1) else: x2 = x y2 = y code2 = computeCode(x2, y2) if accept: print ("Line accepted from %.2f, %.2f to %.2f, %.2f" % (x1, y1, x2, y2)) # Here the user can add code to display the rectangle # along with the accepted (portion of) lines else: print("Line rejected") # Driver Script# First Line segment# P11 = (5, 5), P12 = (7, 7)cohenSutherlandClip(5, 5, 7, 7) # Second Line segment# P21 = (7, 9), P22 = (11, 4)cohenSutherlandClip(7, 9, 11, 4) # Third Line segment# P31 = (1, 5), P32 = (4, 1)cohenSutherlandClip(1, 5, 4, 1)
Output:
Line accepted from 5.00, 5.00 to 7.00, 7.00
Line accepted from 7.80, 8.00 to 10.00, 5.25
Line rejected
Below is C++ code with Graphics using graphics.h
C++
// C++ program to implement Cohen Sutherland algorithm// for line clipping.// including libraries#include <bits/stdc++.h>#include <graphics.h>using namespace std; // Global Variablesint xmin, xmax, ymin, ymax; // Lines where co-ordinates are (x1, y1) and (x2, y2)struct lines { int x1, y1, x2, y2;}; // This will return the sign required.int sign(int x){ if (x > 0) return 1; else return 0;} // CohenSutherLand LineClipping Algorithm As Described in theory.// This will clip the lines as per window boundaries.void clip(struct lines mylines){ // arrays will store bits // Here bits implies initial Point whereas bite implies end points int bits[4], bite[4], i, var; // setting color of graphics to be RED setcolor(RED); // Finding Bits bits[0] = sign(xmin - mylines.x1); bite[0] = sign(xmin - mylines.x2); bits[1] = sign(mylines.x1 - xmax); bite[1] = sign(mylines.x2 - xmax); bits[2] = sign(ymin - mylines.y1); bite[2] = sign(ymin - mylines.y2); bits[3] = sign(mylines.y1 - ymax); bite[3] = sign(mylines.y2 - ymax); // initial will used for initial coordinates and end for final string initial = "", end = "", temp = ""; // convert bits to string for (i = 0; i < 4; i++) { if (bits[i] == 0) initial += '0'; else initial += '1'; } for (i = 0; i < 4; i++) { if (bite[i] == 0) end += '0'; else end += '1'; } // finding slope of line y=mx+c as (y-y1)=m(x-x1)+c // where m is slope m=dy/dx; float m = (mylines.y2 - mylines.y1) / (float)(mylines.x2 - mylines.x1); float c = mylines.y1 - m * mylines.x1; // if both points are inside the Accept the line and draw if (initial == end && end == "0000") { // inbuild function to draw the line from(x1, y1) to (x2, y2) line(mylines.x1, mylines.y1, mylines.x2, mylines.y2); return; } // this will contain cases where line maybe totally outside for partially inside else { // taking bitwise end of every value for (i = 0; i < 4; i++) { int val = (bits[i] & bite[i]); if (val == 0) temp += '0'; else temp += '1'; } // as per algo if AND is not 0000 means line is completely outside hence draw nothing and return if (temp != "0000") return; // Here contain cases of partial inside or outside // So check for every boundary one by one for (i = 0; i < 4; i++) { // if boths bit are same hence we cannot find any intersection with boundary so continue if (bits[i] == bite[i]) continue; // Otherwise there exist a intersection // Case when initial point is in left xmin if (i == 0 && bits[i] == 1) { var = round(m * xmin + c); mylines.y1 = var; mylines.x1 = xmin; } // Case when final point is in left xmin if (i == 0 && bite[i] == 1) { var = round(m * xmin + c); mylines.y2 = var; mylines.x2 = xmin; } // Case when initial point is in right of xmax if (i == 1 && bits[i] == 1) { var = round(m * xmax + c); mylines.y1 = var; mylines.x1 = xmax; } // Case when final point is in right of xmax if (i == 1 && bite[i] == 1) { var = round(m * xmax + c); mylines.y2 = var; mylines.x2 = xmax; } // Case when initial point is in top of ymin if (i == 2 && bits[i] == 1) { var = round((float)(ymin - c) / m); mylines.y1 = ymin; mylines.x1 = var; } // Case when final point is in top of ymin if (i == 2 && bite[i] == 1) { var = round((float)(ymin - c) / m); mylines.y2 = ymin; mylines.x2 = var; } // Case when initial point is in bottom of ymax if (i == 3 && bits[i] == 1) { var = round((float)(ymax - c) / m); mylines.y1 = ymax; mylines.x1 = var; } // Case when final point is in bottom of ymax if (i == 3 && bite[i] == 1) { var = round((float)(ymax - c) / m); mylines.y2 = ymax; mylines.x2 = var; } // Updating Bits at every point bits[0] = sign(xmin - mylines.x1); bite[0] = sign(xmin - mylines.x2); bits[1] = sign(mylines.x1 - xmax); bite[1] = sign(mylines.x2 - xmax); bits[2] = sign(ymin - mylines.y1); bite[2] = sign(ymin - mylines.y2); bits[3] = sign(mylines.y1 - ymax); bite[3] = sign(mylines.y2 - ymax); } // end of for loop // Initialize initial and end to NULL initial = "", end = ""; // Updating strings again by bit for (i = 0; i < 4; i++) { if (bits[i] == 0) initial += '0'; else initial += '1'; } for (i = 0; i < 4; i++) { if (bite[i] == 0) end += '0'; else end += '1'; } // If now both points lie inside or on boundary then simply draw the updated line if (initial == end && end == "0000") { line(mylines.x1, mylines.y1, mylines.x2, mylines.y2); return; } // else line was completely outside hence rejected else return; }} // Driver Functionint main(){ int gd = DETECT, gm; // Setting values of Clipping window xmin = 40; xmax = 100; ymin = 40; ymax = 80; // initialize the graph initgraph(&gd, &gm, NULL); // Drawing Window using Lines line(xmin, ymin, xmax, ymin); line(xmax, ymin, xmax, ymax); line(xmax, ymax, xmin, ymax); line(xmin, ymax, xmin, ymin); // Assume 4 lines to be clipped struct lines mylines[4]; // Setting the coordinated of 4 lines mylines[0].x1 = 30; mylines[0].y1 = 65; mylines[0].x2 = 55; mylines[0].y2 = 30; mylines[1].x1 = 60; mylines[1].y1 = 20; mylines[1].x2 = 100; mylines[1].y2 = 90; mylines[2].x1 = 60; mylines[2].y1 = 100; mylines[2].x2 = 80; mylines[2].y2 = 70; mylines[3].x1 = 85; mylines[3].y1 = 50; mylines[3].x2 = 120; mylines[3].y2 = 75; // Drawing Initial Lines without clipping for (int i = 0; i < 4; i++) { line(mylines[i].x1, mylines[i].y1, mylines[i].x2, mylines[i].y2); delay(1000); } // Drawing clipped Line for (int i = 0; i < 4; i++) { // Calling clip() which in term clip the line as per window and draw it clip(mylines[i]); delay(1000); } delay(4000); getch(); // For Closing the graph. closegraph(); return 0;}
The Cohen–Sutherland algorithm can be used only on a rectangular clip window. For other convex polygon clipping windows, Cyrus–Beck algorithm is used. We will be discussing Cyrus–Beck Algorithm in next set.
Related Post : Polygon Clipping | Sutherland–Hodgman Algorithm Point Clipping Algorithm in Computer GraphicsReference: https://en.wikipedia.org/wiki/Cohen–Sutherland_algorithmThis article is contributed by Saket Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
imkiller
simranarora5sos
as5853535
surinderdawra388
amartyaghoshgfg
simmytarika5
computer-graphics
Algorithms
Geometric
Geometric
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to Start Learning DSA?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to check if a given point lies inside or outside a polygon?
Closest Pair of Points using Divide and Conquer algorithm
Program for distance between two points on earth
How to check if two given line segments intersect?
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) | [
{
"code": null,
"e": 25981,
"s": 25953,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 26160,
"s": 25981,
"text": "Given a set of lines and a rectangular area of interest, the task is to remove lines that are outside the area of interest and clip the lines which are partially inside the area."
},
{
"code": null,
"e": 26692,
"s": 26160,
"text": "Input : Rectangular area of interest (Defined by\n below four values which are coordinates of\n bottom left and top right)\n x_min = 4, y_min = 4, x_max = 10, y_max = 8\n \n A set of lines (Defined by two corner coordinates)\n line 1 : x1 = 5, y1 = 5, x2 = 7, y2 = 7\n Line 2 : x1 = 7, y1 = 9, x2 = 11, y2 = 4\n Line 2 : x1 = 1, y1 = 5, x2 = 4, y2 = 1 \n\nOutput : Line 1 : Accepted from (5, 5) to (7, 7)\n Line 2 : Accepted from (7.8, 8) to (10, 5.25)\n Line 3 : Rejected"
},
{
"code": null,
"e": 26874,
"s": 26692,
"text": "Cohen-Sutherland algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and portions of lines that are inside the given rectangular area."
},
{
"code": null,
"e": 26918,
"s": 26874,
"text": "The algorithm can be outlines as follows:- "
},
{
"code": null,
"e": 27391,
"s": 26918,
"text": "Nine regions are created, eight \"outside\" regions and one \n\"inside\" region.\n\nFor a given line extreme point (x, y), we can quickly\nfind its region's four bit code. Four bit code can \nbe computed by comparing x and y with four values \n(x_min, x_max, y_min and y_max).\n\nIf x is less than x_min then bit number 1 is set.\nIf x is greater than x_max then bit number 2 is set.\nIf y is less than y_min then bit number 3 is set.\nIf y is greater than y_max then bit number 4 is set"
},
{
"code": null,
"e": 27443,
"s": 27391,
"text": "There are three possible cases for any given line. "
},
{
"code": null,
"e": 28047,
"s": 27443,
"text": "Completely inside the given rectangle : Bitwise OR of region of two end points of line is 0 (Both points are inside the rectangle)Completely outside the given rectangle : Both endpoints share at least one outside region which implies that the line does not cross the visible region. (bitwise AND of endpoints != 0).Partially inside the window : Both endpoints are in different regions. In this case, the algorithm finds one of the two points that is outside the rectangular region. The intersection of the line from outside point and rectangular window becomes new corner point and the algorithm repeats"
},
{
"code": null,
"e": 28178,
"s": 28047,
"text": "Completely inside the given rectangle : Bitwise OR of region of two end points of line is 0 (Both points are inside the rectangle)"
},
{
"code": null,
"e": 28364,
"s": 28178,
"text": "Completely outside the given rectangle : Both endpoints share at least one outside region which implies that the line does not cross the visible region. (bitwise AND of endpoints != 0)."
},
{
"code": null,
"e": 28653,
"s": 28364,
"text": "Partially inside the window : Both endpoints are in different regions. In this case, the algorithm finds one of the two points that is outside the rectangular region. The intersection of the line from outside point and rectangular window becomes new corner point and the algorithm repeats"
},
{
"code": null,
"e": 28669,
"s": 28655,
"text": "Pseudo Code: "
},
{
"code": null,
"e": 29577,
"s": 28669,
"text": "Step 1 : Assign a region code for two endpoints of given line.\nStep 2 : If both endpoints have a region code 0000 \n then given line is completely inside.\nStep 3 : Else, perform the logical AND operation for both region codes.\n Step 3.1 : If the result is not 0000, then given line is completely\n outside.\n Step 3.2 : Else line is partially inside.\n Step 3.2.1 : Choose an endpoint of the line \n that is outside the given rectangle.\n Step 3.2.2 : Find the intersection point of the \n rectangular boundary (based on region code).\n Step 3.2.3 : Replace endpoint with the intersection point \n and update the region code.\n Step 3.2.4 : Repeat step 2 until we find a clipped line either \n trivially accepted or trivially rejected.\n Step 4 : Repeat step 1 for other lines"
},
{
"code": null,
"e": 29617,
"s": 29577,
"text": "Below is implementation of above steps."
},
{
"code": null,
"e": 29621,
"s": 29617,
"text": "C++"
},
{
"code": null,
"e": 29629,
"s": 29621,
"text": "Python3"
},
{
"code": "// C++ program to implement Cohen Sutherland algorithm// for line clipping.#include <iostream>using namespace std; // Defining region codesconst int INSIDE = 0; // 0000const int LEFT = 1; // 0001const int RIGHT = 2; // 0010const int BOTTOM = 4; // 0100const int TOP = 8; // 1000 // Defining x_max, y_max and x_min, y_min for// clipping rectangle. Since diagonal points are// enough to define a rectangleconst int x_max = 10;const int y_max = 8;const int x_min = 4;const int y_min = 4; // Function to compute region code for a point(x, y)int computeCode(double x, double y){ // initialized as being inside int code = INSIDE; if (x < x_min) // to the left of rectangle code |= LEFT; else if (x > x_max) // to the right of rectangle code |= RIGHT; if (y < y_min) // below the rectangle code |= BOTTOM; else if (y > y_max) // above the rectangle code |= TOP; return code;} // Implementing Cohen-Sutherland algorithm// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)void cohenSutherlandClip(double x1, double y1, double x2, double y2){ // Compute region codes for P1, P2 int code1 = computeCode(x1, y1); int code2 = computeCode(x2, y2); // Initialize line as outside the rectangular window bool accept = false; while (true) { if ((code1 == 0) && (code2 == 0)) { // If both endpoints lie within rectangle accept = true; break; } else if (code1 & code2) { // If both endpoints are outside rectangle, // in same region break; } else { // Some segment of line lies within the // rectangle int code_out; double x, y; // At least one endpoint is outside the // rectangle, pick it. if (code1 != 0) code_out = code1; else code_out = code2; // Find intersection point; // using formulas y = y1 + slope * (x - x1), // x = x1 + (1 / slope) * (y - y1) if (code_out & TOP) { // point is above the clip rectangle x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1); y = y_max; } else if (code_out & BOTTOM) { // point is below the rectangle x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1); y = y_min; } else if (code_out & RIGHT) { // point is to the right of rectangle y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1); x = x_max; } else if (code_out & LEFT) { // point is to the left of rectangle y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1); x = x_min; } // Now intersection point x, y is found // We replace point outside rectangle // by intersection point if (code_out == code1) { x1 = x; y1 = y; code1 = computeCode(x1, y1); } else { x2 = x; y2 = y; code2 = computeCode(x2, y2); } } } if (accept) { cout << \"Line accepted from \" << x1 << \", \" << y1 << \" to \" << x2 << \", \" << y2 << endl; // Here the user can add code to display the rectangle // along with the accepted (portion of) lines } else cout << \"Line rejected\" << endl;} // Driver codeint main(){ // First Line segment // P11 = (5, 5), P12 = (7, 7) cohenSutherlandClip(5, 5, 7, 7); // Second Line segment // P21 = (7, 9), P22 = (11, 4) cohenSutherlandClip(7, 9, 11, 4); // Third Line segment // P31 = (1, 5), P32 = (4, 1) cohenSutherlandClip(1, 5, 4, 1); return 0;}",
"e": 33511,
"s": 29629,
"text": null
},
{
"code": "# Python program to implement Cohen Sutherland algorithm# for line clipping. # Defining region codesINSIDE = 0 # 0000LEFT = 1 # 0001RIGHT = 2 # 0010BOTTOM = 4 # 0100TOP = 8 # 1000 # Defining x_max, y_max and x_min, y_min for rectangle# Since diagonal points are enough to define a rectanglex_max = 10.0y_max = 8.0x_min = 4.0y_min = 4.0 # Function to compute region code for a point(x, y)def computeCode(x, y): code = INSIDE if x < x_min: # to the left of rectangle code |= LEFT else if x > x_max: # to the right of rectangle code |= RIGHT if y < y_min: # below the rectangle code |= BOTTOM else if y > y_max: # above the rectangle code |= TOP return code # Implementing Cohen-Sutherland algorithm# Clipping a line from P1 = (x1, y1) to P2 = (x2, y2)def cohenSutherlandClip(x1, y1, x2, y2): # Compute region codes for P1, P2 code1 = computeCode(x1, y1) code2 = computeCode(x2, y2) accept = False while True: # If both endpoints lie within rectangle if code1 == 0 and code2 == 0: accept = True break # If both endpoints are outside rectangle else if (code1 & code2) != 0: break # Some segment lies within the rectangle else: # Line Needs clipping # At least one of the points is outside, # select it x = 1.0 y = 1.0 if code1 != 0: code_out = code1 else: code_out = code2 # Find intersection point # using formulas y = y1 + slope * (x - x1), # x = x1 + (1 / slope) * (y - y1) if code_out & TOP: # point is above the clip rectangle x = x1 + (x2 - x1) * \\ (y_max - y1) / (y2 - y1) y = y_max else if code_out & BOTTOM: # point is below the clip rectangle x = x1 + (x2 - x1) * \\ (y_min - y1) / (y2 - y1) y = y_min else if code_out & RIGHT: # point is to the right of the clip rectangle y = y1 + (y2 - y1) * \\ (x_max - x1) / (x2 - x1) x = x_max else if code_out & LEFT: # point is to the left of the clip rectangle y = y1 + (y2 - y1) * \\ (x_min - x1) / (x2 - x1) x = x_min # Now intersection point x, y is found # We replace point outside clipping rectangle # by intersection point if code_out == code1: x1 = x y1 = y code1 = computeCode(x1, y1) else: x2 = x y2 = y code2 = computeCode(x2, y2) if accept: print (\"Line accepted from %.2f, %.2f to %.2f, %.2f\" % (x1, y1, x2, y2)) # Here the user can add code to display the rectangle # along with the accepted (portion of) lines else: print(\"Line rejected\") # Driver Script# First Line segment# P11 = (5, 5), P12 = (7, 7)cohenSutherlandClip(5, 5, 7, 7) # Second Line segment# P21 = (7, 9), P22 = (11, 4)cohenSutherlandClip(7, 9, 11, 4) # Third Line segment# P31 = (1, 5), P32 = (4, 1)cohenSutherlandClip(1, 5, 4, 1)",
"e": 36981,
"s": 33511,
"text": null
},
{
"code": null,
"e": 36990,
"s": 36981,
"text": "Output: "
},
{
"code": null,
"e": 37093,
"s": 36990,
"text": "Line accepted from 5.00, 5.00 to 7.00, 7.00\nLine accepted from 7.80, 8.00 to 10.00, 5.25\nLine rejected"
},
{
"code": null,
"e": 37143,
"s": 37093,
"text": "Below is C++ code with Graphics using graphics.h "
},
{
"code": null,
"e": 37147,
"s": 37143,
"text": "C++"
},
{
"code": "// C++ program to implement Cohen Sutherland algorithm// for line clipping.// including libraries#include <bits/stdc++.h>#include <graphics.h>using namespace std; // Global Variablesint xmin, xmax, ymin, ymax; // Lines where co-ordinates are (x1, y1) and (x2, y2)struct lines { int x1, y1, x2, y2;}; // This will return the sign required.int sign(int x){ if (x > 0) return 1; else return 0;} // CohenSutherLand LineClipping Algorithm As Described in theory.// This will clip the lines as per window boundaries.void clip(struct lines mylines){ // arrays will store bits // Here bits implies initial Point whereas bite implies end points int bits[4], bite[4], i, var; // setting color of graphics to be RED setcolor(RED); // Finding Bits bits[0] = sign(xmin - mylines.x1); bite[0] = sign(xmin - mylines.x2); bits[1] = sign(mylines.x1 - xmax); bite[1] = sign(mylines.x2 - xmax); bits[2] = sign(ymin - mylines.y1); bite[2] = sign(ymin - mylines.y2); bits[3] = sign(mylines.y1 - ymax); bite[3] = sign(mylines.y2 - ymax); // initial will used for initial coordinates and end for final string initial = \"\", end = \"\", temp = \"\"; // convert bits to string for (i = 0; i < 4; i++) { if (bits[i] == 0) initial += '0'; else initial += '1'; } for (i = 0; i < 4; i++) { if (bite[i] == 0) end += '0'; else end += '1'; } // finding slope of line y=mx+c as (y-y1)=m(x-x1)+c // where m is slope m=dy/dx; float m = (mylines.y2 - mylines.y1) / (float)(mylines.x2 - mylines.x1); float c = mylines.y1 - m * mylines.x1; // if both points are inside the Accept the line and draw if (initial == end && end == \"0000\") { // inbuild function to draw the line from(x1, y1) to (x2, y2) line(mylines.x1, mylines.y1, mylines.x2, mylines.y2); return; } // this will contain cases where line maybe totally outside for partially inside else { // taking bitwise end of every value for (i = 0; i < 4; i++) { int val = (bits[i] & bite[i]); if (val == 0) temp += '0'; else temp += '1'; } // as per algo if AND is not 0000 means line is completely outside hence draw nothing and return if (temp != \"0000\") return; // Here contain cases of partial inside or outside // So check for every boundary one by one for (i = 0; i < 4; i++) { // if boths bit are same hence we cannot find any intersection with boundary so continue if (bits[i] == bite[i]) continue; // Otherwise there exist a intersection // Case when initial point is in left xmin if (i == 0 && bits[i] == 1) { var = round(m * xmin + c); mylines.y1 = var; mylines.x1 = xmin; } // Case when final point is in left xmin if (i == 0 && bite[i] == 1) { var = round(m * xmin + c); mylines.y2 = var; mylines.x2 = xmin; } // Case when initial point is in right of xmax if (i == 1 && bits[i] == 1) { var = round(m * xmax + c); mylines.y1 = var; mylines.x1 = xmax; } // Case when final point is in right of xmax if (i == 1 && bite[i] == 1) { var = round(m * xmax + c); mylines.y2 = var; mylines.x2 = xmax; } // Case when initial point is in top of ymin if (i == 2 && bits[i] == 1) { var = round((float)(ymin - c) / m); mylines.y1 = ymin; mylines.x1 = var; } // Case when final point is in top of ymin if (i == 2 && bite[i] == 1) { var = round((float)(ymin - c) / m); mylines.y2 = ymin; mylines.x2 = var; } // Case when initial point is in bottom of ymax if (i == 3 && bits[i] == 1) { var = round((float)(ymax - c) / m); mylines.y1 = ymax; mylines.x1 = var; } // Case when final point is in bottom of ymax if (i == 3 && bite[i] == 1) { var = round((float)(ymax - c) / m); mylines.y2 = ymax; mylines.x2 = var; } // Updating Bits at every point bits[0] = sign(xmin - mylines.x1); bite[0] = sign(xmin - mylines.x2); bits[1] = sign(mylines.x1 - xmax); bite[1] = sign(mylines.x2 - xmax); bits[2] = sign(ymin - mylines.y1); bite[2] = sign(ymin - mylines.y2); bits[3] = sign(mylines.y1 - ymax); bite[3] = sign(mylines.y2 - ymax); } // end of for loop // Initialize initial and end to NULL initial = \"\", end = \"\"; // Updating strings again by bit for (i = 0; i < 4; i++) { if (bits[i] == 0) initial += '0'; else initial += '1'; } for (i = 0; i < 4; i++) { if (bite[i] == 0) end += '0'; else end += '1'; } // If now both points lie inside or on boundary then simply draw the updated line if (initial == end && end == \"0000\") { line(mylines.x1, mylines.y1, mylines.x2, mylines.y2); return; } // else line was completely outside hence rejected else return; }} // Driver Functionint main(){ int gd = DETECT, gm; // Setting values of Clipping window xmin = 40; xmax = 100; ymin = 40; ymax = 80; // initialize the graph initgraph(&gd, &gm, NULL); // Drawing Window using Lines line(xmin, ymin, xmax, ymin); line(xmax, ymin, xmax, ymax); line(xmax, ymax, xmin, ymax); line(xmin, ymax, xmin, ymin); // Assume 4 lines to be clipped struct lines mylines[4]; // Setting the coordinated of 4 lines mylines[0].x1 = 30; mylines[0].y1 = 65; mylines[0].x2 = 55; mylines[0].y2 = 30; mylines[1].x1 = 60; mylines[1].y1 = 20; mylines[1].x2 = 100; mylines[1].y2 = 90; mylines[2].x1 = 60; mylines[2].y1 = 100; mylines[2].x2 = 80; mylines[2].y2 = 70; mylines[3].x1 = 85; mylines[3].y1 = 50; mylines[3].x2 = 120; mylines[3].y2 = 75; // Drawing Initial Lines without clipping for (int i = 0; i < 4; i++) { line(mylines[i].x1, mylines[i].y1, mylines[i].x2, mylines[i].y2); delay(1000); } // Drawing clipped Line for (int i = 0; i < 4; i++) { // Calling clip() which in term clip the line as per window and draw it clip(mylines[i]); delay(1000); } delay(4000); getch(); // For Closing the graph. closegraph(); return 0;}",
"e": 44175,
"s": 37147,
"text": null
},
{
"code": null,
"e": 44382,
"s": 44175,
"text": "The Cohen–Sutherland algorithm can be used only on a rectangular clip window. For other convex polygon clipping windows, Cyrus–Beck algorithm is used. We will be discussing Cyrus–Beck Algorithm in next set."
},
{
"code": null,
"e": 44976,
"s": 44382,
"text": "Related Post : Polygon Clipping | Sutherland–Hodgman Algorithm Point Clipping Algorithm in Computer GraphicsReference: https://en.wikipedia.org/wiki/Cohen–Sutherland_algorithmThis article is contributed by Saket Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 44985,
"s": 44976,
"text": "imkiller"
},
{
"code": null,
"e": 45001,
"s": 44985,
"text": "simranarora5sos"
},
{
"code": null,
"e": 45011,
"s": 45001,
"text": "as5853535"
},
{
"code": null,
"e": 45028,
"s": 45011,
"text": "surinderdawra388"
},
{
"code": null,
"e": 45044,
"s": 45028,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 45057,
"s": 45044,
"text": "simmytarika5"
},
{
"code": null,
"e": 45075,
"s": 45057,
"text": "computer-graphics"
},
{
"code": null,
"e": 45086,
"s": 45075,
"text": "Algorithms"
},
{
"code": null,
"e": 45096,
"s": 45086,
"text": "Geometric"
},
{
"code": null,
"e": 45106,
"s": 45096,
"text": "Geometric"
},
{
"code": null,
"e": 45117,
"s": 45106,
"text": "Algorithms"
},
{
"code": null,
"e": 45215,
"s": 45117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45264,
"s": 45215,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 45289,
"s": 45264,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 45316,
"s": 45289,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 45367,
"s": 45316,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 45394,
"s": 45367,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 45458,
"s": 45394,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 45516,
"s": 45458,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 45565,
"s": 45516,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 45616,
"s": 45565,
"text": "How to check if two given line segments intersect?"
}
] |
How can I intercept the Status Bar Notifications in Android? | This example demonstrate about How can I intercept the Status Bar Notifications in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to src/MyListener.java
public interface MyListener {
void setValue (String packageName) ;
}
Step 3 − Add the following code to src/MyListener.java
package app.tutorialspoint.com.notifyme ;
import android.content.Context ;
import android.service.notification.NotificationListenerService ;
import android.service.notification.StatusBarNotification ;
import android.util.Log ;
public class NotificationService extends NotificationListenerService {
private String TAG = this .getClass().getSimpleName() ;
Context context ;
static MyListener myListener ;
@Override
public void onCreate () {
super .onCreate() ;
context = getApplicationContext() ;
}
@Override
public void onNotificationPosted (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationPosted" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Post: " + sbn.getPackageName()) ;
}
@Override
public void onNotificationRemoved (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationRemoved" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Remove: " + sbn.getPackageName()) ;
}
public void setListener (MyListener myListener) {
NotificationService. myListener = myListener ;
}
}
Step 4 − Add the following code to res/menu/menu_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<menu xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
tools :context = ".MainActivity" >
<item
android :id = "@+id/action_settings"
android :orderInCategory = "100"
android :title = "Settings"
app :showAsAction = "never" />
</menu>
Step 5 − 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 :padding = "16dp"
tools :context = ".MainActivity" >
<Button
android :id = "@+id/btnCreateNotification"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_alignParentStart = "true"
android :layout_alignParentTop = "true"
android :layout_alignParentEnd = "true"
android :text = "Create Notification" />
<ScrollView
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :layout_below = "@+id/btnCreateNotification"
android :layout_alignStart = "@+id/btnCreateNotification"
android :layout_alignEnd = "@+id/btnCreateNotification"
android :layout_alignParentBottom = "true" >
<TextView
android :id = "@+id/textView"
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :text = "NotificationListenerService Example"
android :textAppearance = "?android:attr/textAppearanceMedium" />
</ScrollView>
</RelativeLayout>
Step 6 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.Menu ;
import android.view.MenuItem ;
import android.view.View ;
import android.widget.Button ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity implements MyListener {
private TextView txtView ;
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
new NotificationService().setListener( this ) ;
txtView = findViewById(R.id. textView ) ;
Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
NotificationManager mNotificationManager = (NotificationManager)
getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContentTitle( "My Notification" ) ;
mBuilder.setContentText( "Notification Listener Service Example" ) ;
mBuilder.setTicker( "Notification Listener Service Example" ) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}) ;
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id. action_settings :
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS" ) ;
startActivity(intent) ;
return true;
default :
return super .onOptionsItemSelected(item) ;
}
}
@Override
public void setValue (String packageName) {
txtView .append( " \n " + packageName) ;
}
}
Step 7 − 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.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme= "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android :name = ".NotificationService"
android :label = "@string/app_name"
android :permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android :name = "android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "This example demonstrate about How can I intercept the Status Bar Notifications in Android"
},
{
"code": null,
"e": 1282,
"s": 1153,
"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": 1337,
"s": 1282,
"text": "Step 2 − Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 1409,
"s": 1337,
"text": "public interface MyListener {\n void setValue (String packageName) ;\n}"
},
{
"code": null,
"e": 1464,
"s": 1409,
"text": "Step 3 − Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 2764,
"s": 1464,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.content.Context ;\nimport android.service.notification.NotificationListenerService ;\nimport android.service.notification.StatusBarNotification ;\nimport android.util.Log ;\npublic class NotificationService extends NotificationListenerService {\n private String TAG = this .getClass().getSimpleName() ;\n Context context ;\n static MyListener myListener ;\n @Override\n public void onCreate () {\n super .onCreate() ;\n context = getApplicationContext() ;\n }\n @Override\n public void onNotificationPosted (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationPosted\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Post: \" + sbn.getPackageName()) ;\n }\n @Override\n public void onNotificationRemoved (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationRemoved\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Remove: \" + sbn.getPackageName()) ;\n }\n public void setListener (MyListener myListener) {\n NotificationService. myListener = myListener ;\n }\n}"
},
{
"code": null,
"e": 2823,
"s": 2764,
"text": "Step 4 − Add the following code to res/menu/menu_main.xml."
},
{
"code": null,
"e": 3255,
"s": 2823,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n tools :context = \".MainActivity\" >\n <item\n android :id = \"@+id/action_settings\"\n android :orderInCategory = \"100\"\n android :title = \"Settings\"\n app :showAsAction = \"never\" />\n</menu>"
},
{
"code": null,
"e": 3320,
"s": 3255,
"text": "Step 5 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4653,
"s": 3320,
"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 :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :id = \"@+id/btnCreateNotification\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_alignParentStart = \"true\"\n android :layout_alignParentTop = \"true\"\n android :layout_alignParentEnd = \"true\"\n android :text = \"Create Notification\" />\n <ScrollView\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :layout_below = \"@+id/btnCreateNotification\"\n android :layout_alignStart = \"@+id/btnCreateNotification\"\n android :layout_alignEnd = \"@+id/btnCreateNotification\"\n android :layout_alignParentBottom = \"true\" >\n <TextView\n android :id = \"@+id/textView\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :text = \"NotificationListenerService Example\"\n android :textAppearance = \"?android:attr/textAppearanceMedium\" />\n </ScrollView>\n</RelativeLayout>"
},
{
"code": null,
"e": 4710,
"s": 4653,
"text": "Step 6 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 7862,
"s": 4710,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity implements MyListener {\n private TextView txtView ;\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n new NotificationService().setListener( this ) ;\n txtView = findViewById(R.id. textView ) ;\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n NotificationManager mNotificationManager = (NotificationManager)\n getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n }) ;\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n switch (item.getItemId()) {\n case R.id. action_settings :\n Intent intent = new Intent(\"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS\" ) ;\n startActivity(intent) ;\n return true;\n default :\n return super .onOptionsItemSelected(item) ;\n }\n }\n @Override\n public void setValue (String packageName) {\n txtView .append( \" \\n \" + packageName) ;\n }\n}"
},
{
"code": null,
"e": 7917,
"s": 7862,
"text": "Step 7 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 9077,
"s": 7917,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name = \".NotificationService\"\n android :label = \"@string/app_name\"\n android :permission = \"android.permission.BIND_NOTIFICATION_LISTENER_SERVICE\" >\n <intent-filter>\n <action android :name = \"android.service.notification.NotificationListenerService\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9424,
"s": 9077,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 9466,
"s": 9424,
"text": "Click here to download the project code"
}
] |
Scale the Columns of a Matrix in R Programming – scale() Function | 09 Dec, 2021
scale() function in R Language is a generic function which centers and scales the columns of a numeric matrix. The center parameter takes either numeric alike vector or logical value. If the numeric vector is provided, then each column of the matrix has the corresponding value from center subtracted from it. If the logical value is provided TRUE, then column means of the matrix is subtracted from their corresponding columns. The scale takes either numeric alike vector or logical value. When provided with a numeric like vector, then each column of the matrix is divided by the corresponding value from scale. If the logical value is provided in scale parameter, then centered columns of the matrix is divided by their standard deviations, and the root mean square otherwise. If FALSE, no scaling is done on the matrix.
Syntax:scale(x, center = TRUE, scale = TRUE)
Parameters:x: represents numeric matrixcenter: represents either logical value or numeric alike vector equal to the number of xscale: represents either logical value or numeric alike vector equal to the number of x
Example 1:
r
# Create matrixmt <- matrix(1:10, ncol = 5) # Print matrixcat("Matrix:\n")print(mt) # Scale matrix with default argumentscat("\nAfter scaling:\n")scale(mt)
Output:
Matrix:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 3 5 7 9
[2, ] 2 4 6 8 10
After scaling:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] -0.7071068 -0.7071068 -0.7071068 -0.7071068 -0.7071068
[2, ] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068
attr(, "scaled:center")
[1] 1.5 3.5 5.5 7.5 9.5
attr(, "scaled:scale")
[1] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068
Example 2:
r
# Create matrixmt <- matrix(1:10, ncol = 2) # Print matrixcat("Matrix:\n")print(mt) # Scale center by vector of valuescat("\nScale center by vector of values:\n")scale(mt, center = c(1, 2), scale = FALSE) # Scale by vector of valuescat("\nScale by vector of values:\n")scale(mt, center = FALSE, scale = c(1, 2))
Output:
Matrix:
[, 1] [, 2]
[1, ] 1 6
[2, ] 2 7
[3, ] 3 8
[4, ] 4 9
[5, ] 5 10
Scale center by vector of values:
[, 1] [, 2]
[1, ] 0 4
[2, ] 1 5
[3, ] 2 6
[4, ] 3 7
[5, ] 4 8
attr(, "scaled:center")
[1] 1 2
Scale by vector of values:
[, 1] [, 2]
[1, ] 1 3.0
[2, ] 2 3.5
[3, ] 3 4.0
[4, ] 4 4.5
[5, ] 5 5.0
attr(, "scaled:scale")
[1] 1 2
sooda367
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 852,
"s": 28,
"text": "scale() function in R Language is a generic function which centers and scales the columns of a numeric matrix. The center parameter takes either numeric alike vector or logical value. If the numeric vector is provided, then each column of the matrix has the corresponding value from center subtracted from it. If the logical value is provided TRUE, then column means of the matrix is subtracted from their corresponding columns. The scale takes either numeric alike vector or logical value. When provided with a numeric like vector, then each column of the matrix is divided by the corresponding value from scale. If the logical value is provided in scale parameter, then centered columns of the matrix is divided by their standard deviations, and the root mean square otherwise. If FALSE, no scaling is done on the matrix."
},
{
"code": null,
"e": 897,
"s": 852,
"text": "Syntax:scale(x, center = TRUE, scale = TRUE)"
},
{
"code": null,
"e": 1112,
"s": 897,
"text": "Parameters:x: represents numeric matrixcenter: represents either logical value or numeric alike vector equal to the number of xscale: represents either logical value or numeric alike vector equal to the number of x"
},
{
"code": null,
"e": 1123,
"s": 1112,
"text": "Example 1:"
},
{
"code": null,
"e": 1125,
"s": 1123,
"text": "r"
},
{
"code": "# Create matrixmt <- matrix(1:10, ncol = 5) # Print matrixcat(\"Matrix:\\n\")print(mt) # Scale matrix with default argumentscat(\"\\nAfter scaling:\\n\")scale(mt)",
"e": 1283,
"s": 1125,
"text": null
},
{
"code": null,
"e": 1291,
"s": 1283,
"text": "Output:"
},
{
"code": null,
"e": 1725,
"s": 1291,
"text": "Matrix:\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 3 5 7 9\n[2, ] 2 4 6 8 10\n\nAfter scaling:\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] -0.7071068 -0.7071068 -0.7071068 -0.7071068 -0.7071068\n[2, ] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068\nattr(, \"scaled:center\")\n[1] 1.5 3.5 5.5 7.5 9.5\nattr(, \"scaled:scale\")\n[1] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068\n"
},
{
"code": null,
"e": 1736,
"s": 1725,
"text": "Example 2:"
},
{
"code": null,
"e": 1738,
"s": 1736,
"text": "r"
},
{
"code": "# Create matrixmt <- matrix(1:10, ncol = 2) # Print matrixcat(\"Matrix:\\n\")print(mt) # Scale center by vector of valuescat(\"\\nScale center by vector of values:\\n\")scale(mt, center = c(1, 2), scale = FALSE) # Scale by vector of valuescat(\"\\nScale by vector of values:\\n\")scale(mt, center = FALSE, scale = c(1, 2))",
"e": 2053,
"s": 1738,
"text": null
},
{
"code": null,
"e": 2061,
"s": 2053,
"text": "Output:"
},
{
"code": null,
"e": 2487,
"s": 2061,
"text": "Matrix:\n [, 1] [, 2]\n[1, ] 1 6\n[2, ] 2 7\n[3, ] 3 8\n[4, ] 4 9\n[5, ] 5 10\n\nScale center by vector of values:\n [, 1] [, 2]\n[1, ] 0 4\n[2, ] 1 5\n[3, ] 2 6\n[4, ] 3 7\n[5, ] 4 8\nattr(, \"scaled:center\")\n[1] 1 2\n\nScale by vector of values:\n [, 1] [, 2]\n[1, ] 1 3.0\n[2, ] 2 3.5\n[3, ] 3 4.0\n[4, ] 4 4.5\n[5, ] 5 5.0\nattr(, \"scaled:scale\")\n[1] 1 2\n"
},
{
"code": null,
"e": 2496,
"s": 2487,
"text": "sooda367"
},
{
"code": null,
"e": 2514,
"s": 2496,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 2525,
"s": 2514,
"text": "R Language"
}
] |
How to add an object to an array in JavaScript ? | 20 Jul, 2021
There are 3 popular methods which can be used to insert or add an object to an array.
push()
splice()
unshift()
Method 1: push() method of Array
The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
Syntax:
array.push(objectName)
Example:
<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style="color: green">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick="pushFunction()">Add elements</button> <p id="geeks"></p> <script> var list = ["One", "Two", "Three"]; document.getElementById("geeks").innerHTML = list; function pushFunction() { list.push("Four", "Five", ); document.getElementById("geeks").innerHTML = list; } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: splice() method
The splice method is used to both remove and add elements from a specific index. It takes 3 parameters, the starting index, the number of elements to delete and then the items to be added to the array. An object can only be added without deleting any other element by specifying the second parameter to 0.
The object to be inserted is passed to the method and the index where it is to be inserted is specified. This inserts the object at the specified index.
Syntax:
arr.splice(index, 0, objectName)
Example:
<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style="color: green">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick="spliceFunction()">Add elements</button> <p id="geeks"></p> <script> var list = ["HTML", "CSS", "JavaScript"]; document.getElementById("geeks").innerHTML = list; function spliceFunction() { list.splice(2,0,"Angular", "SQL", ); document.getElementById("geeks").innerHTML = list; } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 3: unshift() method
The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array.
Syntax:
arr.unshift(object);
Example:
<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style="color: green">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick="unshiftFunction()">Add elements</button> <p id="geeks"></p> <script> var list = ["Geeks", "Contribute", "Explore"]; document.getElementById("geeks").innerHTML = list; function unshiftFunction() { list.unshift("for", "Geeks", ); document.getElementById("geeks").innerHTML = list; } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Google Chrome 1.1 or above
Mozilla Firefox 1.1 or above
Safari
Internet Explore 5.5 or above
Opera
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
arorakashish0911
javascript-array
javascript-object
Picked
JavaScript
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "There are 3 popular methods which can be used to insert or add an object to an array."
},
{
"code": null,
"e": 121,
"s": 114,
"text": "push()"
},
{
"code": null,
"e": 130,
"s": 121,
"text": "splice()"
},
{
"code": null,
"e": 140,
"s": 130,
"text": "unshift()"
},
{
"code": null,
"e": 173,
"s": 140,
"text": "Method 1: push() method of Array"
},
{
"code": null,
"e": 432,
"s": 173,
"text": "The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array."
},
{
"code": null,
"e": 440,
"s": 432,
"text": "Syntax:"
},
{
"code": null,
"e": 463,
"s": 440,
"text": "array.push(objectName)"
},
{
"code": null,
"e": 472,
"s": 463,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style=\"color: green\">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick=\"pushFunction()\">Add elements</button> <p id=\"geeks\"></p> <script> var list = [\"One\", \"Two\", \"Three\"]; document.getElementById(\"geeks\").innerHTML = list; function pushFunction() { list.push(\"Four\", \"Five\", ); document.getElementById(\"geeks\").innerHTML = list; } </script> </body> </html>",
"e": 1119,
"s": 472,
"text": null
},
{
"code": null,
"e": 1127,
"s": 1119,
"text": "Output:"
},
{
"code": null,
"e": 1155,
"s": 1127,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1182,
"s": 1155,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1208,
"s": 1182,
"text": "Method 2: splice() method"
},
{
"code": null,
"e": 1514,
"s": 1208,
"text": "The splice method is used to both remove and add elements from a specific index. It takes 3 parameters, the starting index, the number of elements to delete and then the items to be added to the array. An object can only be added without deleting any other element by specifying the second parameter to 0."
},
{
"code": null,
"e": 1667,
"s": 1514,
"text": "The object to be inserted is passed to the method and the index where it is to be inserted is specified. This inserts the object at the specified index."
},
{
"code": null,
"e": 1675,
"s": 1667,
"text": "Syntax:"
},
{
"code": null,
"e": 1708,
"s": 1675,
"text": "arr.splice(index, 0, objectName)"
},
{
"code": null,
"e": 1717,
"s": 1708,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style=\"color: green\">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick=\"spliceFunction()\">Add elements</button> <p id=\"geeks\"></p> <script> var list = [\"HTML\", \"CSS\", \"JavaScript\"]; document.getElementById(\"geeks\").innerHTML = list; function spliceFunction() { list.splice(2,0,\"Angular\", \"SQL\", ); document.getElementById(\"geeks\").innerHTML = list; } </script> </body> </html> ",
"e": 2394,
"s": 1717,
"text": null
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Output:"
},
{
"code": null,
"e": 2430,
"s": 2402,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2457,
"s": 2430,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2484,
"s": 2457,
"text": "Method 3: unshift() method"
},
{
"code": null,
"e": 2758,
"s": 2484,
"text": "The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array."
},
{
"code": null,
"e": 2766,
"s": 2758,
"text": "Syntax:"
},
{
"code": null,
"e": 2787,
"s": 2766,
"text": "arr.unshift(object);"
},
{
"code": null,
"e": 2796,
"s": 2787,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Adding object in array</title> <style> body { text-align: center; } </style></head> <body> <h1 style=\"color: green\">Geeksforgeeks</h1> <p>Click the button to add new elements to the array.</p> <button onclick=\"unshiftFunction()\">Add elements</button> <p id=\"geeks\"></p> <script> var list = [\"Geeks\", \"Contribute\", \"Explore\"]; document.getElementById(\"geeks\").innerHTML = list; function unshiftFunction() { list.unshift(\"for\", \"Geeks\", ); document.getElementById(\"geeks\").innerHTML = list; } </script> </body> </html>",
"e": 3463,
"s": 2796,
"text": null
},
{
"code": null,
"e": 3471,
"s": 3463,
"text": "Output:"
},
{
"code": null,
"e": 3499,
"s": 3471,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3526,
"s": 3499,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3553,
"s": 3526,
"text": "Google Chrome 1.1 or above"
},
{
"code": null,
"e": 3582,
"s": 3553,
"text": "Mozilla Firefox 1.1 or above"
},
{
"code": null,
"e": 3589,
"s": 3582,
"text": "Safari"
},
{
"code": null,
"e": 3619,
"s": 3589,
"text": "Internet Explore 5.5 or above"
},
{
"code": null,
"e": 3625,
"s": 3619,
"text": "Opera"
},
{
"code": null,
"e": 3844,
"s": 3625,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3861,
"s": 3844,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3878,
"s": 3861,
"text": "javascript-array"
},
{
"code": null,
"e": 3896,
"s": 3878,
"text": "javascript-object"
},
{
"code": null,
"e": 3903,
"s": 3896,
"text": "Picked"
},
{
"code": null,
"e": 3914,
"s": 3903,
"text": "JavaScript"
},
{
"code": null,
"e": 4012,
"s": 3914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4073,
"s": 4012,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4145,
"s": 4073,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4185,
"s": 4145,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4238,
"s": 4185,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4279,
"s": 4238,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4331,
"s": 4279,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4377,
"s": 4331,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 4446,
"s": 4377,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 4473,
"s": 4446,
"text": "File uploading in React.js"
}
] |
Node.js process.stdout Property | 01 Jun, 2021
The process.stdout property is an inbuilt application programming interface of the process module which is used to send data out of our program. A Writable Stream to stdout. It implements a write() method.
Syntax:
process.stdout.write()
Return Value: This property continuously prints the information as the data being retrieved and doesn’t add a new line.
Parameters: This property takes only single strings as an argument.
Note:
It only takes strings as arguments. Any other data type passed as a parameter will throw a TypeError.
It can be useful for printing patterns as it does not add a new line.
We can not write more than one string.
We can not make associations.
Below examples illustrate the use of process.stdout property in Node.js:
Example 1: Create a JavaScript file and name this file as index.js.
Javascript
// Node.js program to demonstrate the// process.stdout Property // Printing process.stdout property valueprocess.stdout.write('Greetings of the day');
Run the index.js file using the following command:
node index.js
Output:
Greetings of the day
Example 2: Create a JavaScript file and name this file as index.js.
Javascript
// Node.js program to demonstrate the// process.stdout Property // For process.std.out // Association is not possibleprocess.stdout.write("Geeks");process.stdout.write("for");process.stdout.write("Geeks");
Run the index.js file using the following command:
node index.js
Output:
GeeksforGeeks
simmytarika5
Node.js-Methods
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 260,
"s": 53,
"text": "The process.stdout property is an inbuilt application programming interface of the process module which is used to send data out of our program. A Writable Stream to stdout. It implements a write() method. "
},
{
"code": null,
"e": 268,
"s": 260,
"text": "Syntax:"
},
{
"code": null,
"e": 291,
"s": 268,
"text": "process.stdout.write()"
},
{
"code": null,
"e": 411,
"s": 291,
"text": "Return Value: This property continuously prints the information as the data being retrieved and doesn’t add a new line."
},
{
"code": null,
"e": 479,
"s": 411,
"text": "Parameters: This property takes only single strings as an argument."
},
{
"code": null,
"e": 489,
"s": 483,
"text": "Note:"
},
{
"code": null,
"e": 593,
"s": 491,
"text": "It only takes strings as arguments. Any other data type passed as a parameter will throw a TypeError."
},
{
"code": null,
"e": 663,
"s": 593,
"text": "It can be useful for printing patterns as it does not add a new line."
},
{
"code": null,
"e": 702,
"s": 663,
"text": "We can not write more than one string."
},
{
"code": null,
"e": 732,
"s": 702,
"text": "We can not make associations."
},
{
"code": null,
"e": 805,
"s": 732,
"text": "Below examples illustrate the use of process.stdout property in Node.js:"
},
{
"code": null,
"e": 875,
"s": 807,
"text": "Example 1: Create a JavaScript file and name this file as index.js."
},
{
"code": null,
"e": 888,
"s": 877,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// process.stdout Property // Printing process.stdout property valueprocess.stdout.write('Greetings of the day');",
"e": 1039,
"s": 888,
"text": null
},
{
"code": null,
"e": 1090,
"s": 1039,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1104,
"s": 1090,
"text": "node index.js"
},
{
"code": null,
"e": 1112,
"s": 1104,
"text": "Output:"
},
{
"code": null,
"e": 1133,
"s": 1112,
"text": "Greetings of the day"
},
{
"code": null,
"e": 1201,
"s": 1133,
"text": "Example 2: Create a JavaScript file and name this file as index.js."
},
{
"code": null,
"e": 1212,
"s": 1201,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// process.stdout Property // For process.std.out // Association is not possibleprocess.stdout.write(\"Geeks\");process.stdout.write(\"for\");process.stdout.write(\"Geeks\");",
"e": 1418,
"s": 1212,
"text": null
},
{
"code": null,
"e": 1469,
"s": 1418,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1483,
"s": 1469,
"text": "node index.js"
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "Output:"
},
{
"code": null,
"e": 1505,
"s": 1491,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1518,
"s": 1505,
"text": "simmytarika5"
},
{
"code": null,
"e": 1534,
"s": 1518,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 1557,
"s": 1534,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": "Picked"
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Node.js"
},
{
"code": null,
"e": 1589,
"s": 1572,
"text": "Web Technologies"
},
{
"code": null,
"e": 1687,
"s": 1589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1719,
"s": 1687,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 1754,
"s": 1719,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1824,
"s": 1754,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 1851,
"s": 1824,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 1876,
"s": 1851,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 1926,
"s": 1876,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1988,
"s": 1926,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2046,
"s": 1988,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2106,
"s": 2046,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Program to print double headed arrow pattern | 11 Jun, 2021
Given an integer N which is the number of rows, the task is to draw the number pattern in the shape of a double headed arrow.Prerequisite: The pattern is a grow and shrink type pattern and hence basic knowledge to execute loops is required to understand the topic and the code in any language. The geometric shape can be visualized as-
Examples:
Input: R = 7
Output:
1
2 1 1 2
3 2 1 1 2 3
4 3 2 1 1 2 3 4
3 2 1 1 2 3
2 1 1 2
1
Input: R = 9
Output:
1
2 1 1 2
3 2 1 1 2 3
4 3 2 1 1 2 3 4
5 4 3 2 1 1 2 3 4 5
4 3 2 1 1 2 3 4
3 2 1 1 2 3
2 1 1 2
1
Approach:
In the given example, N=7 and the number of ROWS is 7.VERTICALLY, the pattern GROWS till ROW=N/2 and SHRINKS afterwards.ROW 1 has 4 ” “(SPACE) characters and then a value.The number of SPACE characters decreases whereas NUMERALS increase in count in each successive row.Also, note that the 1st value of the number placed in each row is the same as the number of the row.Also HORIZONTALLY the pattern has NUMERALS, then SPACES and NUMERALS afterwards.
In the given example, N=7 and the number of ROWS is 7.
VERTICALLY, the pattern GROWS till ROW=N/2 and SHRINKS afterwards.
ROW 1 has 4 ” “(SPACE) characters and then a value.
The number of SPACE characters decreases whereas NUMERALS increase in count in each successive row.
Also, note that the 1st value of the number placed in each row is the same as the number of the row.
Also HORIZONTALLY the pattern has NUMERALS, then SPACES and NUMERALS afterwards.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to print the required patternvoid drawPattern(int N){ int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { cout << " " << " "; csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { cout << val1 << " "; val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { cout << " " << " "; csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { cout << val2 << " "; val2 = val2 + 1; cst2 = cst2 + 1; } } cout << endl; // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; }} // Driver codeint main(){ // Number of rows int N = 7; drawPattern(N); return 0;}
// Java implementation of the approachclass GFG { // Function to print the required pattern static void drawPattern(int N) { int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { System.out.print(" "); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { System.out.print(val1 + " "); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { System.out.print(" "); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { System.out.print(val2 + " "); val2 = val2 + 1; cst2 = cst2 + 1; } } System.out.println(); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code public static void main(String args[]) { // Number of rows int N = 7; drawPattern(N); }}
# Python3 implementation of the approach # Function to print the required patterndef drawPattern(N) : n = N; row = 1; # 'nst' is the number of values nst = 1; # 'nsp' is the number of spaces nsp1 = n - 1; nsp2 = -1; val1 = row; val2 = 1; while (row <= n) : # Here spaces are printed # 'csp' is the count of spaces csp1 = 1; while (csp1 <= nsp1) : print(" ",end= " "); csp1 = csp1 + 1; # Now, values are printed # 'cst' is the count of stars cst1 = 1; while (cst1 <= nst) : print(val1,end = " "); val1 = val1 - 1; cst1 = cst1 + 1; # Again spaces have to be printed csp2 = 1; while (csp2 <= nsp2) : print(" ",end = " "); csp2 = csp2 + 1; # Again values have to be printed if (row != 1 and row != n) : cst2 = 1; while (cst2 <= nst) : print(val2,end = " "); val2 = val2 + 1; cst2 = cst2 + 1; print() # Move to the next row if (row <= n // 2) : nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; else : nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; row = row + 1; # Driver codeif __name__ == "__main__" : # Number of rows N = 7; drawPattern(N); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to print the required pattern static void drawPattern(int N) { int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { Console.Write(" "); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { Console.Write(val1 + " "); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { Console.Write(" "); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { Console.Write(val2 + " "); val2 = val2 + 1; cst2 = cst2 + 1; } } Console.WriteLine(); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code public static void Main() { // Number of rows int N = 7; drawPattern(N); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach // Function to print the required pattern function drawPattern(N) { var n = N; var row = 1; // 'nst' is the number of values var nst = 1; // 'nsp' is the number of spaces var nsp1 = n - 1; var nsp2 = -1; var val1 = row; var val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces var csp1 = 1; while (csp1 <= nsp1) { document.write(" " + " "); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars var cst1 = 1; while (cst1 <= nst) { document.write(val1 + " "); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed var csp2 = 1; while (csp2 <= nsp2) { document.write(" " + " "); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { var cst2 = 1; while (cst2 <= nst) { document.write(val2 + " "); val2 = val2 + 1; cst2 = cst2 + 1; } } document.write("<br>"); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code // Number of rows var N = 7; drawPattern(N); </script>
1
2 1 1 2
3 2 1 1 2 3
4 3 2 1 1 2 3 4
3 2 1 1 2 3
2 1 1 2
1
Time Complexity: O(N2) Space Complexity: O(1)
medha130101
ankthon
rdtank
anikaseth98
pattern-printing
Analysis
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 392,
"s": 54,
"text": "Given an integer N which is the number of rows, the task is to draw the number pattern in the shape of a double headed arrow.Prerequisite: The pattern is a grow and shrink type pattern and hence basic knowledge to execute loops is required to understand the topic and the code in any language. The geometric shape can be visualized as- "
},
{
"code": null,
"e": 404,
"s": 392,
"text": "Examples: "
},
{
"code": null,
"e": 890,
"s": 404,
"text": "Input: R = 7\nOutput: \n 1\n 2 1 1 2\n 3 2 1 1 2 3\n 4 3 2 1 1 2 3 4\n 3 2 1 1 2 3\n 2 1 1 2\n 1\n\nInput: R = 9\nOutput:\n 1\n 2 1 1 2\n 3 2 1 1 2 3\n 4 3 2 1 1 2 3 4\n 5 4 3 2 1 1 2 3 4 5\n 4 3 2 1 1 2 3 4\n 3 2 1 1 2 3\n 2 1 1 2\n 1"
},
{
"code": null,
"e": 904,
"s": 892,
"text": "Approach: "
},
{
"code": null,
"e": 1355,
"s": 904,
"text": "In the given example, N=7 and the number of ROWS is 7.VERTICALLY, the pattern GROWS till ROW=N/2 and SHRINKS afterwards.ROW 1 has 4 ” “(SPACE) characters and then a value.The number of SPACE characters decreases whereas NUMERALS increase in count in each successive row.Also, note that the 1st value of the number placed in each row is the same as the number of the row.Also HORIZONTALLY the pattern has NUMERALS, then SPACES and NUMERALS afterwards."
},
{
"code": null,
"e": 1410,
"s": 1355,
"text": "In the given example, N=7 and the number of ROWS is 7."
},
{
"code": null,
"e": 1477,
"s": 1410,
"text": "VERTICALLY, the pattern GROWS till ROW=N/2 and SHRINKS afterwards."
},
{
"code": null,
"e": 1529,
"s": 1477,
"text": "ROW 1 has 4 ” “(SPACE) characters and then a value."
},
{
"code": null,
"e": 1629,
"s": 1529,
"text": "The number of SPACE characters decreases whereas NUMERALS increase in count in each successive row."
},
{
"code": null,
"e": 1730,
"s": 1629,
"text": "Also, note that the 1st value of the number placed in each row is the same as the number of the row."
},
{
"code": null,
"e": 1811,
"s": 1730,
"text": "Also HORIZONTALLY the pattern has NUMERALS, then SPACES and NUMERALS afterwards."
},
{
"code": null,
"e": 1863,
"s": 1811,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1867,
"s": 1863,
"text": "C++"
},
{
"code": null,
"e": 1872,
"s": 1867,
"text": "Java"
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Python3"
},
{
"code": null,
"e": 1883,
"s": 1880,
"text": "C#"
},
{
"code": null,
"e": 1894,
"s": 1883,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to print the required patternvoid drawPattern(int N){ int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { cout << \" \" << \" \"; csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { cout << val1 << \" \"; val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { cout << \" \" << \" \"; csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { cout << val2 << \" \"; val2 = val2 + 1; cst2 = cst2 + 1; } } cout << endl; // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; }} // Driver codeint main(){ // Number of rows int N = 7; drawPattern(N); return 0;}",
"e": 3616,
"s": 1894,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to print the required pattern static void drawPattern(int N) { int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { System.out.print(\" \"); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { System.out.print(val1 + \" \"); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { System.out.print(\" \"); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { System.out.print(val2 + \" \"); val2 = val2 + 1; cst2 = cst2 + 1; } } System.out.println(); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code public static void main(String args[]) { // Number of rows int N = 7; drawPattern(N); }}",
"e": 5611,
"s": 3616,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to print the required patterndef drawPattern(N) : n = N; row = 1; # 'nst' is the number of values nst = 1; # 'nsp' is the number of spaces nsp1 = n - 1; nsp2 = -1; val1 = row; val2 = 1; while (row <= n) : # Here spaces are printed # 'csp' is the count of spaces csp1 = 1; while (csp1 <= nsp1) : print(\" \",end= \" \"); csp1 = csp1 + 1; # Now, values are printed # 'cst' is the count of stars cst1 = 1; while (cst1 <= nst) : print(val1,end = \" \"); val1 = val1 - 1; cst1 = cst1 + 1; # Again spaces have to be printed csp2 = 1; while (csp2 <= nsp2) : print(\" \",end = \" \"); csp2 = csp2 + 1; # Again values have to be printed if (row != 1 and row != n) : cst2 = 1; while (cst2 <= nst) : print(val2,end = \" \"); val2 = val2 + 1; cst2 = cst2 + 1; print() # Move to the next row if (row <= n // 2) : nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; else : nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; row = row + 1; # Driver codeif __name__ == \"__main__\" : # Number of rows N = 7; drawPattern(N); # This code is contributed by AnkitRai01",
"e": 7207,
"s": 5611,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to print the required pattern static void drawPattern(int N) { int n = N; int row = 1; // 'nst' is the number of values int nst = 1; // 'nsp' is the number of spaces int nsp1 = n - 1; int nsp2 = -1; int val1 = row; int val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces int csp1 = 1; while (csp1 <= nsp1) { Console.Write(\" \"); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars int cst1 = 1; while (cst1 <= nst) { Console.Write(val1 + \" \"); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed int csp2 = 1; while (csp2 <= nsp2) { Console.Write(\" \"); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { int cst2 = 1; while (cst2 <= nst) { Console.Write(val2 + \" \"); val2 = val2 + 1; cst2 = cst2 + 1; } } Console.WriteLine(); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code public static void Main() { // Number of rows int N = 7; drawPattern(N); }} // This code is contributed by AnkitRai01",
"e": 9315,
"s": 7207,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to print the required pattern function drawPattern(N) { var n = N; var row = 1; // 'nst' is the number of values var nst = 1; // 'nsp' is the number of spaces var nsp1 = n - 1; var nsp2 = -1; var val1 = row; var val2 = 1; while (row <= n) { // Here spaces are printed // 'csp' is the count of spaces var csp1 = 1; while (csp1 <= nsp1) { document.write(\" \" + \" \"); csp1 = csp1 + 1; } // Now, values are printed // 'cst' is the count of stars var cst1 = 1; while (cst1 <= nst) { document.write(val1 + \" \"); val1 = val1 - 1; cst1 = cst1 + 1; } // Again spaces have to be printed var csp2 = 1; while (csp2 <= nsp2) { document.write(\" \" + \" \"); csp2 = csp2 + 1; } // Again values have to be printed if (row != 1 && row != n) { var cst2 = 1; while (cst2 <= nst) { document.write(val2 + \" \"); val2 = val2 + 1; cst2 = cst2 + 1; } } document.write(\"<br>\"); // Move to the next row if (row <= n / 2) { nst = nst + 1; nsp1 = nsp1 - 2; nsp2 = nsp2 + 2; val1 = row + 1; val2 = 1; } else { nst = nst - 1; nsp1 = nsp1 + 2; nsp2 = nsp2 - 2; val1 = n - row; val2 = 1; } row = row + 1; } } // Driver code // Number of rows var N = 7; drawPattern(N); </script>",
"e": 11123,
"s": 9315,
"text": null
},
{
"code": null,
"e": 11263,
"s": 11123,
"text": " 1 \n 2 1 1 2 \n 3 2 1 1 2 3 \n4 3 2 1 1 2 3 4 \n 3 2 1 1 2 3 \n 2 1 1 2 \n 1"
},
{
"code": null,
"e": 11312,
"s": 11265,
"text": "Time Complexity: O(N2) Space Complexity: O(1) "
},
{
"code": null,
"e": 11324,
"s": 11312,
"text": "medha130101"
},
{
"code": null,
"e": 11332,
"s": 11324,
"text": "ankthon"
},
{
"code": null,
"e": 11339,
"s": 11332,
"text": "rdtank"
},
{
"code": null,
"e": 11351,
"s": 11339,
"text": "anikaseth98"
},
{
"code": null,
"e": 11368,
"s": 11351,
"text": "pattern-printing"
},
{
"code": null,
"e": 11377,
"s": 11368,
"text": "Analysis"
},
{
"code": null,
"e": 11394,
"s": 11377,
"text": "pattern-printing"
}
] |
How to check if an element has any children in JavaScript ? | 31 Jul, 2019
The task is find out whether an element is having child elements or not with the help of JavaScript. We’re going to discuss few techniques.
Approach:
Select the Parent Element.
Use one of the firstChild, childNodes.length, children.length property to find whether element has child or not.
hasChildNodes() method can also be used to find the child of the parent node.
Example 1: In this example, hasChildNodes() method is used to determine the child of <div> element.
<!DOCTYPE HTML><html> <head> <title> How to check if element has any children in JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <div id="div"> <p id="GFG_UP" style= "font-size: 19px; font-weight: bold;"> </p> </div> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style= "color:green; font-size:24px; font-weight:bold;"> </p> <script> var parentDiv = document.getElementById("div"); var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to check " + "whether element has children."; function GFG_Fun() { var ans = "Element <div> has no children"; if (parentDiv.hasChildNodes()) { ans = "Element <div> has children"; } el_down.innerHTML = ans; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, children.length Property is used to determine the child of <div> element.
<!DOCTYPE HTML><html> <head> <title> How to check if element has any children in JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <div id="div"> <p id="GFG_UP" style= "font-size: 19px; font-weight: bold;"> </p> </div> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style= "color:green; font-size:24px; font-weight:bold;"> </p> <script> var parentDiv = document.getElementById("div"); var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to "+ "check whether element has children."; function GFG_Fun() { var ans = "Element <div> has no children"; if (parentDiv.children.length > 0) { ans = "Element <div> has children"; } el_down.innerHTML = ans; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to float three div side by side using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2019"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "The task is find out whether an element is having child elements or not with the help of JavaScript. We’re going to discuss few techniques."
},
{
"code": null,
"e": 178,
"s": 168,
"text": "Approach:"
},
{
"code": null,
"e": 205,
"s": 178,
"text": "Select the Parent Element."
},
{
"code": null,
"e": 318,
"s": 205,
"text": "Use one of the firstChild, childNodes.length, children.length property to find whether element has child or not."
},
{
"code": null,
"e": 396,
"s": 318,
"text": "hasChildNodes() method can also be used to find the child of the parent node."
},
{
"code": null,
"e": 496,
"s": 396,
"text": "Example 1: In this example, hasChildNodes() method is used to determine the child of <div> element."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to check if element has any children in JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <div id=\"div\"> <p id=\"GFG_UP\" style= \"font-size: 19px; font-weight: bold;\"> </p> </div> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style= \"color:green; font-size:24px; font-weight:bold;\"> </p> <script> var parentDiv = document.getElementById(\"div\"); var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to check \" + \"whether element has children.\"; function GFG_Fun() { var ans = \"Element <div> has no children\"; if (parentDiv.hasChildNodes()) { ans = \"Element <div> has children\"; } el_down.innerHTML = ans; } </script></body> </html>",
"e": 1620,
"s": 496,
"text": null
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Output:"
},
{
"code": null,
"e": 1659,
"s": 1628,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1689,
"s": 1659,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1791,
"s": 1689,
"text": "Example 2: In this example, children.length Property is used to determine the child of <div> element."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to check if element has any children in JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <div id=\"div\"> <p id=\"GFG_UP\" style= \"font-size: 19px; font-weight: bold;\"> </p> </div> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style= \"color:green; font-size:24px; font-weight:bold;\"> </p> <script> var parentDiv = document.getElementById(\"div\"); var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to \"+ \"check whether element has children.\"; function GFG_Fun() { var ans = \"Element <div> has no children\"; if (parentDiv.children.length > 0) { ans = \"Element <div> has children\"; } el_down.innerHTML = ans; } </script></body> </html>",
"e": 2914,
"s": 1791,
"text": null
},
{
"code": null,
"e": 2922,
"s": 2914,
"text": "Output:"
},
{
"code": null,
"e": 2953,
"s": 2922,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2983,
"s": 2953,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2999,
"s": 2983,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3010,
"s": 2999,
"text": "JavaScript"
},
{
"code": null,
"e": 3027,
"s": 3010,
"text": "Web Technologies"
},
{
"code": null,
"e": 3054,
"s": 3027,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3152,
"s": 3054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3194,
"s": 3152,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3255,
"s": 3194,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3327,
"s": 3255,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3367,
"s": 3327,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3408,
"s": 3367,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3470,
"s": 3408,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3517,
"s": 3470,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 3550,
"s": 3517,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3611,
"s": 3550,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
exception::what() in C++ with Examples | 28 May, 2020
The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same:
Header File:
#include<exception>
Syntax:
virtual const char* what() const throw();
Return: The function std::what() return a null terminated character sequence that is used to identify the exception.
Note: To make use of std::what(), one should set up the appropriate try and catch blocks.
Below are the programs to understand the implementation of std::what() in a better way:
Program 1:
// C++ code for exception::what()#include <bits/stdc++.h> using namespace std; struct gfg : exception { const char* what() const noexcept { return "GeeksforGeeks!! " "A Computer Science" " Portal For Geeks"; }}; // main methodint main(){ // try block try { throw gfg(); } // catch block to handle the errors catch (exception& gfg1) { cout << gfg1.what(); } return 0;}
GeeksforGeeks!! A Computer Science Portal For Geeks
Program 2:
// C++ code for exception::what() #include <bits/stdc++.h> using namespace std; struct geeksforgeeks : exception { const char* what() const noexcept { return "Hey!!"; }}; // main methodint main(){ // try block try { throw geeksforgeeks(); } // catch block to handle the errors catch (exception& gfg) { cout << gfg.what(); } return 0;}
Hey!!
Reference: http://www.cplusplus.com/reference/exception/exception/what/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 255,
"s": 54,
"text": "The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same:"
},
{
"code": null,
"e": 268,
"s": 255,
"text": "Header File:"
},
{
"code": null,
"e": 289,
"s": 268,
"text": "#include<exception>\n"
},
{
"code": null,
"e": 297,
"s": 289,
"text": "Syntax:"
},
{
"code": null,
"e": 340,
"s": 297,
"text": "virtual const char* what() const throw();\n"
},
{
"code": null,
"e": 457,
"s": 340,
"text": "Return: The function std::what() return a null terminated character sequence that is used to identify the exception."
},
{
"code": null,
"e": 547,
"s": 457,
"text": "Note: To make use of std::what(), one should set up the appropriate try and catch blocks."
},
{
"code": null,
"e": 635,
"s": 547,
"text": "Below are the programs to understand the implementation of std::what() in a better way:"
},
{
"code": null,
"e": 646,
"s": 635,
"text": "Program 1:"
},
{
"code": "// C++ code for exception::what()#include <bits/stdc++.h> using namespace std; struct gfg : exception { const char* what() const noexcept { return \"GeeksforGeeks!! \" \"A Computer Science\" \" Portal For Geeks\"; }}; // main methodint main(){ // try block try { throw gfg(); } // catch block to handle the errors catch (exception& gfg1) { cout << gfg1.what(); } return 0;}",
"e": 1102,
"s": 646,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1102,
"text": "GeeksforGeeks!! A Computer Science Portal For Geeks\n"
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": "Program 2:"
},
{
"code": "// C++ code for exception::what() #include <bits/stdc++.h> using namespace std; struct geeksforgeeks : exception { const char* what() const noexcept { return \"Hey!!\"; }}; // main methodint main(){ // try block try { throw geeksforgeeks(); } // catch block to handle the errors catch (exception& gfg) { cout << gfg.what(); } return 0;}",
"e": 1562,
"s": 1166,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1562,
"text": "Hey!!\n"
},
{
"code": null,
"e": 1641,
"s": 1569,
"text": "Reference: http://www.cplusplus.com/reference/exception/exception/what/"
},
{
"code": null,
"e": 1655,
"s": 1641,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1659,
"s": 1655,
"text": "C++"
},
{
"code": null,
"e": 1663,
"s": 1659,
"text": "CPP"
}
] |
How to stop browser back button using JavaScript ? | 03 Jan, 2022
In this article, we will discuss how to write a javascript function which will prevent the user to navigate back to the last or previous page. There are so many ways to stop the browser back button most popular and will work in all conditions. You can add code to the first or previous page to force the browser to go forwards again and again so when the user tries to back to the previous page the browser will take him again in the same.
This can be done by making custom functions like this:Example 1:
Code 1: Save this file as Login.html for the first page.htmlhtml<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title> <style type="text/css"> body { font-family:Arial; color:green; } </style> <script type="text/javascript"> window.history.forward(); function noBack() { window.history.forward(); } </script></head> <body> <h1>GeeksforGeeks</h2> <p> Click here to Goto <a href="b.html"> Link to second page </a> </p></body> </html>
html
<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title> <style type="text/css"> body { font-family:Arial; color:green; } </style> <script type="text/javascript"> window.history.forward(); function noBack() { window.history.forward(); } </script></head> <body> <h1>GeeksforGeeks</h2> <p> Click here to Goto <a href="b.html"> Link to second page </a> </p></body> </html>
Code 2: Save this file as b.html for the second page.htmlhtml<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title></head> <body> <h3>This is second page</h3> <p> On this page, back button functionality is disabled. </p></body> </html>
html
<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title></head> <body> <h3>This is second page</h3> <p> On this page, back button functionality is disabled. </p></body> </html>
Output:
Example 2:
Code 1: Save this file as a.html for the first page.htmlhtml<!DOCTYPE html><html> <head> <title>First Page</title> <script type="text/javascript"> function preventBack() { window.history.forward(); } setTimeout("preventBack()", 0); window.onunload = function () { null }; </script></head> <body> <h3>This is first page</h3> <hr /> <a href = "b.html">Goto second Page</a></body> </html>
html
<!DOCTYPE html><html> <head> <title>First Page</title> <script type="text/javascript"> function preventBack() { window.history.forward(); } setTimeout("preventBack()", 0); window.onunload = function () { null }; </script></head> <body> <h3>This is first page</h3> <hr /> <a href = "b.html">Goto second Page</a></body> </html>
Code 2: Save this file as b.html for the second page.htmlhtml<!DOCTYPE html><html> <head> <title>Second Page</title></head> <body> <h3> Second Page - Back Button is disabled here. </h3> <hr /></body> </html>
html
<!DOCTYPE html><html> <head> <title>Second Page</title></head> <body> <h3> Second Page - Back Button is disabled here. </h3> <hr /></body> </html>
Output:
sooda367
JavaScript-Misc
Picked
Web technologies
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 494,
"s": 54,
"text": "In this article, we will discuss how to write a javascript function which will prevent the user to navigate back to the last or previous page. There are so many ways to stop the browser back button most popular and will work in all conditions. You can add code to the first or previous page to force the browser to go forwards again and again so when the user tries to back to the previous page the browser will take him again in the same."
},
{
"code": null,
"e": 559,
"s": 494,
"text": "This can be done by making custom functions like this:Example 1:"
},
{
"code": null,
"e": 1187,
"s": 559,
"text": "Code 1: Save this file as Login.html for the first page.htmlhtml<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title> <style type=\"text/css\"> body { font-family:Arial; color:green; } </style> <script type=\"text/javascript\"> window.history.forward(); function noBack() { window.history.forward(); } </script></head> <body> <h1>GeeksforGeeks</h2> <p> Click here to Goto <a href=\"b.html\"> Link to second page </a> </p></body> </html>"
},
{
"code": null,
"e": 1192,
"s": 1187,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title> <style type=\"text/css\"> body { font-family:Arial; color:green; } </style> <script type=\"text/javascript\"> window.history.forward(); function noBack() { window.history.forward(); } </script></head> <body> <h1>GeeksforGeeks</h2> <p> Click here to Goto <a href=\"b.html\"> Link to second page </a> </p></body> </html>",
"e": 1756,
"s": 1192,
"text": null
},
{
"code": null,
"e": 2083,
"s": 1756,
"text": "Code 2: Save this file as b.html for the second page.htmlhtml<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title></head> <body> <h3>This is second page</h3> <p> On this page, back button functionality is disabled. </p></body> </html>"
},
{
"code": null,
"e": 2088,
"s": 2083,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Blocking Back Button using javascript </title></head> <body> <h3>This is second page</h3> <p> On this page, back button functionality is disabled. </p></body> </html>",
"e": 2354,
"s": 2088,
"text": null
},
{
"code": null,
"e": 2362,
"s": 2354,
"text": "Output:"
},
{
"code": null,
"e": 2373,
"s": 2362,
"text": "Example 2:"
},
{
"code": null,
"e": 2850,
"s": 2373,
"text": "Code 1: Save this file as a.html for the first page.htmlhtml<!DOCTYPE html><html> <head> <title>First Page</title> <script type=\"text/javascript\"> function preventBack() { window.history.forward(); } setTimeout(\"preventBack()\", 0); window.onunload = function () { null }; </script></head> <body> <h3>This is first page</h3> <hr /> <a href = \"b.html\">Goto second Page</a></body> </html>"
},
{
"code": null,
"e": 2855,
"s": 2850,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>First Page</title> <script type=\"text/javascript\"> function preventBack() { window.history.forward(); } setTimeout(\"preventBack()\", 0); window.onunload = function () { null }; </script></head> <body> <h3>This is first page</h3> <hr /> <a href = \"b.html\">Goto second Page</a></body> </html>",
"e": 3272,
"s": 2855,
"text": null
},
{
"code": null,
"e": 3513,
"s": 3272,
"text": "Code 2: Save this file as b.html for the second page.htmlhtml<!DOCTYPE html><html> <head> <title>Second Page</title></head> <body> <h3> Second Page - Back Button is disabled here. </h3> <hr /></body> </html>"
},
{
"code": null,
"e": 3518,
"s": 3513,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Second Page</title></head> <body> <h3> Second Page - Back Button is disabled here. </h3> <hr /></body> </html>",
"e": 3698,
"s": 3518,
"text": null
},
{
"code": null,
"e": 3706,
"s": 3698,
"text": "Output:"
},
{
"code": null,
"e": 3715,
"s": 3706,
"text": "sooda367"
},
{
"code": null,
"e": 3731,
"s": 3715,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3738,
"s": 3731,
"text": "Picked"
},
{
"code": null,
"e": 3755,
"s": 3738,
"text": "Web technologies"
},
{
"code": null,
"e": 3766,
"s": 3755,
"text": "JavaScript"
},
{
"code": null,
"e": 3783,
"s": 3766,
"text": "Web Technologies"
},
{
"code": null,
"e": 3810,
"s": 3783,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3908,
"s": 3810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3969,
"s": 3908,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4041,
"s": 3969,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4081,
"s": 4041,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4123,
"s": 4081,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4164,
"s": 4123,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4197,
"s": 4164,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4259,
"s": 4197,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4320,
"s": 4259,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4370,
"s": 4320,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python program to find files having a particular extension using RegEx | 29 Dec, 2020
Prerequisite: Regular Expression in Python
Many of the times we need to search for a particular type of file from a list of different types of files. And we can do so with only a few lines of code using python. And the cool part is we don’t need to install any external package, python has a built-in package called re, with which we can easily write the program for performing this task.
Approach:
This program searches for the files having “.xml” extension from a list of different files.
Make a regular expression/pattern : “\.xml$”
Here re.search() function is used to check for a match anywhere in the string (name of the file). It basically returns the match object when the pattern is found and if the pattern is not found it returns null.
The functionality of different Metacharacters used here:
\ It is used to specify a special meaning of character after it. It is also used to escape special characters. $ The string ends with the pattern which is before it.
\ It is used to specify a special meaning of character after it. It is also used to escape special characters.
$ The string ends with the pattern which is before it.
Here “.xml” pattern is searched and processed.
Below is the implementation:
Python3
# import libraryimport re # list of different types of filefilenames = ["gfg.html", "geeks.xml", "computer.txt", "geeksforgeeks.jpg"] for file in filenames: # search given pattern in the line match = re.search("\.xml$", file) # if match is found if match: print("The file ending with .xml is:", file)
The file ending with .xml is: geeks.xml
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 71,
"s": 28,
"text": "Prerequisite: Regular Expression in Python"
},
{
"code": null,
"e": 417,
"s": 71,
"text": "Many of the times we need to search for a particular type of file from a list of different types of files. And we can do so with only a few lines of code using python. And the cool part is we don’t need to install any external package, python has a built-in package called re, with which we can easily write the program for performing this task."
},
{
"code": null,
"e": 427,
"s": 417,
"text": "Approach:"
},
{
"code": null,
"e": 519,
"s": 427,
"text": "This program searches for the files having “.xml” extension from a list of different files."
},
{
"code": null,
"e": 564,
"s": 519,
"text": "Make a regular expression/pattern : “\\.xml$”"
},
{
"code": null,
"e": 775,
"s": 564,
"text": "Here re.search() function is used to check for a match anywhere in the string (name of the file). It basically returns the match object when the pattern is found and if the pattern is not found it returns null."
},
{
"code": null,
"e": 832,
"s": 775,
"text": "The functionality of different Metacharacters used here:"
},
{
"code": null,
"e": 1000,
"s": 832,
"text": " \\ It is used to specify a special meaning of character after it. It is also used to escape special characters. $ The string ends with the pattern which is before it."
},
{
"code": null,
"e": 1113,
"s": 1000,
"text": " \\ It is used to specify a special meaning of character after it. It is also used to escape special characters."
},
{
"code": null,
"e": 1169,
"s": 1113,
"text": " $ The string ends with the pattern which is before it."
},
{
"code": null,
"e": 1216,
"s": 1169,
"text": "Here “.xml” pattern is searched and processed."
},
{
"code": null,
"e": 1245,
"s": 1216,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1253,
"s": 1245,
"text": "Python3"
},
{
"code": "# import libraryimport re # list of different types of filefilenames = [\"gfg.html\", \"geeks.xml\", \"computer.txt\", \"geeksforgeeks.jpg\"] for file in filenames: # search given pattern in the line match = re.search(\"\\.xml$\", file) # if match is found if match: print(\"The file ending with .xml is:\", file)",
"e": 1602,
"s": 1253,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1602,
"text": "The file ending with .xml is: geeks.xml"
},
{
"code": null,
"e": 1664,
"s": 1642,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1677,
"s": 1664,
"text": "python-regex"
},
{
"code": null,
"e": 1684,
"s": 1677,
"text": "Python"
},
{
"code": null,
"e": 1700,
"s": 1684,
"text": "Python Programs"
}
] |
How to Convert Floats to Strings in Pandas DataFrame? | 20 Aug, 2020
In this post, we’ll see different ways to Convert Floats to Strings in Pandas Dataframe? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, Float to String, etc.
There are three methods to convert Float to String:
Method 1: Using DataFrame.astype().
Syntax :
DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)
This is used to cast a pandas object to a specified dtype. This function also provides the capability to convert any suitable existing column to categorical type.
Example 1: Converting one column from float to string.
Python3
# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey', 10, 45.25], ['Carson', 15, 54.85], ['juli', 14, 87.21], ['Ricky', 20, 45.23], ['Gregory', 21, 77.25], ['Jessie', 16, 95.21]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Marks'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data type # of 'Marks' columnprint (df.dtypes)
Output:
Now, we change the data type of column ‘Marks’ from ‘float64’ to ‘object’.
Python3
# Now we will convert it from # 'float' to 'String' type. df['Marks'] = df['Marks'].astype(str) print() # lets find out the data# type after changingprint(df.dtypes) # print dataframe. df
Output:
Example 2: Converting more than one column from float to string.
Python3
# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Marks', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data type # of 'Age' and 'Accuracy' columnsprint (df.dtypes)
Output:
Now, we change the data type of columns ‘Accuracy‘ and ‘Age‘ from ‘float64’ to ‘object’.
Python3
# Now Pass a dictionary to # astype() function which contains # two columns and hence convert them# from float to string typedf = df.astype({"Age": 'str', "Accuracy": 'str'})print() # lets find out the data # type after changingprint(df.dtypes) # print dataframe. df
Output:
Method 2: Using Series.apply().
Syntax :
DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwds)
This method allows the users to pass a function and apply it on every single value of the Pandas series.
Example: Converting column of a Dataframe from float to string.
Python3
# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Percentage', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data # type of 'Percentage' columnprint (df.dtypes)
Output:
Now, we change the data type of column ‘Percentage‘ from ‘float64′ to ”object’.
Python3
# Now we will convert it from # 'float' to 'string' type. df['Percentage'] = df['Percentage'].apply(str) print() # lets find out the data# type after changingprint(df.dtypes) # print dataframe. df
Output:
Method 3: Using Series.map().
Syntax:
Series.map(arg, na_action=None)
This method is used to map values from two series having one column same.
Example: Converting column of a dataframe from float to string.
Python3
# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Percentage', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data# type of 'Age' columnprint (df.dtypes)
Output:
Now, we change the data type of column ‘Age‘ from ‘float64′ to ”object’.
Python3
# Now we will convert it from 'float' to 'string' type. # using DataFrame.map(str) functiondf['Age'] = df['Age'].map(str) print() # lets find out the data type after changingprint(df.dtypes) # print dataframe. df
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "In this post, we’ll see different ways to Convert Floats to Strings in Pandas Dataframe? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, Float to String, etc."
},
{
"code": null,
"e": 357,
"s": 305,
"text": "There are three methods to convert Float to String:"
},
{
"code": null,
"e": 393,
"s": 357,
"text": "Method 1: Using DataFrame.astype()."
},
{
"code": null,
"e": 402,
"s": 393,
"text": "Syntax :"
},
{
"code": null,
"e": 464,
"s": 402,
"text": "DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)\n"
},
{
"code": null,
"e": 627,
"s": 464,
"text": "This is used to cast a pandas object to a specified dtype. This function also provides the capability to convert any suitable existing column to categorical type."
},
{
"code": null,
"e": 682,
"s": 627,
"text": "Example 1: Converting one column from float to string."
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": "# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey', 10, 45.25], ['Carson', 15, 54.85], ['juli', 14, 87.21], ['Ricky', 20, 45.23], ['Gregory', 21, 77.25], ['Jessie', 16, 95.21]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Marks'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data type # of 'Marks' columnprint (df.dtypes)",
"e": 1139,
"s": 690,
"text": null
},
{
"code": null,
"e": 1147,
"s": 1139,
"text": "Output:"
},
{
"code": null,
"e": 1222,
"s": 1147,
"text": "Now, we change the data type of column ‘Marks’ from ‘float64’ to ‘object’."
},
{
"code": null,
"e": 1230,
"s": 1222,
"text": "Python3"
},
{
"code": "# Now we will convert it from # 'float' to 'String' type. df['Marks'] = df['Marks'].astype(str) print() # lets find out the data# type after changingprint(df.dtypes) # print dataframe. df ",
"e": 1422,
"s": 1230,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1422,
"text": "Output:"
},
{
"code": null,
"e": 1495,
"s": 1430,
"text": "Example 2: Converting more than one column from float to string."
},
{
"code": null,
"e": 1503,
"s": 1495,
"text": "Python3"
},
{
"code": "# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Marks', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data type # of 'Age' and 'Accuracy' columnsprint (df.dtypes)",
"e": 2029,
"s": 1503,
"text": null
},
{
"code": null,
"e": 2037,
"s": 2029,
"text": "Output:"
},
{
"code": null,
"e": 2126,
"s": 2037,
"text": "Now, we change the data type of columns ‘Accuracy‘ and ‘Age‘ from ‘float64’ to ‘object’."
},
{
"code": null,
"e": 2134,
"s": 2126,
"text": "Python3"
},
{
"code": "# Now Pass a dictionary to # astype() function which contains # two columns and hence convert them# from float to string typedf = df.astype({\"Age\": 'str', \"Accuracy\": 'str'})print() # lets find out the data # type after changingprint(df.dtypes) # print dataframe. df ",
"e": 2404,
"s": 2134,
"text": null
},
{
"code": null,
"e": 2412,
"s": 2404,
"text": "Output:"
},
{
"code": null,
"e": 2444,
"s": 2412,
"text": "Method 2: Using Series.apply()."
},
{
"code": null,
"e": 2453,
"s": 2444,
"text": "Syntax :"
},
{
"code": null,
"e": 2530,
"s": 2453,
"text": "DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwds)\n"
},
{
"code": null,
"e": 2635,
"s": 2530,
"text": "This method allows the users to pass a function and apply it on every single value of the Pandas series."
},
{
"code": null,
"e": 2699,
"s": 2635,
"text": "Example: Converting column of a Dataframe from float to string."
},
{
"code": null,
"e": 2707,
"s": 2699,
"text": "Python3"
},
{
"code": "# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Percentage', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data # type of 'Percentage' columnprint (df.dtypes)",
"e": 3228,
"s": 2707,
"text": null
},
{
"code": null,
"e": 3236,
"s": 3228,
"text": "Output:"
},
{
"code": null,
"e": 3316,
"s": 3236,
"text": "Now, we change the data type of column ‘Percentage‘ from ‘float64′ to ”object’."
},
{
"code": null,
"e": 3324,
"s": 3316,
"text": "Python3"
},
{
"code": "# Now we will convert it from # 'float' to 'string' type. df['Percentage'] = df['Percentage'].apply(str) print() # lets find out the data# type after changingprint(df.dtypes) # print dataframe. df",
"e": 3523,
"s": 3324,
"text": null
},
{
"code": null,
"e": 3531,
"s": 3523,
"text": "Output:"
},
{
"code": null,
"e": 3561,
"s": 3531,
"text": "Method 3: Using Series.map()."
},
{
"code": null,
"e": 3569,
"s": 3561,
"text": "Syntax:"
},
{
"code": null,
"e": 3602,
"s": 3569,
"text": "Series.map(arg, na_action=None)\n"
},
{
"code": null,
"e": 3677,
"s": 3602,
"text": "This method is used to map values from two series having one column same. "
},
{
"code": null,
"e": 3741,
"s": 3677,
"text": "Example: Converting column of a dataframe from float to string."
},
{
"code": null,
"e": 3749,
"s": 3741,
"text": "Python3"
},
{
"code": "# Import pandas library import pandas as pd # initialize list of lists data = [['Harvey.', 10.5, 45.25, 95.2], ['Carson', 15.2, 54.85, 50.8], ['juli', 14.9, 87.21, 60.4], ['Ricky', 20.3, 45.23, 99.5], ['Gregory', 21.1, 77.25, 90.9], ['Jessie', 16.4, 95.21, 10.85]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Percentage', 'Accuracy'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # lets find out the data# type of 'Age' columnprint (df.dtypes)",
"e": 4263,
"s": 3749,
"text": null
},
{
"code": null,
"e": 4271,
"s": 4263,
"text": "Output:"
},
{
"code": null,
"e": 4344,
"s": 4271,
"text": "Now, we change the data type of column ‘Age‘ from ‘float64′ to ”object’."
},
{
"code": null,
"e": 4352,
"s": 4344,
"text": "Python3"
},
{
"code": "# Now we will convert it from 'float' to 'string' type. # using DataFrame.map(str) functiondf['Age'] = df['Age'].map(str) print() # lets find out the data type after changingprint(df.dtypes) # print dataframe. df ",
"e": 4569,
"s": 4352,
"text": null
},
{
"code": null,
"e": 4577,
"s": 4569,
"text": "Output:"
},
{
"code": null,
"e": 4601,
"s": 4577,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4624,
"s": 4601,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 4638,
"s": 4624,
"text": "Python-pandas"
},
{
"code": null,
"e": 4645,
"s": 4638,
"text": "Python"
},
{
"code": null,
"e": 4743,
"s": 4645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4761,
"s": 4743,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4803,
"s": 4761,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4825,
"s": 4803,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4860,
"s": 4825,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4886,
"s": 4860,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4918,
"s": 4886,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4947,
"s": 4918,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4974,
"s": 4947,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5004,
"s": 4974,
"text": "Iterate over a list in Python"
}
] |
Drop specific rows from multiindex Pandas Dataframe | 23 May, 2021
In this article, we will learn how to drop specific rows from the multi-index DataFrame.
First, let us create the multi-index DataFrame. The steps are given below:
Python3
import numpy as npimport pandas as pd mldx_arrays = [np.array(['lion', 'lion', 'lion', 'bison', 'bison', 'bison', 'hawk', 'hawk', 'hawk']), np.array(['height', 'weight', 'speed', 'height', 'weight', 'speed', 'height', 'weight', 'speed'])] # creating a multi-index dataframe# with random datamultiindex_df = pd.DataFrame( np.random.randn(9, 4), index=mldx_arrays, columns=['Type A', 'Type B', 'Type C', 'Type D']) multiindex_df.index.names = ['level 0', 'level 1']multiindex_df
Output:
Now, we have to drop some rows from the multi-indexed dataframe. So, we are using the drop() method provided by the pandas module. This function drop rows or columns in pandas dataframe.
Syntax: df.drop(‘labels’, level=0, axis=0, inplace=True)
Parameters:
labels: the parameter mentioned in quotes is the index or column labels to drop
axis : parameter to drop labels from the rows(when axis=0 or ‘index’) / columns (when axis=1 or ‘columns’).
level: parameter indicates the level number like 0,1 etc to help identify and manipulate a particular level of data in a multi-index dataframe. For example, there are two levels in the given examples i.e level 1 and level 2.
inplace: parameter to do operation inplace and return nothing if its value is given True. Here in all the examples, the value of inplace is given True so that it does the operation and then return nothing.
Example 1: To drop the rows containing ‘lion’ in level 0.
Here ‘lion’ is the label name we want to drop,
level=0, axis=0 as which depicts rows will be targeted for deletion,
inplace=True inside the df.drop() function so that it performs the task and returns nothing.
Python3
multiindex_df.drop('lion', level=0, axis=0, inplace=True)multiindex_df
Output:
Example 2: To drop the rows in level 1 containing ‘weight’.
Here ‘weight’ is the label name we want to drop in level 1 from each of the rows in level 0,
level=1, axis=0 as which depicts rows will be targeted for deletion,
inplace=True inside the df.drop() function so that it performs the task and return nothing.
Python3
multiindex_df.drop('weight', level=1, axis=0, inplace=True)multiindex_df
Output:
Example 3: To drop a single row having a label as ‘weight’ in level 1 inside ‘bison’ in level 0.
Here (‘bison’, ‘weight’) are the label names we want to drop from level 0 and 1 respectively. It simply means that only the row from label ‘bison’ in level 0, the label ‘weight’ from level 1 will be deleted. No need to mention the level as it involves two levels, so only the label names within quotes will work fine,
axis=0 as which depicts rows will be targeted for deletion
inplace=True inside the df.drop() function so that it performs the task and return nothing.
Python3
multiindex_df.drop(('bison', 'weight'), axis=0, inplace=True)multiindex_df
Output:
Example 4: To drop two rows from level 0.
Here (‘bison’, ‘hawk’) are the label names we want to drop from level 0 which contains multiple rows from level 1. So deletion of the rows from level 0 will result in the dropping of the respective rows from level 1 also.
axis=0 as which depicts rows will be targeted for deletion,
inplace=True inside the df.drop() function so that it performs the task and returns nothing.
Python3
multiindex_df.drop(['bison', 'hawk'], axis=0, inplace=True)multiindex_df
Output 4:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 143,
"s": 54,
"text": "In this article, we will learn how to drop specific rows from the multi-index DataFrame."
},
{
"code": null,
"e": 218,
"s": 143,
"text": "First, let us create the multi-index DataFrame. The steps are given below:"
},
{
"code": null,
"e": 226,
"s": 218,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pd mldx_arrays = [np.array(['lion', 'lion', 'lion', 'bison', 'bison', 'bison', 'hawk', 'hawk', 'hawk']), np.array(['height', 'weight', 'speed', 'height', 'weight', 'speed', 'height', 'weight', 'speed'])] # creating a multi-index dataframe# with random datamultiindex_df = pd.DataFrame( np.random.randn(9, 4), index=mldx_arrays, columns=['Type A', 'Type B', 'Type C', 'Type D']) multiindex_df.index.names = ['level 0', 'level 1']multiindex_df",
"e": 835,
"s": 226,
"text": null
},
{
"code": null,
"e": 843,
"s": 835,
"text": "Output:"
},
{
"code": null,
"e": 1030,
"s": 843,
"text": "Now, we have to drop some rows from the multi-indexed dataframe. So, we are using the drop() method provided by the pandas module. This function drop rows or columns in pandas dataframe."
},
{
"code": null,
"e": 1087,
"s": 1030,
"text": "Syntax: df.drop(‘labels’, level=0, axis=0, inplace=True)"
},
{
"code": null,
"e": 1099,
"s": 1087,
"text": "Parameters:"
},
{
"code": null,
"e": 1179,
"s": 1099,
"text": "labels: the parameter mentioned in quotes is the index or column labels to drop"
},
{
"code": null,
"e": 1287,
"s": 1179,
"text": "axis : parameter to drop labels from the rows(when axis=0 or ‘index’) / columns (when axis=1 or ‘columns’)."
},
{
"code": null,
"e": 1512,
"s": 1287,
"text": "level: parameter indicates the level number like 0,1 etc to help identify and manipulate a particular level of data in a multi-index dataframe. For example, there are two levels in the given examples i.e level 1 and level 2."
},
{
"code": null,
"e": 1726,
"s": 1512,
"text": "inplace: parameter to do operation inplace and return nothing if its value is given True. Here in all the examples, the value of inplace is given True so that it does the operation and then return nothing."
},
{
"code": null,
"e": 1784,
"s": 1726,
"text": "Example 1: To drop the rows containing ‘lion’ in level 0."
},
{
"code": null,
"e": 1831,
"s": 1784,
"text": "Here ‘lion’ is the label name we want to drop,"
},
{
"code": null,
"e": 1900,
"s": 1831,
"text": "level=0, axis=0 as which depicts rows will be targeted for deletion,"
},
{
"code": null,
"e": 1993,
"s": 1900,
"text": "inplace=True inside the df.drop() function so that it performs the task and returns nothing."
},
{
"code": null,
"e": 2001,
"s": 1993,
"text": "Python3"
},
{
"code": "multiindex_df.drop('lion', level=0, axis=0, inplace=True)multiindex_df",
"e": 2072,
"s": 2001,
"text": null
},
{
"code": null,
"e": 2080,
"s": 2072,
"text": "Output:"
},
{
"code": null,
"e": 2140,
"s": 2080,
"text": "Example 2: To drop the rows in level 1 containing ‘weight’."
},
{
"code": null,
"e": 2233,
"s": 2140,
"text": "Here ‘weight’ is the label name we want to drop in level 1 from each of the rows in level 0,"
},
{
"code": null,
"e": 2302,
"s": 2233,
"text": "level=1, axis=0 as which depicts rows will be targeted for deletion,"
},
{
"code": null,
"e": 2394,
"s": 2302,
"text": "inplace=True inside the df.drop() function so that it performs the task and return nothing."
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Python3"
},
{
"code": "multiindex_df.drop('weight', level=1, axis=0, inplace=True)multiindex_df",
"e": 2475,
"s": 2402,
"text": null
},
{
"code": null,
"e": 2483,
"s": 2475,
"text": "Output:"
},
{
"code": null,
"e": 2580,
"s": 2483,
"text": "Example 3: To drop a single row having a label as ‘weight’ in level 1 inside ‘bison’ in level 0."
},
{
"code": null,
"e": 2898,
"s": 2580,
"text": "Here (‘bison’, ‘weight’) are the label names we want to drop from level 0 and 1 respectively. It simply means that only the row from label ‘bison’ in level 0, the label ‘weight’ from level 1 will be deleted. No need to mention the level as it involves two levels, so only the label names within quotes will work fine,"
},
{
"code": null,
"e": 2957,
"s": 2898,
"text": "axis=0 as which depicts rows will be targeted for deletion"
},
{
"code": null,
"e": 3049,
"s": 2957,
"text": "inplace=True inside the df.drop() function so that it performs the task and return nothing."
},
{
"code": null,
"e": 3057,
"s": 3049,
"text": "Python3"
},
{
"code": "multiindex_df.drop(('bison', 'weight'), axis=0, inplace=True)multiindex_df",
"e": 3132,
"s": 3057,
"text": null
},
{
"code": null,
"e": 3140,
"s": 3132,
"text": "Output:"
},
{
"code": null,
"e": 3182,
"s": 3140,
"text": "Example 4: To drop two rows from level 0."
},
{
"code": null,
"e": 3404,
"s": 3182,
"text": "Here (‘bison’, ‘hawk’) are the label names we want to drop from level 0 which contains multiple rows from level 1. So deletion of the rows from level 0 will result in the dropping of the respective rows from level 1 also."
},
{
"code": null,
"e": 3464,
"s": 3404,
"text": "axis=0 as which depicts rows will be targeted for deletion,"
},
{
"code": null,
"e": 3557,
"s": 3464,
"text": "inplace=True inside the df.drop() function so that it performs the task and returns nothing."
},
{
"code": null,
"e": 3565,
"s": 3557,
"text": "Python3"
},
{
"code": "multiindex_df.drop(['bison', 'hawk'], axis=0, inplace=True)multiindex_df",
"e": 3638,
"s": 3565,
"text": null
},
{
"code": null,
"e": 3648,
"s": 3638,
"text": "Output 4:"
},
{
"code": null,
"e": 3655,
"s": 3648,
"text": "Picked"
},
{
"code": null,
"e": 3679,
"s": 3655,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3702,
"s": 3679,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3716,
"s": 3702,
"text": "Python-pandas"
},
{
"code": null,
"e": 3723,
"s": 3716,
"text": "Python"
}
] |
Java 8 Streams | Collectors.joining() method with Examples | 09 May, 2022
The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object. This method uses the stream to do so. There are various overloads of joining methods present in the Collector class. The class hierarchy is as follows:
java.lang.Object
↳ java.util.stream.Collectors
java.util.stream.Collectors.joining() is the most simple joining method which does not take any parameter. It returns a Collector that joins or concatenates the input streams into String in the order of their appearance.
Syntax:
public static Collector<CharSequence, ?, String> joining()
Illustration: Usage of joining() method
Program 1: Using joining() with an array of characters
In the below program, a character array is created in ‘ch’. Then this array is fed to be converted into Stream using Stream.of(). Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character array is joined into a String using Collectors.joining() method. It is stored in the ‘chString’ variable.
Example
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.stream.Collectors;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a custom character array char[] ch = { 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' }; // Converting character array into string // using joining() method of Collectors class String chString = Stream.of(ch) .map(arr -> new String(arr)) .collect(Collectors.joining()); // Printing concatenated string System.out.println(chString); }}
GeeksforGeeks
Program 2: Using joining() with a list of characters
In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable.
Example
Java
// Java Program to demonstrate Working of joining() Method// of Collectors Class // Importing required classesimport java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a character list List<Character> ch = Arrays.asList( 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Converting character list into string // using joining() method of Collectors class String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining()); // Printing the concatenated string System.out.println(chString); }}
GeeksforGeeks
Program 3: Using joining() with n list of string
In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable.
Example
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList("Geeks", "for", "Geeks"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect(Collectors.joining()); // Print the concatenated String System.out.println(chString); }}
Output:
GeeksforGeeks
java.util.stream.Collectors.joining(CharSequence delimiter) is an overload of joining() method which takes delimiter as a parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. For example, in every sentence, space ‘ ‘ is used as the default delimiter for the words in it. It returns a Collector that joins or concatenates the input elements into String in the order of their appearance, separated by the delimiter.
Syntax:
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)
Below are the illustration for how to use joining(delimiter) method:
Program 1: Using joining(delimiter) with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable.
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a character list List& lt; Character& gt; ch = Arrays.asList('G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Convert the character list into String // using Collectors.joining() method // with, as the delimiter String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining( ", ")); // Print the concatenated String System.out.println(chString); }}
Output:
G, e, e, k, s, f, o, r, G, e, e, k, s
Program 2: Using joining(delimiter) with a list of string:
In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable.
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList("Geeks", "for", "Geeks"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect( Collectors.joining(", ")); // Print the concatenated String System.out.println(chString); }}
Output:
Geeks, for, Geeks
java.util.stream.Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) is an overload of joining() method which takes delimiter, prefix and suffix as parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. A prefix is a symbol or a CharSequence that is joined at the starting of the 1st element of the String. Then suffix is also a CharSequence parameter but this is joined after the last element of the string. i.e. at the end. For example, in every {Geeks, for, Geeks}, space ‘ ‘ is used as the by default delimiter for the words in it. The ‘{‘ is the prefix and ‘}’ is the suffix. It returns a Collector that joins or concatenates the input elements into String in the order of there appearance, separated by the delimiter.
Syntax:
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter.
CharSequence prefix,
CharSequence suffix))
Below are the illustration for how to use joining(delimiter, prefix, suffix) method:
Program 1: Using joining() with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter, “[” as the prefix and “]” as the suffix. It is stored in ‘chString’ variable.
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a character list List& lt; Character& gt; ch = Arrays.asList('G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Convert the character list into String // using Collectors.joining() method // with, as the delimiter String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining( ", ", " [", "] & quot;)); // Print the concatenated String System.out.println(chString); }}
Output:
[G, e, e, k, s, f, o, r, G, e, e, k, s]
Program 2: Using joining() with a list of string: In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter, “{” as the prefix and “}” as the suffix. It is stored in ‘chString’ variable.
Java
// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList("Geeks", "for", "Geeks"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect( Collectors.joining(", ", " { " , " } & quot;)); // Print the concatenated String System.out.println(chString); }}
Output:
{Geeks, for, Geeks}
nidhi_biet
ergirishmenghani
Java - util package
Java-Collectors
Java-Functions
Java-Library
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 325,
"s": 28,
"text": "The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object. This method uses the stream to do so. There are various overloads of joining methods present in the Collector class. The class hierarchy is as follows: "
},
{
"code": null,
"e": 374,
"s": 325,
"text": "java.lang.Object\n ↳ java.util.stream.Collectors"
},
{
"code": null,
"e": 595,
"s": 374,
"text": "java.util.stream.Collectors.joining() is the most simple joining method which does not take any parameter. It returns a Collector that joins or concatenates the input streams into String in the order of their appearance."
},
{
"code": null,
"e": 603,
"s": 595,
"text": "Syntax:"
},
{
"code": null,
"e": 662,
"s": 603,
"text": "public static Collector<CharSequence, ?, String> joining()"
},
{
"code": null,
"e": 702,
"s": 662,
"text": "Illustration: Usage of joining() method"
},
{
"code": null,
"e": 757,
"s": 702,
"text": "Program 1: Using joining() with an array of characters"
},
{
"code": null,
"e": 1121,
"s": 757,
"text": "In the below program, a character array is created in ‘ch’. Then this array is fed to be converted into Stream using Stream.of(). Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character array is joined into a String using Collectors.joining() method. It is stored in the ‘chString’ variable."
},
{
"code": null,
"e": 1130,
"s": 1121,
"text": "Example "
},
{
"code": null,
"e": 1135,
"s": 1130,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.stream.Collectors;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a custom character array char[] ch = { 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' }; // Converting character array into string // using joining() method of Collectors class String chString = Stream.of(ch) .map(arr -> new String(arr)) .collect(Collectors.joining()); // Printing concatenated string System.out.println(chString); }}",
"e": 1867,
"s": 1135,
"text": null
},
{
"code": null,
"e": 1882,
"s": 1867,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1935,
"s": 1882,
"text": "Program 2: Using joining() with a list of characters"
},
{
"code": null,
"e": 2300,
"s": 1935,
"text": "In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 2308,
"s": 2300,
"text": "Example"
},
{
"code": null,
"e": 2313,
"s": 2308,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Working of joining() Method// of Collectors Class // Importing required classesimport java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a character list List<Character> ch = Arrays.asList( 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Converting character list into string // using joining() method of Collectors class String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining()); // Printing the concatenated string System.out.println(chString); }}",
"e": 3133,
"s": 2313,
"text": null
},
{
"code": null,
"e": 3148,
"s": 3133,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 3197,
"s": 3148,
"text": "Program 3: Using joining() with n list of string"
},
{
"code": null,
"e": 3561,
"s": 3197,
"text": "In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 3569,
"s": 3561,
"text": "Example"
},
{
"code": null,
"e": 3574,
"s": 3569,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList(\"Geeks\", \"for\", \"Geeks\"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect(Collectors.joining()); // Print the concatenated String System.out.println(chString); }}",
"e": 4201,
"s": 3574,
"text": null
},
{
"code": null,
"e": 4209,
"s": 4201,
"text": "Output:"
},
{
"code": null,
"e": 4223,
"s": 4209,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 4712,
"s": 4223,
"text": "java.util.stream.Collectors.joining(CharSequence delimiter) is an overload of joining() method which takes delimiter as a parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. For example, in every sentence, space ‘ ‘ is used as the default delimiter for the words in it. It returns a Collector that joins or concatenates the input elements into String in the order of their appearance, separated by the delimiter. "
},
{
"code": null,
"e": 4720,
"s": 4712,
"text": "Syntax:"
},
{
"code": null,
"e": 4801,
"s": 4720,
"text": "public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)"
},
{
"code": null,
"e": 4871,
"s": 4801,
"text": "Below are the illustration for how to use joining(delimiter) method: "
},
{
"code": null,
"e": 5333,
"s": 4871,
"text": "Program 1: Using joining(delimiter) with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 5338,
"s": 5333,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a character list List& lt; Character& gt; ch = Arrays.asList('G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Convert the character list into String // using Collectors.joining() method // with, as the delimiter String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining( \", \")); // Print the concatenated String System.out.println(chString); }}",
"e": 6212,
"s": 5338,
"text": null
},
{
"code": null,
"e": 6220,
"s": 6212,
"text": "Output:"
},
{
"code": null,
"e": 6258,
"s": 6220,
"text": "G, e, e, k, s, f, o, r, G, e, e, k, s"
},
{
"code": null,
"e": 6318,
"s": 6258,
"text": "Program 2: Using joining(delimiter) with a list of string: "
},
{
"code": null,
"e": 6716,
"s": 6318,
"text": "In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 6721,
"s": 6716,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList(\"Geeks\", \"for\", \"Geeks\"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect( Collectors.joining(\", \")); // Print the concatenated String System.out.println(chString); }}",
"e": 7353,
"s": 6721,
"text": null
},
{
"code": null,
"e": 7361,
"s": 7353,
"text": "Output:"
},
{
"code": null,
"e": 7379,
"s": 7361,
"text": "Geeks, for, Geeks"
},
{
"code": null,
"e": 8209,
"s": 7379,
"text": "java.util.stream.Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) is an overload of joining() method which takes delimiter, prefix and suffix as parameter, of the type CharSequence. A delimiter is a symbol or a CharSequence that is used to separate words from each other. A prefix is a symbol or a CharSequence that is joined at the starting of the 1st element of the String. Then suffix is also a CharSequence parameter but this is joined after the last element of the string. i.e. at the end. For example, in every {Geeks, for, Geeks}, space ‘ ‘ is used as the by default delimiter for the words in it. The ‘{‘ is the prefix and ‘}’ is the suffix. It returns a Collector that joins or concatenates the input elements into String in the order of there appearance, separated by the delimiter. "
},
{
"code": null,
"e": 8217,
"s": 8209,
"text": "Syntax:"
},
{
"code": null,
"e": 8452,
"s": 8217,
"text": "public static Collector<CharSequence, ?, String> joining(CharSequence delimiter. \n CharSequence prefix,\n CharSequence suffix))"
},
{
"code": null,
"e": 8538,
"s": 8452,
"text": "Below are the illustration for how to use joining(delimiter, prefix, suffix) method: "
},
{
"code": null,
"e": 9032,
"s": 8538,
"text": "Program 1: Using joining() with a list of characters: In the below program, a character list is created in ‘ch’. Then this list is fed to be converted into Stream using ch.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter, “[” as the prefix and “]” as the suffix. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 9037,
"s": 9032,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a character list List& lt; Character& gt; ch = Arrays.asList('G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'); // Convert the character list into String // using Collectors.joining() method // with, as the delimiter String chString = ch.stream() .map(String::valueOf) .collect(Collectors.joining( \", \", \" [\", \"] & quot;)); // Print the concatenated String System.out.println(chString); }}",
"e": 9929,
"s": 9037,
"text": null
},
{
"code": null,
"e": 9937,
"s": 9929,
"text": "Output:"
},
{
"code": null,
"e": 9977,
"s": 9937,
"text": "[G, e, e, k, s, f, o, r, G, e, e, k, s]"
},
{
"code": null,
"e": 10466,
"s": 9977,
"text": "Program 2: Using joining() with a list of string: In the below program, a String list is created in ‘str’. Then this list is fed to be converted into Stream using str.stream() method. Then the resulted stream is mapped for a sequential series using map(). At last, the sequential stream containing the character list is joined into a String using Collectors.joining() method with “, ” passed as the delimiter, “{” as the prefix and “}” as the suffix. It is stored in ‘chString’ variable. "
},
{
"code": null,
"e": 10471,
"s": 10466,
"text": "Java"
},
{
"code": "// Java Program to demonstrate the working// of the Collectors.joining() method import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // Create a string list List& lt; String& gt; str = Arrays.asList(\"Geeks\", \"for\", \"Geeks\"); // Convert the string list into String // using Collectors.joining() method String chString = str.stream().collect( Collectors.joining(\", \", \" { \" , \" } & quot;)); // Print the concatenated String System.out.println(chString); }}",
"e": 11165,
"s": 10471,
"text": null
},
{
"code": null,
"e": 11173,
"s": 11165,
"text": "Output:"
},
{
"code": null,
"e": 11193,
"s": 11173,
"text": "{Geeks, for, Geeks}"
},
{
"code": null,
"e": 11204,
"s": 11193,
"text": "nidhi_biet"
},
{
"code": null,
"e": 11221,
"s": 11204,
"text": "ergirishmenghani"
},
{
"code": null,
"e": 11241,
"s": 11221,
"text": "Java - util package"
},
{
"code": null,
"e": 11257,
"s": 11241,
"text": "Java-Collectors"
},
{
"code": null,
"e": 11272,
"s": 11257,
"text": "Java-Functions"
},
{
"code": null,
"e": 11285,
"s": 11272,
"text": "Java-Library"
},
{
"code": null,
"e": 11297,
"s": 11285,
"text": "java-stream"
},
{
"code": null,
"e": 11320,
"s": 11297,
"text": "Java-Stream-Collectors"
},
{
"code": null,
"e": 11325,
"s": 11320,
"text": "Java"
},
{
"code": null,
"e": 11330,
"s": 11325,
"text": "Java"
},
{
"code": null,
"e": 11428,
"s": 11330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11479,
"s": 11428,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 11510,
"s": 11479,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 11529,
"s": 11510,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 11559,
"s": 11529,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 11577,
"s": 11559,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 11592,
"s": 11577,
"text": "Stream In Java"
},
{
"code": null,
"e": 11612,
"s": 11592,
"text": "Collections in Java"
},
{
"code": null,
"e": 11636,
"s": 11612,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 11668,
"s": 11636,
"text": "Multidimensional Arrays in Java"
}
] |
PHP | cal_days_in_month( ) Function | 26 Apr, 2018
The cal_days_in_month( ) function in PHP is an inbuilt function which is used to return the number of days in a month for a specific year and according to a specific calendar such as Gregorian calendar, French calendar, Jewish calendar etc.
The cal_days_in_month() function takes three parameters which are the calendar, month and year and returns the number of days according to a specified month, year and calendar.
Syntax:
cal_days_in_month($calendar, $month, $year)
Parameters: The cal_days_in_month() function in PHP accepts three parameters as described below:
$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc.$month: It specifies the month in the calendar you have opted.$year: It specifies the year in the calendar you have opted.
$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc.
$month: It specifies the month in the calendar you have opted.
$year: It specifies the year in the calendar you have opted.
Return Value: It returns the number of days according to a specified month, year and calendar.
Errors And Exception:
The cal_days-in_month function gives wrong output when the date used is before 1550.The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year.
The cal_days-in_month function gives wrong output when the date used is before 1550.
The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year.
Examples:
Input: cal_days_in_month(CAL_JEWISH, 2, 1966);
Output: 29
Explanation: February 1966 had 29 days.
Input: cal_days_in_month(CAL_GREGORIAN, 2, 2004);
Output: 29
Explanation: February 2004 had 29 days
Below programs illustrate the cal_days_in_month() function:
Program 1:
<?php // Using cal_days_in_month() function to// know the number of days in february, 1966$days = cal_days_in_month(CAL_JEWISH, 2, 1966); echo "February 1966 had $days days.<br>"; ?>
Output:
February 1966 had 29 days.
Program 2:
<?php // Using cal_days_in_month() function to// know the number of days in february, 2004$days = cal_days_in_month(CAL_GREGORIAN, 2, 2004); echo "February 2004 had $days days"; ?>
Output:
February 2004 had 29 days
Reference:http://php.net/manual/en/function.cal-days-in-month.php
PHP-date-time
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Apr, 2018"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "The cal_days_in_month( ) function in PHP is an inbuilt function which is used to return the number of days in a month for a specific year and according to a specific calendar such as Gregorian calendar, French calendar, Jewish calendar etc."
},
{
"code": null,
"e": 472,
"s": 295,
"text": "The cal_days_in_month() function takes three parameters which are the calendar, month and year and returns the number of days according to a specified month, year and calendar."
},
{
"code": null,
"e": 480,
"s": 472,
"text": "Syntax:"
},
{
"code": null,
"e": 524,
"s": 480,
"text": "cal_days_in_month($calendar, $month, $year)"
},
{
"code": null,
"e": 621,
"s": 524,
"text": "Parameters: The cal_days_in_month() function in PHP accepts three parameters as described below:"
},
{
"code": null,
"e": 840,
"s": 621,
"text": "$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc.$month: It specifies the month in the calendar you have opted.$year: It specifies the year in the calendar you have opted."
},
{
"code": null,
"e": 937,
"s": 840,
"text": "$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc."
},
{
"code": null,
"e": 1000,
"s": 937,
"text": "$month: It specifies the month in the calendar you have opted."
},
{
"code": null,
"e": 1061,
"s": 1000,
"text": "$year: It specifies the year in the calendar you have opted."
},
{
"code": null,
"e": 1156,
"s": 1061,
"text": "Return Value: It returns the number of days according to a specified month, year and calendar."
},
{
"code": null,
"e": 1178,
"s": 1156,
"text": "Errors And Exception:"
},
{
"code": null,
"e": 1368,
"s": 1178,
"text": "The cal_days-in_month function gives wrong output when the date used is before 1550.The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year."
},
{
"code": null,
"e": 1453,
"s": 1368,
"text": "The cal_days-in_month function gives wrong output when the date used is before 1550."
},
{
"code": null,
"e": 1559,
"s": 1453,
"text": "The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year."
},
{
"code": null,
"e": 1569,
"s": 1559,
"text": "Examples:"
},
{
"code": null,
"e": 1769,
"s": 1569,
"text": "Input: cal_days_in_month(CAL_JEWISH, 2, 1966);\nOutput: 29\nExplanation: February 1966 had 29 days.\n\nInput: cal_days_in_month(CAL_GREGORIAN, 2, 2004);\nOutput: 29\nExplanation: February 2004 had 29 days\n"
},
{
"code": null,
"e": 1829,
"s": 1769,
"text": "Below programs illustrate the cal_days_in_month() function:"
},
{
"code": null,
"e": 1840,
"s": 1829,
"text": "Program 1:"
},
{
"code": "<?php // Using cal_days_in_month() function to// know the number of days in february, 1966$days = cal_days_in_month(CAL_JEWISH, 2, 1966); echo \"February 1966 had $days days.<br>\"; ?>",
"e": 2026,
"s": 1840,
"text": null
},
{
"code": null,
"e": 2034,
"s": 2026,
"text": "Output:"
},
{
"code": null,
"e": 2061,
"s": 2034,
"text": "February 1966 had 29 days."
},
{
"code": null,
"e": 2072,
"s": 2061,
"text": "Program 2:"
},
{
"code": "<?php // Using cal_days_in_month() function to// know the number of days in february, 2004$days = cal_days_in_month(CAL_GREGORIAN, 2, 2004); echo \"February 2004 had $days days\"; ?>",
"e": 2256,
"s": 2072,
"text": null
},
{
"code": null,
"e": 2264,
"s": 2256,
"text": "Output:"
},
{
"code": null,
"e": 2290,
"s": 2264,
"text": "February 2004 had 29 days"
},
{
"code": null,
"e": 2356,
"s": 2290,
"text": "Reference:http://php.net/manual/en/function.cal-days-in-month.php"
},
{
"code": null,
"e": 2370,
"s": 2356,
"text": "PHP-date-time"
},
{
"code": null,
"e": 2374,
"s": 2370,
"text": "PHP"
},
{
"code": null,
"e": 2391,
"s": 2374,
"text": "Web Technologies"
},
{
"code": null,
"e": 2395,
"s": 2391,
"text": "PHP"
},
{
"code": null,
"e": 2493,
"s": 2395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2538,
"s": 2493,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2588,
"s": 2538,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2612,
"s": 2588,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2664,
"s": 2612,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2704,
"s": 2664,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2766,
"s": 2704,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2799,
"s": 2766,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2860,
"s": 2799,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2910,
"s": 2860,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
IEEE Standard 754 Floating Point Numbers | 16 Mar, 2020
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation which was established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found in the diverse floating point implementations that made them difficult to use reliably and reduced their portability. IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, Macs, and most Unix platforms.
There are several ways to represent floating point number but IEEE 754 is the most efficient in most cases. IEEE 754 has 3 basic components:
The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.The Normalised Mantissa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal.
The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.
The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.
The Normalised Mantissa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal.
IEEE 754 numbers are divided into two based on the above three components: single precision and double precision.
Example –
85.125
85 = 1010101
0.125 = 001
85.125 = 1010101.001
=1.010101001 x 2^6
sign = 0
1. Single precision:
biased exponent 127+6=133
133 = 10000101
Normalised mantisa = 010101001
we will add 0's to complete the 23 bits
The IEEE 754 Single precision is:
= 0 10000101 01010100100000000000000
This can be written in hexadecimal form 42AA4000
2. Double precision:
biased exponent 1023+6=1029
1029 = 10000000101
Normalised mantisa = 010101001
we will add 0's to complete the 52 bits
The IEEE 754 Double precision is:
= 0 10000000101 0101010010000000000000000000000000000000000000000000
This can be written in hexadecimal form 4055480000000000
Special Values: IEEE has reserved some values that can ambiguity.
Zero –Zero is a special value denoted with an exponent and mantissa of 0. -0 and +0 are distinct values, though they both are equal.
Denormalised –If the exponent is all zeros, but the mantissa is not then the value is a denormalized number. This means this number does not have an assumed leading one before the binary point.
Infinity –The values +infinity and -infinity are denoted with an exponent of all ones and a mantissa of all zeros. The sign bit distinguishes between negative infinity and positive infinity. Operations with infinite values are well defined in IEEE.
Not A Number (NAN) –The value NAN is used to represent a value that is an error. This is represented when exponent field is all ones with a zero sign bit or a mantissa that it not 1 followed by zeros. This is a special value that might be used to denote a variable that doesn’t yet hold a value.
Similar for Double precision (just replacing 255 by 2049), Ranges of Floating point numbers:
The range of positive floating point numbers can be split into normalized numbers, and denormalized numbers which use only a portion of the fractions’s precision. Since every floating-point number has a corresponding, negated value, the ranges above are symmetric around zero.
There are five distinct numerical ranges that single-precision floating-point numbers are not able to represent with the scheme presented so far:
Negative numbers less than – (2 – 2-23) × 2127 (negative overflow)Negative numbers greater than – 2-149 (negative underflow)ZeroPositive numbers less than 2-149 (positive underflow)Positive numbers greater than (2 – 2-23) × 2127 (positive overflow)
Negative numbers less than – (2 – 2-23) × 2127 (negative overflow)
Negative numbers greater than – 2-149 (negative underflow)
Zero
Positive numbers less than 2-149 (positive underflow)
Positive numbers greater than (2 – 2-23) × 2127 (positive overflow)
Overflow generally means that values have grown too large to be represented. Underflow is a less serious problem because is just denotes a loss of precision, which is guaranteed to be closely approximated by zero.
Table of the total effective range of finite IEEE floating-point numbers is shown below:
Special Operations –
RishabhPrabhu
choudharysp604
pritampandit98
binary-representation
Computer Organization & Architecture
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Full Adder in Digital Logic
Introduction of K-Map (Karnaugh Map)
Flip-flop types, their Conversion and Applications
Shift Registers in Digital Logic
Difference between RAM and ROM | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Mar, 2020"
},
{
"code": null,
"e": 587,
"s": 54,
"text": "The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation which was established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found in the diverse floating point implementations that made them difficult to use reliably and reduced their portability. IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, Macs, and most Unix platforms."
},
{
"code": null,
"e": 728,
"s": 587,
"text": "There are several ways to represent floating point number but IEEE 754 is the most efficient in most cases. IEEE 754 has 3 basic components:"
},
{
"code": null,
"e": 1286,
"s": 728,
"text": "The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number.The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent.The Normalised Mantissa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal."
},
{
"code": null,
"e": 1408,
"s": 1286,
"text": "The Sign of Mantissa –This is as simple as the name. 0 represents a positive number while 1 represents a negative number."
},
{
"code": null,
"e": 1581,
"s": 1408,
"text": "The Biased exponent –The exponent field needs to represent both positive and negative exponents. A bias is added to the actual exponent in order to get the stored exponent."
},
{
"code": null,
"e": 1846,
"s": 1581,
"text": "The Normalised Mantissa –The mantissa is part of a number in scientific notation or a floating-point number, consisting of its significant digits. Here we have only 2 digits, i.e. O and 1. So a normalised mantissa is one with only one 1 to the left of the decimal."
},
{
"code": null,
"e": 1960,
"s": 1846,
"text": "IEEE 754 numbers are divided into two based on the above three components: single precision and double precision."
},
{
"code": null,
"e": 1970,
"s": 1960,
"text": "Example –"
},
{
"code": null,
"e": 2617,
"s": 1970,
"text": "85.125\n85 = 1010101\n0.125 = 001\n85.125 = 1010101.001\n =1.010101001 x 2^6 \nsign = 0 \n\n1. Single precision:\nbiased exponent 127+6=133\n133 = 10000101\nNormalised mantisa = 010101001\nwe will add 0's to complete the 23 bits\n\nThe IEEE 754 Single precision is:\n= 0 10000101 01010100100000000000000\nThis can be written in hexadecimal form 42AA4000\n\n2. Double precision:\nbiased exponent 1023+6=1029\n1029 = 10000000101\nNormalised mantisa = 010101001\nwe will add 0's to complete the 52 bits\n\nThe IEEE 754 Double precision is:\n= 0 10000000101 0101010010000000000000000000000000000000000000000000\nThis can be written in hexadecimal form 4055480000000000 "
},
{
"code": null,
"e": 2683,
"s": 2617,
"text": "Special Values: IEEE has reserved some values that can ambiguity."
},
{
"code": null,
"e": 2816,
"s": 2683,
"text": "Zero –Zero is a special value denoted with an exponent and mantissa of 0. -0 and +0 are distinct values, though they both are equal."
},
{
"code": null,
"e": 3010,
"s": 2816,
"text": "Denormalised –If the exponent is all zeros, but the mantissa is not then the value is a denormalized number. This means this number does not have an assumed leading one before the binary point."
},
{
"code": null,
"e": 3259,
"s": 3010,
"text": "Infinity –The values +infinity and -infinity are denoted with an exponent of all ones and a mantissa of all zeros. The sign bit distinguishes between negative infinity and positive infinity. Operations with infinite values are well defined in IEEE."
},
{
"code": null,
"e": 3555,
"s": 3259,
"text": "Not A Number (NAN) –The value NAN is used to represent a value that is an error. This is represented when exponent field is all ones with a zero sign bit or a mantissa that it not 1 followed by zeros. This is a special value that might be used to denote a variable that doesn’t yet hold a value."
},
{
"code": null,
"e": 3648,
"s": 3555,
"text": "Similar for Double precision (just replacing 255 by 2049), Ranges of Floating point numbers:"
},
{
"code": null,
"e": 3925,
"s": 3648,
"text": "The range of positive floating point numbers can be split into normalized numbers, and denormalized numbers which use only a portion of the fractions’s precision. Since every floating-point number has a corresponding, negated value, the ranges above are symmetric around zero."
},
{
"code": null,
"e": 4071,
"s": 3925,
"text": "There are five distinct numerical ranges that single-precision floating-point numbers are not able to represent with the scheme presented so far:"
},
{
"code": null,
"e": 4320,
"s": 4071,
"text": "Negative numbers less than – (2 – 2-23) × 2127 (negative overflow)Negative numbers greater than – 2-149 (negative underflow)ZeroPositive numbers less than 2-149 (positive underflow)Positive numbers greater than (2 – 2-23) × 2127 (positive overflow)"
},
{
"code": null,
"e": 4387,
"s": 4320,
"text": "Negative numbers less than – (2 – 2-23) × 2127 (negative overflow)"
},
{
"code": null,
"e": 4446,
"s": 4387,
"text": "Negative numbers greater than – 2-149 (negative underflow)"
},
{
"code": null,
"e": 4451,
"s": 4446,
"text": "Zero"
},
{
"code": null,
"e": 4505,
"s": 4451,
"text": "Positive numbers less than 2-149 (positive underflow)"
},
{
"code": null,
"e": 4573,
"s": 4505,
"text": "Positive numbers greater than (2 – 2-23) × 2127 (positive overflow)"
},
{
"code": null,
"e": 4787,
"s": 4573,
"text": "Overflow generally means that values have grown too large to be represented. Underflow is a less serious problem because is just denotes a loss of precision, which is guaranteed to be closely approximated by zero."
},
{
"code": null,
"e": 4876,
"s": 4787,
"text": "Table of the total effective range of finite IEEE floating-point numbers is shown below:"
},
{
"code": null,
"e": 4897,
"s": 4876,
"text": "Special Operations –"
},
{
"code": null,
"e": 4911,
"s": 4897,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 4926,
"s": 4911,
"text": "choudharysp604"
},
{
"code": null,
"e": 4941,
"s": 4926,
"text": "pritampandit98"
},
{
"code": null,
"e": 4963,
"s": 4941,
"text": "binary-representation"
},
{
"code": null,
"e": 5000,
"s": 4963,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 5035,
"s": 5000,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 5133,
"s": 5035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5182,
"s": 5133,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 5244,
"s": 5182,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 5282,
"s": 5244,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 5377,
"s": 5282,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 5425,
"s": 5377,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 5453,
"s": 5425,
"text": "Full Adder in Digital Logic"
},
{
"code": null,
"e": 5490,
"s": 5453,
"text": "Introduction of K-Map (Karnaugh Map)"
},
{
"code": null,
"e": 5541,
"s": 5490,
"text": "Flip-flop types, their Conversion and Applications"
},
{
"code": null,
"e": 5574,
"s": 5541,
"text": "Shift Registers in Digital Logic"
}
] |
PostgreSQL – CREATE ROLE | 28 Aug, 2020
PostgreSQL uses roles to represent user accounts. It doesn’t use the user concept like other database systems. Typically, roles can log in are called login roles. They are equivalent to users in other database systems. When roles contain other roles, they are called group roles. When you create a role, it is valid in all databases in the database server (or cluster).
To create a new role, you use the CREATE ROLE statement as follows:
Syntax: CREATE ROLE role_name;
To get all roles in the current PostgreSQL database server, you can query them from the pg_roles system catalog as follows:
Syntax: SELECT rolname FROM pg_roles;
This will result in the following:
If one uses the psql tool, one can use the \du command to list all existing roles in the current PostgreSQL database server:
Syntax: \du
It will behave as shown below:
The attributes of a role define privileges for that role including login, superuser, database creation, role creation, password, etc:
Syntax: CREATE ROLE name WITH option;
In this syntax, the WITH keyword is optional. And the option can be one or more attributes including SUPER, CREATEDB, CREATEROLE, etc.
The following statement creates a role called ‘Raju’ that has the login privilege and an initial password:
CREATE ROLE raju
LOGIN
PASSWORD 'mypassword1';
Note: It is required to place the password in single quotes (‘).
Now verify the role using the below command:
\du
The role creation is successful as shown below:
The following statement creates a role called ‘Nikhil’ that has the superuser attribute:
CREATE ROLE Nikhil
SUPERUSER
LOGIN
PASSWORD 'mypassword1';
This will lead to the following:
The superuser can override all access restrictions within the database therefore you should create this role only when needed.
Note: One must be a superuser in order to create another superuser role.
If you want to create roles that have the database creation privilege, you use the CREATEDB attribute:
CREATE ROLE dba
CREATEDB
LOGIN
PASSWORD 'Abcd1234';
This will lead to the following:
To set a date and time after which the role’s password is no longer valid, you use the valid until attribute:
VALID UNTIL 'timestamp'
Example:
CREATE ROLE dev_api WITH
LOGIN
PASSWORD 'securePass1'
VALID UNTIL '2030-01-01';
Output:
To specify the number of concurrent connections a role can make, you use the CONNECTION LIMIT attribute:
CONNECTION LIMIT connection_count
The following creates a new role called API that can make 1000 concurrent connections:
CREATE ROLE api
LOGIN
PASSWORD 'securePass1'
CONNECTION LIMIT 1000;
This will create a new role as follows:
The following psql command shows all the roles that we have created so far:
\du
This will show you the results as depicted below:
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 398,
"s": 28,
"text": "PostgreSQL uses roles to represent user accounts. It doesn’t use the user concept like other database systems. Typically, roles can log in are called login roles. They are equivalent to users in other database systems. When roles contain other roles, they are called group roles. When you create a role, it is valid in all databases in the database server (or cluster)."
},
{
"code": null,
"e": 466,
"s": 398,
"text": "To create a new role, you use the CREATE ROLE statement as follows:"
},
{
"code": null,
"e": 498,
"s": 466,
"text": "Syntax: CREATE ROLE role_name;\n"
},
{
"code": null,
"e": 622,
"s": 498,
"text": "To get all roles in the current PostgreSQL database server, you can query them from the pg_roles system catalog as follows:"
},
{
"code": null,
"e": 661,
"s": 622,
"text": "Syntax: SELECT rolname FROM pg_roles;\n"
},
{
"code": null,
"e": 696,
"s": 661,
"text": "This will result in the following:"
},
{
"code": null,
"e": 821,
"s": 696,
"text": "If one uses the psql tool, one can use the \\du command to list all existing roles in the current PostgreSQL database server:"
},
{
"code": null,
"e": 834,
"s": 821,
"text": "Syntax: \\du\n"
},
{
"code": null,
"e": 865,
"s": 834,
"text": "It will behave as shown below:"
},
{
"code": null,
"e": 999,
"s": 865,
"text": "The attributes of a role define privileges for that role including login, superuser, database creation, role creation, password, etc:"
},
{
"code": null,
"e": 1038,
"s": 999,
"text": "Syntax: CREATE ROLE name WITH option;\n"
},
{
"code": null,
"e": 1173,
"s": 1038,
"text": "In this syntax, the WITH keyword is optional. And the option can be one or more attributes including SUPER, CREATEDB, CREATEROLE, etc."
},
{
"code": null,
"e": 1280,
"s": 1173,
"text": "The following statement creates a role called ‘Raju’ that has the login privilege and an initial password:"
},
{
"code": null,
"e": 1329,
"s": 1280,
"text": "CREATE ROLE raju\nLOGIN \nPASSWORD 'mypassword1';\n"
},
{
"code": null,
"e": 1394,
"s": 1329,
"text": "Note: It is required to place the password in single quotes (‘)."
},
{
"code": null,
"e": 1439,
"s": 1394,
"text": "Now verify the role using the below command:"
},
{
"code": null,
"e": 1444,
"s": 1439,
"text": "\\du\n"
},
{
"code": null,
"e": 1492,
"s": 1444,
"text": "The role creation is successful as shown below:"
},
{
"code": null,
"e": 1581,
"s": 1492,
"text": "The following statement creates a role called ‘Nikhil’ that has the superuser attribute:"
},
{
"code": null,
"e": 1642,
"s": 1581,
"text": "CREATE ROLE Nikhil\nSUPERUSER \nLOGIN \nPASSWORD 'mypassword1';"
},
{
"code": null,
"e": 1675,
"s": 1642,
"text": "This will lead to the following:"
},
{
"code": null,
"e": 1802,
"s": 1675,
"text": "The superuser can override all access restrictions within the database therefore you should create this role only when needed."
},
{
"code": null,
"e": 1875,
"s": 1802,
"text": "Note: One must be a superuser in order to create another superuser role."
},
{
"code": null,
"e": 1978,
"s": 1875,
"text": "If you want to create roles that have the database creation privilege, you use the CREATEDB attribute:"
},
{
"code": null,
"e": 2033,
"s": 1978,
"text": "CREATE ROLE dba \nCREATEDB \nLOGIN \nPASSWORD 'Abcd1234';"
},
{
"code": null,
"e": 2066,
"s": 2033,
"text": "This will lead to the following:"
},
{
"code": null,
"e": 2176,
"s": 2066,
"text": "To set a date and time after which the role’s password is no longer valid, you use the valid until attribute:"
},
{
"code": null,
"e": 2200,
"s": 2176,
"text": "VALID UNTIL 'timestamp'"
},
{
"code": null,
"e": 2209,
"s": 2200,
"text": "Example:"
},
{
"code": null,
"e": 2289,
"s": 2209,
"text": "CREATE ROLE dev_api WITH\nLOGIN\nPASSWORD 'securePass1'\nVALID UNTIL '2030-01-01';"
},
{
"code": null,
"e": 2297,
"s": 2289,
"text": "Output:"
},
{
"code": null,
"e": 2402,
"s": 2297,
"text": "To specify the number of concurrent connections a role can make, you use the CONNECTION LIMIT attribute:"
},
{
"code": null,
"e": 2436,
"s": 2402,
"text": "CONNECTION LIMIT connection_count"
},
{
"code": null,
"e": 2523,
"s": 2436,
"text": "The following creates a new role called API that can make 1000 concurrent connections:"
},
{
"code": null,
"e": 2591,
"s": 2523,
"text": "CREATE ROLE api\nLOGIN\nPASSWORD 'securePass1'\nCONNECTION LIMIT 1000;"
},
{
"code": null,
"e": 2631,
"s": 2591,
"text": "This will create a new role as follows:"
},
{
"code": null,
"e": 2707,
"s": 2631,
"text": "The following psql command shows all the roles that we have created so far:"
},
{
"code": null,
"e": 2711,
"s": 2707,
"text": "\\du"
},
{
"code": null,
"e": 2761,
"s": 2711,
"text": "This will show you the results as depicted below:"
},
{
"code": null,
"e": 2787,
"s": 2761,
"text": "postgreSQL-administration"
},
{
"code": null,
"e": 2798,
"s": 2787,
"text": "PostgreSQL"
}
] |
How to Create Circular Determinate ProgressBar in Android? | 24 Jun, 2021
In this article, we are going to demonstrate how to create a circular progress bar in Android Studio that displays the current progress value and has a gray background color initially. Here progress is shown in the center of the Bar. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that you have to select Java as the programming language.
Step 2: Create a New Drawable Resource File
Create a new Drawable Resource File with the name circle.xml in the drawable folder. To create a new Drawable Resource File navigate to res > drawable and follow the images
given below:
Click on Drawable Resource File, a new dialog box opens as shown in the below image. Add file name and choose Root element as layer-list and click OK.
Step 3: Working with the circle.xml file
Navigate to res > drawable > circle.xml and add the code given below to that file. In this file, we will be drawing a circle that shows progress. Comments have been added to the code for better understanding.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!--Adding our first item--> <item> <!--Here ring shape is created. The important attribute used here is, android:useLevel="false". Attribute with the useLevel=true makes the ring disabled, so it must be false for the ring to appear with color code "#DDD"--> <shape android:shape="ring" android:thicknessRatio="16" android:useLevel="false"> <solid android:color="#DDD" /> </shape> </item> <!--Adding our second item--> <item> <!--Rotation degree of Ring is made from 270 to 270--> <rotate android:fromDegrees="270" android:toDegrees="270"> <!--The main attribute used here is android:useLevel="true" in shape tag. Also gradient is added to set the startColor and endColor of the ring.--> <shape android:shape="ring" android:thicknessRatio="16" android:useLevel="true"> <gradient android:endColor="@color/teal_700" android:startColor="@color/black" android:type="sweep" /> </shape> </rotate> </item></layer-list>
Step 4: Adding style to the ProgressBar
Navigate to res > layout > theme.xml and add the code given below to that file. We have added a new style in this file. Comments have been added properly for clear understanding.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.ProgressBar" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/green</item> <item name="colorPrimaryVariant">@color/green</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <!--Here, android: indeterminateDrawable sets the picture displayed in the animation or the xml file of this animation and android: indeterminateOnly This property is set to true,the progress bar will be ignored Progress and present an infinite loop of animation --> <style name="CircularDeterminateProgressBar"> <item name="android:indeterminateOnly">false </item> <item name="android:progressDrawable">@drawable/circle</item> </style> </resources>
Step 5: Working with the activity_main.xml file
Go to res > layout > activity_main.xml and add the code given below to that file. Here we have added a ProgressBar that shows the progress and a TextView is added to display the percentage of progress. Two Buttons also have been added to increase or decrease the progress. Required comments have been added to the code.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Add ProgressBar. Main Attribute used here are style="@style/CircularDeterminateProgressBar" that takes style as created in theme.xml file above and android:progressDrawable="@drawable/circle" that has been created in circle.xml file above.--> <ProgressBar android:id="@+id/progress_bar" style="@style/CircularDeterminateProgressBar" android:layout_width="200dp" android:layout_height="200dp" android:indeterminateOnly="false" android:progress="60" android:progressDrawable="@drawable/circle" android:rotation="-90" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" tools:progress="60" /> <TextView android:id="@+id/text_view_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.AppCompat.Large" app:layout_constraintBottom_toBottomOf="@+id/progress_bar" app:layout_constraintEnd_toEndOf="@+id/progress_bar" app:layout_constraintStart_toStartOf="@+id/progress_bar" app:layout_constraintTop_toTopOf="@+id/progress_bar" tools:text="60%" /> <!--Increment button that will decrement the progress by 10%--> <Button android:id="@+id/button_decr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="- 10%" app:layout_constraintStart_toStartOf="@+id/progress_bar" app:layout_constraintTop_toBottomOf="@+id/progress_bar" /> <!--Increment button that will increment the progress by 10%--> <Button android:id="@+id/button_incr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+ 10%" app:layout_constraintEnd_toEndOf="@+id/progress_bar" app:layout_constraintTop_toBottomOf="@+id/progress_bar" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and add the code given below to that file. ProgressBar property is implemented here. Comments have been added to the code for quick and clear understanding.
Java
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private int progress = 0; Button buttonIncrement; Button buttonDecrement; ProgressBar progressBar; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDecrement = (Button) findViewById(R.id.button_decr); buttonIncrement = (Button) findViewById(R.id.button_incr); progressBar = (ProgressBar) findViewById(R.id.progress_bar); textView = (TextView) findViewById(R.id.text_view_progress); // when clicked on buttonIncrement progress in increased by 10% buttonIncrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // if progress is less than or equal // to 90% then only it can be increased if (progress <= 90) { progress += 10; updateProgressBar(); } } }); // when clicked on buttonIncrement progress in decreased by 10% buttonDecrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If progress is greater than // 10% then only it can be decreased if (progress >= 10) { progress -= 10; updateProgressBar(); } } }); } // updateProgressBar() method sets // the progress of ProgressBar in text private void updateProgressBar() { progressBar.setProgress(progress); textView.setText(String.valueOf(progress)); }}
Output:
surinderdawra388
Android-Bars
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Navigation Drawer in Android
How to Create and Add Data to SQLite Database in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 451,
"s": 52,
"text": "In this article, we are going to demonstrate how to create a circular progress bar in Android Studio that displays the current progress value and has a gray background color initially. Here progress is shown in the center of the Bar. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 480,
"s": 451,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 654,
"s": 480,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that you have to select Java as the programming language."
},
{
"code": null,
"e": 698,
"s": 654,
"text": "Step 2: Create a New Drawable Resource File"
},
{
"code": null,
"e": 872,
"s": 698,
"text": "Create a new Drawable Resource File with the name circle.xml in the drawable folder. To create a new Drawable Resource File navigate to res > drawable and follow the images "
},
{
"code": null,
"e": 885,
"s": 872,
"text": "given below:"
},
{
"code": null,
"e": 1037,
"s": 885,
"text": "Click on Drawable Resource File, a new dialog box opens as shown in the below image. Add file name and choose Root element as layer-list and click OK. "
},
{
"code": null,
"e": 1078,
"s": 1037,
"text": "Step 3: Working with the circle.xml file"
},
{
"code": null,
"e": 1287,
"s": 1078,
"text": "Navigate to res > drawable > circle.xml and add the code given below to that file. In this file, we will be drawing a circle that shows progress. Comments have been added to the code for better understanding."
},
{
"code": null,
"e": 1291,
"s": 1287,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--Adding our first item--> <item> <!--Here ring shape is created. The important attribute used here is, android:useLevel=\"false\". Attribute with the useLevel=true makes the ring disabled, so it must be false for the ring to appear with color code \"#DDD\"--> <shape android:shape=\"ring\" android:thicknessRatio=\"16\" android:useLevel=\"false\"> <solid android:color=\"#DDD\" /> </shape> </item> <!--Adding our second item--> <item> <!--Rotation degree of Ring is made from 270 to 270--> <rotate android:fromDegrees=\"270\" android:toDegrees=\"270\"> <!--The main attribute used here is android:useLevel=\"true\" in shape tag. Also gradient is added to set the startColor and endColor of the ring.--> <shape android:shape=\"ring\" android:thicknessRatio=\"16\" android:useLevel=\"true\"> <gradient android:endColor=\"@color/teal_700\" android:startColor=\"@color/black\" android:type=\"sweep\" /> </shape> </rotate> </item></layer-list>",
"e": 2638,
"s": 1291,
"text": null
},
{
"code": null,
"e": 2682,
"s": 2642,
"text": "Step 4: Adding style to the ProgressBar"
},
{
"code": null,
"e": 2863,
"s": 2684,
"text": "Navigate to res > layout > theme.xml and add the code given below to that file. We have added a new style in this file. Comments have been added properly for clear understanding."
},
{
"code": null,
"e": 2869,
"s": 2865,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.ProgressBar\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/green</item> <item name=\"colorPrimaryVariant\">@color/green</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <!--Here, android: indeterminateDrawable sets the picture displayed in the animation or the xml file of this animation and android: indeterminateOnly This property is set to true,the progress bar will be ignored Progress and present an infinite loop of animation --> <style name=\"CircularDeterminateProgressBar\"> <item name=\"android:indeterminateOnly\">false </item> <item name=\"android:progressDrawable\">@drawable/circle</item> </style> </resources>",
"e": 4181,
"s": 2869,
"text": null
},
{
"code": null,
"e": 4233,
"s": 4185,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 4555,
"s": 4235,
"text": "Go to res > layout > activity_main.xml and add the code given below to that file. Here we have added a ProgressBar that shows the progress and a TextView is added to display the percentage of progress. Two Buttons also have been added to increase or decrease the progress. Required comments have been added to the code."
},
{
"code": null,
"e": 4561,
"s": 4557,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Add ProgressBar. Main Attribute used here are style=\"@style/CircularDeterminateProgressBar\" that takes style as created in theme.xml file above and android:progressDrawable=\"@drawable/circle\" that has been created in circle.xml file above.--> <ProgressBar android:id=\"@+id/progress_bar\" style=\"@style/CircularDeterminateProgressBar\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:indeterminateOnly=\"false\" android:progress=\"60\" android:progressDrawable=\"@drawable/circle\" android:rotation=\"-90\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" tools:progress=\"60\" /> <TextView android:id=\"@+id/text_view_progress\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" app:layout_constraintBottom_toBottomOf=\"@+id/progress_bar\" app:layout_constraintEnd_toEndOf=\"@+id/progress_bar\" app:layout_constraintStart_toStartOf=\"@+id/progress_bar\" app:layout_constraintTop_toTopOf=\"@+id/progress_bar\" tools:text=\"60%\" /> <!--Increment button that will decrement the progress by 10%--> <Button android:id=\"@+id/button_decr\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"- 10%\" app:layout_constraintStart_toStartOf=\"@+id/progress_bar\" app:layout_constraintTop_toBottomOf=\"@+id/progress_bar\" /> <!--Increment button that will increment the progress by 10%--> <Button android:id=\"@+id/button_incr\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"+ 10%\" app:layout_constraintEnd_toEndOf=\"@+id/progress_bar\" app:layout_constraintTop_toBottomOf=\"@+id/progress_bar\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 7054,
"s": 4561,
"text": null
},
{
"code": null,
"e": 7106,
"s": 7058,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 7298,
"s": 7108,
"text": "Go to the MainActivity.java file and add the code given below to that file. ProgressBar property is implemented here. Comments have been added to the code for quick and clear understanding."
},
{
"code": null,
"e": 7305,
"s": 7300,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private int progress = 0; Button buttonIncrement; Button buttonDecrement; ProgressBar progressBar; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDecrement = (Button) findViewById(R.id.button_decr); buttonIncrement = (Button) findViewById(R.id.button_incr); progressBar = (ProgressBar) findViewById(R.id.progress_bar); textView = (TextView) findViewById(R.id.text_view_progress); // when clicked on buttonIncrement progress in increased by 10% buttonIncrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // if progress is less than or equal // to 90% then only it can be increased if (progress <= 90) { progress += 10; updateProgressBar(); } } }); // when clicked on buttonIncrement progress in decreased by 10% buttonDecrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If progress is greater than // 10% then only it can be decreased if (progress >= 10) { progress -= 10; updateProgressBar(); } } }); } // updateProgressBar() method sets // the progress of ProgressBar in text private void updateProgressBar() { progressBar.setProgress(progress); textView.setText(String.valueOf(progress)); }}",
"e": 9263,
"s": 7305,
"text": null
},
{
"code": null,
"e": 9275,
"s": 9267,
"text": "Output:"
},
{
"code": null,
"e": 9296,
"s": 9279,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9309,
"s": 9296,
"text": "Android-Bars"
},
{
"code": null,
"e": 9317,
"s": 9309,
"text": "Android"
},
{
"code": null,
"e": 9322,
"s": 9317,
"text": "Java"
},
{
"code": null,
"e": 9327,
"s": 9322,
"text": "Java"
},
{
"code": null,
"e": 9335,
"s": 9327,
"text": "Android"
},
{
"code": null,
"e": 9433,
"s": 9335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9465,
"s": 9433,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 9496,
"s": 9465,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 9539,
"s": 9496,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 9568,
"s": 9539,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 9626,
"s": 9568,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 9641,
"s": 9626,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9685,
"s": 9641,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9721,
"s": 9685,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9772,
"s": 9721,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Python Dictionary fromkeys() Method | 05 Oct, 2021
Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value.
Syntax : fromkeys(seq, val)
Parameters :
seq : The sequence to be transformed into a dictionary.
val : Initial values that need to be assigned to the generated keys. Defaults to None.
Returns : A dictionary with keys mapped to None if no value is provided, else to the value provided in the field.
Python3
# Python 3 code to demonstrate# working of fromkeys() # initializing sequenceseq = {'a', 'b', 'c', 'd', 'e'} # using fromkeys() to convert sequence to dict# initializing with Noneres_dict = dict.fromkeys(seq) # Printing created dictprint("The newly created dict with None values : " + str(res_dict)) # using fromkeys() to convert sequence to dict# initializing with 1res_dict2 = dict.fromkeys(seq, 1) # Printing created dictprint("The newly created dict with 1 as value : " + str(res_dict2))
Output :
The newly created dict with None values : {‘d’: None, ‘a’: None, ‘b’: None, ‘c’: None, ‘e’: None} The newly created dict with 1 as value : {‘d’: 1, ‘a’: 1, ‘b’: 1, ‘c’: 1, ‘e’: 1}
fromdict() can also be supplied with the mutable object as the default value. But in this case, a deep copy is made of the dictionary, i.e if we append value in the original list, the append takes place in all the values of keys.
Prevention: Certain dictionary comprehension techniques can be used to create a new list as key values, that do not point to the original list as values of keys.
Python3
# Python 3 code to demonstrate# behaviour with mutable objects # initializing sequence and listseq = {'a', 'b', 'c', 'd', 'e'}lis1 = [2, 3] # using fromkeys() to convert sequence to dict# using conventional methodres_dict = dict.fromkeys(seq, lis1) # Printing created dictprint("The newly created dict with list values : " + str(res_dict)) # appending to lis1lis1.append(4) # Printing dict after appending# Notice that append takes place in all valuesprint("The dict with list values after appending : " + str(res_dict)) lis1 = [2, 3]print('\n') # using fromkeys() to convert sequence to dict# using dict. comprehensionres_dict2 = {key: list(lis1) for key in seq} # Printing created dictprint("The newly created dict with list values : " + str(res_dict2)) # appending to lis1lis1.append(4) # Printing dict after appending# Notice that append doesnt take place now.print("The dict with list values after appending (no change) : " + str(res_dict2))
Output:
The newly created dict with list values : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]} The dict with list values after appending : {‘d’: [2, 3, 4], ‘e’: [2, 3, 4], ‘c’: [2, 3, 4], ‘a’: [2, 3, 4], ‘b’: [2, 3, 4]}The newly created dict with list values : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]} The dict with list values after appending (no change) : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]}
Python3
x = ('key1', 'key2', 'key3')y = 0 d = dict.fromkeys(x, y) print(d)
Output:
{'key1': 0, 'key2': 0, 'key3': 0}
Python3
# Python3 code to demonstrate# to initialize dictionary with list# using fromkeys() # using fromkeys() to constructnew_dict = dict.fromkeys(range(4), []) # printing resultprint ("New dictionary with empty lists as keys : " + str(new_dict))
Output:
New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}
kumar_satyam
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 226,
"s": 52,
"text": "Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value."
},
{
"code": null,
"e": 254,
"s": 226,
"text": "Syntax : fromkeys(seq, val)"
},
{
"code": null,
"e": 268,
"s": 254,
"text": "Parameters : "
},
{
"code": null,
"e": 324,
"s": 268,
"text": "seq : The sequence to be transformed into a dictionary."
},
{
"code": null,
"e": 411,
"s": 324,
"text": "val : Initial values that need to be assigned to the generated keys. Defaults to None."
},
{
"code": null,
"e": 526,
"s": 411,
"text": "Returns : A dictionary with keys mapped to None if no value is provided, else to the value provided in the field. "
},
{
"code": null,
"e": 534,
"s": 526,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of fromkeys() # initializing sequenceseq = {'a', 'b', 'c', 'd', 'e'} # using fromkeys() to convert sequence to dict# initializing with Noneres_dict = dict.fromkeys(seq) # Printing created dictprint(\"The newly created dict with None values : \" + str(res_dict)) # using fromkeys() to convert sequence to dict# initializing with 1res_dict2 = dict.fromkeys(seq, 1) # Printing created dictprint(\"The newly created dict with 1 as value : \" + str(res_dict2))",
"e": 1027,
"s": 534,
"text": null
},
{
"code": null,
"e": 1037,
"s": 1027,
"text": "Output : "
},
{
"code": null,
"e": 1217,
"s": 1037,
"text": "The newly created dict with None values : {‘d’: None, ‘a’: None, ‘b’: None, ‘c’: None, ‘e’: None} The newly created dict with 1 as value : {‘d’: 1, ‘a’: 1, ‘b’: 1, ‘c’: 1, ‘e’: 1}"
},
{
"code": null,
"e": 1447,
"s": 1217,
"text": "fromdict() can also be supplied with the mutable object as the default value. But in this case, a deep copy is made of the dictionary, i.e if we append value in the original list, the append takes place in all the values of keys."
},
{
"code": null,
"e": 1609,
"s": 1447,
"text": "Prevention: Certain dictionary comprehension techniques can be used to create a new list as key values, that do not point to the original list as values of keys."
},
{
"code": null,
"e": 1617,
"s": 1609,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# behaviour with mutable objects # initializing sequence and listseq = {'a', 'b', 'c', 'd', 'e'}lis1 = [2, 3] # using fromkeys() to convert sequence to dict# using conventional methodres_dict = dict.fromkeys(seq, lis1) # Printing created dictprint(\"The newly created dict with list values : \" + str(res_dict)) # appending to lis1lis1.append(4) # Printing dict after appending# Notice that append takes place in all valuesprint(\"The dict with list values after appending : \" + str(res_dict)) lis1 = [2, 3]print('\\n') # using fromkeys() to convert sequence to dict# using dict. comprehensionres_dict2 = {key: list(lis1) for key in seq} # Printing created dictprint(\"The newly created dict with list values : \" + str(res_dict2)) # appending to lis1lis1.append(4) # Printing dict after appending# Notice that append doesnt take place now.print(\"The dict with list values after appending (no change) : \" + str(res_dict2))",
"e": 2584,
"s": 1617,
"text": null
},
{
"code": null,
"e": 2592,
"s": 2584,
"text": "Output:"
},
{
"code": null,
"e": 3054,
"s": 2592,
"text": "The newly created dict with list values : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]} The dict with list values after appending : {‘d’: [2, 3, 4], ‘e’: [2, 3, 4], ‘c’: [2, 3, 4], ‘a’: [2, 3, 4], ‘b’: [2, 3, 4]}The newly created dict with list values : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]} The dict with list values after appending (no change) : {‘d’: [2, 3], ‘e’: [2, 3], ‘c’: [2, 3], ‘a’: [2, 3], ‘b’: [2, 3]}"
},
{
"code": null,
"e": 3062,
"s": 3054,
"text": "Python3"
},
{
"code": "x = ('key1', 'key2', 'key3')y = 0 d = dict.fromkeys(x, y) print(d)",
"e": 3129,
"s": 3062,
"text": null
},
{
"code": null,
"e": 3137,
"s": 3129,
"text": "Output:"
},
{
"code": null,
"e": 3171,
"s": 3137,
"text": "{'key1': 0, 'key2': 0, 'key3': 0}"
},
{
"code": null,
"e": 3179,
"s": 3171,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to initialize dictionary with list# using fromkeys() # using fromkeys() to constructnew_dict = dict.fromkeys(range(4), []) # printing resultprint (\"New dictionary with empty lists as keys : \" + str(new_dict))",
"e": 3427,
"s": 3179,
"text": null
},
{
"code": null,
"e": 3435,
"s": 3427,
"text": "Output:"
},
{
"code": null,
"e": 3506,
"s": 3435,
"text": "New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}"
},
{
"code": null,
"e": 3519,
"s": 3506,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3531,
"s": 3519,
"text": "python-dict"
},
{
"code": null,
"e": 3553,
"s": 3531,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 3560,
"s": 3553,
"text": "Python"
},
{
"code": null,
"e": 3572,
"s": 3560,
"text": "python-dict"
},
{
"code": null,
"e": 3670,
"s": 3572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3698,
"s": 3670,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3748,
"s": 3698,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3770,
"s": 3748,
"text": "Python map() function"
},
{
"code": null,
"e": 3788,
"s": 3770,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3832,
"s": 3788,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3874,
"s": 3832,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3897,
"s": 3874,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3919,
"s": 3897,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3954,
"s": 3919,
"text": "Read a file line by line in Python"
}
] |
Python | Accessing variable value from code scope | 29 Oct, 2019
Sometimes, we just need to access a variable other than the usual way of accessing by it’s name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let’s talk about some of this functions.
Method #1 : Using locals()This is a function that stores the values of all variables in local scope of function if in a function or of global scope if outside.
# Python3 code to demonstrate working of# Accessing variable value from code scope# using locals # initialize variabletest_var = "gfg is best" # printing original variableprint("The original variable : " + str(test_var)) # Accessing variable value from code scope# using localsres = locals()['test_var'] # printing resultprint("Variable accessed using dictionary : " + str(res))
The original variable : gfg is best
Variable accessed using dictionary : gfg is best
Method #2 : Using globals()This is yet another function that maintains a dictionary of variables of global scope.
# Python3 code to demonstrate working of# Accessing variable value from code scope# using globals # initialize variabletest_var = "gfg is best" # printing original variableprint("The original variable : " + str(test_var)) # Accessing variable value from code scope# using globalsres = globals()['test_var'] # printing resultprint("Variable accessed using dictionary : " + str(res))
The original variable : gfg is best
Variable accessed using dictionary : gfg is best
python-basics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 361,
"s": 28,
"text": "Sometimes, we just need to access a variable other than the usual way of accessing by it’s name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let’s talk about some of this functions."
},
{
"code": null,
"e": 521,
"s": 361,
"text": "Method #1 : Using locals()This is a function that stores the values of all variables in local scope of function if in a function or of global scope if outside."
},
{
"code": "# Python3 code to demonstrate working of# Accessing variable value from code scope# using locals # initialize variabletest_var = \"gfg is best\" # printing original variableprint(\"The original variable : \" + str(test_var)) # Accessing variable value from code scope# using localsres = locals()['test_var'] # printing resultprint(\"Variable accessed using dictionary : \" + str(res))",
"e": 904,
"s": 521,
"text": null
},
{
"code": null,
"e": 990,
"s": 904,
"text": "The original variable : gfg is best\nVariable accessed using dictionary : gfg is best\n"
},
{
"code": null,
"e": 1106,
"s": 992,
"text": "Method #2 : Using globals()This is yet another function that maintains a dictionary of variables of global scope."
},
{
"code": "# Python3 code to demonstrate working of# Accessing variable value from code scope# using globals # initialize variabletest_var = \"gfg is best\" # printing original variableprint(\"The original variable : \" + str(test_var)) # Accessing variable value from code scope# using globalsres = globals()['test_var'] # printing resultprint(\"Variable accessed using dictionary : \" + str(res))",
"e": 1492,
"s": 1106,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1492,
"text": "The original variable : gfg is best\nVariable accessed using dictionary : gfg is best\n"
},
{
"code": null,
"e": 1592,
"s": 1578,
"text": "python-basics"
},
{
"code": null,
"e": 1599,
"s": 1592,
"text": "Python"
},
{
"code": null,
"e": 1615,
"s": 1599,
"text": "Python Programs"
},
{
"code": null,
"e": 1713,
"s": 1615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1745,
"s": 1713,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1772,
"s": 1745,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1793,
"s": 1772,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1816,
"s": 1793,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1872,
"s": 1816,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1894,
"s": 1872,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1933,
"s": 1894,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1971,
"s": 1933,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2020,
"s": 1971,
"text": "Python | Convert string dictionary to dictionary"
}
] |
C Program to check whether a number is a Perfect Cube or not - GeeksforGeeks | 19 Aug, 2020
Given a number N, the task is to write C program to check if the given number is perfect cube or not.
Examples:
Input: N = 216Output: YesExplanation:As 216 = 6*6*6.Therefore the cube root of 216 is 6.
Input: N = 100Output: No
Method 1: Naive Approach To find the cube root of the given number iterate over all the natural numbers from 1 till N and check if cube of any number in this range is equal to the given number N then print Yes else print No
Below is the implementation of the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// a perfect Cubevoid perfectCube(int N){ for (int i = 1; i < N; i++) { // If cube of i is equals to N // then print Yes and return if (i * i * i == N) { printf("Yes"); return; } } // No number was found whose cube // is equal to N printf("No"); return;} // Driver Codeint main(){ // Given Number int N = 216; // Function Call perfectCube(N); return 0;}
Yes
Complexity Analysis:
Time Complexity: O(N), only one traversal of the solution is needed, so the time complexity is O(N).
Auxiliary Space: O(1). Constant extra space is needed.
Method 2: Using inbuilt function The idea is to use the inbuilt function pow() to find the cube root of a number which returns floor value of the cube root of the number N. If the cube of this number equals N, then N is a perfect cube otherwise N is not a perfect cube.
Below is the implementation of the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// perfect cube using inbuilt functionvoid perfectCube(int N){ int cube_root; cube_root = (int)round(pow(N, 1.0 / 3.0)); // If cube of cube_root is equals // to N, then print Yes else No if (cube_root * cube_root * cube_root == N) { printf("Yes"); return; } else { printf("No"); return; }} // Driver Codeint main(){ // Given number N int N = 216; // Function Call perfectCube(N); return 0;}
Yes
Complexity Analysis:
Time Complexity: O(N), since the pow() function works in O(N), so the time complexity is O(N).
Auxiliary Space: O(1). Constant extra space is needed.
Method 3: Using Binary Search The idea is to use Binary Search to solve the problem. The values of i * i * i is monotonically increasing, so the problem can be solved using binary search.Below are the steps:
Initialise low and high as 0 and N respectively.Iterate until low ≤ high and do the following:Find the value of mid as = (low + high)/2.Check if mid*mid*mid is equals to N then print “Yes”.If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1.If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1.If cube of N is not obtained in the above step then print “No”.
Initialise low and high as 0 and N respectively.
Iterate until low ≤ high and do the following:Find the value of mid as = (low + high)/2.Check if mid*mid*mid is equals to N then print “Yes”.If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1.If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1.
Find the value of mid as = (low + high)/2.
Check if mid*mid*mid is equals to N then print “Yes”.
If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1.
If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1.
If cube of N is not obtained in the above step then print “No”.
Below is the implementation of the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// a perfect Cube using binary searchvoid perfectCube(int N){ int start = 1, end = N; while (start <= end) { // Calculating mid int mid = (start + end) / 2; // If N is a perfect cube if (mid * mid * mid == N) { printf("Yes"); return; } // If mid^3 is smaller than N, // then move closer to cube // root of N if (mid * mid * mid < N) { start = mid + 1; } // If mid^3 is greater than N else end = mid - 1; } printf("No"); return;} // Driver Codeint main(){ // Given Number N int N = 216; // Function Call perfectCube(N); return 0;}
Yes
Complexity Analysis:
Time Complexity: O(log N). The time complexity of binary search is O(log N).
Auxiliary Space: O(1). Constant extra space is needed.
Binary Search
Maths
maths-cube
maths-perfect-cube
maths-power
C Programs
Mathematical
School Programming
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25032,
"s": 25004,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 25134,
"s": 25032,
"text": "Given a number N, the task is to write C program to check if the given number is perfect cube or not."
},
{
"code": null,
"e": 25144,
"s": 25134,
"text": "Examples:"
},
{
"code": null,
"e": 25233,
"s": 25144,
"text": "Input: N = 216Output: YesExplanation:As 216 = 6*6*6.Therefore the cube root of 216 is 6."
},
{
"code": null,
"e": 25258,
"s": 25233,
"text": "Input: N = 100Output: No"
},
{
"code": null,
"e": 25482,
"s": 25258,
"text": "Method 1: Naive Approach To find the cube root of the given number iterate over all the natural numbers from 1 till N and check if cube of any number in this range is equal to the given number N then print Yes else print No"
},
{
"code": null,
"e": 25533,
"s": 25482,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25535,
"s": 25533,
"text": "C"
},
{
"code": "// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// a perfect Cubevoid perfectCube(int N){ for (int i = 1; i < N; i++) { // If cube of i is equals to N // then print Yes and return if (i * i * i == N) { printf(\"Yes\"); return; } } // No number was found whose cube // is equal to N printf(\"No\"); return;} // Driver Codeint main(){ // Given Number int N = 216; // Function Call perfectCube(N); return 0;}",
"e": 26086,
"s": 25535,
"text": null
},
{
"code": null,
"e": 26091,
"s": 26086,
"text": "Yes\n"
},
{
"code": null,
"e": 26112,
"s": 26091,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 26213,
"s": 26112,
"text": "Time Complexity: O(N), only one traversal of the solution is needed, so the time complexity is O(N)."
},
{
"code": null,
"e": 26268,
"s": 26213,
"text": "Auxiliary Space: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 26538,
"s": 26268,
"text": "Method 2: Using inbuilt function The idea is to use the inbuilt function pow() to find the cube root of a number which returns floor value of the cube root of the number N. If the cube of this number equals N, then N is a perfect cube otherwise N is not a perfect cube."
},
{
"code": null,
"e": 26589,
"s": 26538,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26591,
"s": 26589,
"text": "C"
},
{
"code": "// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// perfect cube using inbuilt functionvoid perfectCube(int N){ int cube_root; cube_root = (int)round(pow(N, 1.0 / 3.0)); // If cube of cube_root is equals // to N, then print Yes else No if (cube_root * cube_root * cube_root == N) { printf(\"Yes\"); return; } else { printf(\"No\"); return; }} // Driver Codeint main(){ // Given number N int N = 216; // Function Call perfectCube(N); return 0;}",
"e": 27161,
"s": 26591,
"text": null
},
{
"code": null,
"e": 27166,
"s": 27161,
"text": "Yes\n"
},
{
"code": null,
"e": 27187,
"s": 27166,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 27282,
"s": 27187,
"text": "Time Complexity: O(N), since the pow() function works in O(N), so the time complexity is O(N)."
},
{
"code": null,
"e": 27337,
"s": 27282,
"text": "Auxiliary Space: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 27545,
"s": 27337,
"text": "Method 3: Using Binary Search The idea is to use Binary Search to solve the problem. The values of i * i * i is monotonically increasing, so the problem can be solved using binary search.Below are the steps:"
},
{
"code": null,
"e": 28056,
"s": 27545,
"text": "Initialise low and high as 0 and N respectively.Iterate until low ≤ high and do the following:Find the value of mid as = (low + high)/2.Check if mid*mid*mid is equals to N then print “Yes”.If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1.If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1.If cube of N is not obtained in the above step then print “No”."
},
{
"code": null,
"e": 28105,
"s": 28056,
"text": "Initialise low and high as 0 and N respectively."
},
{
"code": null,
"e": 28505,
"s": 28105,
"text": "Iterate until low ≤ high and do the following:Find the value of mid as = (low + high)/2.Check if mid*mid*mid is equals to N then print “Yes”.If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1.If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1."
},
{
"code": null,
"e": 28548,
"s": 28505,
"text": "Find the value of mid as = (low + high)/2."
},
{
"code": null,
"e": 28602,
"s": 28548,
"text": "Check if mid*mid*mid is equals to N then print “Yes”."
},
{
"code": null,
"e": 28730,
"s": 28602,
"text": "If the cube of mid is less than N then search for a larger value in the second half of search space by updating low to mid + 1."
},
{
"code": null,
"e": 28862,
"s": 28730,
"text": "If the cube of mid is greater than N then search for a smaller value in the first half of search space by updating high to mid – 1."
},
{
"code": null,
"e": 28926,
"s": 28862,
"text": "If cube of N is not obtained in the above step then print “No”."
},
{
"code": null,
"e": 28977,
"s": 28926,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28979,
"s": 28977,
"text": "C"
},
{
"code": "// C program for the above approach#include <math.h>#include <stdio.h> // Function to check if a number is// a perfect Cube using binary searchvoid perfectCube(int N){ int start = 1, end = N; while (start <= end) { // Calculating mid int mid = (start + end) / 2; // If N is a perfect cube if (mid * mid * mid == N) { printf(\"Yes\"); return; } // If mid^3 is smaller than N, // then move closer to cube // root of N if (mid * mid * mid < N) { start = mid + 1; } // If mid^3 is greater than N else end = mid - 1; } printf(\"No\"); return;} // Driver Codeint main(){ // Given Number N int N = 216; // Function Call perfectCube(N); return 0;}",
"e": 29787,
"s": 28979,
"text": null
},
{
"code": null,
"e": 29792,
"s": 29787,
"text": "Yes\n"
},
{
"code": null,
"e": 29813,
"s": 29792,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 29890,
"s": 29813,
"text": "Time Complexity: O(log N). The time complexity of binary search is O(log N)."
},
{
"code": null,
"e": 29945,
"s": 29890,
"text": "Auxiliary Space: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 29959,
"s": 29945,
"text": "Binary Search"
},
{
"code": null,
"e": 29965,
"s": 29959,
"text": "Maths"
},
{
"code": null,
"e": 29976,
"s": 29965,
"text": "maths-cube"
},
{
"code": null,
"e": 29995,
"s": 29976,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 30007,
"s": 29995,
"text": "maths-power"
},
{
"code": null,
"e": 30018,
"s": 30007,
"text": "C Programs"
},
{
"code": null,
"e": 30031,
"s": 30018,
"text": "Mathematical"
},
{
"code": null,
"e": 30050,
"s": 30031,
"text": "School Programming"
},
{
"code": null,
"e": 30063,
"s": 30050,
"text": "Mathematical"
},
{
"code": null,
"e": 30077,
"s": 30063,
"text": "Binary Search"
},
{
"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": 30216,
"s": 30175,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30247,
"s": 30216,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 30288,
"s": 30247,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 30322,
"s": 30288,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 30347,
"s": 30322,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 30377,
"s": 30347,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30437,
"s": 30377,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30452,
"s": 30437,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30495,
"s": 30452,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
F# - Classes | Classes are types that represent objects that can have properties, methods, and events. ‘They are used to model actions, processes, and any conceptual entities in applications’.
Syntax for defining a class type is as follows −
// Class definition:
type [access-modifier] type-name [type-params] [access-modifier] ( parameter-list ) [ as identifier ] =
[ class ]
[ inherit base-type-name(base-constructor-args) ]
[ let-bindings ]
[ do-bindings ]
member-list
...
[ end ]
// Mutually recursive class definitions:
type [access-modifier] type-name1 ...
and [access-modifier] type-name2 ...
...
Where,
The type-name is any valid identifier. Default access modifier for this is public.
The type-name is any valid identifier. Default access modifier for this is public.
The type-params describes optional generic type parameters.
The type-params describes optional generic type parameters.
The parameter-list describes constructor parameters. Default access modifier for primary constructor is public.
The parameter-list describes constructor parameters. Default access modifier for primary constructor is public.
The identifier used with the optional as keyword gives a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type.
The identifier used with the optional as keyword gives a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type.
The inherit keyword allows you to specify the base class for a class.
The inherit keyword allows you to specify the base class for a class.
The let bindings allow you to declare fields or function values local to the class.
The let bindings allow you to declare fields or function values local to the class.
The do-bindings section includes code to be executed upon object construction.
The do-bindings section includes code to be executed upon object construction.
The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations.
The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations.
The keywords class and end that mark the start and end of the definition are optional.
The keywords class and end that mark the start and end of the definition are optional.
The constructor is code that creates an instance of the class type.
In F#, constructors work little differently than other .Net languages. In the class definition, the arguments of the primary constructor are described as parameter-list.
The body of the constructor consists of the let and do bindings.
You can add additional constructors by using the new keyword to add a member −
new (argument-list) = constructor-body
The following example illustrates the concept −
The following program creates a line class along with a constructor that calculates the length of the line while an object of the class is created −
type Line = class
val X1 : float
val Y1 : float
val X2 : float
val Y2 : float
new (x1, y1, x2, y2) as this =
{ X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}
then
printfn " Creating Line: {(%g, %g), (%g, %g)}\nLength: %g"
this.X1 this.Y1 this.X2 this.Y2 this.Length
member x.Length =
let sqr x = x * x
sqrt(sqr(x.X1 - x.X2) + sqr(x.Y1 - x.Y2) )
end
let aLine = new Line(1.0, 1.0, 4.0, 5.0)
When you compile and execute the program, it yields the following output −
Creating Line: {(1, 1), (4, 5)}
Length: 5
The let bindings in a class definition allow you to define private fields and private functions for F# classes.
type Greetings(name) as gr =
let data = name
do
gr.PrintMessage()
member this.PrintMessage() =
printf "Hello %s\n" data
let gtr = new Greetings("Zara")
When you compile and execute the program, it yields the following output −
Hello Zara
Please note the use of self-identifier gr for the Greetings class.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2339,
"s": 2161,
"text": "Classes are types that represent objects that can have properties, methods, and events. ‘They are used to model actions, processes, and any conceptual entities in applications’."
},
{
"code": null,
"e": 2388,
"s": 2339,
"text": "Syntax for defining a class type is as follows −"
},
{
"code": null,
"e": 2788,
"s": 2388,
"text": "// Class definition:\ntype [access-modifier] type-name [type-params] [access-modifier] ( parameter-list ) [ as identifier ] =\n [ class ]\n [ inherit base-type-name(base-constructor-args) ]\n [ let-bindings ]\n [ do-bindings ]\n member-list\n ...\n [ end ]\n\n// Mutually recursive class definitions:\ntype [access-modifier] type-name1 ...\nand [access-modifier] type-name2 ...\n...\n"
},
{
"code": null,
"e": 2795,
"s": 2788,
"text": "Where,"
},
{
"code": null,
"e": 2878,
"s": 2795,
"text": "The type-name is any valid identifier. Default access modifier for this is public."
},
{
"code": null,
"e": 2961,
"s": 2878,
"text": "The type-name is any valid identifier. Default access modifier for this is public."
},
{
"code": null,
"e": 3021,
"s": 2961,
"text": "The type-params describes optional generic type parameters."
},
{
"code": null,
"e": 3081,
"s": 3021,
"text": "The type-params describes optional generic type parameters."
},
{
"code": null,
"e": 3193,
"s": 3081,
"text": "The parameter-list describes constructor parameters. Default access modifier for primary constructor is public."
},
{
"code": null,
"e": 3305,
"s": 3193,
"text": "The parameter-list describes constructor parameters. Default access modifier for primary constructor is public."
},
{
"code": null,
"e": 3492,
"s": 3305,
"text": "The identifier used with the optional as keyword gives a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type."
},
{
"code": null,
"e": 3679,
"s": 3492,
"text": "The identifier used with the optional as keyword gives a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type."
},
{
"code": null,
"e": 3749,
"s": 3679,
"text": "The inherit keyword allows you to specify the base class for a class."
},
{
"code": null,
"e": 3819,
"s": 3749,
"text": "The inherit keyword allows you to specify the base class for a class."
},
{
"code": null,
"e": 3903,
"s": 3819,
"text": "The let bindings allow you to declare fields or function values local to the class."
},
{
"code": null,
"e": 3987,
"s": 3903,
"text": "The let bindings allow you to declare fields or function values local to the class."
},
{
"code": null,
"e": 4066,
"s": 3987,
"text": "The do-bindings section includes code to be executed upon object construction."
},
{
"code": null,
"e": 4145,
"s": 4066,
"text": "The do-bindings section includes code to be executed upon object construction."
},
{
"code": null,
"e": 4319,
"s": 4145,
"text": "The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations."
},
{
"code": null,
"e": 4493,
"s": 4319,
"text": "The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations."
},
{
"code": null,
"e": 4580,
"s": 4493,
"text": "The keywords class and end that mark the start and end of the definition are optional."
},
{
"code": null,
"e": 4667,
"s": 4580,
"text": "The keywords class and end that mark the start and end of the definition are optional."
},
{
"code": null,
"e": 4735,
"s": 4667,
"text": "The constructor is code that creates an instance of the class type."
},
{
"code": null,
"e": 4905,
"s": 4735,
"text": "In F#, constructors work little differently than other .Net languages. In the class definition, the arguments of the primary constructor are described as parameter-list."
},
{
"code": null,
"e": 4970,
"s": 4905,
"text": "The body of the constructor consists of the let and do bindings."
},
{
"code": null,
"e": 5049,
"s": 4970,
"text": "You can add additional constructors by using the new keyword to add a member −"
},
{
"code": null,
"e": 5089,
"s": 5049,
"text": "new (argument-list) = constructor-body\n"
},
{
"code": null,
"e": 5137,
"s": 5089,
"text": "The following example illustrates the concept −"
},
{
"code": null,
"e": 5286,
"s": 5137,
"text": "The following program creates a line class along with a constructor that calculates the length of the line while an object of the class is created −"
},
{
"code": null,
"e": 5731,
"s": 5286,
"text": "type Line = class\n val X1 : float\n val Y1 : float\n val X2 : float\n val Y2 : float\n\n new (x1, y1, x2, y2) as this =\n { X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}\n then\n printfn \" Creating Line: {(%g, %g), (%g, %g)}\\nLength: %g\"\n this.X1 this.Y1 this.X2 this.Y2 this.Length\n\n member x.Length =\n let sqr x = x * x\n sqrt(sqr(x.X1 - x.X2) + sqr(x.Y1 - x.Y2) )\nend\nlet aLine = new Line(1.0, 1.0, 4.0, 5.0)"
},
{
"code": null,
"e": 5806,
"s": 5731,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 5849,
"s": 5806,
"text": "Creating Line: {(1, 1), (4, 5)}\nLength: 5\n"
},
{
"code": null,
"e": 5961,
"s": 5849,
"text": "The let bindings in a class definition allow you to define private fields and private functions for F# classes."
},
{
"code": null,
"e": 6134,
"s": 5961,
"text": "type Greetings(name) as gr =\n let data = name\n do\n gr.PrintMessage()\n member this.PrintMessage() =\n printf \"Hello %s\\n\" data\nlet gtr = new Greetings(\"Zara\")"
},
{
"code": null,
"e": 6209,
"s": 6134,
"text": "When you compile and execute the program, it yields the following output −"
},
{
"code": null,
"e": 6221,
"s": 6209,
"text": "Hello Zara\n"
},
{
"code": null,
"e": 6288,
"s": 6221,
"text": "Please note the use of self-identifier gr for the Greetings class."
},
{
"code": null,
"e": 6295,
"s": 6288,
"text": " Print"
},
{
"code": null,
"e": 6306,
"s": 6295,
"text": " Add Notes"
}
] |
return keyword in Java | 31 Mar, 2022
In Java, return is a reserved keyword i.e, we can’t use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:
Case 1: Methods returning a value
Case 2: Methods not returning a value
Let us illustrate by directly implementing them as follows:
Case 1: Methods returning a value
For methods that define a return type, return statement must be immediately followed by return value.
Example:
Java
// Java Program to Illustrate Usage of return Keyword // Main methodclass GFG { // Method 1 // Since return type of RR method is double // so this method should return double value double RR(double a, double b) { double sum = 0; sum = (a + b) / 2.0; // Return statement as we already above have declared // return type to be double return sum; } // Method 2 // Main driver method public static void main(String[] args) { // Print statement System.out.println(new GFG().RR(5.5, 6.5)); }}
6.0
Time Complexity: O(1)
Auxiliary Space : O(1)
Output explanation: When we are calling a class GFG method that has return sum which returns the value of sum and that’s value gets displayed on the console.
Case 2: Methods not returning a value
For methods that do not return a value, return statement in Java can be skipped. here there arise two cases when there is no value been returned by the user as listed below as follows:
#1: Method not using return statement in void function
#2: Methods with return type void
#1: Method not using return statement in void function
Example
Java
// Java program to illustrate no return// keyword needed inside void method // Main classclass GFG { // Since return type of RR method is // void so this method shouldn't return any value void demoSum(int a, int b) { int sum = 0; sum = (a + b) / 10; System.out.println(sum); // No return statement in this method } // Method 2 // Main driver method public static void main(String[] args) { // Calling the method // Over custom inputs new GFG().demoSum(5, 5); // Display message on the console for successful // execution of the program System.out.print( "No return keyword is used and program executed successfully"); } // Note here we are not returning anything // as the return type is void}
1
No return keyword is used and program executed successfully
Note: Return statement not required (but can be used) for methods with return type void. We can use “return;” which means not return anything.
#2: Methods with void return type
Example 1-A:
Java
// Java program to illustrate usage of// return keyword in void method // Class 1// Main classclass GFG { // Method 1 // Since return type of RR method is // void so this method should not return any value void demofunction(double j) { if (j < 9) // return statement below(only using // return statement and not returning // anything): // control exits the method if this // condition(i.e, j<9) is true. return; ++j; } // Method 2 // Main driver method public static void main(String[] args) { // Calling above method declared in above class new GFG().demofunction(5.5); // Display message on console to illustrate // successful execution of program System.out.println("Program executed successfully"); }}
Program executed successfully
Output explanation: If the statement if(j<9) is true then control exits from the method and does not execute the rest of the statement of the RR method and hence comes back again to main() method.
Now moving ahead geek you must be wondering what if we do use return statement at the end of the program?
return statement can be used at various places in the method but we need to ensure that it must be the last statement to get executed in a method.
Note: return statement need not to be last statement in a method, but it must be last statement to execute in a method.
Example 1-B:
Java
// Java program to illustrate return must not be always// last statement, but must be last statement// in a method to execute // Main classclass GFG { // Method 1 // Helper method // Since return type of RR method is void // so this method should not return any value void demofunction(double i) { // Demo condition check if (i < 9) // See here return need not be last // statement but must be last statement // in a method to execute return; else ++i; } // Method 2 // main driver method public static void main(String[] args) { // Calling the method new GFG().demofunction(7); // Display message to illustrate // successful execution of program System.out.println("Program executed successfully"); }}
Program executed successfully
Output explanation:
As the condition (i<9) becomes true, it executes return statement, and hence flow comes out of ‘demofunction’ method and comes back again to main. Following this, the return statement must be the last statement to execute in a method, which means there is no point in defining any code after return which is clarified below as follows:
Example 2A
Java
// Java program to illustrate usage of// statement after return statement // Main classclass GFG { // Since return type of RR method is void // so this method should return any value // Method 1 void demofunction(double j) { return; // Here get compile error since can't // write any statement after return keyword ++j; } // Method 2 // Main driver method public static void main(String[] args) { // Calling the above defined function new GFG().demofunction(5); }}
Output:
Example 2-B
Java
// Java program to illustrate usage// of return keyword // Main classclass GFG { // Since return type of RR method is // void so this method should not return any value // Method 1 void demofunction(double val) { // Condition check if (val < 0) { System.out.println(val); return; // System.out.println("oshea"); } else ++val; } // Method 2 // Main drive method public static void main(String[] args) { // CAlling the above method new GFG().demofunction(-1); // Display message to illustrate // successful execution of program System.out.println("Program Executed Successfully"); }}
-1.0
Program Executed Successfully
Note: In the above program we do uncomment statements it will throw an error.
This article is contributed by Rajat Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
surindertarika1234
kashishsoda
idvishalshah
rishavnitro
Java-keyword
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 265,
"s": 52,
"text": "In Java, return is a reserved keyword i.e, we can’t use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows: "
},
{
"code": null,
"e": 299,
"s": 265,
"text": "Case 1: Methods returning a value"
},
{
"code": null,
"e": 337,
"s": 299,
"text": "Case 2: Methods not returning a value"
},
{
"code": null,
"e": 397,
"s": 337,
"text": "Let us illustrate by directly implementing them as follows:"
},
{
"code": null,
"e": 431,
"s": 397,
"text": "Case 1: Methods returning a value"
},
{
"code": null,
"e": 534,
"s": 431,
"text": "For methods that define a return type, return statement must be immediately followed by return value. "
},
{
"code": null,
"e": 543,
"s": 534,
"text": "Example:"
},
{
"code": null,
"e": 548,
"s": 543,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Usage of return Keyword // Main methodclass GFG { // Method 1 // Since return type of RR method is double // so this method should return double value double RR(double a, double b) { double sum = 0; sum = (a + b) / 2.0; // Return statement as we already above have declared // return type to be double return sum; } // Method 2 // Main driver method public static void main(String[] args) { // Print statement System.out.println(new GFG().RR(5.5, 6.5)); }}",
"e": 1123,
"s": 548,
"text": null
},
{
"code": null,
"e": 1127,
"s": 1123,
"text": "6.0"
},
{
"code": null,
"e": 1149,
"s": 1127,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 1172,
"s": 1149,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 1331,
"s": 1172,
"text": "Output explanation: When we are calling a class GFG method that has return sum which returns the value of sum and that’s value gets displayed on the console. "
},
{
"code": null,
"e": 1369,
"s": 1331,
"text": "Case 2: Methods not returning a value"
},
{
"code": null,
"e": 1554,
"s": 1369,
"text": "For methods that do not return a value, return statement in Java can be skipped. here there arise two cases when there is no value been returned by the user as listed below as follows:"
},
{
"code": null,
"e": 1609,
"s": 1554,
"text": "#1: Method not using return statement in void function"
},
{
"code": null,
"e": 1644,
"s": 1609,
"text": "#2: Methods with return type void "
},
{
"code": null,
"e": 1699,
"s": 1644,
"text": "#1: Method not using return statement in void function"
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Example"
},
{
"code": null,
"e": 1712,
"s": 1707,
"text": "Java"
},
{
"code": "// Java program to illustrate no return// keyword needed inside void method // Main classclass GFG { // Since return type of RR method is // void so this method shouldn't return any value void demoSum(int a, int b) { int sum = 0; sum = (a + b) / 10; System.out.println(sum); // No return statement in this method } // Method 2 // Main driver method public static void main(String[] args) { // Calling the method // Over custom inputs new GFG().demoSum(5, 5); // Display message on the console for successful // execution of the program System.out.print( \"No return keyword is used and program executed successfully\"); } // Note here we are not returning anything // as the return type is void}",
"e": 2528,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2590,
"s": 2528,
"text": "1\nNo return keyword is used and program executed successfully"
},
{
"code": null,
"e": 2734,
"s": 2590,
"text": "Note: Return statement not required (but can be used) for methods with return type void. We can use “return;” which means not return anything. "
},
{
"code": null,
"e": 2768,
"s": 2734,
"text": "#2: Methods with void return type"
},
{
"code": null,
"e": 2781,
"s": 2768,
"text": "Example 1-A:"
},
{
"code": null,
"e": 2786,
"s": 2781,
"text": "Java"
},
{
"code": "// Java program to illustrate usage of// return keyword in void method // Class 1// Main classclass GFG { // Method 1 // Since return type of RR method is // void so this method should not return any value void demofunction(double j) { if (j < 9) // return statement below(only using // return statement and not returning // anything): // control exits the method if this // condition(i.e, j<9) is true. return; ++j; } // Method 2 // Main driver method public static void main(String[] args) { // Calling above method declared in above class new GFG().demofunction(5.5); // Display message on console to illustrate // successful execution of program System.out.println(\"Program executed successfully\"); }}",
"e": 3644,
"s": 2786,
"text": null
},
{
"code": null,
"e": 3674,
"s": 3644,
"text": "Program executed successfully"
},
{
"code": null,
"e": 3871,
"s": 3674,
"text": "Output explanation: If the statement if(j<9) is true then control exits from the method and does not execute the rest of the statement of the RR method and hence comes back again to main() method."
},
{
"code": null,
"e": 3977,
"s": 3871,
"text": "Now moving ahead geek you must be wondering what if we do use return statement at the end of the program?"
},
{
"code": null,
"e": 4124,
"s": 3977,
"text": "return statement can be used at various places in the method but we need to ensure that it must be the last statement to get executed in a method."
},
{
"code": null,
"e": 4245,
"s": 4124,
"text": "Note: return statement need not to be last statement in a method, but it must be last statement to execute in a method. "
},
{
"code": null,
"e": 4258,
"s": 4245,
"text": "Example 1-B:"
},
{
"code": null,
"e": 4263,
"s": 4258,
"text": "Java"
},
{
"code": "// Java program to illustrate return must not be always// last statement, but must be last statement// in a method to execute // Main classclass GFG { // Method 1 // Helper method // Since return type of RR method is void // so this method should not return any value void demofunction(double i) { // Demo condition check if (i < 9) // See here return need not be last // statement but must be last statement // in a method to execute return; else ++i; } // Method 2 // main driver method public static void main(String[] args) { // Calling the method new GFG().demofunction(7); // Display message to illustrate // successful execution of program System.out.println(\"Program executed successfully\"); }}",
"e": 5118,
"s": 4263,
"text": null
},
{
"code": null,
"e": 5148,
"s": 5118,
"text": "Program executed successfully"
},
{
"code": null,
"e": 5169,
"s": 5148,
"text": "Output explanation: "
},
{
"code": null,
"e": 5505,
"s": 5169,
"text": "As the condition (i<9) becomes true, it executes return statement, and hence flow comes out of ‘demofunction’ method and comes back again to main. Following this, the return statement must be the last statement to execute in a method, which means there is no point in defining any code after return which is clarified below as follows:"
},
{
"code": null,
"e": 5516,
"s": 5505,
"text": "Example 2A"
},
{
"code": null,
"e": 5521,
"s": 5516,
"text": "Java"
},
{
"code": "// Java program to illustrate usage of// statement after return statement // Main classclass GFG { // Since return type of RR method is void // so this method should return any value // Method 1 void demofunction(double j) { return; // Here get compile error since can't // write any statement after return keyword ++j; } // Method 2 // Main driver method public static void main(String[] args) { // Calling the above defined function new GFG().demofunction(5); }}",
"e": 6066,
"s": 5521,
"text": null
},
{
"code": null,
"e": 6074,
"s": 6066,
"text": "Output:"
},
{
"code": null,
"e": 6086,
"s": 6074,
"text": "Example 2-B"
},
{
"code": null,
"e": 6091,
"s": 6086,
"text": "Java"
},
{
"code": "// Java program to illustrate usage// of return keyword // Main classclass GFG { // Since return type of RR method is // void so this method should not return any value // Method 1 void demofunction(double val) { // Condition check if (val < 0) { System.out.println(val); return; // System.out.println(\"oshea\"); } else ++val; } // Method 2 // Main drive method public static void main(String[] args) { // CAlling the above method new GFG().demofunction(-1); // Display message to illustrate // successful execution of program System.out.println(\"Program Executed Successfully\"); }}",
"e": 6820,
"s": 6091,
"text": null
},
{
"code": null,
"e": 6855,
"s": 6820,
"text": "-1.0\nProgram Executed Successfully"
},
{
"code": null,
"e": 6933,
"s": 6855,
"text": "Note: In the above program we do uncomment statements it will throw an error."
},
{
"code": null,
"e": 7353,
"s": 6933,
"text": "This article is contributed by Rajat Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7367,
"s": 7353,
"text": "solankimayank"
},
{
"code": null,
"e": 7386,
"s": 7367,
"text": "surindertarika1234"
},
{
"code": null,
"e": 7398,
"s": 7386,
"text": "kashishsoda"
},
{
"code": null,
"e": 7411,
"s": 7398,
"text": "idvishalshah"
},
{
"code": null,
"e": 7423,
"s": 7411,
"text": "rishavnitro"
},
{
"code": null,
"e": 7436,
"s": 7423,
"text": "Java-keyword"
},
{
"code": null,
"e": 7449,
"s": 7436,
"text": "Java-Library"
},
{
"code": null,
"e": 7454,
"s": 7449,
"text": "Java"
},
{
"code": null,
"e": 7459,
"s": 7454,
"text": "Java"
}
] |
Java String trim() method with Example | 25 Sep, 2021
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is ‘\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The trim() method also helps in trimming the characters in Java.
Note: The trim() method doesn’t eliminate middle spaces.
Method Signature:
public String trim()
Parameters: The trim() method accepts no parameters.
Return Type: The return type of trim() method is String. It returns the omitted string with no leading and trailing spaces.
Below are examples to show the working of the string trim() method in Java.
Example 1:
Java
// Java program to demonstrate working// of java string trim() method class Gfg { // driver code public static void main(String args[]) { // trims the trailing and leading spaces String s = " geeks for geeks has all java functions to read "; System.out.println(s.trim()); // trims the leading spaces s = " Chetna loves reading books"; System.out.println(s.trim()); }}
geeks for geeks has all java functions to read
Chetna loves reading books
Java
// Java program to demonstrate working// of java string trim() method import java.io.*; class GFG { public static void main (String[] args) { String s1 = " Geeks For Geeks "; // Before Trim() method System.out.println("Before Trim() - "); System.out.println("String - "+s1); System.out.println("Length - "+s1.length()); // applying trim() method on string s1 s1=s1.trim(); // After Trim() method System.out.println("\nAfter Trim() - "); System.out.println("String - "+s1); System.out.println("Length - "+s1.length()); }}
Before Trim() -
String - Geeks For Geeks
Length - 21
After Trim() -
String - Geeks For Geeks
Length - 15
nishkarshgandhi
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Sep, 2021"
},
{
"code": null,
"e": 419,
"s": 53,
"text": "The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is ‘\\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The trim() method also helps in trimming the characters in Java."
},
{
"code": null,
"e": 476,
"s": 419,
"text": "Note: The trim() method doesn’t eliminate middle spaces."
},
{
"code": null,
"e": 494,
"s": 476,
"text": "Method Signature:"
},
{
"code": null,
"e": 515,
"s": 494,
"text": "public String trim()"
},
{
"code": null,
"e": 569,
"s": 515,
"text": "Parameters: The trim() method accepts no parameters. "
},
{
"code": null,
"e": 694,
"s": 569,
"text": "Return Type: The return type of trim() method is String. It returns the omitted string with no leading and trailing spaces. "
},
{
"code": null,
"e": 771,
"s": 694,
"text": "Below are examples to show the working of the string trim() method in Java. "
},
{
"code": null,
"e": 782,
"s": 771,
"text": "Example 1:"
},
{
"code": null,
"e": 787,
"s": 782,
"text": "Java"
},
{
"code": "// Java program to demonstrate working// of java string trim() method class Gfg { // driver code public static void main(String args[]) { // trims the trailing and leading spaces String s = \" geeks for geeks has all java functions to read \"; System.out.println(s.trim()); // trims the leading spaces s = \" Chetna loves reading books\"; System.out.println(s.trim()); }}",
"e": 1213,
"s": 787,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1213,
"text": "geeks for geeks has all java functions to read\nChetna loves reading books"
},
{
"code": null,
"e": 1292,
"s": 1287,
"text": "Java"
},
{
"code": "// Java program to demonstrate working// of java string trim() method import java.io.*; class GFG { public static void main (String[] args) { String s1 = \" Geeks For Geeks \"; // Before Trim() method System.out.println(\"Before Trim() - \"); System.out.println(\"String - \"+s1); System.out.println(\"Length - \"+s1.length()); // applying trim() method on string s1 s1=s1.trim(); // After Trim() method System.out.println(\"\\nAfter Trim() - \"); System.out.println(\"String - \"+s1); System.out.println(\"Length - \"+s1.length()); }}",
"e": 1915,
"s": 1292,
"text": null
},
{
"code": null,
"e": 2029,
"s": 1915,
"text": "Before Trim() - \nString - Geeks For Geeks \nLength - 21\n\nAfter Trim() - \nString - Geeks For Geeks\nLength - 15"
},
{
"code": null,
"e": 2045,
"s": 2029,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 2060,
"s": 2045,
"text": "Java-Functions"
},
{
"code": null,
"e": 2078,
"s": 2060,
"text": "Java-lang package"
},
{
"code": null,
"e": 2091,
"s": 2078,
"text": "Java-Strings"
},
{
"code": null,
"e": 2096,
"s": 2091,
"text": "Java"
},
{
"code": null,
"e": 2109,
"s": 2096,
"text": "Java-Strings"
},
{
"code": null,
"e": 2114,
"s": 2109,
"text": "Java"
}
] |
Stream ofNullable(T) method in Java with examples | 25 Apr, 2019
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException.
Syntax:
static <T> Stream<T> ofNullable(T t)
Parameters: This method accepts a single parameter t which is the single element of which the Stream is to be returned.
Return value: This method returns a stream with a single element if the specified element is non-null, otherwise an empty stream.
Below programs illustrate ofNullable(T) method:
Program 1:
// Java program to demonstrate// Stream.ofNullable() method import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // Create a stream with null Stream<String> value = Stream.ofNullable(null); // Print values System.out.println("Values of Stream:"); value.forEach(System.out::println); }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Stream.ofNullable method import java.util.ArrayList;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // Create ArrayList containing names ArrayList<String> list = new ArrayList<String>(); list.add("Aman"); list.add("Suraj"); list.add("Zufaq"); // create a stream with ArrayList Stream<ArrayList<String> > value = Stream.ofNullable(list); // print values System.out.println("Values of Stream:"); value.forEach(System.out::println); }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#ofNullable(T)
Java - util package
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Apr, 2019"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException."
},
{
"code": null,
"e": 271,
"s": 263,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 271,
"text": "static <T> Stream<T> ofNullable(T t)\n"
},
{
"code": null,
"e": 429,
"s": 309,
"text": "Parameters: This method accepts a single parameter t which is the single element of which the Stream is to be returned."
},
{
"code": null,
"e": 559,
"s": 429,
"text": "Return value: This method returns a stream with a single element if the specified element is non-null, otherwise an empty stream."
},
{
"code": null,
"e": 607,
"s": 559,
"text": "Below programs illustrate ofNullable(T) method:"
},
{
"code": null,
"e": 618,
"s": 607,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Stream.ofNullable() method import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // Create a stream with null Stream<String> value = Stream.ofNullable(null); // Print values System.out.println(\"Values of Stream:\"); value.forEach(System.out::println); }}",
"e": 1004,
"s": 618,
"text": null
},
{
"code": null,
"e": 1064,
"s": 1004,
"text": "The output printed on console of IDE is shown below.Output:"
},
{
"code": null,
"e": 1075,
"s": 1064,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Stream.ofNullable method import java.util.ArrayList;import java.util.stream.Stream;public class GFG { public static void main(String[] args) { // Create ArrayList containing names ArrayList<String> list = new ArrayList<String>(); list.add(\"Aman\"); list.add(\"Suraj\"); list.add(\"Zufaq\"); // create a stream with ArrayList Stream<ArrayList<String> > value = Stream.ofNullable(list); // print values System.out.println(\"Values of Stream:\"); value.forEach(System.out::println); }}",
"e": 1683,
"s": 1075,
"text": null
},
{
"code": null,
"e": 1736,
"s": 1683,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 1834,
"s": 1736,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#ofNullable(T)"
},
{
"code": null,
"e": 1854,
"s": 1834,
"text": "Java - util package"
},
{
"code": null,
"e": 1869,
"s": 1854,
"text": "Java-Functions"
},
{
"code": null,
"e": 1881,
"s": 1869,
"text": "java-stream"
},
{
"code": null,
"e": 1886,
"s": 1881,
"text": "Java"
},
{
"code": null,
"e": 1891,
"s": 1886,
"text": "Java"
},
{
"code": null,
"e": 1989,
"s": 1891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2040,
"s": 1989,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2071,
"s": 2040,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2090,
"s": 2071,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2120,
"s": 2090,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2138,
"s": 2120,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2153,
"s": 2138,
"text": "Stream In Java"
},
{
"code": null,
"e": 2173,
"s": 2153,
"text": "Collections in Java"
},
{
"code": null,
"e": 2197,
"s": 2173,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2229,
"s": 2197,
"text": "Multidimensional Arrays in Java"
}
] |
What is the equivalent of document.getElementById() in React? | 01 Feb, 2021
In React we have a concept of Refs which is equivalent to document.getElementById() in Javascript. Refs provide a way to access DOM nodes or React elements created in the render method.
Creating Refs
Refs are created using React.createRef() and attached to React elements via the ref attribute.
class App extends React.Component {
constructor(props) {
super(props);
//creating ref
this.myRef= React.createRef();
}
render() {
//assigning ref
return <div ref={this.myRef} />;
}
}
Accessing Refs
When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref.
const node = this.myRef.current;
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
filepathe- src/App.js:
Javascript
import React from 'react' class App extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } onFocus() { this.myRef.current.value ="focus" } onBlur() { this.myRef.current.value = "blur" } render() { return ( <div> <input ref= {this.myRef} onFocus={this.onFocus.bind(this)} onBlur={this.onBlur.bind(this)} /> </div> ); } } export default App;
Output:
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "In React we have a concept of Refs which is equivalent to document.getElementById() in Javascript. Refs provide a way to access DOM nodes or React elements created in the render method."
},
{
"code": null,
"e": 228,
"s": 214,
"text": "Creating Refs"
},
{
"code": null,
"e": 324,
"s": 228,
"text": "Refs are created using React.createRef() and attached to React elements via the ref attribute. "
},
{
"code": null,
"e": 524,
"s": 324,
"text": "class App extends React.Component {\n constructor(props) {\n super(props);\n //creating ref\n this.myRef= React.createRef();\n }\n render() {\n //assigning ref\n return <div ref={this.myRef} />;\n }\n}"
},
{
"code": null,
"e": 539,
"s": 524,
"text": "Accessing Refs"
},
{
"code": null,
"e": 660,
"s": 539,
"text": "When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref."
},
{
"code": null,
"e": 693,
"s": 660,
"text": "const node = this.myRef.current;"
},
{
"code": null,
"e": 721,
"s": 693,
"text": "Creating React Application:"
},
{
"code": null,
"e": 785,
"s": 721,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 817,
"s": 785,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 917,
"s": 817,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 931,
"s": 917,
"text": "cd foldername"
},
{
"code": null,
"e": 983,
"s": 931,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1006,
"s": 983,
"text": "filepathe- src/App.js:"
},
{
"code": null,
"e": 1017,
"s": 1006,
"text": "Javascript"
},
{
"code": "import React from 'react' class App extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } onFocus() { this.myRef.current.value =\"focus\" } onBlur() { this.myRef.current.value = \"blur\" } render() { return ( <div> <input ref= {this.myRef} onFocus={this.onFocus.bind(this)} onBlur={this.onBlur.bind(this)} /> </div> ); } } export default App;",
"e": 1537,
"s": 1017,
"text": null
},
{
"code": null,
"e": 1545,
"s": 1537,
"text": "Output:"
},
{
"code": null,
"e": 1552,
"s": 1545,
"text": "Picked"
},
{
"code": null,
"e": 1560,
"s": 1552,
"text": "ReactJS"
},
{
"code": null,
"e": 1577,
"s": 1560,
"text": "Web Technologies"
},
{
"code": null,
"e": 1675,
"s": 1577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1713,
"s": 1675,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 1732,
"s": 1713,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 1800,
"s": 1732,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 1835,
"s": 1800,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 1856,
"s": 1835,
"text": "ReactJS defaultProps"
},
{
"code": null,
"e": 1889,
"s": 1856,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1951,
"s": 1889,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2012,
"s": 1951,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2062,
"s": 2012,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Fetch top 10 starred repositories of user on GitHub | Python | 17 Jun, 2021
Prerequisites: Basic understanding of python, urllib2 and BeautifulSoup
We often write python scripts to make our task easier, so here is the script which helps you to fetch top 10 starred repositories of any user on GitHub.You just need Github username (For example: msdeep14) to run the script.Script Explanation:
First access the repository url of user, for example: username = “msdeep14”, then url = “https://github.com/msdeep14?tab=repositories”Now scrape the url page and fetch stars, repository name and repository url using BeautifulSoup.On one page there are 30 repositories, so if the user has more than 30 repositories, you need a loop to access all the pages.Use urllib2 or BeautifulSoup to scrape the page, The code uses both, see the code below.
First access the repository url of user, for example: username = “msdeep14”, then url = “https://github.com/msdeep14?tab=repositories”
Now scrape the url page and fetch stars, repository name and repository url using BeautifulSoup.
On one page there are 30 repositories, so if the user has more than 30 repositories, you need a loop to access all the pages.
Use urllib2 or BeautifulSoup to scrape the page, The code uses both, see the code below.
python
# Python3 script to fetch top 10 starred# repositories of a user on githubimport urllib.request, urllib.parse, urllib.errorimport urllib.request, urllib.error, urllib.parseimport http.cookiejarimport requestsfrom lxml import htmlfrom lxml import etreefrom bs4 import BeautifulSoupimport reimport operator top_limit = 9 def openWebsite(): # enter Github username # of user username = str(input("enter GitHub username: ")) # Dictionary to store key as repository # name and value as no. of stars repo_dict = {} # This is first page url where user # repositories are located url = "https://github.com/"+username+"?tab=repositories" # loop for all the pages while True: ''' You can read the docs of urllib2 and BeautifulSoup to see how html page can be scraped to extract data urllib2 : https://docs.python.org/2/library/urllib2.html BeautifulSoup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ''' # open the website and get # the html of webpage into doc cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) resp = opener.open(url) doc = html.fromstring(resp.read()) # extract all the repository names repo_name = doc.xpath('//li[@class="col-12 d-block width-full py-4 border-bottom public source"]/div[@class="d-inline-block mb-1"]/h3/a/text()') # list to store repository names repo_list = [] # get the repository name for name in repo_name: name = ' '.join(''.join(name).split()) repo_list.append(name) repo_dict[name] = 0 # print repo_list response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') ''' The path mentioned to get the no. of stargazers, you can get it by right click on star symbol on Github page, and then select inspect element ''' soup = BeautifulSoup(response.text, 'html.parser') div = soup.find_all('li', {'class': 'col-12 d-block width-full py-4 border-bottom public source'}) for d in div: temp = d.find_all('div',{'class':'f6 text-gray mt-2'}) for t in temp: # Get the no. of stars of # particular repository x = t.find_all('a', attrs={'href': re.compile("^\/[a-zA-Z0-9\-\_\.]+\/[a-zA-Z0-9\.\-\_]+\/stargazers")}) # Get the url of the repository # and populate the values of dictionary # with no. of stars if len(x) is not 0: name = x[0].get('href') name = name[len(username)+2:-11] repo_dict[name] = int(x[0].text) # Check if next page exists # for more repositories div = soup.find('a',{'class':'next_page'}) # print div if div is not None: url = div.get('href') url = "https://github.com/"+url else: # if there is no next repository # page, then exit loop break # Get the sorted list of all # repos and print top 10 i = 0 sorted_repo = sorted(iter(repo_dict.items()), key = operator.itemgetter(1)) # Print the sorted repos in # reverse order for val in reversed(sorted_repo): repo_url = "https://github.com/" + username + "/" + val[0] print("\nrepo name : ",val[0], "\nrepo url : ",repo_url, "\nstars : ",val[1]) i = i + 1 if i > top_limit: break # Driver programif __name__ == "__main__": openWebsite()
Output:
enter GitHub username: msdeep14
repo name : DeepDataBase
repo url : https://github.com/msdeep14/DeepDataBase
stars : 13
repo name : MiniDataBase
repo url : https://github.com/msdeep14/MiniDataBase
stars : 8
repo name : hackerranksolutions
repo url : https://github.com/msdeep14/hackerranksolutions
stars : 6
repo name : stayUpdated
repo url : https://github.com/msdeep14/stayUpdated
stars : 6
repo name : IRCTC
repo url : https://github.com/msdeep14/IRCTC
stars : 4
repo name : play_2048
repo url : https://github.com/msdeep14/play_2048
stars : 3
repo name : Tripcount
repo url : https://github.com/msdeep14/Tripcount
stars : 3
repo name : SnapLook
repo url : https://github.com/msdeep14/SnapLook
stars : 2
repo name : fbFun
repo url : https://github.com/msdeep14/fbFun
stars : 2
repo name : ByteCode
repo url : https://github.com/msdeep14/ByteCode
stars : 2
Video Tutorial
Complete repository link : trackGitHubStars
rajeev0719singh
python-utility
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 101,
"s": 28,
"text": "Prerequisites: Basic understanding of python, urllib2 and BeautifulSoup "
},
{
"code": null,
"e": 347,
"s": 101,
"text": "We often write python scripts to make our task easier, so here is the script which helps you to fetch top 10 starred repositories of any user on GitHub.You just need Github username (For example: msdeep14) to run the script.Script Explanation: "
},
{
"code": null,
"e": 791,
"s": 347,
"text": "First access the repository url of user, for example: username = “msdeep14”, then url = “https://github.com/msdeep14?tab=repositories”Now scrape the url page and fetch stars, repository name and repository url using BeautifulSoup.On one page there are 30 repositories, so if the user has more than 30 repositories, you need a loop to access all the pages.Use urllib2 or BeautifulSoup to scrape the page, The code uses both, see the code below."
},
{
"code": null,
"e": 926,
"s": 791,
"text": "First access the repository url of user, for example: username = “msdeep14”, then url = “https://github.com/msdeep14?tab=repositories”"
},
{
"code": null,
"e": 1023,
"s": 926,
"text": "Now scrape the url page and fetch stars, repository name and repository url using BeautifulSoup."
},
{
"code": null,
"e": 1149,
"s": 1023,
"text": "On one page there are 30 repositories, so if the user has more than 30 repositories, you need a loop to access all the pages."
},
{
"code": null,
"e": 1238,
"s": 1149,
"text": "Use urllib2 or BeautifulSoup to scrape the page, The code uses both, see the code below."
},
{
"code": null,
"e": 1247,
"s": 1240,
"text": "python"
},
{
"code": "# Python3 script to fetch top 10 starred# repositories of a user on githubimport urllib.request, urllib.parse, urllib.errorimport urllib.request, urllib.error, urllib.parseimport http.cookiejarimport requestsfrom lxml import htmlfrom lxml import etreefrom bs4 import BeautifulSoupimport reimport operator top_limit = 9 def openWebsite(): # enter Github username # of user username = str(input(\"enter GitHub username: \")) # Dictionary to store key as repository # name and value as no. of stars repo_dict = {} # This is first page url where user # repositories are located url = \"https://github.com/\"+username+\"?tab=repositories\" # loop for all the pages while True: ''' You can read the docs of urllib2 and BeautifulSoup to see how html page can be scraped to extract data urllib2 : https://docs.python.org/2/library/urllib2.html BeautifulSoup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ''' # open the website and get # the html of webpage into doc cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) resp = opener.open(url) doc = html.fromstring(resp.read()) # extract all the repository names repo_name = doc.xpath('//li[@class=\"col-12 d-block width-full py-4 border-bottom public source\"]/div[@class=\"d-inline-block mb-1\"]/h3/a/text()') # list to store repository names repo_list = [] # get the repository name for name in repo_name: name = ' '.join(''.join(name).split()) repo_list.append(name) repo_dict[name] = 0 # print repo_list response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') ''' The path mentioned to get the no. of stargazers, you can get it by right click on star symbol on Github page, and then select inspect element ''' soup = BeautifulSoup(response.text, 'html.parser') div = soup.find_all('li', {'class': 'col-12 d-block width-full py-4 border-bottom public source'}) for d in div: temp = d.find_all('div',{'class':'f6 text-gray mt-2'}) for t in temp: # Get the no. of stars of # particular repository x = t.find_all('a', attrs={'href': re.compile(\"^\\/[a-zA-Z0-9\\-\\_\\.]+\\/[a-zA-Z0-9\\.\\-\\_]+\\/stargazers\")}) # Get the url of the repository # and populate the values of dictionary # with no. of stars if len(x) is not 0: name = x[0].get('href') name = name[len(username)+2:-11] repo_dict[name] = int(x[0].text) # Check if next page exists # for more repositories div = soup.find('a',{'class':'next_page'}) # print div if div is not None: url = div.get('href') url = \"https://github.com/\"+url else: # if there is no next repository # page, then exit loop break # Get the sorted list of all # repos and print top 10 i = 0 sorted_repo = sorted(iter(repo_dict.items()), key = operator.itemgetter(1)) # Print the sorted repos in # reverse order for val in reversed(sorted_repo): repo_url = \"https://github.com/\" + username + \"/\" + val[0] print(\"\\nrepo name : \",val[0], \"\\nrepo url : \",repo_url, \"\\nstars : \",val[1]) i = i + 1 if i > top_limit: break # Driver programif __name__ == \"__main__\": openWebsite()",
"e": 4957,
"s": 1247,
"text": null
},
{
"code": null,
"e": 4967,
"s": 4957,
"text": "Output: "
},
{
"code": null,
"e": 5936,
"s": 4967,
"text": "enter GitHub username: msdeep14\n\nrepo name : DeepDataBase \nrepo url : https://github.com/msdeep14/DeepDataBase \nstars : 13\n\nrepo name : MiniDataBase \nrepo url : https://github.com/msdeep14/MiniDataBase \nstars : 8\n\nrepo name : hackerranksolutions \nrepo url : https://github.com/msdeep14/hackerranksolutions \nstars : 6\n\nrepo name : stayUpdated \nrepo url : https://github.com/msdeep14/stayUpdated \nstars : 6\n\nrepo name : IRCTC \nrepo url : https://github.com/msdeep14/IRCTC \nstars : 4\n\nrepo name : play_2048 \nrepo url : https://github.com/msdeep14/play_2048 \nstars : 3\n\nrepo name : Tripcount \nrepo url : https://github.com/msdeep14/Tripcount \nstars : 3\n\nrepo name : SnapLook \nrepo url : https://github.com/msdeep14/SnapLook \nstars : 2\n\nrepo name : fbFun \nrepo url : https://github.com/msdeep14/fbFun \nstars : 2\n\nrepo name : ByteCode \nrepo url : https://github.com/msdeep14/ByteCode \nstars : 2"
},
{
"code": null,
"e": 5953,
"s": 5936,
"text": "Video Tutorial "
},
{
"code": null,
"e": 5998,
"s": 5953,
"text": "Complete repository link : trackGitHubStars "
},
{
"code": null,
"e": 6014,
"s": 5998,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 6029,
"s": 6014,
"text": "python-utility"
},
{
"code": null,
"e": 6035,
"s": 6029,
"text": "GBlog"
},
{
"code": null,
"e": 6042,
"s": 6035,
"text": "Python"
}
] |
ReactJS Semantic UI icon element | 13 Jun, 2021
Semantic UI is a modern framework used in developing seamless designs for the website, It gives the user a lightweight experience with its components. It uses the predefined CSS, JQuery language to incorporate in different frameworks.
In this article we will know how to use icon elements in ReactJS Semantic UI. Icon element is a visual representation of any element which can be a link or some representation.
States:
Disabled: we can use as a disable icon.
Loading: we can use as a loading icon
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: Install semantic UI in your given directory. npm install semantic-ui-react semantic-ui-css
Step 3: Install semantic UI in your given directory.
npm install semantic-ui-react semantic-ui-css
Project Structure: It will look like the following.
Example 1: In this example, we will use a icon component with state of icons as enabled by using ReactJS Semantic UI Icon element.
App.js
import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement("link");styleLink.rel = "stylesheet";styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon enabled name='angle double left' size='big' /> <Icon enabled name='angle left' size='big' /> <Icon enabled name='circle' size='big' /> <Icon enabled name='angle right' size='big' /> <Icon enabled name='angle double right' size='big' /> </div>) export default Btt
Step to Run Application: Run the application from the root directory of the project, using the following command.
npm start
Output:
Example 2: In this example, we will use a icon component with state of icons as disabled by using ReactJS Semantic UI Icon element
App.js
import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement("link");styleLink.rel = "stylesheet";styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon disabled name='angle double left' size='big' /> <Icon disabled name='angle left' size='big' /> <Icon disabled name='circle' size='big' /> <Icon disabled name='angle right' size='big' /> <Icon disabled name='angle double right' size='big' /> </div>) export default Btt
Step to Run Application: Run the application from the root directory of the project, using the following command.
npm start
Output:
Example 3: In this example, we will use a icon component with state of icons as loading by using ReactJS Semantic UI Icon element.
App.js
import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement("link");styleLink.rel = "stylesheet";styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon loading name='angle double left' size='big' /> <Icon loading name='angle left' size='big' /> <Icon loading name='circle' size='big' /> <Icon loading name='angle right' size='big' /> <Icon loading name='angle double right' size='big' /> </div>) export default Btt
Step to Run Application: Run the application from the root directory of the project, using the following command.
npm start
Output:
Reference: https://react.semantic-ui.com/elements/icon
Semantic-UI
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2021"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "Semantic UI is a modern framework used in developing seamless designs for the website, It gives the user a lightweight experience with its components. It uses the predefined CSS, JQuery language to incorporate in different frameworks."
},
{
"code": null,
"e": 440,
"s": 263,
"text": "In this article we will know how to use icon elements in ReactJS Semantic UI. Icon element is a visual representation of any element which can be a link or some representation."
},
{
"code": null,
"e": 448,
"s": 440,
"text": "States:"
},
{
"code": null,
"e": 488,
"s": 448,
"text": "Disabled: we can use as a disable icon."
},
{
"code": null,
"e": 526,
"s": 488,
"text": "Loading: we can use as a loading icon"
},
{
"code": null,
"e": 578,
"s": 528,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 673,
"s": 578,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 737,
"s": 673,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 769,
"s": 737,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 882,
"s": 769,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 982,
"s": 882,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 996,
"s": 982,
"text": "cd foldername"
},
{
"code": null,
"e": 1095,
"s": 996,
"text": "Step 3: Install semantic UI in your given directory. npm install semantic-ui-react semantic-ui-css"
},
{
"code": null,
"e": 1148,
"s": 1095,
"text": "Step 3: Install semantic UI in your given directory."
},
{
"code": null,
"e": 1195,
"s": 1148,
"text": " npm install semantic-ui-react semantic-ui-css"
},
{
"code": null,
"e": 1247,
"s": 1195,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1380,
"s": 1249,
"text": "Example 1: In this example, we will use a icon component with state of icons as enabled by using ReactJS Semantic UI Icon element."
},
{
"code": null,
"e": 1387,
"s": 1380,
"text": "App.js"
},
{
"code": "import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement(\"link\");styleLink.rel = \"stylesheet\";styleLink.href = \"https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css\";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon enabled name='angle double left' size='big' /> <Icon enabled name='angle left' size='big' /> <Icon enabled name='circle' size='big' /> <Icon enabled name='angle right' size='big' /> <Icon enabled name='angle double right' size='big' /> </div>) export default Btt ",
"e": 1975,
"s": 1387,
"text": null
},
{
"code": null,
"e": 2090,
"s": 1975,
"text": "Step to Run Application: Run the application from the root directory of the project, using the following command."
},
{
"code": null,
"e": 2100,
"s": 2090,
"text": "npm start"
},
{
"code": null,
"e": 2108,
"s": 2100,
"text": "Output:"
},
{
"code": null,
"e": 2239,
"s": 2108,
"text": "Example 2: In this example, we will use a icon component with state of icons as disabled by using ReactJS Semantic UI Icon element"
},
{
"code": null,
"e": 2246,
"s": 2239,
"text": "App.js"
},
{
"code": "import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement(\"link\");styleLink.rel = \"stylesheet\";styleLink.href = \"https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css\";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon disabled name='angle double left' size='big' /> <Icon disabled name='angle left' size='big' /> <Icon disabled name='circle' size='big' /> <Icon disabled name='angle right' size='big' /> <Icon disabled name='angle double right' size='big' /> </div>) export default Btt ",
"e": 2839,
"s": 2246,
"text": null
},
{
"code": null,
"e": 2954,
"s": 2839,
"text": "Step to Run Application: Run the application from the root directory of the project, using the following command."
},
{
"code": null,
"e": 2964,
"s": 2954,
"text": "npm start"
},
{
"code": null,
"e": 2972,
"s": 2964,
"text": "Output:"
},
{
"code": null,
"e": 3103,
"s": 2972,
"text": "Example 3: In this example, we will use a icon component with state of icons as loading by using ReactJS Semantic UI Icon element."
},
{
"code": null,
"e": 3110,
"s": 3103,
"text": "App.js"
},
{
"code": "import React from 'react'import {Icon} from 'semantic-ui-react' const styleLink = document.createElement(\"link\");styleLink.rel = \"stylesheet\";styleLink.href = \"https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css\";document.head.appendChild(styleLink); const Btt = () =>( <div> <br/> <Icon loading name='angle double left' size='big' /> <Icon loading name='angle left' size='big' /> <Icon loading name='circle' size='big' /> <Icon loading name='angle right' size='big' /> <Icon loading name='angle double right' size='big' /> </div>) export default Btt ",
"e": 3698,
"s": 3110,
"text": null
},
{
"code": null,
"e": 3813,
"s": 3698,
"text": "Step to Run Application: Run the application from the root directory of the project, using the following command."
},
{
"code": null,
"e": 3823,
"s": 3813,
"text": "npm start"
},
{
"code": null,
"e": 3831,
"s": 3823,
"text": "Output:"
},
{
"code": null,
"e": 3886,
"s": 3831,
"text": "Reference: https://react.semantic-ui.com/elements/icon"
},
{
"code": null,
"e": 3898,
"s": 3886,
"text": "Semantic-UI"
},
{
"code": null,
"e": 3906,
"s": 3898,
"text": "ReactJS"
},
{
"code": null,
"e": 3923,
"s": 3906,
"text": "Web Technologies"
},
{
"code": null,
"e": 4021,
"s": 3923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4059,
"s": 4021,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 4086,
"s": 4059,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 4125,
"s": 4086,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 4177,
"s": 4125,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 4216,
"s": 4177,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 4278,
"s": 4216,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4311,
"s": 4278,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4372,
"s": 4311,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4422,
"s": 4372,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Unzip a list of tuples | 29 Nov, 2018
The zipping techniques, that is assigning a key-value or pairing from two different lists has been covered in many articles before, sometimes we have specific utility to perform the reverse task. This task can be achieved by various methods.
Let’s discuss some of the methods to unzip a list of tuples.
Method #1 : Using List Comprehension
Using list comprehension is the most naive approach to perform this task of unzipping and usually not used to perform this task, but good method to start with.
# Python3 code to demonstrate # Unzip a list of tuples# using list comprehension # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint ("Original list is : " + str(test_list)) # using list comprehension to# perform Unzippingres = [[ i for i, j in test_list ], [ j for i, j in test_list ]] # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [['Akshat', 'Bro', 'is', 'Placed'], [1, 2, 3, 4]]
Method #2 : Using zip() and * operator
Mostly used method to perform unzip and most Pythonic and recommended as well. This method is generally used to perform this task by programmers all over. * operator unzips the tuples into independent lists.
# Python3 code to demonstrate # Unzip a list of tuples# using zip() and * operator # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint ("Original list is : " + str(test_list)) # using zip() and * operator to# perform Unzippingres = list(zip(*test_list)) # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]
Method #3 : Using map()This is yet another way that can be employed to perform this task of unzipping which is less known but indeed a method to achieve this task. This also uses the * operator to perform the basic unpacking of the list. This function is deprecated in Python >= 3 versions.
# Python code to demonstrate # Unzip a list of tuples# using map() # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint ("Original list is : " + str(test_list)) # using map() to# perform Unzippingres = map(None, *test_list) # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]
Python list-programs
python-list
python-tuple
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 296,
"s": 54,
"text": "The zipping techniques, that is assigning a key-value or pairing from two different lists has been covered in many articles before, sometimes we have specific utility to perform the reverse task. This task can be achieved by various methods."
},
{
"code": null,
"e": 357,
"s": 296,
"text": "Let’s discuss some of the methods to unzip a list of tuples."
},
{
"code": null,
"e": 394,
"s": 357,
"text": "Method #1 : Using List Comprehension"
},
{
"code": null,
"e": 554,
"s": 394,
"text": "Using list comprehension is the most naive approach to perform this task of unzipping and usually not used to perform this task, but good method to start with."
},
{
"code": "# Python3 code to demonstrate # Unzip a list of tuples# using list comprehension # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint (\"Original list is : \" + str(test_list)) # using list comprehension to# perform Unzippingres = [[ i for i, j in test_list ], [ j for i, j in test_list ]] # Printing modified list print (\"Modified list is : \" + str(res))",
"e": 994,
"s": 554,
"text": null
},
{
"code": null,
"e": 1003,
"s": 994,
"text": "Output :"
},
{
"code": null,
"e": 1146,
"s": 1003,
"text": "Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]\nModified list is : [['Akshat', 'Bro', 'is', 'Placed'], [1, 2, 3, 4]]\n"
},
{
"code": null,
"e": 1187,
"s": 1148,
"text": "Method #2 : Using zip() and * operator"
},
{
"code": null,
"e": 1395,
"s": 1187,
"text": "Mostly used method to perform unzip and most Pythonic and recommended as well. This method is generally used to perform this task by programmers all over. * operator unzips the tuples into independent lists."
},
{
"code": "# Python3 code to demonstrate # Unzip a list of tuples# using zip() and * operator # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint (\"Original list is : \" + str(test_list)) # using zip() and * operator to# perform Unzippingres = list(zip(*test_list)) # Printing modified list print (\"Modified list is : \" + str(res))",
"e": 1796,
"s": 1395,
"text": null
},
{
"code": null,
"e": 1805,
"s": 1796,
"text": "Output :"
},
{
"code": null,
"e": 1948,
"s": 1805,
"text": "Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]\nModified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]\n"
},
{
"code": null,
"e": 2240,
"s": 1948,
"text": " Method #3 : Using map()This is yet another way that can be employed to perform this task of unzipping which is less known but indeed a method to achieve this task. This also uses the * operator to perform the basic unpacking of the list. This function is deprecated in Python >= 3 versions."
},
{
"code": "# Python code to demonstrate # Unzip a list of tuples# using map() # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)] # Printing original listprint (\"Original list is : \" + str(test_list)) # using map() to# perform Unzippingres = map(None, *test_list) # Printing modified list print (\"Modified list is : \" + str(res))",
"e": 2610,
"s": 2240,
"text": null
},
{
"code": null,
"e": 2619,
"s": 2610,
"text": "Output :"
},
{
"code": null,
"e": 2762,
"s": 2619,
"text": "Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]\nModified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]\n"
},
{
"code": null,
"e": 2783,
"s": 2762,
"text": "Python list-programs"
},
{
"code": null,
"e": 2795,
"s": 2783,
"text": "python-list"
},
{
"code": null,
"e": 2808,
"s": 2795,
"text": "python-tuple"
},
{
"code": null,
"e": 2815,
"s": 2808,
"text": "Python"
},
{
"code": null,
"e": 2827,
"s": 2815,
"text": "python-list"
}
] |
Find minimum s-t cut in a flow network | 21 Jun, 2022
In a flow network, an s-t cut is a cut that requires the source ‘s’ and the sink ‘t’ to be in different subsets, and it consists of edges going from the source’s side to the sink’s side. The capacity of an s-t cut is defined by the sum of the capacity of each edge in the cut-set. (Source: Wiki) The problem discussed here is to find minimum capacity s-t cut of the given network. Expected output is all edges of the minimum cut. For example, in the following flow network, example s-t cuts are {{0 ,1}, {0, 2}}, {{0, 2}, {1, 2}, {1, 3}}, etc. The minimum s-t cut is {{1, 3}, {4, 3}, {4 5}} which has capacity as 12+7+4 = 23.
We strongly recommend to read the below post first. Ford-Fulkerson Algorithm for Maximum Flow Problem
Minimum Cut and Maximum Flow:
Like Maximum Bipartite Matching, this is another problem which can solved using Ford-Fulkerson Algorithm. This is based on max-flow min-cut theorem.
The max-flow min-cut theorem states that in a flow network, the amount of maximum flow is equal to capacity of the minimum cut.
From Ford-Fulkerson, we get capacity of minimum cut. How to print all edges that form the minimum cut? The idea is to use residual graph.
Following are steps to print all edges of the minimum cut.
Run Ford-Fulkerson algorithm and consider the final residual graph. Find the set of vertices that are reachable from the source in the residual graph. All edges which are from a reachable vertex to non-reachable vertex are minimum cut edges. Print all such edges.
Run Ford-Fulkerson algorithm and consider the final residual graph.
Find the set of vertices that are reachable from the source in the residual graph.
All edges which are from a reachable vertex to non-reachable vertex are minimum cut edges. Print all such edges.
Following is the implementation of the above approach.
C++
Java
Python
C#
// C++ program for finding minimum cut using Ford-Fulkerson#include <iostream>#include <limits.h>#include <string.h>#include <queue>using namespace std; // Number of vertices in given graph#define V 6 /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */int bfs(int rGraph[V][V], int s, int t, int parent[]){ // Create a visited array and mark all vertices as not visited bool visited[V]; memset(visited, 0, sizeof(visited)); // Create a queue, enqueue source vertex and mark source vertex // as visited queue <int> q; q.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.empty()) { int u = q.front(); q.pop(); for (int v=0; v<V; v++) { if (visited[v]==false && rGraph[u][v] > 0) { q.push(v); parent[v] = u; visited[v] = true; } } } // If we reached sink in BFS starting from source, then return // true, else false return (visited[t] == true);} // A DFS based function to find all reachable vertices from s. The function// marks visited[i] as true if i is reachable from s. The initial values in// visited[] must be false. We can also use BFS to find reachable verticesvoid dfs(int rGraph[V][V], int s, bool visited[]){ visited[s] = true; for (int i = 0; i < V; i++) if (rGraph[s][i] && !visited[i]) dfs(rGraph, i, visited);} // Prints the minimum s-t cutvoid minCut(int graph[V][V], int s, int t){ int u, v; // Create a residual graph and fill the residual graph with // given capacities in the original graph as residual capacities // in residual graph int rGraph[V][V]; // rGraph[i][j] indicates residual capacity of edge i-j for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; int parent[V]; // This array is filled by BFS and to store path // Augment the flow while there is a path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes along the // path filled by BFS. Or we can say find the maximum flow // through the path found. int path_flow = INT_MAX; for (v=t; v!=s; v=parent[v]) { u = parent[v]; path_flow = min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and reverse edges // along the path for (v=t; v != s; v=parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } } // Flow is maximum now, find vertices reachable from s bool visited[V]; memset(visited, false, sizeof(visited)); dfs(rGraph, s, visited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < V; i++) for (int j = 0; j < V; j++) if (visited[i] && !visited[j] && graph[i][j]) cout << i << " - " << j << endl; return;} // Driver program to test above functionsint main(){ // Let us create a graph shown in the above example int graph[V][V] = { {0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0} }; minCut(graph, 0, 5); return 0;}
// Java program for finding min-cut in the given graphimport java.util.LinkedList;import java.util.Queue; public class Graph { // Returns true if there is a path // from source 's' to sink 't' in residual // graph. Also fills parent[] to store the path private static boolean bfs(int[][] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited boolean[] visited = new boolean[rGraph.length]; // Create a queue, enqueue source vertex // and mark source vertex as visited Queue<Integer> q = new LinkedList<Integer>(); q.add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.isEmpty()) { int v = q.poll(); for (int i = 0; i < rGraph.length; i++) { if (rGraph[v][i] > 0 && !visited[i]) { q.offer(i); visited[i] = true; parent[i] = v; } } } // If we reached sink in BFS starting // from source, then return true, else false return (visited[t] == true); } // A DFS based function to find all reachable // vertices from s. The function marks visited[i] // as true if i is reachable from s. The initial // values in visited[] must be false. We can also // use BFS to find reachable vertices private static void dfs(int[][] rGraph, int s, boolean[] visited) { visited[s] = true; for (int i = 0; i < rGraph.length; i++) { if (rGraph[s][i] > 0 && !visited[i]) { dfs(rGraph, i, visited); } } } // Prints the minimum s-t cut private static void minCut(int[][] graph, int s, int t) { int u,v; // Create a residual graph and fill the residual // graph with given capacities in the original // graph as residual capacities in residual graph // rGraph[i][j] indicates residual capacity of edge i-j int[][] rGraph = new int[graph.length][graph.length]; for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph.length; j++) { rGraph[i][j] = graph[i][j]; } } // This array is filled by BFS and to store path int[] parent = new int[graph.length]; // Augment the flow while tere is path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int pathFlow = Integer.MAX_VALUE; for (v = t; v != s; v = parent[v]) { u = parent[v]; pathFlow = Math.min(pathFlow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] = rGraph[u][v] - pathFlow; rGraph[v][u] = rGraph[v][u] + pathFlow; } } // Flow is maximum now, find vertices reachable from s boolean[] isVisited = new boolean[graph.length]; dfs(rGraph, s, isVisited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph.length; j++) { if (graph[i][j] > 0 && isVisited[i] && !isVisited[j]) { System.out.println(i + " - " + j); } } } } //Driver Program public static void main(String args[]) { // Let us create a graph shown in the above example int graph[][] = { {0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0} }; minCut(graph, 0, 5); }}// This code is contributed by Himanshu Shekhar
# Python program for finding min-cut in the given graph# Complexity : (E*(V^3))# Total augmenting path = VE and BFS# with adj matrix takes :V^2 times from collections import defaultdict # This class represents a directed graph# using adjacency matrix representationclass Graph: def __init__(self,graph): self.graph = graph # residual graph self.org_graph = [i[:] for i in graph] self. ROW = len(graph) self.COL = len(graph[0]) '''Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path ''' def BFS(self,s, t, parent): # Mark all the vertices as not visited visited =[False]*(self.ROW) # Create a queue for BFS queue=[] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True # Standard BFS Loop while queue: #Dequeue a vertex from queue and print it u = queue.pop(0) # Get all adjacent vertices of # the dequeued vertex u # If a adjacent has not been # visited, then mark it # visited and enqueue it for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0 : queue.append(ind) visited[ind] = True parent[ind] = u # If we reached sink in BFS starting # from source, then return # true, else false return True if visited[t] else False # Function for Depth first search # Traversal of the graph def dfs(self, graph,s,visited): visited[s]=True for i in range(len(graph)): if graph[s][i]>0 and not visited[i]: self.dfs(graph,i,visited) # Returns the min-cut of the given graph def minCut(self, source, sink): # This array is filled by BFS and to store path parent = [-1]*(self.ROW) max_flow = 0 # There is no flow initially # Augment the flow while there is path from source to sink while self.BFS(source, sink, parent) : # Find minimum residual capacity of the edges along the # path filled by BFS. Or we can say find the maximum flow # through the path found. path_flow = float("Inf") s = sink while(s != source): path_flow = min (path_flow, self.graph[parent[s]][s]) s = parent[s] # Add path flow to overall flow max_flow += path_flow # update residual capacities of the edges and reverse edges # along the path v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] visited=len(self.graph)*[False] self.dfs(self.graph,s,visited) # print the edges which initially had weights # but now have 0 weight for i in range(self.ROW): for j in range(self.COL): if self.graph[i][j] == 0 and\ self.org_graph[i][j] > 0 and visited[i]: print str(i) + " - " + str(j) # Create a graph given in the above diagramgraph = [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] g = Graph(graph) source = 0; sink = 5 g.minCut(source, sink) # This code is contributed by Neelam Yadav
// C# program for finding min-cut in the given graphusing System;using System.Collections.Generic; class Graph{ // Returns true if there is a path // from source 's' to sink 't' in residual // graph. Also fills parent[] to store the path private static bool bfs(int[,] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited bool[] visited = new bool[rGraph.Length]; // Create a queue, enqueue source vertex // and mark source vertex as visited Queue<int> q = new Queue<int>(); q.Enqueue(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (q.Count != 0) { int v = q.Dequeue(); for (int i = 0; i < rGraph.GetLength(0); i++) { if (rGraph[v,i] > 0 && !visited[i]) { q.Enqueue(i); visited[i] = true; parent[i] = v; } } } // If we reached sink in BFS starting // from source, then return true, else false return (visited[t] == true); } // A DFS based function to find all reachable // vertices from s. The function marks visited[i] // as true if i is reachable from s. The initial // values in visited[] must be false. We can also // use BFS to find reachable vertices private static void dfs(int[,] rGraph, int s, bool[] visited) { visited[s] = true; for (int i = 0; i < rGraph.GetLength(0); i++) { if (rGraph[s,i] > 0 && !visited[i]) { dfs(rGraph, i, visited); } } } // Prints the minimum s-t cut private static void minCut(int[,] graph, int s, int t) { int u, v; // Create a residual graph and fill the residual // graph with given capacities in the original // graph as residual capacities in residual graph // rGraph[i,j] indicates residual capacity of edge i-j int[,] rGraph = new int[graph.Length,graph.Length]; for (int i = 0; i < graph.GetLength(0); i++) { for (int j = 0; j < graph.GetLength(1); j++) { rGraph[i, j] = graph[i, j]; } } // This array is filled by BFS and to store path int[] parent = new int[graph.Length]; // Augment the flow while there is path // from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int pathFlow = int.MaxValue; for (v = t; v != s; v = parent[v]) { u = parent[v]; pathFlow = Math.Min(pathFlow, rGraph[u, v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u, v] = rGraph[u, v] - pathFlow; rGraph[v, u] = rGraph[v, u] + pathFlow; } } // Flow is maximum now, find vertices reachable from s bool[] isVisited = new bool[graph.Length]; dfs(rGraph, s, isVisited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < graph.GetLength(0); i++) { for (int j = 0; j < graph.GetLength(1); j++) { if (graph[i, j] > 0 && isVisited[i] && !isVisited[j]) { Console.WriteLine(i + " - " + j); } } } } // Driver Code public static void Main(String []args) { // Let us create a graph shown // in the above example int [,]graph = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; minCut(graph, 0, 5); }} // This code is contributed by PrinciRaj1992
1 - 3
4 - 3
4 - 5
princiraj1992
hardikkoriintern
Max-Flow
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Floyd Warshall Algorithm | DP-16
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
What is Data Structure: Types, Classifications and Applications
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 678,
"s": 52,
"text": "In a flow network, an s-t cut is a cut that requires the source ‘s’ and the sink ‘t’ to be in different subsets, and it consists of edges going from the source’s side to the sink’s side. The capacity of an s-t cut is defined by the sum of the capacity of each edge in the cut-set. (Source: Wiki) The problem discussed here is to find minimum capacity s-t cut of the given network. Expected output is all edges of the minimum cut. For example, in the following flow network, example s-t cuts are {{0 ,1}, {0, 2}}, {{0, 2}, {1, 2}, {1, 3}}, etc. The minimum s-t cut is {{1, 3}, {4, 3}, {4 5}} which has capacity as 12+7+4 = 23."
},
{
"code": null,
"e": 782,
"s": 680,
"text": "We strongly recommend to read the below post first. Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 812,
"s": 782,
"text": "Minimum Cut and Maximum Flow:"
},
{
"code": null,
"e": 962,
"s": 812,
"text": "Like Maximum Bipartite Matching, this is another problem which can solved using Ford-Fulkerson Algorithm. This is based on max-flow min-cut theorem. "
},
{
"code": null,
"e": 1091,
"s": 962,
"text": "The max-flow min-cut theorem states that in a flow network, the amount of maximum flow is equal to capacity of the minimum cut. "
},
{
"code": null,
"e": 1230,
"s": 1091,
"text": "From Ford-Fulkerson, we get capacity of minimum cut. How to print all edges that form the minimum cut? The idea is to use residual graph. "
},
{
"code": null,
"e": 1289,
"s": 1230,
"text": "Following are steps to print all edges of the minimum cut."
},
{
"code": null,
"e": 1554,
"s": 1289,
"text": "Run Ford-Fulkerson algorithm and consider the final residual graph. Find the set of vertices that are reachable from the source in the residual graph. All edges which are from a reachable vertex to non-reachable vertex are minimum cut edges. Print all such edges. "
},
{
"code": null,
"e": 1623,
"s": 1554,
"text": "Run Ford-Fulkerson algorithm and consider the final residual graph. "
},
{
"code": null,
"e": 1707,
"s": 1623,
"text": "Find the set of vertices that are reachable from the source in the residual graph. "
},
{
"code": null,
"e": 1821,
"s": 1707,
"text": "All edges which are from a reachable vertex to non-reachable vertex are minimum cut edges. Print all such edges. "
},
{
"code": null,
"e": 1877,
"s": 1821,
"text": "Following is the implementation of the above approach. "
},
{
"code": null,
"e": 1881,
"s": 1877,
"text": "C++"
},
{
"code": null,
"e": 1886,
"s": 1881,
"text": "Java"
},
{
"code": null,
"e": 1893,
"s": 1886,
"text": "Python"
},
{
"code": null,
"e": 1896,
"s": 1893,
"text": "C#"
},
{
"code": "// C++ program for finding minimum cut using Ford-Fulkerson#include <iostream>#include <limits.h>#include <string.h>#include <queue>using namespace std; // Number of vertices in given graph#define V 6 /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */int bfs(int rGraph[V][V], int s, int t, int parent[]){ // Create a visited array and mark all vertices as not visited bool visited[V]; memset(visited, 0, sizeof(visited)); // Create a queue, enqueue source vertex and mark source vertex // as visited queue <int> q; q.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.empty()) { int u = q.front(); q.pop(); for (int v=0; v<V; v++) { if (visited[v]==false && rGraph[u][v] > 0) { q.push(v); parent[v] = u; visited[v] = true; } } } // If we reached sink in BFS starting from source, then return // true, else false return (visited[t] == true);} // A DFS based function to find all reachable vertices from s. The function// marks visited[i] as true if i is reachable from s. The initial values in// visited[] must be false. We can also use BFS to find reachable verticesvoid dfs(int rGraph[V][V], int s, bool visited[]){ visited[s] = true; for (int i = 0; i < V; i++) if (rGraph[s][i] && !visited[i]) dfs(rGraph, i, visited);} // Prints the minimum s-t cutvoid minCut(int graph[V][V], int s, int t){ int u, v; // Create a residual graph and fill the residual graph with // given capacities in the original graph as residual capacities // in residual graph int rGraph[V][V]; // rGraph[i][j] indicates residual capacity of edge i-j for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; int parent[V]; // This array is filled by BFS and to store path // Augment the flow while there is a path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes along the // path filled by BFS. Or we can say find the maximum flow // through the path found. int path_flow = INT_MAX; for (v=t; v!=s; v=parent[v]) { u = parent[v]; path_flow = min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and reverse edges // along the path for (v=t; v != s; v=parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } } // Flow is maximum now, find vertices reachable from s bool visited[V]; memset(visited, false, sizeof(visited)); dfs(rGraph, s, visited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < V; i++) for (int j = 0; j < V; j++) if (visited[i] && !visited[j] && graph[i][j]) cout << i << \" - \" << j << endl; return;} // Driver program to test above functionsint main(){ // Let us create a graph shown in the above example int graph[V][V] = { {0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0} }; minCut(graph, 0, 5); return 0;}",
"e": 5457,
"s": 1896,
"text": null
},
{
"code": "// Java program for finding min-cut in the given graphimport java.util.LinkedList;import java.util.Queue; public class Graph { // Returns true if there is a path // from source 's' to sink 't' in residual // graph. Also fills parent[] to store the path private static boolean bfs(int[][] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited boolean[] visited = new boolean[rGraph.length]; // Create a queue, enqueue source vertex // and mark source vertex as visited Queue<Integer> q = new LinkedList<Integer>(); q.add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.isEmpty()) { int v = q.poll(); for (int i = 0; i < rGraph.length; i++) { if (rGraph[v][i] > 0 && !visited[i]) { q.offer(i); visited[i] = true; parent[i] = v; } } } // If we reached sink in BFS starting // from source, then return true, else false return (visited[t] == true); } // A DFS based function to find all reachable // vertices from s. The function marks visited[i] // as true if i is reachable from s. The initial // values in visited[] must be false. We can also // use BFS to find reachable vertices private static void dfs(int[][] rGraph, int s, boolean[] visited) { visited[s] = true; for (int i = 0; i < rGraph.length; i++) { if (rGraph[s][i] > 0 && !visited[i]) { dfs(rGraph, i, visited); } } } // Prints the minimum s-t cut private static void minCut(int[][] graph, int s, int t) { int u,v; // Create a residual graph and fill the residual // graph with given capacities in the original // graph as residual capacities in residual graph // rGraph[i][j] indicates residual capacity of edge i-j int[][] rGraph = new int[graph.length][graph.length]; for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph.length; j++) { rGraph[i][j] = graph[i][j]; } } // This array is filled by BFS and to store path int[] parent = new int[graph.length]; // Augment the flow while tere is path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int pathFlow = Integer.MAX_VALUE; for (v = t; v != s; v = parent[v]) { u = parent[v]; pathFlow = Math.min(pathFlow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] = rGraph[u][v] - pathFlow; rGraph[v][u] = rGraph[v][u] + pathFlow; } } // Flow is maximum now, find vertices reachable from s boolean[] isVisited = new boolean[graph.length]; dfs(rGraph, s, isVisited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph.length; j++) { if (graph[i][j] > 0 && isVisited[i] && !isVisited[j]) { System.out.println(i + \" - \" + j); } } } } //Driver Program public static void main(String args[]) { // Let us create a graph shown in the above example int graph[][] = { {0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0} }; minCut(graph, 0, 5); }}// This code is contributed by Himanshu Shekhar",
"e": 9802,
"s": 5457,
"text": null
},
{
"code": "# Python program for finding min-cut in the given graph# Complexity : (E*(V^3))# Total augmenting path = VE and BFS# with adj matrix takes :V^2 times from collections import defaultdict # This class represents a directed graph# using adjacency matrix representationclass Graph: def __init__(self,graph): self.graph = graph # residual graph self.org_graph = [i[:] for i in graph] self. ROW = len(graph) self.COL = len(graph[0]) '''Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path ''' def BFS(self,s, t, parent): # Mark all the vertices as not visited visited =[False]*(self.ROW) # Create a queue for BFS queue=[] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True # Standard BFS Loop while queue: #Dequeue a vertex from queue and print it u = queue.pop(0) # Get all adjacent vertices of # the dequeued vertex u # If a adjacent has not been # visited, then mark it # visited and enqueue it for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0 : queue.append(ind) visited[ind] = True parent[ind] = u # If we reached sink in BFS starting # from source, then return # true, else false return True if visited[t] else False # Function for Depth first search # Traversal of the graph def dfs(self, graph,s,visited): visited[s]=True for i in range(len(graph)): if graph[s][i]>0 and not visited[i]: self.dfs(graph,i,visited) # Returns the min-cut of the given graph def minCut(self, source, sink): # This array is filled by BFS and to store path parent = [-1]*(self.ROW) max_flow = 0 # There is no flow initially # Augment the flow while there is path from source to sink while self.BFS(source, sink, parent) : # Find minimum residual capacity of the edges along the # path filled by BFS. Or we can say find the maximum flow # through the path found. path_flow = float(\"Inf\") s = sink while(s != source): path_flow = min (path_flow, self.graph[parent[s]][s]) s = parent[s] # Add path flow to overall flow max_flow += path_flow # update residual capacities of the edges and reverse edges # along the path v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] visited=len(self.graph)*[False] self.dfs(self.graph,s,visited) # print the edges which initially had weights # but now have 0 weight for i in range(self.ROW): for j in range(self.COL): if self.graph[i][j] == 0 and\\ self.org_graph[i][j] > 0 and visited[i]: print str(i) + \" - \" + str(j) # Create a graph given in the above diagramgraph = [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] g = Graph(graph) source = 0; sink = 5 g.minCut(source, sink) # This code is contributed by Neelam Yadav",
"e": 13375,
"s": 9802,
"text": null
},
{
"code": "// C# program for finding min-cut in the given graphusing System;using System.Collections.Generic; class Graph{ // Returns true if there is a path // from source 's' to sink 't' in residual // graph. Also fills parent[] to store the path private static bool bfs(int[,] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited bool[] visited = new bool[rGraph.Length]; // Create a queue, enqueue source vertex // and mark source vertex as visited Queue<int> q = new Queue<int>(); q.Enqueue(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (q.Count != 0) { int v = q.Dequeue(); for (int i = 0; i < rGraph.GetLength(0); i++) { if (rGraph[v,i] > 0 && !visited[i]) { q.Enqueue(i); visited[i] = true; parent[i] = v; } } } // If we reached sink in BFS starting // from source, then return true, else false return (visited[t] == true); } // A DFS based function to find all reachable // vertices from s. The function marks visited[i] // as true if i is reachable from s. The initial // values in visited[] must be false. We can also // use BFS to find reachable vertices private static void dfs(int[,] rGraph, int s, bool[] visited) { visited[s] = true; for (int i = 0; i < rGraph.GetLength(0); i++) { if (rGraph[s,i] > 0 && !visited[i]) { dfs(rGraph, i, visited); } } } // Prints the minimum s-t cut private static void minCut(int[,] graph, int s, int t) { int u, v; // Create a residual graph and fill the residual // graph with given capacities in the original // graph as residual capacities in residual graph // rGraph[i,j] indicates residual capacity of edge i-j int[,] rGraph = new int[graph.Length,graph.Length]; for (int i = 0; i < graph.GetLength(0); i++) { for (int j = 0; j < graph.GetLength(1); j++) { rGraph[i, j] = graph[i, j]; } } // This array is filled by BFS and to store path int[] parent = new int[graph.Length]; // Augment the flow while there is path // from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int pathFlow = int.MaxValue; for (v = t; v != s; v = parent[v]) { u = parent[v]; pathFlow = Math.Min(pathFlow, rGraph[u, v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u, v] = rGraph[u, v] - pathFlow; rGraph[v, u] = rGraph[v, u] + pathFlow; } } // Flow is maximum now, find vertices reachable from s bool[] isVisited = new bool[graph.Length]; dfs(rGraph, s, isVisited); // Print all edges that are from a reachable vertex to // non-reachable vertex in the original graph for (int i = 0; i < graph.GetLength(0); i++) { for (int j = 0; j < graph.GetLength(1); j++) { if (graph[i, j] > 0 && isVisited[i] && !isVisited[j]) { Console.WriteLine(i + \" - \" + j); } } } } // Driver Code public static void Main(String []args) { // Let us create a graph shown // in the above example int [,]graph = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}}; minCut(graph, 0, 5); }} // This code is contributed by PrinciRaj1992",
"e": 17891,
"s": 13375,
"text": null
},
{
"code": null,
"e": 17910,
"s": 17891,
"text": "1 - 3\n4 - 3\n4 - 5\n"
},
{
"code": null,
"e": 17924,
"s": 17910,
"text": "princiraj1992"
},
{
"code": null,
"e": 17941,
"s": 17924,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 17950,
"s": 17941,
"text": "Max-Flow"
},
{
"code": null,
"e": 17956,
"s": 17950,
"text": "Graph"
},
{
"code": null,
"e": 17962,
"s": 17956,
"text": "Graph"
},
{
"code": null,
"e": 18060,
"s": 17962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18080,
"s": 18060,
"text": "Topological Sorting"
},
{
"code": null,
"e": 18138,
"s": 18080,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 18171,
"s": 18138,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 18236,
"s": 18171,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 18268,
"s": 18236,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 18301,
"s": 18268,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 18376,
"s": 18301,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 18440,
"s": 18376,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 18471,
"s": 18440,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Information Entropy using MATLAB | 18 Aug, 2020
Information entropy is the aggregate rate at which information is created by a stochastic wellspring of information. The proportion of information entropy related to every potential information value is the negative logarithm of the likelihood mass function for the worth. Hence, when the information source has lower likelihood esteem(i.e., when a low-likelihood occasion happens), the occasion conveys more data than when the source information has higher-likelihood esteem. The measure of data passed on by each occasion characterized along these lines turns into a random variable whose expected worth is the information entropy. Entropy is zero when one result is sure to happen.
Formula:
Example 1 : A discrete memoryless source i.e. DMS ‘X’ has 4 symbols x1, x2, x3 and x4 with probabilities P(x1) = 0.333, P(x2) = 0.333, P(x3) = 0.167 and P(x4) = 0.167.So, H(X) = -0.333 log2(0.333)-0.333 log2(0.333)-0.167 log2(0.167)-0.167 log2(0.167) H(X) = 1.918
Example 2 : A discrete memoryless source i.e. DMS ‘X’ has 2 symbols x1 and x2 with probabilities P(x1) = 0.600 and P(x2) = 0.400So, H(X) = -0.600 log2(0.600)-0.400 log2(0.400) H(X) = 0.970
Here is the MATLAB code to calculate the information entropy of a string.
clc; # the stringx = 'GeeksforGeeks' # length of the stringlen = length(x);display(len); # unique charactersu = unique(x);display(u); # length of unique character stringlenChar = length(u);display(lenChar); # creating 2 zero vectorsz = zeros(1, lenChar);p = zeros(1, lenChar); # finding the values of probabilityfor i = 1 : lenChar z(i) = length(findstr(x, u(i))); p(i) = z(i) / len;enddisplay(z);display(p); # information entropyH = 0;for i=1:lenChar H = H + (-p(i) * log2(p(i)));enddisplay(H);
x = GeeksforGeeks
len = 13
u = Gefkors
lenChar = 7
z =
2 4 1 2 1 1 2
p =
0.153846 0.307692 0.076923 0.153846 0.076923 0.076923 0.153846
H = 2.6235
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
Docker - COPY Instruction
Supervised and Unsupervised learning
Decision Tree Introduction with example
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
How to Run a Python Script using Docker?
Markov Decision Process | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 739,
"s": 54,
"text": "Information entropy is the aggregate rate at which information is created by a stochastic wellspring of information. The proportion of information entropy related to every potential information value is the negative logarithm of the likelihood mass function for the worth. Hence, when the information source has lower likelihood esteem(i.e., when a low-likelihood occasion happens), the occasion conveys more data than when the source information has higher-likelihood esteem. The measure of data passed on by each occasion characterized along these lines turns into a random variable whose expected worth is the information entropy. Entropy is zero when one result is sure to happen."
},
{
"code": null,
"e": 749,
"s": 739,
"text": "Formula: "
},
{
"code": null,
"e": 1018,
"s": 749,
"text": "Example 1 : A discrete memoryless source i.e. DMS ‘X’ has 4 symbols x1, x2, x3 and x4 with probabilities P(x1) = 0.333, P(x2) = 0.333, P(x3) = 0.167 and P(x4) = 0.167.So, H(X) = -0.333 log2(0.333)-0.333 log2(0.333)-0.167 log2(0.167)-0.167 log2(0.167) H(X) = 1.918"
},
{
"code": null,
"e": 1212,
"s": 1018,
"text": "Example 2 : A discrete memoryless source i.e. DMS ‘X’ has 2 symbols x1 and x2 with probabilities P(x1) = 0.600 and P(x2) = 0.400So, H(X) = -0.600 log2(0.600)-0.400 log2(0.400) H(X) = 0.970"
},
{
"code": null,
"e": 1286,
"s": 1212,
"text": "Here is the MATLAB code to calculate the information entropy of a string."
},
{
"code": "clc; # the stringx = 'GeeksforGeeks' # length of the stringlen = length(x);display(len); # unique charactersu = unique(x);display(u); # length of unique character stringlenChar = length(u);display(lenChar); # creating 2 zero vectorsz = zeros(1, lenChar);p = zeros(1, lenChar); # finding the values of probabilityfor i = 1 : lenChar z(i) = length(findstr(x, u(i))); p(i) = z(i) / len;enddisplay(z);display(p); # information entropyH = 0;for i=1:lenChar H = H + (-p(i) * log2(p(i)));enddisplay(H);",
"e": 1794,
"s": 1286,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1794,
"text": "x = GeeksforGeeks\nlen = 13\nu = Gefkors\nlenChar = 7\nz =\n\n 2 4 1 2 1 1 2\n\np =\n\n 0.153846 0.307692 0.076923 0.153846 0.076923 0.076923 0.153846\n\nH = 2.6235\n"
},
{
"code": null,
"e": 1986,
"s": 1979,
"text": "MATLAB"
},
{
"code": null,
"e": 2012,
"s": 1986,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2110,
"s": 2012,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2133,
"s": 2110,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 2156,
"s": 2133,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 2179,
"s": 2156,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 2205,
"s": 2179,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2242,
"s": 2205,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 2282,
"s": 2242,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 2318,
"s": 2282,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2356,
"s": 2318,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 2397,
"s": 2356,
"text": "How to Run a Python Script using Docker?"
}
] |
java.nio.file.FileSystem class in java | 30 Jul, 2021
java.nio.file.FileSystem class provides an interface to a file system. The file system acts as a factory for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object help to access the files and other objects in the file system.
Syntax: Class declaration
public abstract class FileSystem
extends Object
implements Closeable
The constructor of this class is as follows:
Methods of this class are as follows:
Example 1:
Java
// Java program to Create a new FileSystem object and// print its file stores and root directories // Importing required classes from java.nio package// Importing input output classesimport java.io.*;import java.nio.file.FileStore;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Create a new File system Object FileSystem filesystem = FileSystems.getDefault(); // Display messages only System.out.println( "File System created successfully"); System.out.println( "Underlying file stores of this FileSystem :"); // Print the Underlying file stores of this // FileSystem using for each loop for (FileStore store : filesystem.getFileStores()) { System.out.println(store.toString()); } // Display message only System.out.println( "Root directories of this FileSystem :"); for (Path rootdir : filesystem.getRootDirectories()) { // Print the Root directories of this // FileSystem using standard toString() // method System.out.println(rootdir.toString()); } } // Catch block to handle exceptions catch (Exception e) { // Print the exception along with // line number where it occurred e.printStackTrace(); } }}
Output:
File System created successfully
Underlying file stores of this FileSystem :
/ (/dev/disk1s1)
/dev (devfs)
/private/var/vm (/dev/disk1s4)
/net (map -hosts)
/home (map auto_home)
Root directories of this FileSystem :
/
Example 2:
Java
// Java program to illustrate Working of FileSystem Class// Via its Methods // importing required classes from java.nio package// Importing input output classesimport java.io.*;import java.nio.file.FileSystem;import java.nio.file.FileSystems; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of FileSystem class in the // main() method using getDefault() method FileSystem filesystem = FileSystems.getDefault(); // Display message only System.out.println( "FileSystem created successfully"); // Checking if file system is open or close if (filesystem.isOpen()) // Print statement System.out.println("File system is open"); else // Print statement System.out.println("File system is close"); // Check if file system is read-only if (filesystem.isReadOnly()) // Print statement System.out.println( "File system is Read-only"); else // Print statement System.out.println( "File system is not Read-only"); // Now, print the name separator // using getSeparator() method System.out.println("Separator: " + filesystem.getSeparator()); // Print hash value of this file system // using hashCode() method System.out.println("Hashcode: " + filesystem.hashCode()); // Print provider of this file system System.out.println( "Provider: " + filesystem.provider().toString()); } // Catch block to handle the exceptions catch (Exception e) { // Print the exception along with line number // using printStackTrace() method and // display it on the console e.printStackTrace(); } }}
Output:
FileSystem created successfully
File system is open
File system is not Read-only
Separator: /
Hashcode: 929338653
Provider: sun.nio.fs.MacOSXFileSystemProvider@4b1210ee
surinderdawra388
simranarora5sos
arorakashish0911
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "java.nio.file.FileSystem class provides an interface to a file system. The file system acts as a factory for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object help to access the files and other objects in the file system."
},
{
"code": null,
"e": 335,
"s": 309,
"text": "Syntax: Class declaration"
},
{
"code": null,
"e": 404,
"s": 335,
"text": "public abstract class FileSystem\nextends Object\nimplements Closeable"
},
{
"code": null,
"e": 449,
"s": 404,
"text": "The constructor of this class is as follows:"
},
{
"code": null,
"e": 487,
"s": 449,
"text": "Methods of this class are as follows:"
},
{
"code": null,
"e": 498,
"s": 487,
"text": "Example 1:"
},
{
"code": null,
"e": 503,
"s": 498,
"text": "Java"
},
{
"code": "// Java program to Create a new FileSystem object and// print its file stores and root directories // Importing required classes from java.nio package// Importing input output classesimport java.io.*;import java.nio.file.FileStore;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Create a new File system Object FileSystem filesystem = FileSystems.getDefault(); // Display messages only System.out.println( \"File System created successfully\"); System.out.println( \"Underlying file stores of this FileSystem :\"); // Print the Underlying file stores of this // FileSystem using for each loop for (FileStore store : filesystem.getFileStores()) { System.out.println(store.toString()); } // Display message only System.out.println( \"Root directories of this FileSystem :\"); for (Path rootdir : filesystem.getRootDirectories()) { // Print the Root directories of this // FileSystem using standard toString() // method System.out.println(rootdir.toString()); } } // Catch block to handle exceptions catch (Exception e) { // Print the exception along with // line number where it occurred e.printStackTrace(); } }}",
"e": 2200,
"s": 503,
"text": null
},
{
"code": null,
"e": 2212,
"s": 2203,
"text": "Output: "
},
{
"code": null,
"e": 2430,
"s": 2212,
"text": "File System created successfully\nUnderlying file stores of this FileSystem :\n/ (/dev/disk1s1)\n/dev (devfs)\n/private/var/vm (/dev/disk1s4)\n/net (map -hosts)\n/home (map auto_home)\nRoot directories of this FileSystem :\n/"
},
{
"code": null,
"e": 2441,
"s": 2430,
"text": "Example 2:"
},
{
"code": null,
"e": 2446,
"s": 2441,
"text": "Java"
},
{
"code": "// Java program to illustrate Working of FileSystem Class// Via its Methods // importing required classes from java.nio package// Importing input output classesimport java.io.*;import java.nio.file.FileSystem;import java.nio.file.FileSystems; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of FileSystem class in the // main() method using getDefault() method FileSystem filesystem = FileSystems.getDefault(); // Display message only System.out.println( \"FileSystem created successfully\"); // Checking if file system is open or close if (filesystem.isOpen()) // Print statement System.out.println(\"File system is open\"); else // Print statement System.out.println(\"File system is close\"); // Check if file system is read-only if (filesystem.isReadOnly()) // Print statement System.out.println( \"File system is Read-only\"); else // Print statement System.out.println( \"File system is not Read-only\"); // Now, print the name separator // using getSeparator() method System.out.println(\"Separator: \" + filesystem.getSeparator()); // Print hash value of this file system // using hashCode() method System.out.println(\"Hashcode: \" + filesystem.hashCode()); // Print provider of this file system System.out.println( \"Provider: \" + filesystem.provider().toString()); } // Catch block to handle the exceptions catch (Exception e) { // Print the exception along with line number // using printStackTrace() method and // display it on the console e.printStackTrace(); } }}",
"e": 4621,
"s": 2446,
"text": null
},
{
"code": null,
"e": 4630,
"s": 4621,
"text": "Output: "
},
{
"code": null,
"e": 4800,
"s": 4630,
"text": "FileSystem created successfully\nFile system is open\nFile system is not Read-only\nSeparator: /\nHashcode: 929338653\nProvider: sun.nio.fs.MacOSXFileSystemProvider@4b1210ee "
},
{
"code": null,
"e": 4817,
"s": 4800,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4833,
"s": 4817,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4850,
"s": 4833,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4867,
"s": 4850,
"text": "Java-NIO package"
},
{
"code": null,
"e": 4872,
"s": 4867,
"text": "Java"
},
{
"code": null,
"e": 4877,
"s": 4872,
"text": "Java"
},
{
"code": null,
"e": 4975,
"s": 4877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4990,
"s": 4975,
"text": "Stream In Java"
},
{
"code": null,
"e": 5011,
"s": 4990,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5032,
"s": 5011,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5051,
"s": 5032,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5068,
"s": 5051,
"text": "Generics in Java"
},
{
"code": null,
"e": 5098,
"s": 5068,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5124,
"s": 5098,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5140,
"s": 5124,
"text": "Strings in Java"
},
{
"code": null,
"e": 5177,
"s": 5140,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to make Bootstrap table with sticky table head? | 30 Jul, 2021
Tables that can be used for aligning/recording data properly but sometimes it happens that the data in the table is too long so in order to read the data properly the header respective to various columns should be available all the time while traversing the table. In such cases, a sticky table head is required to make the table more informative and accurate which can be implemented using CSS attributes i.e is position and top of the elements of the head row
Syntax:
In CSS file:<style>
.header{
position:sticky;
top: 0 ;
}
</style>
<style>
.header{
position:sticky;
top: 0 ;
}
</style>
In HTML file:<th class="header" scope="col">
<th class="header" scope="col">
Below examples illustrates the approach:Example 1: Table at the top with long list of columns and a fixed header.
<!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> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"> </script> <style> .header { position: sticky; top:0; } .container { width: 600px; height: 300px; overflow: auto; } h1{ color: green; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <b>Sticky header in table</b> <table class="table"> <thead style="position: sticky;top: 0" class="thead-dark"> <tr> <th class="header" scope="col">Course</th> <th class="header" scope="col">Start Date</th> <th class="header" scope="col">Fees</th> <th class="header" scope="col">Type</th> </tr> </thead> <tbody> <tr> <td>CAT</td> <td>1st Aug</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>GATE</td> <td>5th July</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>DSA</td> <td>1st July</td> <td>2499</td> <td>Online</td> </tr> <tr> <td>Java Backend</td> <td>28th March</td> <td>10999</td> <td>Offline</td> </tr> <tr> <td>SDE</td> <td>1st Sept</td> <td>299</td> <td>Online</td> </tr> <tr> <td>SUDO Placement</td> <td>20th Sept</td> <td>Free</td> <td>Online</td> </tr> </tbody> </table> </body> </html>
Output:
Example 2 Header with a text followed by table with a sticky header.
<!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> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"> </script> <style> .header { position: sticky; top:0; } body { height: 800px; } </style></head> <body> <table class="table"> <thead style="position: sticky;top: 0" class="thead-dark"> <tr> <th class="header" scope="col">Course</th> <th class="header" scope="col">Start Date</th> <th class="header" scope="col">Fees</th> <th class="header" scope="col">Type</th> </tr> </thead> <tbody> <tr> <td>CAT</td> <td>1st Aug</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>GATE</td> <td>5th July</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>DSA</td> <td>1st July</td> <td>2499</td> <td>Online</td> </tr> <tr> <td>Java Backend</td> <td>28th March</td> <td>10999</td> <td>Offline</td> </tr> <tr> <td>SDE</td> <td>1st Sept</td> <td>299</td> <td>Online</td> </tr> <tr> <td>SUDO Placement</td> <td>20th Sept</td> <td>Free</td> <td>Online</td> </tr> </tbody> </table></body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
HTML-Misc
Picked
Technical Scripter 2019
Bootstrap
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to Align modal content box to center of any screen?
Tailwind CSS vs Bootstrap
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 490,
"s": 28,
"text": "Tables that can be used for aligning/recording data properly but sometimes it happens that the data in the table is too long so in order to read the data properly the header respective to various columns should be available all the time while traversing the table. In such cases, a sticky table head is required to make the table more informative and accurate which can be implemented using CSS attributes i.e is position and top of the elements of the head row"
},
{
"code": null,
"e": 498,
"s": 490,
"text": "Syntax:"
},
{
"code": null,
"e": 588,
"s": 498,
"text": "In CSS file:<style>\n .header{\n position:sticky;\n top: 0 ;\n }\n</style>"
},
{
"code": null,
"e": 666,
"s": 588,
"text": "<style>\n .header{\n position:sticky;\n top: 0 ;\n }\n</style>"
},
{
"code": null,
"e": 711,
"s": 666,
"text": "In HTML file:<th class=\"header\" scope=\"col\">"
},
{
"code": null,
"e": 743,
"s": 711,
"text": "<th class=\"header\" scope=\"col\">"
},
{
"code": null,
"e": 857,
"s": 743,
"text": "Below examples illustrates the approach:Example 1: Table at the top with long list of columns and a fixed header."
},
{
"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> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\" /> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"> </script> <style> .header { position: sticky; top:0; } .container { width: 600px; height: 300px; overflow: auto; } h1{ color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <b>Sticky header in table</b> <table class=\"table\"> <thead style=\"position: sticky;top: 0\" class=\"thead-dark\"> <tr> <th class=\"header\" scope=\"col\">Course</th> <th class=\"header\" scope=\"col\">Start Date</th> <th class=\"header\" scope=\"col\">Fees</th> <th class=\"header\" scope=\"col\">Type</th> </tr> </thead> <tbody> <tr> <td>CAT</td> <td>1st Aug</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>GATE</td> <td>5th July</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>DSA</td> <td>1st July</td> <td>2499</td> <td>Online</td> </tr> <tr> <td>Java Backend</td> <td>28th March</td> <td>10999</td> <td>Offline</td> </tr> <tr> <td>SDE</td> <td>1st Sept</td> <td>299</td> <td>Online</td> </tr> <tr> <td>SUDO Placement</td> <td>20th Sept</td> <td>Free</td> <td>Online</td> </tr> </tbody> </table> </body> </html> ",
"e": 3753,
"s": 857,
"text": null
},
{
"code": null,
"e": 3761,
"s": 3753,
"text": "Output:"
},
{
"code": null,
"e": 3830,
"s": 3761,
"text": "Example 2 Header with a text followed by table with a sticky header."
},
{
"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> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\" /> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"> </script> <style> .header { position: sticky; top:0; } body { height: 800px; } </style></head> <body> <table class=\"table\"> <thead style=\"position: sticky;top: 0\" class=\"thead-dark\"> <tr> <th class=\"header\" scope=\"col\">Course</th> <th class=\"header\" scope=\"col\">Start Date</th> <th class=\"header\" scope=\"col\">Fees</th> <th class=\"header\" scope=\"col\">Type</th> </tr> </thead> <tbody> <tr> <td>CAT</td> <td>1st Aug</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>GATE</td> <td>5th July</td> <td>Free</td> <td>Online</td> </tr> <tr> <td>DSA</td> <td>1st July</td> <td>2499</td> <td>Online</td> </tr> <tr> <td>Java Backend</td> <td>28th March</td> <td>10999</td> <td>Offline</td> </tr> <tr> <td>SDE</td> <td>1st Sept</td> <td>299</td> <td>Online</td> </tr> <tr> <td>SUDO Placement</td> <td>20th Sept</td> <td>Free</td> <td>Online</td> </tr> </tbody> </table></body> </html> ",
"e": 6540,
"s": 3830,
"text": null
},
{
"code": null,
"e": 6548,
"s": 6540,
"text": "Output:"
},
{
"code": null,
"e": 6734,
"s": 6548,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 6743,
"s": 6734,
"text": "CSS-Misc"
},
{
"code": null,
"e": 6753,
"s": 6743,
"text": "HTML-Misc"
},
{
"code": null,
"e": 6760,
"s": 6753,
"text": "Picked"
},
{
"code": null,
"e": 6784,
"s": 6760,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 6794,
"s": 6784,
"text": "Bootstrap"
},
{
"code": null,
"e": 6798,
"s": 6794,
"text": "CSS"
},
{
"code": null,
"e": 6803,
"s": 6798,
"text": "HTML"
},
{
"code": null,
"e": 6822,
"s": 6803,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6839,
"s": 6822,
"text": "Web Technologies"
},
{
"code": null,
"e": 6866,
"s": 6839,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 6871,
"s": 6866,
"text": "HTML"
},
{
"code": null,
"e": 6969,
"s": 6871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7032,
"s": 6969,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 7073,
"s": 7032,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 7106,
"s": 7073,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 7162,
"s": 7106,
"text": "How to Align modal content box to center of any screen?"
},
{
"code": null,
"e": 7188,
"s": 7162,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 7236,
"s": 7188,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 7298,
"s": 7236,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7348,
"s": 7298,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7406,
"s": 7348,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Defining Clean Up Actions in Python | 11 Oct, 2021
Think of a task you will always want your program to do, whether it runs perfectly or raise any kind of error. For example, We use of try statement which has an optional clause – “finally” to perform clean up actions, that must be executed under all conditions.Cleanup actions: Before leaving the try statement, “finally” clause is always executed, whether an exception is raised or not. These are clauses which are intended to define clean-up actions that must be executed under all circumstances.Whenever an exception occurs and is not being handled by the except clause, first finally will occur and then the error is raised as default [Code 3].
Python Programs illustrating “Defining Clean Up Actions”
Code 1 : Code works normally and clean-up action is taken at the end
# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print("Sorry ! You are dividing by zero ") else: print("Yeah ! Your answer is:", result) finally: print("I'm finally clause, always raised !! ") # Look at parameters and note the working of Programdivide(3, 2)
Output :
Yeah ! Your answer is : 1
I'm finally clause, always raised !!
Code 2 : Code raise error and is carefully handled in the except clause. Note that Clean-up action is taken at the end.
# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print("Sorry ! You are dividing by zero ") else: print("Yeah ! Your answer is:", result) finally: print("I'm finally clause, always raised !! ") # Look at parameters and note the working of Programdivide(3, 0)
Output :
Sorry ! You are dividing by zero
I'm finally clause, always raised !!
Code 3 : Code, raise error but we don’t have any except clause to handle it. So, clean-up action is taken first and then the error(by default) is raised by the compiler.
# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print("Sorry ! You are dividing by zero ") else: print("Yeah ! Your answer is:", result) finally: print("I'm finally clause, always raised !! ") # Look at parameters and note the working of Programdivide(3, "3")
Output :
I'm finally clause, always raised !!
Error:
Traceback (most recent call last):
File "C:/Users/DELL/Desktop/Code.py", line 15, in
divide(3, "3")
File "C:/Users/DELL/Desktop/Code.py", line 7, in divide
result = x // y
TypeError: unsupported operand type(s) for //: 'int' and 'str'
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kumaripunam984122
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 703,
"s": 54,
"text": "Think of a task you will always want your program to do, whether it runs perfectly or raise any kind of error. For example, We use of try statement which has an optional clause – “finally” to perform clean up actions, that must be executed under all conditions.Cleanup actions: Before leaving the try statement, “finally” clause is always executed, whether an exception is raised or not. These are clauses which are intended to define clean-up actions that must be executed under all circumstances.Whenever an exception occurs and is not being handled by the except clause, first finally will occur and then the error is raised as default [Code 3]."
},
{
"code": null,
"e": 760,
"s": 703,
"text": "Python Programs illustrating “Defining Clean Up Actions”"
},
{
"code": null,
"e": 829,
"s": 760,
"text": "Code 1 : Code works normally and clean-up action is taken at the end"
},
{
"code": "# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") else: print(\"Yeah ! Your answer is:\", result) finally: print(\"I'm finally clause, always raised !! \") # Look at parameters and note the working of Programdivide(3, 2)",
"e": 1253,
"s": 829,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1253,
"text": "Output :"
},
{
"code": null,
"e": 1327,
"s": 1262,
"text": "Yeah ! Your answer is : 1\nI'm finally clause, always raised !! \n"
},
{
"code": null,
"e": 1448,
"s": 1327,
"text": " Code 2 : Code raise error and is carefully handled in the except clause. Note that Clean-up action is taken at the end."
},
{
"code": "# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") else: print(\"Yeah ! Your answer is:\", result) finally: print(\"I'm finally clause, always raised !! \") # Look at parameters and note the working of Programdivide(3, 0)",
"e": 1872,
"s": 1448,
"text": null
},
{
"code": null,
"e": 1881,
"s": 1872,
"text": "Output :"
},
{
"code": null,
"e": 1953,
"s": 1881,
"text": "Sorry ! You are dividing by zero \nI'm finally clause, always raised !!\n"
},
{
"code": null,
"e": 2125,
"s": 1955,
"text": "Code 3 : Code, raise error but we don’t have any except clause to handle it. So, clean-up action is taken first and then the error(by default) is raised by the compiler."
},
{
"code": "# Python code to illustrate# clean up actionsdef divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y except ZeroDivisionError: print(\"Sorry ! You are dividing by zero \") else: print(\"Yeah ! Your answer is:\", result) finally: print(\"I'm finally clause, always raised !! \") # Look at parameters and note the working of Programdivide(3, \"3\")",
"e": 2551,
"s": 2125,
"text": null
},
{
"code": null,
"e": 2560,
"s": 2551,
"text": "Output :"
},
{
"code": null,
"e": 2598,
"s": 2560,
"text": "I'm finally clause, always raised !! "
},
{
"code": null,
"e": 2605,
"s": 2598,
"text": "Error:"
},
{
"code": null,
"e": 2854,
"s": 2605,
"text": "Traceback (most recent call last):\n File \"C:/Users/DELL/Desktop/Code.py\", line 15, in \n divide(3, \"3\")\n File \"C:/Users/DELL/Desktop/Code.py\", line 7, in divide\n result = x // y\nTypeError: unsupported operand type(s) for //: 'int' and 'str'\n"
},
{
"code": null,
"e": 3154,
"s": 2854,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3279,
"s": 3154,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3297,
"s": 3279,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 3304,
"s": 3297,
"text": "Python"
},
{
"code": null,
"e": 3402,
"s": 3304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3434,
"s": 3402,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3461,
"s": 3434,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3482,
"s": 3461,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3505,
"s": 3482,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3561,
"s": 3505,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3592,
"s": 3561,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3634,
"s": 3592,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3676,
"s": 3634,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3715,
"s": 3676,
"text": "Python | Get unique values from a list"
}
] |
Stuffing a Pandas DataFrame.plot into a Matplotlib subplot | To stuff a Pandas dataframe plot into a Matplotlib subplot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots, two axes.
Create a Pandas dataframe using DataFrame.
Use DataFrame.plot() method to plot.
To display the figure, use show() method.
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2) = plt.subplots(2)
df = pd.DataFrame(dict(name=["Joe", "James", "Jack"], age=[23, 34, 26]))
df.set_index("name").plot(ax=ax1)
df.set_index("name").plot(ax=ax2)
plt.show() | [
{
"code": null,
"e": 1281,
"s": 1187,
"text": "To stuff a Pandas dataframe plot into a Matplotlib subplot, we can take the following steps −"
},
{
"code": null,
"e": 1357,
"s": 1281,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1406,
"s": 1357,
"text": "Create a figure and a set of subplots, two axes."
},
{
"code": null,
"e": 1449,
"s": 1406,
"text": "Create a Pandas dataframe using DataFrame."
},
{
"code": null,
"e": 1486,
"s": 1449,
"text": "Use DataFrame.plot() method to plot."
},
{
"code": null,
"e": 1528,
"s": 1486,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1857,
"s": 1528,
"text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, (ax1, ax2) = plt.subplots(2)\ndf = pd.DataFrame(dict(name=[\"Joe\", \"James\", \"Jack\"], age=[23, 34, 26]))\n\ndf.set_index(\"name\").plot(ax=ax1)\ndf.set_index(\"name\").plot(ax=ax2)\n\nplt.show()"
}
] |
numpy.ndarray.view() in Python | 27 Aug, 2021
numpy.ndarray.view() helps to get a new view of array with the same data.
Syntax: ndarray.view(dtype=None, type=None)Parameters: dtype : Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. type : Python type, optionalReturns : ndarray or matrix.
Code #1:
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16') print("a is: \n", a) # using view() methodv = a.view('int32')print("\n After using view() with dtype = 'int32' a is : \n", a) v += 1 # addition of 1 to each element of vprint("\n After using view() with dtype = 'int32' and adding 1 a is : \n", a)
a is:
[0 1 2 3 4 5 6 7 8 9]
After using view() with dtype = 'int32' a is :
[0 1 2 3 4 5 6 7 8 9]
After using view() with dtype = 'int32' and adding 1 a is :
[1 1 3 3 5 5 7 7 9 9]
Code #2:
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print("a is:", a) # Using view() methodv = a.view('int16')print("\n After using view() with dtype = 'int16' a is :\n", a) v += 1# addition of 1 to each element of vprint("\n After using view() with dtype = 'int16' and adding 1 a is : \n", a)
a is: [0 1 2 3 4 5 6 7 8 9]
After using view() with dtype = 'int16' a is :
[0 1 2 3 4 5 6 7 8 9]
After using view() with dtype = 'int16' and adding 1 a is :
[ 1 2 3 4 5 6 7 8 9 10]
Code #3:
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print("a is: \n", a) v = a.view('int8')print("\n After using view() with dtype = 'int8' a is : \n", a) v += 1# addition of 1 to each element of vprint("\n After using view() with dtype = 'int8' and adding 1 a is : \n", a)
surinderdawra388
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "numpy.ndarray.view() helps to get a new view of array with the same data. "
},
{
"code": null,
"e": 361,
"s": 103,
"text": "Syntax: ndarray.view(dtype=None, type=None)Parameters: dtype : Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. type : Python type, optionalReturns : ndarray or matrix."
},
{
"code": null,
"e": 372,
"s": 361,
"text": "Code #1: "
},
{
"code": null,
"e": 380,
"s": 372,
"text": "Python3"
},
{
"code": "# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16') print(\"a is: \\n\", a) # using view() methodv = a.view('int32')print(\"\\n After using view() with dtype = 'int32' a is : \\n\", a) v += 1 # addition of 1 to each element of vprint(\"\\n After using view() with dtype = 'int32' and adding 1 a is : \\n\", a)",
"e": 744,
"s": 380,
"text": null
},
{
"code": null,
"e": 933,
"s": 744,
"text": "a is: \n [0 1 2 3 4 5 6 7 8 9]\n\n After using view() with dtype = 'int32' a is : \n [0 1 2 3 4 5 6 7 8 9]\n\n After using view() with dtype = 'int32' and adding 1 a is : \n [1 1 3 3 5 5 7 7 9 9]"
},
{
"code": null,
"e": 948,
"s": 935,
"text": " Code #2: "
},
{
"code": null,
"e": 956,
"s": 948,
"text": "Python3"
},
{
"code": "# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print(\"a is:\", a) # Using view() methodv = a.view('int16')print(\"\\n After using view() with dtype = 'int16' a is :\\n\", a) v += 1# addition of 1 to each element of vprint(\"\\n After using view() with dtype = 'int16' and adding 1 a is : \\n\", a)",
"e": 1314,
"s": 956,
"text": null
},
{
"code": null,
"e": 1510,
"s": 1314,
"text": "a is: [0 1 2 3 4 5 6 7 8 9]\n\n After using view() with dtype = 'int16' a is :\n [0 1 2 3 4 5 6 7 8 9]\n\n After using view() with dtype = 'int16' and adding 1 a is : \n [ 1 2 3 4 5 6 7 8 9 10]"
},
{
"code": null,
"e": 1525,
"s": 1512,
"text": " Code #3: "
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Python3"
},
{
"code": "# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print(\"a is: \\n\", a) v = a.view('int8')print(\"\\n After using view() with dtype = 'int8' a is : \\n\", a) v += 1# addition of 1 to each element of vprint(\"\\n After using view() with dtype = 'int8' and adding 1 a is : \\n\", a)",
"e": 1871,
"s": 1533,
"text": null
},
{
"code": null,
"e": 1888,
"s": 1871,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1909,
"s": 1888,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 1922,
"s": 1909,
"text": "Python-numpy"
},
{
"code": null,
"e": 1929,
"s": 1922,
"text": "Python"
},
{
"code": null,
"e": 2027,
"s": 1929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2057,
"s": 2027,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2107,
"s": 2057,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2129,
"s": 2107,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2145,
"s": 2129,
"text": "Deque in Python"
},
{
"code": null,
"e": 2161,
"s": 2145,
"text": "Stack in Python"
},
{
"code": null,
"e": 2179,
"s": 2161,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2204,
"s": 2179,
"text": "sum() function in Python"
},
{
"code": null,
"e": 2245,
"s": 2204,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 2287,
"s": 2245,
"text": "Different ways to create Pandas Dataframe"
}
] |
VBScript Erase Function | The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays.
Erase ArrayName
Fixed numeric array, each element in an array is reset to Zero.
Fixed numeric array, each element in an array is reset to Zero.
Fixed String array, each element in an array is reset to Zero length " ".
Fixed String array, each element in an array is reset to Zero length " ".
Array of Objects, each element in an array is reset to s special value Nothing.
Array of Objects, each element in an array is reset to s special value Nothing.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim NumArray(3)
NumArray(0) = "VBScript"
NumArray(1) = 1.05
NumArray(2) = 25
NumArray(3) = #23/04/2013#
Dim DynamicArray()
ReDim DynamicArray(9) ' Allocate storage space.
Erase NumArray ' Each element is reinitialized.
Erase DynamicArray ' Free memory used by array.
' All values would be erased.
Document.write("The value at Zeroth index of NumArray is " & NumArray(0) & "<br />")
Document.write("The value at First index of NumArray is " & NumArray(1) & "<br />")
Document.write("The value at Second index of NumArray is " & NumArray(2) & "<br />")
Document.write("The value at Third index of NumArray is " & NumArray(3) & "<br />")
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result −
The value at Zero index of NumArray is
The value at First index of NumArray is
The value at Second index of NumArray is
The value at Third index of NumArray is | [
{
"code": null,
"e": 2375,
"s": 2214,
"text": "The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays."
},
{
"code": null,
"e": 2392,
"s": 2375,
"text": "Erase ArrayName\n"
},
{
"code": null,
"e": 2456,
"s": 2392,
"text": "Fixed numeric array, each element in an array is reset to Zero."
},
{
"code": null,
"e": 2520,
"s": 2456,
"text": "Fixed numeric array, each element in an array is reset to Zero."
},
{
"code": null,
"e": 2594,
"s": 2520,
"text": "Fixed String array, each element in an array is reset to Zero length \" \"."
},
{
"code": null,
"e": 2668,
"s": 2594,
"text": "Fixed String array, each element in an array is reset to Zero length \" \"."
},
{
"code": null,
"e": 2748,
"s": 2668,
"text": "Array of Objects, each element in an array is reset to s special value Nothing."
},
{
"code": null,
"e": 2828,
"s": 2748,
"text": "Array of Objects, each element in an array is reset to s special value Nothing."
},
{
"code": null,
"e": 3737,
"s": 2828,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim NumArray(3)\n NumArray(0) = \"VBScript\"\n NumArray(1) = 1.05\n NumArray(2) = 25\n NumArray(3) = #23/04/2013#\n\n Dim DynamicArray()\n ReDim DynamicArray(9) ' Allocate storage space.\n\n Erase NumArray ' Each element is reinitialized.\n Erase DynamicArray ' Free memory used by array.\n\n ' All values would be erased.\n Document.write(\"The value at Zeroth index of NumArray is \" & NumArray(0) & \"<br />\")\n Document.write(\"The value at First index of NumArray is \" & NumArray(1) & \"<br />\")\n Document.write(\"The value at Second index of NumArray is \" & NumArray(2) & \"<br />\")\n Document.write(\"The value at Third index of NumArray is \" & NumArray(3) & \"<br />\")\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3845,
"s": 3737,
"text": "When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result −"
}
] |
BOTP – SMS and Email Bomber in Kali Linux | 17 Jun, 2021
The BOTP tool is a free and open-source tool available on GitHub that is used to perform call and SMS bombing on the target phone numbers. You must ensure that you always install the latest version of BOTP from GitHub in order to not get stuck with the work of the tool.
This tool is written in python. You must have python installed in your Kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. BOTP doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work.
Step 1:
Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/botolmehedi/botp
cd botp
Step 2:
The tool has been downloaded and now the tool runs using the following command.
python2 botp.py
The tool is running successfully. Now let’s see some examples of using the tool.
Example 1:
Use the BOTP tool to perform SMS Bombing on a number.
1
<phone number>
You can see that the tool has started running and the number of threats is 5000.
Example 2:
Use the BOTP tool to perform email bombing on an email address.
02
The tool has opened a list where you have to select the type of email your target has. For example, let’s select 1 here for Gmail bombing.
Now you have to provide the email address which is your target
The tool has started email bombing on the email that you have provided now. In this way, you can perform email bombing and SMS bombing. You can give your own credentials here. The tool has started sending SMS and emails. Some of them achieve success, some of them fail, but you can try again and again for the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "The BOTP tool is a free and open-source tool available on GitHub that is used to perform call and SMS bombing on the target phone numbers. You must ensure that you always install the latest version of BOTP from GitHub in order to not get stuck with the work of the tool. "
},
{
"code": null,
"e": 652,
"s": 300,
"text": "This tool is written in python. You must have python installed in your Kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. BOTP doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. "
},
{
"code": null,
"e": 661,
"s": 652,
"text": "Step 1: "
},
{
"code": null,
"e": 823,
"s": 661,
"text": "Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command."
},
{
"code": null,
"e": 877,
"s": 823,
"text": "git clone https://github.com/botolmehedi/botp\ncd botp"
},
{
"code": null,
"e": 886,
"s": 877,
"text": "Step 2: "
},
{
"code": null,
"e": 966,
"s": 886,
"text": "The tool has been downloaded and now the tool runs using the following command."
},
{
"code": null,
"e": 982,
"s": 966,
"text": "python2 botp.py"
},
{
"code": null,
"e": 1063,
"s": 982,
"text": "The tool is running successfully. Now let’s see some examples of using the tool."
},
{
"code": null,
"e": 1076,
"s": 1063,
"text": "Example 1: "
},
{
"code": null,
"e": 1130,
"s": 1076,
"text": "Use the BOTP tool to perform SMS Bombing on a number."
},
{
"code": null,
"e": 1147,
"s": 1130,
"text": "1\n<phone number>"
},
{
"code": null,
"e": 1230,
"s": 1147,
"text": " You can see that the tool has started running and the number of threats is 5000. "
},
{
"code": null,
"e": 1242,
"s": 1230,
"text": "Example 2: "
},
{
"code": null,
"e": 1306,
"s": 1242,
"text": "Use the BOTP tool to perform email bombing on an email address."
},
{
"code": null,
"e": 1309,
"s": 1306,
"text": "02"
},
{
"code": null,
"e": 1448,
"s": 1309,
"text": "The tool has opened a list where you have to select the type of email your target has. For example, let’s select 1 here for Gmail bombing."
},
{
"code": null,
"e": 1511,
"s": 1448,
"text": "Now you have to provide the email address which is your target"
},
{
"code": null,
"e": 1943,
"s": 1511,
"text": "The tool has started email bombing on the email that you have provided now. In this way, you can perform email bombing and SMS bombing. You can give your own credentials here. The tool has started sending SMS and emails. Some of them achieve success, some of them fail, but you can try again and again for the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail."
},
{
"code": null,
"e": 1954,
"s": 1943,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1966,
"s": 1954,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1977,
"s": 1966,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2075,
"s": 1977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2101,
"s": 2075,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2136,
"s": 2101,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2173,
"s": 2136,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2202,
"s": 2173,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2239,
"s": 2202,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2278,
"s": 2239,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2318,
"s": 2278,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2355,
"s": 2318,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2389,
"s": 2355,
"text": "mv command in Linux with examples"
}
] |
Longest subsegment of ‘1’s formed by changing at most k ‘0’s | 25 May, 2021
Given a binary array a[] and a number k, we need to find length of the longest subsegment of ‘1’s possible by changing at most k ‘0’s. Examples:
Input : a[] = {1, 0, 0, 1, 1, 0, 1},
k = 1.
Output : 4
Explanation : Here, we should only change 1
zero(0). Maximum possible length we can get
is by changing the 3rd zero in the array,
we get a[] = {1, 0, 0, 1, 1, 1, 1}
Input : a[] = {1, 0, 0, 1, 0, 1, 0, 1, 0, 1},
k = 2.
Output : 5
Output: Here, we can change only 2 zeros.
Maximum possible length we can get is by
changing the 3rd and 4th (or) 4th and 5th
zeros.
We can solve this problem using two pointers technique. Let us take a subarray [l, r] which contains at most k zeroes. Let our left pointer be l and right pointer be r. We always maintain our subsegment [l, r] to contain no more than k zeroes by moving the left pointer l. Check at every step for maximum size (i.e, r-l+1).
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find length of longest// subsegment of all 1's by changing at// most k 0's#include <iostream>using namespace std; int longestSubSeg(int a[], int n, int k){ int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = max(max_len, i - l + 1); } return max_len;} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = sizeof(a) / sizeof(a[0]); cout << longestSubSeg(a, n, k); return 0;}
// Java program to find length of// longest subsegment of all 1's// by changing at most k 0'simport java.io.*; class GFG { static int longestSubSeg(int a[], int n, int k){ int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.max(max_len, i - l + 1); } return max_len;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = a.length; System.out.println( longestSubSeg(a, n, k)); }} // This code is contributed by vt_m
# Python3 program to find length# of longest subsegment of all 1's # by changing at most k 0's def longestSubSeg(a, n, k): cnt0 = 0 l = 0 max_len = 0; # i decides current ending point for i in range(0, n): if a[i] == 0: cnt0 += 1 # If there are more 0's move # left point for current # ending point. while (cnt0 > k): if a[l] == 0: cnt0 -= 1 l += 1 max_len = max(max_len, i - l + 1); return max_len # Driver codea = [1, 0, 0, 1, 0, 1, 0, 1 ]k = 2n = len(a)print(longestSubSeg(a, n, k)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find length of// longest subsegment of all 1's// by changing at most k 0'susing System; class GFG { static int longestSubSeg(int[] a, int n, int k) { int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.Max(max_len, i - l + 1); } return max_len; } // Driver code public static void Main() { int[] a = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = a.Length; Console.WriteLine(longestSubSeg(a, n, k)); }} // This code is contributed by vt_m
<?php// PHP program to find length of longest// subsegment of all 1's by changing at// most k 0's function longestSubSeg( $a, $n, $k){ $cnt0 = 0; $l = 0; $max_len = 0; // i decides current ending point for($i = 0; $i < $n; $i++) { if ($a[$i] == 0) $cnt0++; // If there are more 0's move // left point for current ending // point. while ($cnt0 > $k) { if ($a[$l] == 0) $cnt0--; $l++; } $max_len = max($max_len, $i - $l + 1); } return $max_len;} // Driver code $a = array(1, 0, 0, 1, 0, 1, 0, 1); $k = 2; $n = count($a); echo longestSubSeg($a, $n, $k); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find length of // longest subsegment of all 1's // by changing at most k 0's function longestSubSeg(a, n, k) { let cnt0 = 0; let l = 0; let max_len = 0; // i decides current ending point for (let i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.max(max_len, i - l + 1); } return max_len; } let a = [ 1, 0, 0, 1, 0, 1, 0, 1 ]; let k = 2; let n = a.length; document.write(longestSubSeg(a, n, k)); </script>
Output:
5
vt_m
mukesh07
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 201,
"s": 54,
"text": "Given a binary array a[] and a number k, we need to find length of the longest subsegment of ‘1’s possible by changing at most k ‘0’s. Examples: "
},
{
"code": null,
"e": 643,
"s": 201,
"text": "Input : a[] = {1, 0, 0, 1, 1, 0, 1}, \n k = 1.\nOutput : 4\nExplanation : Here, we should only change 1\nzero(0). Maximum possible length we can get\nis by changing the 3rd zero in the array, \nwe get a[] = {1, 0, 0, 1, 1, 1, 1}\n\nInput : a[] = {1, 0, 0, 1, 0, 1, 0, 1, 0, 1}, \n k = 2.\nOutput : 5\nOutput: Here, we can change only 2 zeros. \nMaximum possible length we can get is by \nchanging the 3rd and 4th (or) 4th and 5th \nzeros."
},
{
"code": null,
"e": 971,
"s": 645,
"text": "We can solve this problem using two pointers technique. Let us take a subarray [l, r] which contains at most k zeroes. Let our left pointer be l and right pointer be r. We always maintain our subsegment [l, r] to contain no more than k zeroes by moving the left pointer l. Check at every step for maximum size (i.e, r-l+1). "
},
{
"code": null,
"e": 975,
"s": 971,
"text": "C++"
},
{
"code": null,
"e": 980,
"s": 975,
"text": "Java"
},
{
"code": null,
"e": 988,
"s": 980,
"text": "Python3"
},
{
"code": null,
"e": 991,
"s": 988,
"text": "C#"
},
{
"code": null,
"e": 995,
"s": 991,
"text": "PHP"
},
{
"code": null,
"e": 1006,
"s": 995,
"text": "Javascript"
},
{
"code": "// CPP program to find length of longest// subsegment of all 1's by changing at// most k 0's#include <iostream>using namespace std; int longestSubSeg(int a[], int n, int k){ int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = max(max_len, i - l + 1); } return max_len;} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = sizeof(a) / sizeof(a[0]); cout << longestSubSeg(a, n, k); return 0;}",
"e": 1774,
"s": 1006,
"text": null
},
{
"code": "// Java program to find length of// longest subsegment of all 1's// by changing at most k 0'simport java.io.*; class GFG { static int longestSubSeg(int a[], int n, int k){ int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.max(max_len, i - l + 1); } return max_len;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = a.length; System.out.println( longestSubSeg(a, n, k)); }} // This code is contributed by vt_m",
"e": 2637,
"s": 1774,
"text": null
},
{
"code": "# Python3 program to find length# of longest subsegment of all 1's # by changing at most k 0's def longestSubSeg(a, n, k): cnt0 = 0 l = 0 max_len = 0; # i decides current ending point for i in range(0, n): if a[i] == 0: cnt0 += 1 # If there are more 0's move # left point for current # ending point. while (cnt0 > k): if a[l] == 0: cnt0 -= 1 l += 1 max_len = max(max_len, i - l + 1); return max_len # Driver codea = [1, 0, 0, 1, 0, 1, 0, 1 ]k = 2n = len(a)print(longestSubSeg(a, n, k)) # This code is contributed by Smitha Dinesh Semwal",
"e": 3301,
"s": 2637,
"text": null
},
{
"code": "// C# program to find length of// longest subsegment of all 1's// by changing at most k 0'susing System; class GFG { static int longestSubSeg(int[] a, int n, int k) { int cnt0 = 0; int l = 0; int max_len = 0; // i decides current ending point for (int i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.Max(max_len, i - l + 1); } return max_len; } // Driver code public static void Main() { int[] a = { 1, 0, 0, 1, 0, 1, 0, 1 }; int k = 2; int n = a.Length; Console.WriteLine(longestSubSeg(a, n, k)); }} // This code is contributed by vt_m",
"e": 4260,
"s": 3301,
"text": null
},
{
"code": "<?php// PHP program to find length of longest// subsegment of all 1's by changing at// most k 0's function longestSubSeg( $a, $n, $k){ $cnt0 = 0; $l = 0; $max_len = 0; // i decides current ending point for($i = 0; $i < $n; $i++) { if ($a[$i] == 0) $cnt0++; // If there are more 0's move // left point for current ending // point. while ($cnt0 > $k) { if ($a[$l] == 0) $cnt0--; $l++; } $max_len = max($max_len, $i - $l + 1); } return $max_len;} // Driver code $a = array(1, 0, 0, 1, 0, 1, 0, 1); $k = 2; $n = count($a); echo longestSubSeg($a, $n, $k); // This code is contributed by anuj_67.?>",
"e": 5001,
"s": 4260,
"text": null
},
{
"code": "<script> // JavaScript program to find length of // longest subsegment of all 1's // by changing at most k 0's function longestSubSeg(a, n, k) { let cnt0 = 0; let l = 0; let max_len = 0; // i decides current ending point for (let i = 0; i < n; i++) { if (a[i] == 0) cnt0++; // If there are more 0's move // left point for current ending // point. while (cnt0 > k) { if (a[l] == 0) cnt0--; l++; } max_len = Math.max(max_len, i - l + 1); } return max_len; } let a = [ 1, 0, 0, 1, 0, 1, 0, 1 ]; let k = 2; let n = a.length; document.write(longestSubSeg(a, n, k)); </script>",
"e": 5826,
"s": 5001,
"text": null
},
{
"code": null,
"e": 5836,
"s": 5826,
"text": "Output: "
},
{
"code": null,
"e": 5838,
"s": 5836,
"text": "5"
},
{
"code": null,
"e": 5845,
"s": 5840,
"text": "vt_m"
},
{
"code": null,
"e": 5854,
"s": 5845,
"text": "mukesh07"
},
{
"code": null,
"e": 5868,
"s": 5854,
"text": "binary-string"
},
{
"code": null,
"e": 5875,
"s": 5868,
"text": "Arrays"
},
{
"code": null,
"e": 5882,
"s": 5875,
"text": "Arrays"
}
] |
Convert two lists into a dictionary in Python | While a Python list contains a series of values a dictionary on the other hand contains a pair of values which are called key-value pairs. In this article we will take two lists and mark them together to create a Python dictionary.
We create two nested for loops. In the inner loop will assign one of the list as key for the dictionary while keep removing the values from the list which is outer for loop.
Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# Empty dictionary
res = {}
# COnvert to dictionary
for key in listK:
for value in listV:
res[key] = value
listV.remove(value)
break
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
The two lists are combined to create a pair of values by putting them into a for loop. The range and len functions are used to keep track of the number of elements till all the key value pairs are created.
Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = {listK[i]: listV[i] for i in range(len(listK))}
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
The zip function does something similar to above approach. It also combines the elements from the two lists, creating key and value pairs.
Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = dict(zip(listK, listV))
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6}) | [
{
"code": null,
"e": 1419,
"s": 1187,
"text": "While a Python list contains a series of values a dictionary on the other hand contains a pair of values which are called key-value pairs. In this article we will take two lists and mark them together to create a Python dictionary."
},
{
"code": null,
"e": 1593,
"s": 1419,
"text": "We create two nested for loops. In the inner loop will assign one of the list as key for the dictionary while keep removing the values from the list which is outer for loop."
},
{
"code": null,
"e": 1604,
"s": 1593,
"text": " Live Demo"
},
{
"code": null,
"e": 1918,
"s": 1604,
"text": "listK = [\"Mon\", \"Tue\", \"Wed\"]\nlistV = [3, 6, 5]\n# Given lists\nprint(\"List of K : \", listK)\nprint(\"list of V : \", listV)\n# Empty dictionary\nres = {}\n# COnvert to dictionary\nfor key in listK:\n for value in listV:\n res[key] = value\n listV.remove(value)\n break\nprint(\"Dictionary from lists :\\n \",res)"
},
{
"code": null,
"e": 1973,
"s": 1918,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2104,
"s": 1973,
"text": "('List of K : ', ['Mon', 'Tue', 'Wed'])\n('list of V : ', [3, 6, 5])\n('Dictionary from lists :\\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})"
},
{
"code": null,
"e": 2310,
"s": 2104,
"text": "The two lists are combined to create a pair of values by putting them into a for loop. The range and len functions are used to keep track of the number of elements till all the key value pairs are created."
},
{
"code": null,
"e": 2321,
"s": 2310,
"text": " Live Demo"
},
{
"code": null,
"e": 2559,
"s": 2321,
"text": "listK = [\"Mon\", \"Tue\", \"Wed\"]\nlistV = [3, 6, 5]\n# Given lists\nprint(\"List of K : \", listK)\nprint(\"list of V : \", listV)\n# COnvert to dictionary\nres = {listK[i]: listV[i] for i in range(len(listK))}\nprint(\"Dictionary from lists :\\n \",res)"
},
{
"code": null,
"e": 2614,
"s": 2559,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2745,
"s": 2614,
"text": "('List of K : ', ['Mon', 'Tue', 'Wed'])\n('list of V : ', [3, 6, 5])\n('Dictionary from lists :\\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})"
},
{
"code": null,
"e": 2884,
"s": 2745,
"text": "The zip function does something similar to above approach. It also combines the elements from the two lists, creating key and value pairs."
},
{
"code": null,
"e": 2895,
"s": 2884,
"text": " Live Demo"
},
{
"code": null,
"e": 3109,
"s": 2895,
"text": "listK = [\"Mon\", \"Tue\", \"Wed\"]\nlistV = [3, 6, 5]\n# Given lists\nprint(\"List of K : \", listK)\nprint(\"list of V : \", listV)\n# COnvert to dictionary\nres = dict(zip(listK, listV))\nprint(\"Dictionary from lists :\\n \",res)"
},
{
"code": null,
"e": 3164,
"s": 3109,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3295,
"s": 3164,
"text": "('List of K : ', ['Mon', 'Tue', 'Wed'])\n('list of V : ', [3, 6, 5])\n('Dictionary from lists :\\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})"
}
] |
Convert Text and Text File to PDF using Python | 25 May, 2022
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in various projects that we do in real life. So, if you don’t know how to convert a given text to PDF then this article is for you. In this article, you will come to know the way to convert text and text file to PDF in Python. FPDF is a Python class that allows generating PDF files with Python code. It is free to use and it does not require any API keys. FPDF stands for Free PDF. It means that any kind of modification can be done in PDF files. The main features of this class are:
Easy to use
It allows page format and margin
It allows to manage page header and footer
Python 2.5 to 3.7 support
Unicode (UTF-8) TrueType font subset embedding
Barcode I2of5 and code39, QR code coming soon ...
PNG, GIF and JPG support (including transparency and alpha channel)
Templates with a visual designer & basic html2pdf
Exceptions support, other minor fixes, improvements and PEP8 code cleanups
To install the fpdf module type the below command in the terminal.
pip install fpdf
Approach:
Import the class FPDF from module fpdfAdd a pageSet the fontInsert a cell and provide the textSave the pdf with “.pdf” extension
Import the class FPDF from module fpdf
Add a page
Set the font
Insert a cell and provide the text
Save the pdf with “.pdf” extension
Example:
Python3
# Python program to create# a pdf file from fpdf import FPDF # save FPDF() class into a# variable pdfpdf = FPDF() # Add a pagepdf.add_page() # set style and size of font# that you want in the pdfpdf.set_font("Arial", size = 15) # create a cellpdf.cell(200, 10, txt = "GeeksforGeeks", ln = 1, align = 'C') # add another cellpdf.cell(200, 10, txt = "A Computer Science portal for geeks.", ln = 2, align = 'C') # save the pdf with name .pdfpdf.output("GFG.pdf")
Output:
Now if we want to make the above program more advance what we can do is that from a given text file extract the data using file handling and then insert it into the pdf file. The approach is all same as above, one thing you have to do is extract the data from a text file using file handling. Note: Refer this article to know more about file handling in Python. Example: Let’s suppose the text file looks like this –
Python3
# Python program to convert# text file to pdf file from fpdf import FPDF # save FPDF() class into# a variable pdfpdf = FPDF() # Add a pagepdf.add_page() # set style and size of font# that you want in the pdfpdf.set_font("Arial", size = 15) # open the text file in read modef = open("myfile.txt", "r") # insert the texts in pdffor x in f: pdf.cell(200, 10, txt = x, ln = 1, align = 'C') # save the pdf with name .pdfpdf.output("mygfg.pdf")
Output:
prachisoda1234
vinayedula
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 887,
"s": 54,
"text": "PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in various projects that we do in real life. So, if you don’t know how to convert a given text to PDF then this article is for you. In this article, you will come to know the way to convert text and text file to PDF in Python. FPDF is a Python class that allows generating PDF files with Python code. It is free to use and it does not require any API keys. FPDF stands for Free PDF. It means that any kind of modification can be done in PDF files. The main features of this class are:"
},
{
"code": null,
"e": 899,
"s": 887,
"text": "Easy to use"
},
{
"code": null,
"e": 932,
"s": 899,
"text": "It allows page format and margin"
},
{
"code": null,
"e": 975,
"s": 932,
"text": "It allows to manage page header and footer"
},
{
"code": null,
"e": 1001,
"s": 975,
"text": "Python 2.5 to 3.7 support"
},
{
"code": null,
"e": 1048,
"s": 1001,
"text": "Unicode (UTF-8) TrueType font subset embedding"
},
{
"code": null,
"e": 1098,
"s": 1048,
"text": "Barcode I2of5 and code39, QR code coming soon ..."
},
{
"code": null,
"e": 1166,
"s": 1098,
"text": "PNG, GIF and JPG support (including transparency and alpha channel)"
},
{
"code": null,
"e": 1216,
"s": 1166,
"text": "Templates with a visual designer & basic html2pdf"
},
{
"code": null,
"e": 1291,
"s": 1216,
"text": "Exceptions support, other minor fixes, improvements and PEP8 code cleanups"
},
{
"code": null,
"e": 1358,
"s": 1291,
"text": "To install the fpdf module type the below command in the terminal."
},
{
"code": null,
"e": 1375,
"s": 1358,
"text": "pip install fpdf"
},
{
"code": null,
"e": 1385,
"s": 1375,
"text": "Approach:"
},
{
"code": null,
"e": 1514,
"s": 1385,
"text": "Import the class FPDF from module fpdfAdd a pageSet the fontInsert a cell and provide the textSave the pdf with “.pdf” extension"
},
{
"code": null,
"e": 1553,
"s": 1514,
"text": "Import the class FPDF from module fpdf"
},
{
"code": null,
"e": 1564,
"s": 1553,
"text": "Add a page"
},
{
"code": null,
"e": 1577,
"s": 1564,
"text": "Set the font"
},
{
"code": null,
"e": 1612,
"s": 1577,
"text": "Insert a cell and provide the text"
},
{
"code": null,
"e": 1647,
"s": 1612,
"text": "Save the pdf with “.pdf” extension"
},
{
"code": null,
"e": 1657,
"s": 1647,
"text": "Example: "
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Python3"
},
{
"code": "# Python program to create# a pdf file from fpdf import FPDF # save FPDF() class into a# variable pdfpdf = FPDF() # Add a pagepdf.add_page() # set style and size of font# that you want in the pdfpdf.set_font(\"Arial\", size = 15) # create a cellpdf.cell(200, 10, txt = \"GeeksforGeeks\", ln = 1, align = 'C') # add another cellpdf.cell(200, 10, txt = \"A Computer Science portal for geeks.\", ln = 2, align = 'C') # save the pdf with name .pdfpdf.output(\"GFG.pdf\") ",
"e": 2144,
"s": 1665,
"text": null
},
{
"code": null,
"e": 2153,
"s": 2144,
"text": "Output: "
},
{
"code": null,
"e": 2572,
"s": 2153,
"text": "Now if we want to make the above program more advance what we can do is that from a given text file extract the data using file handling and then insert it into the pdf file. The approach is all same as above, one thing you have to do is extract the data from a text file using file handling. Note: Refer this article to know more about file handling in Python. Example: Let’s suppose the text file looks like this – "
},
{
"code": null,
"e": 2580,
"s": 2572,
"text": "Python3"
},
{
"code": "# Python program to convert# text file to pdf file from fpdf import FPDF # save FPDF() class into# a variable pdfpdf = FPDF() # Add a pagepdf.add_page() # set style and size of font# that you want in the pdfpdf.set_font(\"Arial\", size = 15) # open the text file in read modef = open(\"myfile.txt\", \"r\") # insert the texts in pdffor x in f: pdf.cell(200, 10, txt = x, ln = 1, align = 'C') # save the pdf with name .pdfpdf.output(\"mygfg.pdf\") ",
"e": 3031,
"s": 2580,
"text": null
},
{
"code": null,
"e": 3040,
"s": 3031,
"text": "Output: "
},
{
"code": null,
"e": 3055,
"s": 3040,
"text": "prachisoda1234"
},
{
"code": null,
"e": 3066,
"s": 3055,
"text": "vinayedula"
},
{
"code": null,
"e": 3081,
"s": 3066,
"text": "python-utility"
},
{
"code": null,
"e": 3088,
"s": 3081,
"text": "Python"
},
{
"code": null,
"e": 3107,
"s": 3088,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3205,
"s": 3107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3223,
"s": 3205,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3265,
"s": 3223,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3287,
"s": 3265,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3322,
"s": 3287,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3354,
"s": 3322,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3380,
"s": 3354,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3409,
"s": 3380,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3436,
"s": 3409,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3457,
"s": 3436,
"text": "Python OOPs Concepts"
}
] |
WPF - Calendar | Calendar is a control that enables a user to select a date by using a visual calendar display. It provides some basic navigation using either the mouse or keyboard. The hierarchical inheritance of Calendar class is as follows −
BlackoutDates
Gets a collection of dates that are marked as not selectable.
CalendarButtonStyle
Gets or sets the Style associated with the control's internal CalendarButton object.
CalendarDayButtonStyle
Gets or sets the Style associated with the control's internal CalendarDayButton object.
CalendarItemStyle
Gets or sets the Style associated with the control's internal CalendarItem object.
DisplayDate
Gets or sets the date to display.
DisplayDateEnd
Gets or sets the last date in the date range that is available in the calendar.
DisplayDateStart
Gets or sets the first date that is available in the calendar.
DisplayMode
Gets or sets a value that indicates whether the calendar displays a month, year, or decade.
FirstDayOfWeek
Gets or sets the day that is considered the beginning of the week.
IsTodayHighlighted
Gets or sets a value that indicates whether the current date is highlighted.
SelectedDate
Gets or sets the currently selected date.
SelectedDates
Gets a collection of selected dates.
SelectionMode
Gets or sets a value that indicates what kind of selections are allowed.
OnApplyTemplate
Builds the visual tree for the Calendar control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().)
ToString
Provides a text representation of the selected date. (Overrides Control.ToString().)
DisplayDateChanged
Occurs when the DisplayDate property is changed.
DisplayModeChanged
Occurs when the DisplayMode property is changed.
SelectedDatesChanged
Occurs when the collection returned by the SelectedDates property is changed.
SelectionModeChanged
Occurs when the SelectionMode changes.
Let’s create a new WPF project with WPFCalenderControl name.
Let’s create a new WPF project with WPFCalenderControl name.
Drag the calendar control from a toolbox and change the background color in the properties window.
Drag the calendar control from a toolbox and change the background color in the properties window.
Now switch to XAML window in which you will see the XAML tags for calendar and its background.
Now switch to XAML window in which you will see the XAML tags for calendar and its background.
Add some more properties to set the blackouts dates and selection event, as shown in the following XAML code.
Add some more properties to set the blackouts dates and selection event, as shown in the following XAML code.
<Window x:Class = "WPFCalenderControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFCalenderControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<Calendar Margin = "20" SelectionMode = "MultipleRange"
IsTodayHighlighted = "false" DisplayDate = "1/1/2015"
DisplayDateEnd = "1/31/2015" SelectedDatesChanged = "Calendar_SelectedDatesChanged"
xmlns:sys = "clr-namespace:System;assembly = mscorlib">
<Calendar.BlackoutDates>
<CalendarDateRange Start = "1/2/2015" End = "1/4/2015"/>
<CalendarDateRange Start = "1/9/2015" End = "1/9/2015"/>
<CalendarDateRange Start = "1/16/2015" End = "1/16/2015"/>
<CalendarDateRange Start = "1/23/2015" End = "1/25/2015"/>
<CalendarDateRange Start = "1/30/2015" End = "1/30/2015"/>
</Calendar.BlackoutDates>
<Calendar.SelectedDates>
<sys:DateTime>1/5/2015</sys:DateTime>
<sys:DateTime>1/12/2015</sys:DateTime>
<sys:DateTime>1/14/2015</sys:DateTime>
<sys:DateTime>1/13/2015</sys:DateTime>
<sys:DateTime>1/15/2015</sys:DateTime>
<sys:DateTime>1/27/2015</sys:DateTime>
<sys:DateTime>4/2/2015</sys:DateTime>
</Calendar.SelectedDates>
<Calendar.Background>
<LinearGradientBrush EndPoint = "0.5,1" StartPoint = "0.5,0">
<GradientStop Color = "#FFE4EAF0" Offset = "0" />
<GradientStop Color = "#FFECF0F4" Offset = "0.16" />
<GradientStop Color = "#FFFCFCFD" Offset = "0.16" />
<GradientStop Color = "#FFD80320" Offset = "1" />
</LinearGradientBrush>
</Calendar.Background>
</Calendar>
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WPFCalenderControl {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e) {
var calendar = sender as Calendar;
if (calendar.SelectedDate.HasValue) {
DateTime date = calendar.SelectedDate.Value;
this.Title = date.ToShortDateString();
}
}
}
}
When you compile and execute the above code, it will produce the following window which shows some of the dates are selected while some are blacked out.
If you select another date, then it will be shown on the title of this window.
We recommend that you execute the above example code and try its other properties and events.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2248,
"s": 2020,
"text": "Calendar is a control that enables a user to select a date by using a visual calendar display. It provides some basic navigation using either the mouse or keyboard. The hierarchical inheritance of Calendar class is as follows −"
},
{
"code": null,
"e": 2262,
"s": 2248,
"text": "BlackoutDates"
},
{
"code": null,
"e": 2324,
"s": 2262,
"text": "Gets a collection of dates that are marked as not selectable."
},
{
"code": null,
"e": 2344,
"s": 2324,
"text": "CalendarButtonStyle"
},
{
"code": null,
"e": 2429,
"s": 2344,
"text": "Gets or sets the Style associated with the control's internal CalendarButton object."
},
{
"code": null,
"e": 2452,
"s": 2429,
"text": "CalendarDayButtonStyle"
},
{
"code": null,
"e": 2540,
"s": 2452,
"text": "Gets or sets the Style associated with the control's internal CalendarDayButton object."
},
{
"code": null,
"e": 2558,
"s": 2540,
"text": "CalendarItemStyle"
},
{
"code": null,
"e": 2641,
"s": 2558,
"text": "Gets or sets the Style associated with the control's internal CalendarItem object."
},
{
"code": null,
"e": 2653,
"s": 2641,
"text": "DisplayDate"
},
{
"code": null,
"e": 2687,
"s": 2653,
"text": "Gets or sets the date to display."
},
{
"code": null,
"e": 2702,
"s": 2687,
"text": "DisplayDateEnd"
},
{
"code": null,
"e": 2782,
"s": 2702,
"text": "Gets or sets the last date in the date range that is available in the calendar."
},
{
"code": null,
"e": 2799,
"s": 2782,
"text": "DisplayDateStart"
},
{
"code": null,
"e": 2862,
"s": 2799,
"text": "Gets or sets the first date that is available in the calendar."
},
{
"code": null,
"e": 2874,
"s": 2862,
"text": "DisplayMode"
},
{
"code": null,
"e": 2966,
"s": 2874,
"text": "Gets or sets a value that indicates whether the calendar displays a month, year, or decade."
},
{
"code": null,
"e": 2981,
"s": 2966,
"text": "FirstDayOfWeek"
},
{
"code": null,
"e": 3048,
"s": 2981,
"text": "Gets or sets the day that is considered the beginning of the week."
},
{
"code": null,
"e": 3067,
"s": 3048,
"text": "IsTodayHighlighted"
},
{
"code": null,
"e": 3144,
"s": 3067,
"text": "Gets or sets a value that indicates whether the current date is highlighted."
},
{
"code": null,
"e": 3157,
"s": 3144,
"text": "SelectedDate"
},
{
"code": null,
"e": 3199,
"s": 3157,
"text": "Gets or sets the currently selected date."
},
{
"code": null,
"e": 3213,
"s": 3199,
"text": "SelectedDates"
},
{
"code": null,
"e": 3250,
"s": 3213,
"text": "Gets a collection of selected dates."
},
{
"code": null,
"e": 3264,
"s": 3250,
"text": "SelectionMode"
},
{
"code": null,
"e": 3337,
"s": 3264,
"text": "Gets or sets a value that indicates what kind of selections are allowed."
},
{
"code": null,
"e": 3353,
"s": 3337,
"text": "OnApplyTemplate"
},
{
"code": null,
"e": 3481,
"s": 3353,
"text": "Builds the visual tree for the Calendar control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().)"
},
{
"code": null,
"e": 3490,
"s": 3481,
"text": "ToString"
},
{
"code": null,
"e": 3575,
"s": 3490,
"text": "Provides a text representation of the selected date. (Overrides Control.ToString().)"
},
{
"code": null,
"e": 3594,
"s": 3575,
"text": "DisplayDateChanged"
},
{
"code": null,
"e": 3643,
"s": 3594,
"text": "Occurs when the DisplayDate property is changed."
},
{
"code": null,
"e": 3662,
"s": 3643,
"text": "DisplayModeChanged"
},
{
"code": null,
"e": 3711,
"s": 3662,
"text": "Occurs when the DisplayMode property is changed."
},
{
"code": null,
"e": 3732,
"s": 3711,
"text": "SelectedDatesChanged"
},
{
"code": null,
"e": 3810,
"s": 3732,
"text": "Occurs when the collection returned by the SelectedDates property is changed."
},
{
"code": null,
"e": 3831,
"s": 3810,
"text": "SelectionModeChanged"
},
{
"code": null,
"e": 3870,
"s": 3831,
"text": "Occurs when the SelectionMode changes."
},
{
"code": null,
"e": 3931,
"s": 3870,
"text": "Let’s create a new WPF project with WPFCalenderControl name."
},
{
"code": null,
"e": 3992,
"s": 3931,
"text": "Let’s create a new WPF project with WPFCalenderControl name."
},
{
"code": null,
"e": 4091,
"s": 3992,
"text": "Drag the calendar control from a toolbox and change the background color in the properties window."
},
{
"code": null,
"e": 4190,
"s": 4091,
"text": "Drag the calendar control from a toolbox and change the background color in the properties window."
},
{
"code": null,
"e": 4285,
"s": 4190,
"text": "Now switch to XAML window in which you will see the XAML tags for calendar and its background."
},
{
"code": null,
"e": 4380,
"s": 4285,
"text": "Now switch to XAML window in which you will see the XAML tags for calendar and its background."
},
{
"code": null,
"e": 4490,
"s": 4380,
"text": "Add some more properties to set the blackouts dates and selection event, as shown in the following XAML code."
},
{
"code": null,
"e": 4600,
"s": 4490,
"text": "Add some more properties to set the blackouts dates and selection event, as shown in the following XAML code."
},
{
"code": null,
"e": 6721,
"s": 4600,
"text": "<Window x:Class = \"WPFCalenderControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFCalenderControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Calendar Margin = \"20\" SelectionMode = \"MultipleRange\"\n IsTodayHighlighted = \"false\" DisplayDate = \"1/1/2015\" \n DisplayDateEnd = \"1/31/2015\" SelectedDatesChanged = \"Calendar_SelectedDatesChanged\" \n xmlns:sys = \"clr-namespace:System;assembly = mscorlib\"> \n\t\t\t\n <Calendar.BlackoutDates> \n <CalendarDateRange Start = \"1/2/2015\" End = \"1/4/2015\"/> \n <CalendarDateRange Start = \"1/9/2015\" End = \"1/9/2015\"/> \n <CalendarDateRange Start = \"1/16/2015\" End = \"1/16/2015\"/> \n <CalendarDateRange Start = \"1/23/2015\" End = \"1/25/2015\"/> \n <CalendarDateRange Start = \"1/30/2015\" End = \"1/30/2015\"/> \n </Calendar.BlackoutDates> \n\t\t\t\n <Calendar.SelectedDates> \n <sys:DateTime>1/5/2015</sys:DateTime> \n <sys:DateTime>1/12/2015</sys:DateTime> \n <sys:DateTime>1/14/2015</sys:DateTime> \n <sys:DateTime>1/13/2015</sys:DateTime> \n <sys:DateTime>1/15/2015</sys:DateTime> \n <sys:DateTime>1/27/2015</sys:DateTime> \n <sys:DateTime>4/2/2015</sys:DateTime> \n </Calendar.SelectedDates> \n\t\t\t\n <Calendar.Background> \n <LinearGradientBrush EndPoint = \"0.5,1\" StartPoint = \"0.5,0\"> \n <GradientStop Color = \"#FFE4EAF0\" Offset = \"0\" /> \n <GradientStop Color = \"#FFECF0F4\" Offset = \"0.16\" /> \n <GradientStop Color = \"#FFFCFCFD\" Offset = \"0.16\" /> \n <GradientStop Color = \"#FFD80320\" Offset = \"1\" /> \n </LinearGradientBrush> \n </Calendar.Background> \n\t\t\t\n </Calendar>\n\t\t\n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 7373,
"s": 6721,
"text": "using System; \nusing System.Windows;\t\nusing System.Windows.Controls; \n\nnamespace WPFCalenderControl { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e) { \n var calendar = sender as Calendar; \n\t\t\t\n if (calendar.SelectedDate.HasValue) { \n DateTime date = calendar.SelectedDate.Value; \n this.Title = date.ToShortDateString(); \n } \n } \n\t\t\n } \n}"
},
{
"code": null,
"e": 7526,
"s": 7373,
"text": "When you compile and execute the above code, it will produce the following window which shows some of the dates are selected while some are blacked out."
},
{
"code": null,
"e": 7605,
"s": 7526,
"text": "If you select another date, then it will be shown on the title of this window."
},
{
"code": null,
"e": 7699,
"s": 7605,
"text": "We recommend that you execute the above example code and try its other properties and events."
},
{
"code": null,
"e": 7734,
"s": 7699,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7748,
"s": 7734,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7783,
"s": 7748,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7806,
"s": 7783,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 7813,
"s": 7806,
"text": " Print"
},
{
"code": null,
"e": 7824,
"s": 7813,
"text": " Add Notes"
}
] |
Replace diagonal elements in each row of given Matrix by Kth smallest element of that row - GeeksforGeeks | 17 Jan, 2022
Given a matrix mat[ ][ ] of size N*N and an integer K, containing integer values, the task is to replace diagonal elements by the Kth smallest element of row.
Examples:
Input: mat[][]= {{1, 2, 3, 4} {4, 2, 7, 6} {3, 5, 1, 9} {2, 4, 6, 8}}K = 2Output: 2, 2, 3, 4 4, 4, 7, 6 3, 5, 3, 8 2, 4, 6, 4Explanation: 2nd smallest element of 1st row = 22nd smallest element of 2nd row is 42nd smallest element of 3rd row is 32nd smallest element of 4th row is 4
Input: mat[][] = {{1, 2, 3} {7, 9, 8} {2, 3, 6}}K = 2Output: 2, 2, 3 7, 8, 8 2, 3, 3
Approach: The solution is based on the concept of sorting. Follow the steps mentioned below:
Traverse the matrix row-wise.
Copy this row in another list.
Sort the list and get the Kth smallest element and replace the diagonal element with that.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
const int N = 4;
// Function to print Matrix
void showMatrix(int mat[][N])
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}
// Function to return k'th smallest element
// in a given array
int kthSmallest(int arr[], int n, int K)
{
// Sort the given array
sort(arr, arr + n);
// Return k'th element
// in the sorted array
return arr[K - 1];
}
// Function to replace diagonal elements
// with Kth min element of row.
void ReplaceDiagonal(int mat[][N], int K)
{
int i, j;
int arr[N];
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
arr[j] = mat[i][j];
mat[i][i] = kthSmallest(arr, N, K);
}
showMatrix(mat);
}
// Utility Main function.
int main()
{
int mat[][N] = { { 1, 2, 3, 4 },
{ 4, 2, 7, 6 },
{ 3, 5, 1, 9 },
{ 2, 4, 6, 8 } };
int K = 3;
ReplaceDiagonal(mat, K);
return 0;
}
// Java code to find the maximum median
// of a sub array having length at least K.
import java.util.*;
public class GFG
{
static int N = 4;
// Function to print Matrix
static void showMatrix(int mat[][])
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Function to return k'th smallest element
// in a given array
static int kthSmallest(int arr[], int n, int K)
{
// Sort the given array
Arrays.sort(arr);
// Return k'th element
// in the sorted array
return arr[K - 1];
}
// Function to replace diagonal elements
// with Kth min element of row.
static void ReplaceDiagonal(int mat[][], int K)
{
int i, j;
int arr[] = new int[N];
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
arr[j] = mat[i][j];
mat[i][i] = kthSmallest(arr, N, K);
}
showMatrix(mat);
}
// Driver code
public static void main(String args[])
{
int mat[][] = { { 1, 2, 3, 4 },
{ 4, 2, 7, 6 },
{ 3, 5, 1, 9 },
{ 2, 4, 6, 8 } };
int K = 3;
ReplaceDiagonal(mat, K);
}
}
// This code is contributed by Samim Hossain Mondal.
# Python code for the above approach
N = 4
# Function to print Matrix
def showMatrix(mat):
i = None
j = None
for i in range(N):
for j in range(N):
print(mat[i][j], end= " ")
print('')
# Function to return k'th smallest element
# in a given array
def kthSmallest(arr, n, K):
# Sort the given array
arr.sort()
# Return k'th element
# in the sorted array
return arr[K - 1]
# Function to replace diagonal elements
# with Kth min element of row.
def ReplaceDiagonal(mat, K):
i = None
j = None
arr = [0] * N
for i in range(N):
for j in range(N):
arr[j] = mat[i][j]
mat[i][i] = kthSmallest(arr, N, K)
showMatrix(mat)
# Utility Main function.
mat = [[1, 2, 3, 4], [4, 2, 7, 6], [3, 5, 1, 9], [2, 4, 6, 8]]
K = 3
ReplaceDiagonal(mat, K)
# This code is contributed by Saurabh Jaiswal
// C# code to find the maximum median
// of a sub array having length at least K.
using System;
public class GFG {
static int N = 4;
// Function to print Matrix
static void showMatrix(int[, ] mat)
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
Console.Write(mat[i, j] + " ");
}
Console.WriteLine();
}
}
// Function to return k'th smallest element
// in a given array
static int kthSmallest(int[] arr, int n, int K)
{
// Sort the given array
Array.Sort(arr);
// Return k'th element
// in the sorted array
return arr[K - 1];
}
// Function to replace diagonal elements
// with Kth min element of row.
static void ReplaceDiagonal(int[, ] mat, int K)
{
int i, j;
int[] arr = new int[N];
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
arr[j] = mat[i, j];
mat[i, i] = kthSmallest(arr, N, K);
}
showMatrix(mat);
}
// Driver code
public static void Main()
{
int[, ] mat = { { 1, 2, 3, 4 },
{ 4, 2, 7, 6 },
{ 3, 5, 1, 9 },
{ 2, 4, 6, 8 } };
int K = 3;
ReplaceDiagonal(mat, K);
}
}
// This code is contributed by ukasp.
<script>
// JavaScript code for the above approach
let N = 4;
// Function to print Matrix
function showMatrix(mat) {
let i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
document.write(mat[i][j] + " ");
}
document.write('<br>')
}
}
// Function to return k'th smallest element
// in a given array
function kthSmallest(arr, n, K)
{
// Sort the given array
arr.sort(function (a, b) { return a - b })
// Return k'th element
// in the sorted array
return arr[K - 1];
}
// Function to replace diagonal elements
// with Kth min element of row.
function ReplaceDiagonal(mat, K)
{
let i, j;
let arr = new Array(N);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
arr[j] = mat[i][j];
mat[i][i] = kthSmallest(arr, N, K);
}
showMatrix(mat);
}
// Utility Main function.
let mat = [[1, 2, 3, 4],
[4, 2, 7, 6],
[3, 5, 1, 9],
[2, 4, 6, 8]];
let K = 3;
ReplaceDiagonal(mat, K);
// This code is contributed by Potta Lokesh
</script>
3 2 3 4
4 6 7 6
3 5 5 9
2 4 6 6
Time Complexity: O(N2 * logN)Auxiliary Space: O(N)
lokeshpotta20
_saurabh_jaiswal
samim2000
ukasp
Algo-Geek 2021
Algo Geek
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Minimize cost to sort given array by sorting unsorted subarrays
Divide given number into two even parts
Program to find simple moving average | Set-2
Check if the given string is valid English word or not
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews | [
{
"code": null,
"e": 25857,
"s": 25826,
"text": " \n17 Jan, 2022\n"
},
{
"code": null,
"e": 26016,
"s": 25857,
"text": "Given a matrix mat[ ][ ] of size N*N and an integer K, containing integer values, the task is to replace diagonal elements by the Kth smallest element of row."
},
{
"code": null,
"e": 26027,
"s": 26016,
"text": "Examples: "
},
{
"code": null,
"e": 26430,
"s": 26027,
"text": "Input: mat[][]= {{1, 2, 3, 4} {4, 2, 7, 6} {3, 5, 1, 9} {2, 4, 6, 8}}K = 2Output: 2, 2, 3, 4 4, 4, 7, 6 3, 5, 3, 8 2, 4, 6, 4Explanation: 2nd smallest element of 1st row = 22nd smallest element of 2nd row is 42nd smallest element of 3rd row is 32nd smallest element of 4th row is 4 "
},
{
"code": null,
"e": 26589,
"s": 26430,
"text": "Input: mat[][] = {{1, 2, 3} {7, 9, 8} {2, 3, 6}}K = 2Output: 2, 2, 3 7, 8, 8 2, 3, 3"
},
{
"code": null,
"e": 26682,
"s": 26589,
"text": "Approach: The solution is based on the concept of sorting. Follow the steps mentioned below:"
},
{
"code": null,
"e": 26712,
"s": 26682,
"text": "Traverse the matrix row-wise."
},
{
"code": null,
"e": 26743,
"s": 26712,
"text": "Copy this row in another list."
},
{
"code": null,
"e": 26834,
"s": 26743,
"text": "Sort the list and get the Kth smallest element and replace the diagonal element with that."
},
{
"code": null,
"e": 26885,
"s": 26834,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 26889,
"s": 26885,
"text": "C++"
},
{
"code": null,
"e": 26894,
"s": 26889,
"text": "Java"
},
{
"code": null,
"e": 26902,
"s": 26894,
"text": "Python3"
},
{
"code": null,
"e": 26905,
"s": 26902,
"text": "C#"
},
{
"code": null,
"e": 26916,
"s": 26905,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ code to implement the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 4;\n \n// Function to print Matrix\nvoid showMatrix(int mat[][N])\n{\n int i, j;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n cout << mat[i][j] << \" \";\n }\n cout << endl;\n }\n}\n \n// Function to return k'th smallest element\n// in a given array\nint kthSmallest(int arr[], int n, int K)\n{\n // Sort the given array\n sort(arr, arr + n);\n \n // Return k'th element\n // in the sorted array\n return arr[K - 1];\n}\n \n// Function to replace diagonal elements\n// with Kth min element of row.\nvoid ReplaceDiagonal(int mat[][N], int K)\n{\n int i, j;\n int arr[N];\n \n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++)\n arr[j] = mat[i][j];\n mat[i][i] = kthSmallest(arr, N, K);\n }\n showMatrix(mat);\n}\n \n// Utility Main function.\nint main()\n{\n int mat[][N] = { { 1, 2, 3, 4 },\n { 4, 2, 7, 6 },\n { 3, 5, 1, 9 },\n { 2, 4, 6, 8 } };\n \n int K = 3;\n ReplaceDiagonal(mat, K);\n return 0;\n}\n\n\n\n\n\n",
"e": 28079,
"s": 26926,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java code to find the maximum median\n// of a sub array having length at least K.\nimport java.util.*;\npublic class GFG\n{\n \n static int N = 4;\n \n // Function to print Matrix\n static void showMatrix(int mat[][])\n {\n int i, j;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n System.out.print(mat[i][j] + \" \");\n }\n System.out.println();\n }\n }\n \n // Function to return k'th smallest element\n // in a given array\n static int kthSmallest(int arr[], int n, int K)\n {\n // Sort the given array\n Arrays.sort(arr);\n \n // Return k'th element\n // in the sorted array\n return arr[K - 1];\n }\n \n // Function to replace diagonal elements\n // with Kth min element of row.\n static void ReplaceDiagonal(int mat[][], int K)\n {\n int i, j;\n int arr[] = new int[N];\n \n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++)\n arr[j] = mat[i][j];\n mat[i][i] = kthSmallest(arr, N, K);\n }\n showMatrix(mat);\n }\n \n // Driver code\n public static void main(String args[])\n {\n int mat[][] = { { 1, 2, 3, 4 },\n { 4, 2, 7, 6 },\n { 3, 5, 1, 9 },\n { 2, 4, 6, 8 } };\n \n int K = 3;\n ReplaceDiagonal(mat, K);\n }\n}\n \n// This code is contributed by Samim Hossain Mondal.\n\n\n\n\n\n",
"e": 29395,
"s": 28089,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python code for the above approach\nN = 4\n \n# Function to print Matrix\ndef showMatrix(mat):\n i = None\n j = None\n for i in range(N):\n for j in range(N):\n print(mat[i][j], end= \" \")\n print('')\n \n# Function to return k'th smallest element\n# in a given array\ndef kthSmallest(arr, n, K):\n \n # Sort the given array\n arr.sort()\n \n # Return k'th element\n # in the sorted array\n return arr[K - 1]\n \n# Function to replace diagonal elements\n# with Kth min element of row.\ndef ReplaceDiagonal(mat, K):\n i = None\n j = None\n arr = [0] * N\n \n for i in range(N):\n for j in range(N):\n arr[j] = mat[i][j]\n mat[i][i] = kthSmallest(arr, N, K)\n showMatrix(mat)\n \n# Utility Main function.\nmat = [[1, 2, 3, 4], [4, 2, 7, 6], [3, 5, 1, 9], [2, 4, 6, 8]]\n \nK = 3\nReplaceDiagonal(mat, K)\n \n# This code is contributed by Saurabh Jaiswal\n\n\n\n\n\n",
"e": 30322,
"s": 29405,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# code to find the maximum median\n// of a sub array having length at least K.\nusing System;\n \npublic class GFG {\n \n static int N = 4;\n \n // Function to print Matrix\n static void showMatrix(int[, ] mat)\n {\n int i, j;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n Console.Write(mat[i, j] + \" \");\n }\n Console.WriteLine();\n }\n }\n \n // Function to return k'th smallest element\n // in a given array\n static int kthSmallest(int[] arr, int n, int K)\n {\n // Sort the given array\n Array.Sort(arr);\n \n // Return k'th element\n // in the sorted array\n return arr[K - 1];\n }\n \n // Function to replace diagonal elements\n // with Kth min element of row.\n static void ReplaceDiagonal(int[, ] mat, int K)\n {\n int i, j;\n int[] arr = new int[N];\n \n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++)\n arr[j] = mat[i, j];\n mat[i, i] = kthSmallest(arr, N, K);\n }\n showMatrix(mat);\n }\n \n // Driver code\n public static void Main()\n {\n int[, ] mat = { { 1, 2, 3, 4 },\n { 4, 2, 7, 6 },\n { 3, 5, 1, 9 },\n { 2, 4, 6, 8 } };\n \n int K = 3;\n ReplaceDiagonal(mat, K);\n }\n}\n \n// This code is contributed by ukasp.\n\n\n\n\n\n",
"e": 31599,
"s": 30332,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n // JavaScript code for the above approach \n let N = 4;\n \n // Function to print Matrix\n function showMatrix(mat) {\n let i, j;\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++) {\n document.write(mat[i][j] + \" \");\n }\n document.write('<br>')\n }\n }\n \n // Function to return k'th smallest element\n // in a given array\n function kthSmallest(arr, n, K)\n {\n \n // Sort the given array\n arr.sort(function (a, b) { return a - b })\n \n // Return k'th element\n // in the sorted array\n return arr[K - 1];\n }\n \n // Function to replace diagonal elements\n // with Kth min element of row.\n function ReplaceDiagonal(mat, K) \n {\n let i, j;\n let arr = new Array(N);\n \n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++)\n arr[j] = mat[i][j];\n mat[i][i] = kthSmallest(arr, N, K);\n }\n showMatrix(mat);\n }\n \n // Utility Main function.\n let mat = [[1, 2, 3, 4],\n [4, 2, 7, 6],\n [3, 5, 1, 9],\n [2, 4, 6, 8]];\n \n let K = 3;\n ReplaceDiagonal(mat, K);\n \n // This code is contributed by Potta Lokesh\n </script>\n\n\n\n\n\n",
"e": 32989,
"s": 31609,
"text": null
},
{
"code": null,
"e": 33028,
"s": 32992,
"text": "3 2 3 4 \n4 6 7 6 \n3 5 5 9 \n2 4 6 6 "
},
{
"code": null,
"e": 33081,
"s": 33030,
"text": "Time Complexity: O(N2 * logN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33097,
"s": 33083,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 33114,
"s": 33097,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33124,
"s": 33114,
"text": "samim2000"
},
{
"code": null,
"e": 33130,
"s": 33124,
"text": "ukasp"
},
{
"code": null,
"e": 33147,
"s": 33130,
"text": "\nAlgo-Geek 2021\n"
},
{
"code": null,
"e": 33159,
"s": 33147,
"text": "\nAlgo Geek\n"
},
{
"code": null,
"e": 33168,
"s": 33159,
"text": "\nArrays\n"
},
{
"code": null,
"e": 33177,
"s": 33168,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 33382,
"s": 33177,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 33446,
"s": 33382,
"text": "Minimize cost to sort given array by sorting unsorted subarrays"
},
{
"code": null,
"e": 33486,
"s": 33446,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 33532,
"s": 33486,
"text": "Program to find simple moving average | Set-2"
},
{
"code": null,
"e": 33587,
"s": 33532,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 33684,
"s": 33587,
"text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index"
},
{
"code": null,
"e": 33699,
"s": 33684,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33715,
"s": 33699,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 33742,
"s": 33715,
"text": "Program for array rotation"
},
{
"code": null,
"e": 33790,
"s": 33742,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
ASP.NET MVC - Validation | Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.
DRY stands for Don't Repeat Yourself and is one of the core design principles of ASP.NET MVC. From the development point of view, it is encouraged to specify functionality or behavior only at one place and then it is used in the entire application from that one place.
This reduces the amount of code you need to write and makes the code you do write less error prone and easier to maintain.
Let’s take a look at a simple example of validation in our project from the last chapter. In this example, we will add data annotations to our model class, which provides some builtin set of validation attributes that can be applied to any model class or property directly in your application, such as Required, StringLength, RegularExpression, and Range validation attributes.
It also contains formatting attributes like DataType that help with formatting and don't provide any validation. The validation attributes specify behavior that you want to enforce on the model properties they are applied to.
The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input.
Let’s update Employee class by adding different annotation attributes as shown in the following code.
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MVCSimpleApp.Models {
public class Employee{
public int ID { get; set; }
[StringLength(60, MinimumLength = 3)]
public string Name { get; set; }
[Display(Name = "Joining Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",
ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }
[Range(22, 60)]
public int Age { get; set; }
}
}
Now we also need to set limits to the database. However, the database in SQL Server Object Explorer shows the name property is set to NVARCHAR (MAX) as seen in the following screenshot.
To set this limitation on the database, we will use migrations to update the schema.
Open the Package Manager Console window from Tools → NuGet Package Manager → Package Manager Console.
Enter the following commands one by one in the Package Manager Console window.
Enable-Migrations
add-migration DataAnnotations
update-database
Following is the log after executing these commands in Package Manager Console window.
Visual Studio will also open the class which is derived from the DbMIgration class in which you can see the code that updates the schema constraints in Up method.
namespace MVCSimpleApp.Migrations {
using System;
using System.Data.Entity.Migrations;
public partial class DataAnnotations : DbMigration{
public override void Up(){
AlterColumn("dbo.Employees", "Name", c => c.String(maxLength: 60));
}
public override void Down(){
AlterColumn("dbo.Employees", "Name", c => c.String());
}
}
}
The Name field has a maximum length of 60, which is the new length limits in the database as shown in the following snapshot.
Run this application and go to Create view by specifying the following URL http://localhost:63004/Employees/Create
Let’s enter some invalid data in these fields and click Create Button as shown in the following screenshot.
You will see that jQuery client side validation detects the error, and it also displays an error message.
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": 2563,
"s": 2269,
"text": "Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user."
},
{
"code": null,
"e": 2832,
"s": 2563,
"text": "DRY stands for Don't Repeat Yourself and is one of the core design principles of ASP.NET MVC. From the development point of view, it is encouraged to specify functionality or behavior only at one place and then it is used in the entire application from that one place."
},
{
"code": null,
"e": 2955,
"s": 2832,
"text": "This reduces the amount of code you need to write and makes the code you do write less error prone and easier to maintain."
},
{
"code": null,
"e": 3333,
"s": 2955,
"text": "Let’s take a look at a simple example of validation in our project from the last chapter. In this example, we will add data annotations to our model class, which provides some builtin set of validation attributes that can be applied to any model class or property directly in your application, such as Required, StringLength, RegularExpression, and Range validation attributes."
},
{
"code": null,
"e": 3559,
"s": 3333,
"text": "It also contains formatting attributes like DataType that help with formatting and don't provide any validation. The validation attributes specify behavior that you want to enforce on the model properties they are applied to."
},
{
"code": null,
"e": 3807,
"s": 3559,
"text": "The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input."
},
{
"code": null,
"e": 3909,
"s": 3807,
"text": "Let’s update Employee class by adding different annotation attributes as shown in the following code."
},
{
"code": null,
"e": 4454,
"s": 3909,
"text": "using System;\nusing System.ComponentModel.DataAnnotations;\nusing System.Data.Entity;\n\nnamespace MVCSimpleApp.Models {\n public class Employee{\n public int ID { get; set; }\n [StringLength(60, MinimumLength = 3)]\n\t\t\n public string Name { get; set; }\n [Display(Name = \"Joining Date\")]\n [DataType(DataType.Date)]\n [DisplayFormat(DataFormatString = \"{0:yyyy-MM-dd}\",\n\t\t\n ApplyFormatInEditMode = true)]\n public DateTime JoiningDate { get; set; }\n [Range(22, 60)]\n public int Age { get; set; }\n }\n}"
},
{
"code": null,
"e": 4640,
"s": 4454,
"text": "Now we also need to set limits to the database. However, the database in SQL Server Object Explorer shows the name property is set to NVARCHAR (MAX) as seen in the following screenshot."
},
{
"code": null,
"e": 4725,
"s": 4640,
"text": "To set this limitation on the database, we will use migrations to update the schema."
},
{
"code": null,
"e": 4827,
"s": 4725,
"text": "Open the Package Manager Console window from Tools → NuGet Package Manager → Package Manager Console."
},
{
"code": null,
"e": 4906,
"s": 4827,
"text": "Enter the following commands one by one in the Package Manager Console window."
},
{
"code": null,
"e": 4971,
"s": 4906,
"text": "Enable-Migrations\nadd-migration DataAnnotations\nupdate-database\n"
},
{
"code": null,
"e": 5058,
"s": 4971,
"text": "Following is the log after executing these commands in Package Manager Console window."
},
{
"code": null,
"e": 5221,
"s": 5058,
"text": "Visual Studio will also open the class which is derived from the DbMIgration class in which you can see the code that updates the schema constraints in Up method."
},
{
"code": null,
"e": 5606,
"s": 5221,
"text": "namespace MVCSimpleApp.Migrations {\n using System;\n using System.Data.Entity.Migrations;\n\t\n public partial class DataAnnotations : DbMigration{\n public override void Up(){\n AlterColumn(\"dbo.Employees\", \"Name\", c => c.String(maxLength: 60));\n }\n\t\t\n public override void Down(){\n AlterColumn(\"dbo.Employees\", \"Name\", c => c.String());\n }\n }\n}"
},
{
"code": null,
"e": 5732,
"s": 5606,
"text": "The Name field has a maximum length of 60, which is the new length limits in the database as shown in the following snapshot."
},
{
"code": null,
"e": 5847,
"s": 5732,
"text": "Run this application and go to Create view by specifying the following URL http://localhost:63004/Employees/Create"
},
{
"code": null,
"e": 5955,
"s": 5847,
"text": "Let’s enter some invalid data in these fields and click Create Button as shown in the following screenshot."
},
{
"code": null,
"e": 6061,
"s": 5955,
"text": "You will see that jQuery client side validation detects the error, and it also displays an error message."
},
{
"code": null,
"e": 6096,
"s": 6061,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6110,
"s": 6096,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6145,
"s": 6110,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6168,
"s": 6145,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6202,
"s": 6168,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6222,
"s": 6202,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6257,
"s": 6222,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6274,
"s": 6257,
"text": " University Code"
},
{
"code": null,
"e": 6309,
"s": 6274,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6326,
"s": 6309,
"text": " University Code"
},
{
"code": null,
"e": 6360,
"s": 6326,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6375,
"s": 6360,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6382,
"s": 6375,
"text": " Print"
},
{
"code": null,
"e": 6393,
"s": 6382,
"text": " Add Notes"
}
] |
Create a form that uses the horizontal layout with Bootstrap | To create a horizontal layout in Bootstrap, use the form-horizontal class.
You can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name = "viewport" content = "width=device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<form class = "form-horizontal" role = "form">
<div class = "form-group">
<label for = "name" class = "col-sm-2 control-label">Name</label>
<div class = "col-sm-10">
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
</div>
</div>
<div class = "form-group">
<label for = "country" class = "col-sm-2 control-label">Country</label>
<div class = "col-sm-10">
<input type = "text" class = "form-control" id = "country" placeholder = "Enter Country">
</div>
</div>
<div class = "form-group">
<div class = "col-sm-offset-2 col-sm-10">
<button type = "submit" class = "btn btn-default">Sign in</button>
</div>
</div>
</form>
</body>
</html> | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To create a horizontal layout in Bootstrap, use the form-horizontal class."
},
{
"code": null,
"e": 1177,
"s": 1137,
"text": "You can try to run the following code −"
},
{
"code": null,
"e": 1187,
"s": 1177,
"text": "Live Demo"
},
{
"code": null,
"e": 2552,
"s": 1187,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form class = \"form-horizontal\" role = \"form\">\n <div class = \"form-group\">\n <label for = \"name\" class = \"col-sm-2 control-label\">Name</label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"name\" placeholder = \"Enter Name\">\n </div>\n </div>\n <div class = \"form-group\">\n <label for = \"country\" class = \"col-sm-2 control-label\">Country</label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"country\" placeholder = \"Enter Country\">\n </div>\n </div>\n <div class = \"form-group\">\n <div class = \"col-sm-offset-2 col-sm-10\">\n <button type = \"submit\" class = \"btn btn-default\">Sign in</button>\n </div>\n </div>\n </form>\n </body>\n</html>"
}
] |
A Simple and Scalable Analytics Pipeline | by Ben Weber | Towards Data Science | Gathering data about application usage and user behavior such as player progress in games is invaluable for product teams. Typically, entire teams have been dedicated to building and maintaining data pipelines for collecting and storing tracking data for applications. However, with many new serverless tools available, the barriers to building an analytics pipeline for collecting data about application usage have been significantly reduced. Managed tools such as Google’s PubSub, DataFlow, and BigQuery have made it possible for a small team to set up analytics pipelines that can scale to a huge volume of events, while requiring minimal operational overhead. This post describes how to build a lightweight analytics pipeline on the Google Cloud platform (GCP) that is fully-managed (serverless) and auto scales to meet demand.
I was inspired by Google’s reference architecture for mobile game analytics. The goal of this post is to show that it’s possible for a small team to build and maintain a data pipeline that scales to large event volumes, provides a data lake for data science tasks, provides a query environment for analytics teams, and has extensibility for additional components such as an experiment framework for applications.
The core piece of technology I’m using to implement this data pipeline is Google’s DataFlow, which is now integrated with the Apache Beam library. DataFlow tasks define a graph of operations to perform on a collection of events, which can be streaming data sources. This post presents a DataFlow task implemented in Java that streams tracking events from a PubSub topic to a data lake and to BigQuery. An introduction to DataFlow and it’s concepts is available in Google’s documentation. While DataFlow tasks are portable, since they are now based on Apache Beam, this post focuses on how to use DataFlow in conjunction with additional managed services on GCP to build a simple, serverless, and scalable data pipeline.
The data pipeline that performs all of this functionality is relatively simple. The pipeline reads messages from PubSub and then transforms the events for persistence: the BigQuery portion of the pipeline converts messages to TableRow objects and streams directly to BigQuery, while the AVRO portion of the pipeline batches events into discrete windows and then saves the events to Google Storage. The graph of operations is shown in the figure below.
The first step in building a data pipeline is setting up the dependencies necessary to compile and deploy the project. I used the following maven dependencies to set up environments for the tracking API that sends events to the pipeline, and the data pipeline that processes events.
<!-- Dependencies for the Tracking API -><dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> <version>0.32.0-beta</version> </dependency></dependencies><!-- Dependencies for the data pipeline -><dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version></dependency>
I used Eclipse to author and compile the code for this tutorial, since it is open source. However, other IDEs such as IntelliJ provide additional features for deploying and monitoring DataFlow tasks. Before you can deploy jobs to Google Cloud, you’ll need to set up a service account for both PubSub and DataFlow. Setting up these credentials is outside the scope of this post, and more details are available in the Google documentation.
An additional prerequisite for running this data pipeline is setting up a PubSub topic on GCP. I defined a raw-events topic that is used for publishing and consuming messages for the data pipeline. Additional details on creating a PubSub topic are available here.
To deploy this data pipeline, you’ll need to set up a java environment with the maven dependencies listed above, set up a Google Cloud project and enable billing, enable billing on the storage and BigQuery services, and create a PubSub topic for sending and receiving messages. All of these managed services do cost money, but there is a free tier that can be used for prototyping a data pipeline.
In order to build a usable data pipeline, it’s useful to build APIs that encapsulate the details of sending event data. The Tracking API class provides this functionality, and can be used to send generated event data to the data pipeline. The code below shows the method signature for sending events, and shows how to generate sample data.
/** Event Signature for the Tracking API public void sendEvent(String eventType, String eventVersion, HashMap<String, String> attributes);*/// send a batch of events for (int i=0; i<10000; i++) { // generate event names String eventType = Math.random() < 0.5 ? "Session" : (Math.random() < 0.5 ? "Login" : "MatchStart"); // create attributes to send HashMap<String, String> attributes = new HashMap<String,String>(); attributes.put("userID", "" + (int)(Math.random()*10000)); attributes.put("deviceType", Math.random() < 0.5 ? "Android" : (Math.random() < 0.5 ? "iOS" : "Web")); // send the event tracking.sendEvent(eventType, "V1", attributes); }
The tracking API establishes a connection to a PubSub topic, passes events as a JSON format, and implements a callback for notification of delivery failures. The code used to send events is provided below, and is based on Google’s PubSub example provided here.
// Setup a PubSub connection TopicName topicName = TopicName.of(projectID, topicID);Publisher publisher = Publisher.newBuilder(topicName).build();// Specify an event to sendString event = {\"eventType\":\"session\",\"eventVersion\":\"1\"}";// Convert the event to bytes ByteString data = ByteString.copyFromUtf8(event.toString());//schedule a message to be published PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();// publish the message, and add this class as a callback listenerApiFuture<String> future = publisher.publish(pubsubMessage); ApiFutures.addCallback(future, this);
The code above enables apps to send events to a PubSub topic. The next step is to process this events in a fully-managed environment that can scale as necessary to meet demand.
One of the key functions of a data pipeline is to make instrumented events available to data science and analytics teams for analysis. The data sources used as endpoints should have low latency and be able to scale up to a massive volume of events. The data pipeline defined in this tutorial shows how to output events to both BigQuery and a data lake that can be used to support a large number of analytics business users.
The first step in this data pipeline is reading events from a PubSub topic and passing ingested messages to the DataFlow process. DataFlow provides a PubSub connector that enables streaming of PubSub messages to other DataFlow components. The code below shows how to instantiate the data pipeline, specify streaming mode, and to consume messages from a specific PubSub topic. The output of this process is a collection of PubSub messages that can be stored for later analysis.
// set up pipeline options Options options = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); options.setStreaming(true); Pipeline pipeline = Pipeline.create(options);// read game events from PubSub PCollection<PubsubMessage> events = pipeline .apply(PubsubIO.readMessages().fromTopic(topic));
The first way we want to store events is in a columnar format that can be used to build a data lake. While this post doesn’t show how to utilize these files in downstream ETLs, having a data lake is a great way to maintain a copy of your data set in case you need to make changes to your database. The data lake provides a way to backload your data if necessary due to changes in schemas or data ingestion issues. The portion of the data pipeline allocated to this process is shown below.
For AVRO, we can’t use a direct streaming approach. We need to group events into batches before we can save to flat files. The way this can be accomplished in DataFlow is by applying a windowing function that groups events into fixed batches. The code below applies transformations that convert the PubSub messages into String objects, group the messages into 5 minute intervals, and output the resulting batches to AVRO files on Google Storage.
// AVRO output portion of the pipeline events.apply("To String", ParDo.of(new DoFn<PubsubMessage, String>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); c.output(message); } }))// Batch events into 5 minute windows .apply("Batch Events", Window.<String>into( FixedWindows.of(Duration.standardMinutes(5))) .triggering(AfterWatermark.pastEndOfWindow()) .discardingFiredPanes() .withAllowedLateness(Duration.standardMinutes(5))) // Save the events in ARVO format .apply("To AVRO", AvroIO.write(String.class) .to("gs://your_gs_bucket/avro/raw-events.avro") .withWindowedWrites() .withNumShards(8) .withSuffix(".avro"));
To summarize, the above code batches events into 5 minute windows and then exports the events to AVRO files on Google Storage.
The result of this portion of the data pipeline is a collection of AVRO files on google storage that can be used to build a data lake. A new AVRO output is generated every 5 minutes, and downstream ETLs can parse the raw events into processed event-specific table schemas. The image below shows a sample output of AVRO files.
In addition to creating a data lake, we want the events to be immediately accessible in a query environment. DataFlow provides a BigQuery connector which serves this functionality, and data streamed to this endpoint is available for analysis after a short duration. This portion of the data pipeline is shown in the figure below.
The data pipeline converts the PubSub messages into TableRow objects, which can be directly inserted into BigQuery. The code below consists of two apply methods: a data transformation and a IO writer. The transform step reads the message payloads from PubSub, parses the message as a JSON object, extracts the eventType and eventVersion attributes, and creates a TableRow object with these attributes in addition to a timestamp and the message payload. The second apply method tells the pipeline to write the records to BigQuery and to append the events to an existing table.
// parse the PubSub events and create rows to insert into BigQuery events.apply("To Table Rows", new PTransform<PCollection<PubsubMessage>, PCollection<TableRow>>() { public PCollection<TableRow> expand( PCollection<PubsubMessage> input) { return input.apply("To Predictions", ParDo.of(new DoFn<PubsubMessage, TableRow>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the json message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get("eventType").getAsString(); String eventVersion = jsonObject. get("eventVersion").getAsString(); String serverTime = dateFormat.format(new Date()); // create and output the table row TableRow record = new TableRow(); record.set("eventType", eventType); record.set("eventVersion", eventVersion); record.set("serverTime", serverTime); record.set("message", message); c.output(record); }})); }}) //stream the events to Big Query .apply("To BigQuery",BigQueryIO.writeTableRows() .to(table) .withSchema(schema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND));
To summarize the above code, each message that is consumed from PubSub is converted into a TableRow object with a timestamp and then streamed to BigQuery for storage.
The result of this portion of the data pipeline is that events will be streamed to BigQuery and will be available for analysis in the output table specified by the DataFlow task. In order to effectively use these events for queries, you’ll need to build additional ETLs for creating processed event tables with schematized records, but you now have a data collection mechanism in place for storing tracking events.
With DataFlow you can test the data pipeline locally or deploy to the cloud. If you run the code samples without specifying additional attributes, then the data pipeline will execute on your local machine. In order to deploy to the cloud and take advantage of the auto scaling capabilities of this data pipeline, you need to specify a new runner class as part of your runtime arguments. In order to run the data pipeline, I used the following runtime arguments:
--runner=org.apache.beam.runners.dataflow.DataflowRunner --jobName=game-analytics--project=your_project_id --tempLocation=gs://temp-bucket
Once the job is deployed, you should see a message that the job has been submitted. You can then click on the DataFlow console to see the task:
The runtime configuration specified above will not default to an auto scaling configuration. In order to deploy a job that scales up based on demand, you’ll need to specify additional attributes, such as:
--autoscalingAlgorithm=THROUGHPUT_BASED--maxNumWorkers=30
Additional details on setting up a DataFlow task to scale to heavy workload conditions are available in this Google article and this post from Spotify. The image below shows how DataFlow can scale up to meet demand as necessary.
There is now a variety of tools available that make it possible to set up an analytics pipeline for a game or web application with minimal effort. Using managed resources enables small teams to take advantage of serverless and autoscaling infrastructure to scale up to massive event volumes with minimal infrastructure management. Rather than using a data vendor’s off-the-shelf solution for collecting data, you can record all relevant data for your app.
The goal of this post was to show how a data lake and query environment can be set up using the GCP stack. While the approach presented here isn’t directly portable to other clouds, the Apache Beam library used to implement the core functionality of this data pipeline is portable and similar tools can be leveraged to build scalable data pipelines on other cloud providers.
This architecture is a minimal implementation of an event collection system that is useful for analytics and data science teams. In order to meet the demands of most analytics teams, the raw events will need to be transformed into processed and cooked events in order to meet business needs. This discussion is outside the scope of this post, but the analytics foundation should now be in place for building out a highly effective data platform.
The full source code for this sample pipeline is available on Github:
github.com
Ben Weber is the lead data scientist at Windfall Data, where our mission is to build the most accurate and comprehensive model of net worth. The Windfall team is growing and is hiring engineers and data scientists. | [
{
"code": null,
"e": 1004,
"s": 172,
"text": "Gathering data about application usage and user behavior such as player progress in games is invaluable for product teams. Typically, entire teams have been dedicated to building and maintaining data pipelines for collecting and storing tracking data for applications. However, with many new serverless tools available, the barriers to building an analytics pipeline for collecting data about application usage have been significantly reduced. Managed tools such as Google’s PubSub, DataFlow, and BigQuery have made it possible for a small team to set up analytics pipelines that can scale to a huge volume of events, while requiring minimal operational overhead. This post describes how to build a lightweight analytics pipeline on the Google Cloud platform (GCP) that is fully-managed (serverless) and auto scales to meet demand."
},
{
"code": null,
"e": 1417,
"s": 1004,
"text": "I was inspired by Google’s reference architecture for mobile game analytics. The goal of this post is to show that it’s possible for a small team to build and maintain a data pipeline that scales to large event volumes, provides a data lake for data science tasks, provides a query environment for analytics teams, and has extensibility for additional components such as an experiment framework for applications."
},
{
"code": null,
"e": 2136,
"s": 1417,
"text": "The core piece of technology I’m using to implement this data pipeline is Google’s DataFlow, which is now integrated with the Apache Beam library. DataFlow tasks define a graph of operations to perform on a collection of events, which can be streaming data sources. This post presents a DataFlow task implemented in Java that streams tracking events from a PubSub topic to a data lake and to BigQuery. An introduction to DataFlow and it’s concepts is available in Google’s documentation. While DataFlow tasks are portable, since they are now based on Apache Beam, this post focuses on how to use DataFlow in conjunction with additional managed services on GCP to build a simple, serverless, and scalable data pipeline."
},
{
"code": null,
"e": 2588,
"s": 2136,
"text": "The data pipeline that performs all of this functionality is relatively simple. The pipeline reads messages from PubSub and then transforms the events for persistence: the BigQuery portion of the pipeline converts messages to TableRow objects and streams directly to BigQuery, while the AVRO portion of the pipeline batches events into discrete windows and then saves the events to Google Storage. The graph of operations is shown in the figure below."
},
{
"code": null,
"e": 2871,
"s": 2588,
"text": "The first step in building a data pipeline is setting up the dependencies necessary to compile and deploy the project. I used the following maven dependencies to set up environments for the tracking API that sends events to the pipeline, and the data pipeline that processes events."
},
{
"code": null,
"e": 3270,
"s": 2871,
"text": "<!-- Dependencies for the Tracking API -><dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-pubsub</artifactId> <version>0.32.0-beta</version> </dependency></dependencies><!-- Dependencies for the data pipeline -><dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version></dependency>"
},
{
"code": null,
"e": 3708,
"s": 3270,
"text": "I used Eclipse to author and compile the code for this tutorial, since it is open source. However, other IDEs such as IntelliJ provide additional features for deploying and monitoring DataFlow tasks. Before you can deploy jobs to Google Cloud, you’ll need to set up a service account for both PubSub and DataFlow. Setting up these credentials is outside the scope of this post, and more details are available in the Google documentation."
},
{
"code": null,
"e": 3972,
"s": 3708,
"text": "An additional prerequisite for running this data pipeline is setting up a PubSub topic on GCP. I defined a raw-events topic that is used for publishing and consuming messages for the data pipeline. Additional details on creating a PubSub topic are available here."
},
{
"code": null,
"e": 4370,
"s": 3972,
"text": "To deploy this data pipeline, you’ll need to set up a java environment with the maven dependencies listed above, set up a Google Cloud project and enable billing, enable billing on the storage and BigQuery services, and create a PubSub topic for sending and receiving messages. All of these managed services do cost money, but there is a free tier that can be used for prototyping a data pipeline."
},
{
"code": null,
"e": 4710,
"s": 4370,
"text": "In order to build a usable data pipeline, it’s useful to build APIs that encapsulate the details of sending event data. The Tracking API class provides this functionality, and can be used to send generated event data to the data pipeline. The code below shows the method signature for sending events, and shows how to generate sample data."
},
{
"code": null,
"e": 5404,
"s": 4710,
"text": "/** Event Signature for the Tracking API public void sendEvent(String eventType, String eventVersion, HashMap<String, String> attributes);*/// send a batch of events for (int i=0; i<10000; i++) { // generate event names String eventType = Math.random() < 0.5 ? \"Session\" : (Math.random() < 0.5 ? \"Login\" : \"MatchStart\"); // create attributes to send HashMap<String, String> attributes = new HashMap<String,String>(); attributes.put(\"userID\", \"\" + (int)(Math.random()*10000)); attributes.put(\"deviceType\", Math.random() < 0.5 ? \"Android\" : (Math.random() < 0.5 ? \"iOS\" : \"Web\")); // send the event tracking.sendEvent(eventType, \"V1\", attributes); }"
},
{
"code": null,
"e": 5665,
"s": 5404,
"text": "The tracking API establishes a connection to a PubSub topic, passes events as a JSON format, and implements a callback for notification of delivery failures. The code used to send events is provided below, and is based on Google’s PubSub example provided here."
},
{
"code": null,
"e": 6286,
"s": 5665,
"text": "// Setup a PubSub connection TopicName topicName = TopicName.of(projectID, topicID);Publisher publisher = Publisher.newBuilder(topicName).build();// Specify an event to sendString event = {\\\"eventType\\\":\\\"session\\\",\\\"eventVersion\\\":\\\"1\\\"}\";// Convert the event to bytes ByteString data = ByteString.copyFromUtf8(event.toString());//schedule a message to be published PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();// publish the message, and add this class as a callback listenerApiFuture<String> future = publisher.publish(pubsubMessage); ApiFutures.addCallback(future, this);"
},
{
"code": null,
"e": 6463,
"s": 6286,
"text": "The code above enables apps to send events to a PubSub topic. The next step is to process this events in a fully-managed environment that can scale as necessary to meet demand."
},
{
"code": null,
"e": 6887,
"s": 6463,
"text": "One of the key functions of a data pipeline is to make instrumented events available to data science and analytics teams for analysis. The data sources used as endpoints should have low latency and be able to scale up to a massive volume of events. The data pipeline defined in this tutorial shows how to output events to both BigQuery and a data lake that can be used to support a large number of analytics business users."
},
{
"code": null,
"e": 7364,
"s": 6887,
"text": "The first step in this data pipeline is reading events from a PubSub topic and passing ingested messages to the DataFlow process. DataFlow provides a PubSub connector that enables streaming of PubSub messages to other DataFlow components. The code below shows how to instantiate the data pipeline, specify streaming mode, and to consume messages from a specific PubSub topic. The output of this process is a collection of PubSub messages that can be stored for later analysis."
},
{
"code": null,
"e": 7698,
"s": 7364,
"text": "// set up pipeline options Options options = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); options.setStreaming(true); Pipeline pipeline = Pipeline.create(options);// read game events from PubSub PCollection<PubsubMessage> events = pipeline .apply(PubsubIO.readMessages().fromTopic(topic));"
},
{
"code": null,
"e": 8187,
"s": 7698,
"text": "The first way we want to store events is in a columnar format that can be used to build a data lake. While this post doesn’t show how to utilize these files in downstream ETLs, having a data lake is a great way to maintain a copy of your data set in case you need to make changes to your database. The data lake provides a way to backload your data if necessary due to changes in schemas or data ingestion issues. The portion of the data pipeline allocated to this process is shown below."
},
{
"code": null,
"e": 8633,
"s": 8187,
"text": "For AVRO, we can’t use a direct streaming approach. We need to group events into batches before we can save to flat files. The way this can be accomplished in DataFlow is by applying a windowing function that groups events into fixed batches. The code below applies transformations that convert the PubSub messages into String objects, group the messages into 5 minute intervals, and output the resulting batches to AVRO files on Google Storage."
},
{
"code": null,
"e": 9431,
"s": 8633,
"text": "// AVRO output portion of the pipeline events.apply(\"To String\", ParDo.of(new DoFn<PubsubMessage, String>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); c.output(message); } }))// Batch events into 5 minute windows .apply(\"Batch Events\", Window.<String>into( FixedWindows.of(Duration.standardMinutes(5))) .triggering(AfterWatermark.pastEndOfWindow()) .discardingFiredPanes() .withAllowedLateness(Duration.standardMinutes(5))) // Save the events in ARVO format .apply(\"To AVRO\", AvroIO.write(String.class) .to(\"gs://your_gs_bucket/avro/raw-events.avro\") .withWindowedWrites() .withNumShards(8) .withSuffix(\".avro\"));"
},
{
"code": null,
"e": 9558,
"s": 9431,
"text": "To summarize, the above code batches events into 5 minute windows and then exports the events to AVRO files on Google Storage."
},
{
"code": null,
"e": 9884,
"s": 9558,
"text": "The result of this portion of the data pipeline is a collection of AVRO files on google storage that can be used to build a data lake. A new AVRO output is generated every 5 minutes, and downstream ETLs can parse the raw events into processed event-specific table schemas. The image below shows a sample output of AVRO files."
},
{
"code": null,
"e": 10214,
"s": 9884,
"text": "In addition to creating a data lake, we want the events to be immediately accessible in a query environment. DataFlow provides a BigQuery connector which serves this functionality, and data streamed to this endpoint is available for analysis after a short duration. This portion of the data pipeline is shown in the figure below."
},
{
"code": null,
"e": 10790,
"s": 10214,
"text": "The data pipeline converts the PubSub messages into TableRow objects, which can be directly inserted into BigQuery. The code below consists of two apply methods: a data transformation and a IO writer. The transform step reads the message payloads from PubSub, parses the message as a JSON object, extracts the eventType and eventVersion attributes, and creates a TableRow object with these attributes in addition to a timestamp and the message payload. The second apply method tells the pipeline to write the records to BigQuery and to append the events to an existing table."
},
{
"code": null,
"e": 12277,
"s": 10790,
"text": "// parse the PubSub events and create rows to insert into BigQuery events.apply(\"To Table Rows\", new PTransform<PCollection<PubsubMessage>, PCollection<TableRow>>() { public PCollection<TableRow> expand( PCollection<PubsubMessage> input) { return input.apply(\"To Predictions\", ParDo.of(new DoFn<PubsubMessage, TableRow>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { String message = new String(c.element().getPayload()); // parse the json message for attributes JsonObject jsonObject = new JsonParser().parse(message).getAsJsonObject(); String eventType = jsonObject.get(\"eventType\").getAsString(); String eventVersion = jsonObject. get(\"eventVersion\").getAsString(); String serverTime = dateFormat.format(new Date()); // create and output the table row TableRow record = new TableRow(); record.set(\"eventType\", eventType); record.set(\"eventVersion\", eventVersion); record.set(\"serverTime\", serverTime); record.set(\"message\", message); c.output(record); }})); }}) //stream the events to Big Query .apply(\"To BigQuery\",BigQueryIO.writeTableRows() .to(table) .withSchema(schema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND));"
},
{
"code": null,
"e": 12444,
"s": 12277,
"text": "To summarize the above code, each message that is consumed from PubSub is converted into a TableRow object with a timestamp and then streamed to BigQuery for storage."
},
{
"code": null,
"e": 12859,
"s": 12444,
"text": "The result of this portion of the data pipeline is that events will be streamed to BigQuery and will be available for analysis in the output table specified by the DataFlow task. In order to effectively use these events for queries, you’ll need to build additional ETLs for creating processed event tables with schematized records, but you now have a data collection mechanism in place for storing tracking events."
},
{
"code": null,
"e": 13321,
"s": 12859,
"text": "With DataFlow you can test the data pipeline locally or deploy to the cloud. If you run the code samples without specifying additional attributes, then the data pipeline will execute on your local machine. In order to deploy to the cloud and take advantage of the auto scaling capabilities of this data pipeline, you need to specify a new runner class as part of your runtime arguments. In order to run the data pipeline, I used the following runtime arguments:"
},
{
"code": null,
"e": 13460,
"s": 13321,
"text": "--runner=org.apache.beam.runners.dataflow.DataflowRunner --jobName=game-analytics--project=your_project_id --tempLocation=gs://temp-bucket"
},
{
"code": null,
"e": 13604,
"s": 13460,
"text": "Once the job is deployed, you should see a message that the job has been submitted. You can then click on the DataFlow console to see the task:"
},
{
"code": null,
"e": 13809,
"s": 13604,
"text": "The runtime configuration specified above will not default to an auto scaling configuration. In order to deploy a job that scales up based on demand, you’ll need to specify additional attributes, such as:"
},
{
"code": null,
"e": 13867,
"s": 13809,
"text": "--autoscalingAlgorithm=THROUGHPUT_BASED--maxNumWorkers=30"
},
{
"code": null,
"e": 14096,
"s": 13867,
"text": "Additional details on setting up a DataFlow task to scale to heavy workload conditions are available in this Google article and this post from Spotify. The image below shows how DataFlow can scale up to meet demand as necessary."
},
{
"code": null,
"e": 14552,
"s": 14096,
"text": "There is now a variety of tools available that make it possible to set up an analytics pipeline for a game or web application with minimal effort. Using managed resources enables small teams to take advantage of serverless and autoscaling infrastructure to scale up to massive event volumes with minimal infrastructure management. Rather than using a data vendor’s off-the-shelf solution for collecting data, you can record all relevant data for your app."
},
{
"code": null,
"e": 14927,
"s": 14552,
"text": "The goal of this post was to show how a data lake and query environment can be set up using the GCP stack. While the approach presented here isn’t directly portable to other clouds, the Apache Beam library used to implement the core functionality of this data pipeline is portable and similar tools can be leveraged to build scalable data pipelines on other cloud providers."
},
{
"code": null,
"e": 15373,
"s": 14927,
"text": "This architecture is a minimal implementation of an event collection system that is useful for analytics and data science teams. In order to meet the demands of most analytics teams, the raw events will need to be transformed into processed and cooked events in order to meet business needs. This discussion is outside the scope of this post, but the analytics foundation should now be in place for building out a highly effective data platform."
},
{
"code": null,
"e": 15443,
"s": 15373,
"text": "The full source code for this sample pipeline is available on Github:"
},
{
"code": null,
"e": 15454,
"s": 15443,
"text": "github.com"
}
] |
How to turn Android device screen on and off programmatically using Kotlin? | This example demonstrates how to turn an Android device screen on and off programmatically using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<Button
android:id="@+id/btnEnable"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="enablePhone"
android:text="Enable" />
<Button
android:id="@+id/btnLock"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="lockPhone"
android:text="Lock" />
</LinearLayout>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val enableResult = 1
lateinit var deviceManger: DevicePolicyManager
lateinit var compName: ComponentName
lateinit var btnEnable: Button
lateinit var btnLock: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
btnEnable = findViewById(R.id.btnEnable)
btnLock = findViewById(R.id.btnLock)
deviceManger = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
compName = ComponentName(this, DeviceAdmin::class.java)
val active = deviceManger.isAdminActive(compName)
if (active) {
btnEnable.text = "Disable"
btnLock.visibility = View.VISIBLE
}
else {
btnEnable.text = "Enable"
btnLock.visibility = View.GONE
}
}
fun enablePhone(view: View) {
val active = deviceManger.isAdminActive(compName)
if (active) {
deviceManger.removeActiveAdmin(compName)
btnEnable.text = "Enable"
btnLock.visibility = View.GONE
}
else {
val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName)
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "You should enable the app!")
startActivityForResult(intent, enableResult)
}
}
fun lockPhone(view: View) {
deviceManger.lockNow()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
enableResult -> {
if (resultCode == RESULT_OK) {
btnEnable.text = "Disable"
btnLock.visibility = View.VISIBLE
}
else {
Toast.makeText(
applicationContext, "Failed!",
Toast.LENGTH_SHORT
).show()
}
return
}
}
}
}
Step 4 − Create a new Kotlin class (DeviceAdmin.kt) and add the following code −
import android.app.admin.DeviceAdminReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class DeviceAdmin : DeviceAdminReceiver() {
override fun onEnabled(context: Context, intent: Intent) {
super.onEnabled(context, intent)
Toast.makeText(context, "Enabled", Toast.LENGTH_SHORT).show()
}
override fun onDisabled(context: Context, intent: Intent) {
super.onDisabled(context, intent)
Toast.makeText(context, "Disabled", Toast.LENGTH_SHORT).show()
}
}
Step 5 − Add the following code to res/xml/policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q2">
<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>
<receiver
android:name=".DeviceAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name= "android.app.device_admin"
android:resource= "@xml/policies" />
<intent-filter>
<action android:name= "android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "This example demonstrates how to turn an Android device screen on and off programmatically using Kotlin."
},
{
"code": null,
"e": 1296,
"s": 1167,
"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": 1361,
"s": 1296,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2650,
"s": 1361,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"8dp\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:orientation=\"horizontal\">\n <Button\n android:id=\"@+id/btnEnable\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:onClick=\"enablePhone\"\n android:text=\"Enable\" />\n <Button\n android:id=\"@+id/btnLock\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:onClick=\"lockPhone\"\n android:text=\"Lock\" />\n </LinearLayout>\n</RelativeLayout>"
},
{
"code": null,
"e": 2705,
"s": 2650,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 5132,
"s": 2705,
"text": "import android.app.admin.DevicePolicyManager\nimport android.content.ComponentName\nimport android.content.Context\nimport android.content.Intent\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.Toast\nimport androidx.annotation.Nullable\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private val enableResult = 1\n lateinit var deviceManger: DevicePolicyManager\n lateinit var compName: ComponentName\n lateinit var btnEnable: Button\n lateinit var btnLock: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n btnEnable = findViewById(R.id.btnEnable)\n btnLock = findViewById(R.id.btnLock)\n deviceManger = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager\n compName = ComponentName(this, DeviceAdmin::class.java)\n val active = deviceManger.isAdminActive(compName)\n if (active) {\n btnEnable.text = \"Disable\"\n btnLock.visibility = View.VISIBLE\n }\n else {\n btnEnable.text = \"Enable\"\n btnLock.visibility = View.GONE\n }\n }\n fun enablePhone(view: View) {\n val active = deviceManger.isAdminActive(compName)\n if (active) {\n deviceManger.removeActiveAdmin(compName)\n btnEnable.text = \"Enable\"\n btnLock.visibility = View.GONE\n }\n else {\n val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)\n intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName)\n intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, \"You should enable the app!\")\n startActivityForResult(intent, enableResult)\n }\n }\n fun lockPhone(view: View) {\n deviceManger.lockNow()\n }\n override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n when (requestCode) {\n enableResult -> {\n if (resultCode == RESULT_OK) {\n btnEnable.text = \"Disable\"\n btnLock.visibility = View.VISIBLE\n }\n else {\n Toast.makeText(\n applicationContext, \"Failed!\",\n Toast.LENGTH_SHORT\n ).show()\n }\n return\n }\n }\n}\n}"
},
{
"code": null,
"e": 5213,
"s": 5132,
"text": "Step 4 − Create a new Kotlin class (DeviceAdmin.kt) and add the following code −"
},
{
"code": null,
"e": 5744,
"s": 5213,
"text": "import android.app.admin.DeviceAdminReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.widget.Toast\nclass DeviceAdmin : DeviceAdminReceiver() {\n override fun onEnabled(context: Context, intent: Intent) {\n super.onEnabled(context, intent)\n Toast.makeText(context, \"Enabled\", Toast.LENGTH_SHORT).show()\n }\n override fun onDisabled(context: Context, intent: Intent) {\n super.onDisabled(context, intent)\n Toast.makeText(context, \"Disabled\", Toast.LENGTH_SHORT).show()\n }\n}"
},
{
"code": null,
"e": 5800,
"s": 5744,
"text": "Step 5 − Add the following code to res/xml/policies.xml"
},
{
"code": null,
"e": 5990,
"s": 5800,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<device-admin xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <uses-policies>\n <force-lock />\n </uses-policies>\n</device-admin>\n"
},
{
"code": null,
"e": 6045,
"s": 5990,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 7092,
"s": 6045,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q2\">\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 <receiver\n android:name=\".DeviceAdmin\"\n android:permission=\"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android:name= \"android.app.device_admin\"\n android:resource= \"@xml/policies\" />\n <intent-filter>\n <action android:name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7441,
"s": 7092,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
Bamboolib: One of the Most Useful Python Libraries You Have Ever Seen | by Ismael Araujo | Towards Data Science | I love writing about Python libraries. If you have read any of my blogs, you might know I have written about multiple libraries. Before writing, I test some Python libraries, check their most remarkable features, and, if I like, I write about them. Usually, I try to include a few libraries in the same blog to make it more informative. However, once in a while, I find libraries that are so cool that deserve their own blog. That’s the case for Bamboolib!
Bamboolib is one of those libraries that makes you think: How didn’t I know this before? Yeah, it sounds a little dramatic, but believe me, you will be surprised. Bamboolib can build the code for things that take a while to write, such as complex group by clauses. Let’s jump right in because I’m very excited to show you how it works.
Bamboolib sells itself as making any person do Data Analysis in Python without becoming a programmer or googling syntax. Based on my tests, that’s true! It requires zero coding skills. However, I see how it could be handy for people running short in time or for someone who doesn’t want to type long codes for simple tasks. I can also see how people learning Python can take advantage of it. For example, if you want to learn how to do something in Python, you can use Bamboolib, check the code it generates, and learn from it.
Either way, let’s explore how you can use it, and you can decide if it can be helpful for you or not. Let’s get started!
Installing Bamboolib is simple. I have written about different ways to install it in this blog, showing how to create an environment before installing Bamboolib. If you are not in the mood to create a new environment, you can just type pip install — upgrade bamboolib — user in your terminal, and it will work just fine. Now you can import it to a Jupyter Notebook by typing import bamboolib as bam, and we are good to go.
Now, we will need a dataset. I will use the All Video Games Sales dataset because it seems fun, but you can use anything you like. Once you have downloaded your dataset, let’s import it, and that’s when we can start using Bamboolib.
Remember that I said that Bamboolib doesn’t require coding? I’m serious about it. To import a dataset to your Jupyter Notebook, type bam, and it will show you a UI where you can import your dataset with three clicks.
Type bam > Read CSV file > Navigate to your file > Choose the file name > Open CSV file
Note that Bamboolib imported Pandas and created the code for you. And yeah, it will work like this throughout the whole project.
You loaded the data and realized that the date column is a string. Then, click on the column type (the little letter on the side of the column name), select the new datatype, the format, choose a new name if you want to, and click in execute.
Did you see that more code was added in the cell as well?
Also, it seems like the user_review column is an object. Let’s fix this by creating an integer.
Remember that I said that the little letter on the side of the column name is the column datatype? If you look at the letter on the side of user_review column name, you will see an f instead of i as in integer, even though I changed the datatype to be an integer. That’s because Bamboolib understood the datatype as float, so instead of throwing an error, it just fixed it for you.
Instead of changing the column datatype and name, what if you need a new column with a different datatype and name? Just click on the column datatype, select the new format and name, and click in execute. You will see the new column in the dataset immediately.
In the image below, I selected the meta_score column, changed the datatype to float, chose a new name, and the new column was created.
If you realize that you don’t need a column, just search for drop in the Search transformations box, select drop, choose the column you want to drop, and click in execute.
Now you need to rename a column, and it can’t be any easier. Just search for rename, choose the column you want to rename, write the new column name, and click execute. You can select as many columns as you wish.
Let’s say you need to split a column with people’s names into two columns, one with the first name and another one with the last name. You can easily do that. I’m splitting the game’s name for demonstration purposes, which doesn’t really make sense, but you can see how it works.
Just type split in the Search transformation box, choose the column you want to split, the separator, and the maximum of columns you want to have. Boom!
Since this was just a demonstration, let’s drop the additional columns. Search for drop, select the columns you want to drop, and click in execute.
And then, we can select to visualize only a few columns. Here I will select the game name, the platform, and the score. Just type select in the Search transformation, choose the columns you want to select and execute.
At the end of these steps, Bamboolib create the following code that someone could use even if they don’t have Bamboolib installed. Pretty cool, right?
If you want to filter your dataset or create a new one with filtered information, you can search for filter in the Search transformation, choose what you want to filter, decide if you want to create a new dataset, and click on execute. That simple!
If you need to merge two datasets, just search for merge, select the two datasets you want to merge, the type of join, select the key column you wish to use to merge the datasets, and click in execute. You can create a new dataset or just edit the current one.
In case you want to extract a string such as the day of the week and the month from a date column, do you know the code, or would you have to Google it? Well, with Bamboolib, you don’t need either one. Just search for extract datatime property, select the date column, and choose what you want to extract.
There are multiple options for you to play around with. I must confess that I didn’t know how to do that or if that was even possible to do using Pandas... And I just learned something new.
Using group by is one of the most valuable things that you can do with Pandas. However, it can get very complex at times. Luckily, Bamboolib can make group by very intuitive and easy. Search for the group by in the Search transformation box, choose the columns you want to group, and then select the calculations you want to see.
In this example, I want to see the count and the average score of the games for each platform. Doing this, I just learned that PlayStation 4 has the lowest score average among all the platforms.
Bamboolib is a great tool to create quick data visualizations. For example, to create histograms, click on create plot, select the figure type, the x-axis, and that’s pretty much it. You just created a nice chart with four clicks.
Or you can create a box plot. The process is very similar. Nice and easy!
There are many other types of charts to explore, but the all games dataset isn’t the best option to create graphs. You can test this feature with other datasets, though. There is a lot to explore.
Bamboolib makes data exploration super easy. You can get insights from your dataset with a click. To do so, click on Explore DataFrame, and it will return information such as summary statistics with mean, median, quartiles, standard deviation, number of observations, missing values, number of positive and negative observations, and much more. It also creates charts so that you can understand the data distribution.
If you have DateTime datatypes in the dataset, it can also create charts showing how the data changed throughout the time. So instead of wasting time creating individual charts to understand a dataset, you can use this feature to get insights about it.
Phew! I’m now satisfied for having given the attention that this library deserves. And yes, I know that this is not the first blog about Bamboolib out there, but I wanted to have my take on it. There is a lot more to explore. Bamboolib has a lot of potentials to transform the way we analyze data and how we learn. I have been using Pandas for a few years, and I learned new things that we could do using Bamboolib. Thanks for reading, and I’ll see you in the next blog.
You might also like...
5 Python Libraries That You Don’t Know About, But Should4 Cool Python Libraries That You Should Know About4 Amazing Python Libraries That You Should Try Right Now | [
{
"code": null,
"e": 629,
"s": 172,
"text": "I love writing about Python libraries. If you have read any of my blogs, you might know I have written about multiple libraries. Before writing, I test some Python libraries, check their most remarkable features, and, if I like, I write about them. Usually, I try to include a few libraries in the same blog to make it more informative. However, once in a while, I find libraries that are so cool that deserve their own blog. That’s the case for Bamboolib!"
},
{
"code": null,
"e": 965,
"s": 629,
"text": "Bamboolib is one of those libraries that makes you think: How didn’t I know this before? Yeah, it sounds a little dramatic, but believe me, you will be surprised. Bamboolib can build the code for things that take a while to write, such as complex group by clauses. Let’s jump right in because I’m very excited to show you how it works."
},
{
"code": null,
"e": 1493,
"s": 965,
"text": "Bamboolib sells itself as making any person do Data Analysis in Python without becoming a programmer or googling syntax. Based on my tests, that’s true! It requires zero coding skills. However, I see how it could be handy for people running short in time or for someone who doesn’t want to type long codes for simple tasks. I can also see how people learning Python can take advantage of it. For example, if you want to learn how to do something in Python, you can use Bamboolib, check the code it generates, and learn from it."
},
{
"code": null,
"e": 1614,
"s": 1493,
"text": "Either way, let’s explore how you can use it, and you can decide if it can be helpful for you or not. Let’s get started!"
},
{
"code": null,
"e": 2037,
"s": 1614,
"text": "Installing Bamboolib is simple. I have written about different ways to install it in this blog, showing how to create an environment before installing Bamboolib. If you are not in the mood to create a new environment, you can just type pip install — upgrade bamboolib — user in your terminal, and it will work just fine. Now you can import it to a Jupyter Notebook by typing import bamboolib as bam, and we are good to go."
},
{
"code": null,
"e": 2270,
"s": 2037,
"text": "Now, we will need a dataset. I will use the All Video Games Sales dataset because it seems fun, but you can use anything you like. Once you have downloaded your dataset, let’s import it, and that’s when we can start using Bamboolib."
},
{
"code": null,
"e": 2487,
"s": 2270,
"text": "Remember that I said that Bamboolib doesn’t require coding? I’m serious about it. To import a dataset to your Jupyter Notebook, type bam, and it will show you a UI where you can import your dataset with three clicks."
},
{
"code": null,
"e": 2575,
"s": 2487,
"text": "Type bam > Read CSV file > Navigate to your file > Choose the file name > Open CSV file"
},
{
"code": null,
"e": 2704,
"s": 2575,
"text": "Note that Bamboolib imported Pandas and created the code for you. And yeah, it will work like this throughout the whole project."
},
{
"code": null,
"e": 2947,
"s": 2704,
"text": "You loaded the data and realized that the date column is a string. Then, click on the column type (the little letter on the side of the column name), select the new datatype, the format, choose a new name if you want to, and click in execute."
},
{
"code": null,
"e": 3005,
"s": 2947,
"text": "Did you see that more code was added in the cell as well?"
},
{
"code": null,
"e": 3101,
"s": 3005,
"text": "Also, it seems like the user_review column is an object. Let’s fix this by creating an integer."
},
{
"code": null,
"e": 3483,
"s": 3101,
"text": "Remember that I said that the little letter on the side of the column name is the column datatype? If you look at the letter on the side of user_review column name, you will see an f instead of i as in integer, even though I changed the datatype to be an integer. That’s because Bamboolib understood the datatype as float, so instead of throwing an error, it just fixed it for you."
},
{
"code": null,
"e": 3744,
"s": 3483,
"text": "Instead of changing the column datatype and name, what if you need a new column with a different datatype and name? Just click on the column datatype, select the new format and name, and click in execute. You will see the new column in the dataset immediately."
},
{
"code": null,
"e": 3879,
"s": 3744,
"text": "In the image below, I selected the meta_score column, changed the datatype to float, chose a new name, and the new column was created."
},
{
"code": null,
"e": 4051,
"s": 3879,
"text": "If you realize that you don’t need a column, just search for drop in the Search transformations box, select drop, choose the column you want to drop, and click in execute."
},
{
"code": null,
"e": 4264,
"s": 4051,
"text": "Now you need to rename a column, and it can’t be any easier. Just search for rename, choose the column you want to rename, write the new column name, and click execute. You can select as many columns as you wish."
},
{
"code": null,
"e": 4544,
"s": 4264,
"text": "Let’s say you need to split a column with people’s names into two columns, one with the first name and another one with the last name. You can easily do that. I’m splitting the game’s name for demonstration purposes, which doesn’t really make sense, but you can see how it works."
},
{
"code": null,
"e": 4697,
"s": 4544,
"text": "Just type split in the Search transformation box, choose the column you want to split, the separator, and the maximum of columns you want to have. Boom!"
},
{
"code": null,
"e": 4845,
"s": 4697,
"text": "Since this was just a demonstration, let’s drop the additional columns. Search for drop, select the columns you want to drop, and click in execute."
},
{
"code": null,
"e": 5063,
"s": 4845,
"text": "And then, we can select to visualize only a few columns. Here I will select the game name, the platform, and the score. Just type select in the Search transformation, choose the columns you want to select and execute."
},
{
"code": null,
"e": 5214,
"s": 5063,
"text": "At the end of these steps, Bamboolib create the following code that someone could use even if they don’t have Bamboolib installed. Pretty cool, right?"
},
{
"code": null,
"e": 5463,
"s": 5214,
"text": "If you want to filter your dataset or create a new one with filtered information, you can search for filter in the Search transformation, choose what you want to filter, decide if you want to create a new dataset, and click on execute. That simple!"
},
{
"code": null,
"e": 5724,
"s": 5463,
"text": "If you need to merge two datasets, just search for merge, select the two datasets you want to merge, the type of join, select the key column you wish to use to merge the datasets, and click in execute. You can create a new dataset or just edit the current one."
},
{
"code": null,
"e": 6030,
"s": 5724,
"text": "In case you want to extract a string such as the day of the week and the month from a date column, do you know the code, or would you have to Google it? Well, with Bamboolib, you don’t need either one. Just search for extract datatime property, select the date column, and choose what you want to extract."
},
{
"code": null,
"e": 6220,
"s": 6030,
"text": "There are multiple options for you to play around with. I must confess that I didn’t know how to do that or if that was even possible to do using Pandas... And I just learned something new."
},
{
"code": null,
"e": 6550,
"s": 6220,
"text": "Using group by is one of the most valuable things that you can do with Pandas. However, it can get very complex at times. Luckily, Bamboolib can make group by very intuitive and easy. Search for the group by in the Search transformation box, choose the columns you want to group, and then select the calculations you want to see."
},
{
"code": null,
"e": 6745,
"s": 6550,
"text": "In this example, I want to see the count and the average score of the games for each platform. Doing this, I just learned that PlayStation 4 has the lowest score average among all the platforms."
},
{
"code": null,
"e": 6976,
"s": 6745,
"text": "Bamboolib is a great tool to create quick data visualizations. For example, to create histograms, click on create plot, select the figure type, the x-axis, and that’s pretty much it. You just created a nice chart with four clicks."
},
{
"code": null,
"e": 7050,
"s": 6976,
"text": "Or you can create a box plot. The process is very similar. Nice and easy!"
},
{
"code": null,
"e": 7247,
"s": 7050,
"text": "There are many other types of charts to explore, but the all games dataset isn’t the best option to create graphs. You can test this feature with other datasets, though. There is a lot to explore."
},
{
"code": null,
"e": 7665,
"s": 7247,
"text": "Bamboolib makes data exploration super easy. You can get insights from your dataset with a click. To do so, click on Explore DataFrame, and it will return information such as summary statistics with mean, median, quartiles, standard deviation, number of observations, missing values, number of positive and negative observations, and much more. It also creates charts so that you can understand the data distribution."
},
{
"code": null,
"e": 7918,
"s": 7665,
"text": "If you have DateTime datatypes in the dataset, it can also create charts showing how the data changed throughout the time. So instead of wasting time creating individual charts to understand a dataset, you can use this feature to get insights about it."
},
{
"code": null,
"e": 8389,
"s": 7918,
"text": "Phew! I’m now satisfied for having given the attention that this library deserves. And yes, I know that this is not the first blog about Bamboolib out there, but I wanted to have my take on it. There is a lot more to explore. Bamboolib has a lot of potentials to transform the way we analyze data and how we learn. I have been using Pandas for a few years, and I learned new things that we could do using Bamboolib. Thanks for reading, and I’ll see you in the next blog."
},
{
"code": null,
"e": 8412,
"s": 8389,
"text": "You might also like..."
}
] |
Displaying XML Using XSLT - GeeksforGeeks | 13 May, 2021
XSLT stands for Extensible Stylesheet Language Transformation.
XSLT is used to transform XML document from one form to another form.
XSLT uses Xpath to perform matching of nodes to perform these transformation .
The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspective.
The XSL code is written within the XML document with the extension of (.xsl).
In other words, an XSLT document is a different kind of XML document.
XML Namespace: XML Namespaces are the unique names .
XML Namespace is a mechanism by which element or attribute is assigned to a group.
XML Namespace is used to avoid the name conflicts in the XML document.
XML Namespace is recommended by W3C.
XML Namespace Declaration:It is declared using reserved attribute such as the attribute is xmlns or it can begin with xmlns:
Syntax: <element xmlns:name = "URL">whereNamespace starts with the xmlns.The word name is the namespace prefix.the URL is the namespace identifier.
<element xmlns:name = "URL">
where
Namespace starts with the xmlns.
The word name is the namespace prefix.
the URL is the namespace identifier.
Example:Consider the following xml document named Table.xml :-<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="rule.css"?> <tables> <table> <tr> <td>Apple</td> <td>Banana</td> </tr> </table> <table> <height>100</height> <width>150</width> </table> </tables>In the above code, there would be a name conflict, both of them contain the same table element but the contents of the table element are different.To handle this situation, the concept of XML Namespace is used.
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="rule.css"?> <tables> <table> <tr> <td>Apple</td> <td>Banana</td> </tr> </table> <table> <height>100</height> <width>150</width> </table> </tables>
In the above code, there would be a name conflict, both of them contain the same table element but the contents of the table element are different.To handle this situation, the concept of XML Namespace is used.
Example:Consider the same XML document to resolve name conflict:<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="rule.css"?> <tables> <m:table xmlns:m=""http://www.google.co.in"> <m:tr> <m:td>Apple</m:td> <m:td>Banana</m:td> </m:tr> </m:table> <n:table xmlns:m=""http://www.yahoo.co.in"> <n:height>100</n:height> <n:width>150</n:width> </n:table> </tables>
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/css" href="rule.css"?> <tables> <m:table xmlns:m=""http://www.google.co.in"> <m:tr> <m:td>Apple</m:td> <m:td>Banana</m:td> </m:tr> </m:table> <n:table xmlns:m=""http://www.yahoo.co.in"> <n:height>100</n:height> <n:width>150</n:width> </n:table> </tables>
Xpath:
Xpath is an important component of XSLT standard.
Xpath is used to traverse the element and attributes of an XML document.
Xpath uses different types of expression to retrieve relevant information from the XML document.
Xpath contains a library of standard functions.Example:bookstore/book[1] => Fetches details of first child of bookstore element.bookstore/book[last()] => Fetches details of last child of bookstore element.
bookstore/book[1] => Fetches details of first child of bookstore element.
bookstore/book[last()] => Fetches details of last child of bookstore element.
Templates:
An XSL stylesheet contains one or more set of rules that are called templates.
A template contains rules that are applied when the specific element is matched.
An XSLT document has the following things:The root element of the stylesheet.A file of extension .xsl .The syntax of XSLT i.e what is allowed and what is not allowed.The standard namespace whose URL is http://www.w3.org/1999/XSL/Transform.
The root element of the stylesheet.
A file of extension .xsl .
The syntax of XSLT i.e what is allowed and what is not allowed.
The standard namespace whose URL is http://www.w3.org/1999/XSL/Transform.
Example:In this example, creating the XML file that contains the information about five students and displaying the XML file using XSLT.
XML file:Creating Students.xml as:<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl "href="Rule.xsl" ?> <student> <s> <name> Divyank Singh Sikarwar </name> <branch> CSE</branch> <age>18</age> <city> Agra </city> </s> <s> <name> Aniket Chauhan </name> <branch> CSE</branch> <age> 20</age> <city> Shahjahanpur </city> </s> <s> <name> Simran Agarwal</name> <branch> CSE</branch> <age> 23</age> <city> Buland Shar</city> </s> <s> <name> Abhay Chauhan</name> <branch> CSE</branch> <age> 17</age> <city> Shahjahanpur</city> </s> <s> <name> Himanshu Bhatia</name> <branch> IT</branch> <age> 25</age> <city> Indore</city> </s> </student>In the above example, Students.xml is created and linking it with Rule.xsl which contains the corresponding XSL style sheet rules.
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl "href="Rule.xsl" ?> <student> <s> <name> Divyank Singh Sikarwar </name> <branch> CSE</branch> <age>18</age> <city> Agra </city> </s> <s> <name> Aniket Chauhan </name> <branch> CSE</branch> <age> 20</age> <city> Shahjahanpur </city> </s> <s> <name> Simran Agarwal</name> <branch> CSE</branch> <age> 23</age> <city> Buland Shar</city> </s> <s> <name> Abhay Chauhan</name> <branch> CSE</branch> <age> 17</age> <city> Shahjahanpur</city> </s> <s> <name> Himanshu Bhatia</name> <branch> IT</branch> <age> 25</age> <city> Indore</city> </s> </student>
In the above example, Students.xml is created and linking it with Rule.xsl which contains the corresponding XSL style sheet rules.
XSLT Code:Creating Rule.xsl as:<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"> <html> <body> <h1 align="center">Students' Basic Details</h1> <table border="3" align="center" > <tr> <th>Name</th> <th>Branch</th> <th>Age</th> <th>City</th> </tr> <xsl:for-each select="student/s"> <tr> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="branch"/></td> <td><xsl:value-of select="age"/></td> <td><xsl:value-of select="city"/></td> </tr> </xsl:for-each> </table></body></html></xsl:template></xsl:stylesheet>
Creating Rule.xsl as:
<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"> <html> <body> <h1 align="center">Students' Basic Details</h1> <table border="3" align="center" > <tr> <th>Name</th> <th>Branch</th> <th>Age</th> <th>City</th> </tr> <xsl:for-each select="student/s"> <tr> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="branch"/></td> <td><xsl:value-of select="age"/></td> <td><xsl:value-of select="city"/></td> </tr> </xsl:for-each> </table></body></html></xsl:template></xsl:stylesheet>
Output :
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
clintra
HTML and XML
Web technologies-HTML and XML
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to Open URL in New Tab using JavaScript ?
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ? | [
{
"code": null,
"e": 23847,
"s": 23819,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 23910,
"s": 23847,
"text": "XSLT stands for Extensible Stylesheet Language Transformation."
},
{
"code": null,
"e": 23980,
"s": 23910,
"text": "XSLT is used to transform XML document from one form to another form."
},
{
"code": null,
"e": 24059,
"s": 23980,
"text": "XSLT uses Xpath to perform matching of nodes to perform these transformation ."
},
{
"code": null,
"e": 24201,
"s": 24059,
"text": "The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspective."
},
{
"code": null,
"e": 24279,
"s": 24201,
"text": "The XSL code is written within the XML document with the extension of (.xsl)."
},
{
"code": null,
"e": 24349,
"s": 24279,
"text": "In other words, an XSLT document is a different kind of XML document."
},
{
"code": null,
"e": 24402,
"s": 24349,
"text": "XML Namespace: XML Namespaces are the unique names ."
},
{
"code": null,
"e": 24485,
"s": 24402,
"text": "XML Namespace is a mechanism by which element or attribute is assigned to a group."
},
{
"code": null,
"e": 24556,
"s": 24485,
"text": "XML Namespace is used to avoid the name conflicts in the XML document."
},
{
"code": null,
"e": 24593,
"s": 24556,
"text": "XML Namespace is recommended by W3C."
},
{
"code": null,
"e": 24718,
"s": 24593,
"text": "XML Namespace Declaration:It is declared using reserved attribute such as the attribute is xmlns or it can begin with xmlns:"
},
{
"code": null,
"e": 24866,
"s": 24718,
"text": "Syntax: <element xmlns:name = \"URL\">whereNamespace starts with the xmlns.The word name is the namespace prefix.the URL is the namespace identifier."
},
{
"code": null,
"e": 24896,
"s": 24866,
"text": " <element xmlns:name = \"URL\">"
},
{
"code": null,
"e": 24902,
"s": 24896,
"text": "where"
},
{
"code": null,
"e": 24935,
"s": 24902,
"text": "Namespace starts with the xmlns."
},
{
"code": null,
"e": 24974,
"s": 24935,
"text": "The word name is the namespace prefix."
},
{
"code": null,
"e": 25011,
"s": 24974,
"text": "the URL is the namespace identifier."
},
{
"code": null,
"e": 25525,
"s": 25011,
"text": "Example:Consider the following xml document named Table.xml :-<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"rule.css\"?> <tables> <table> <tr> <td>Apple</td> <td>Banana</td> </tr> </table> <table> <height>100</height> <width>150</width> </table> </tables>In the above code, there would be a name conflict, both of them contain the same table element but the contents of the table element are different.To handle this situation, the concept of XML Namespace is used."
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"rule.css\"?> <tables> <table> <tr> <td>Apple</td> <td>Banana</td> </tr> </table> <table> <height>100</height> <width>150</width> </table> </tables>",
"e": 25767,
"s": 25525,
"text": null
},
{
"code": null,
"e": 25978,
"s": 25767,
"text": "In the above code, there would be a name conflict, both of them contain the same table element but the contents of the table element are different.To handle this situation, the concept of XML Namespace is used."
},
{
"code": null,
"e": 26381,
"s": 25978,
"text": "Example:Consider the same XML document to resolve name conflict:<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"rule.css\"?> <tables> <m:table xmlns:m=\"\"http://www.google.co.in\"> <m:tr> <m:td>Apple</m:td> <m:td>Banana</m:td> </m:tr> </m:table> <n:table xmlns:m=\"\"http://www.yahoo.co.in\"> <n:height>100</n:height> <n:width>150</n:width> </n:table> </tables>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/css\" href=\"rule.css\"?> <tables> <m:table xmlns:m=\"\"http://www.google.co.in\"> <m:tr> <m:td>Apple</m:td> <m:td>Banana</m:td> </m:tr> </m:table> <n:table xmlns:m=\"\"http://www.yahoo.co.in\"> <n:height>100</n:height> <n:width>150</n:width> </n:table> </tables>",
"e": 26720,
"s": 26381,
"text": null
},
{
"code": null,
"e": 26727,
"s": 26720,
"text": "Xpath:"
},
{
"code": null,
"e": 26777,
"s": 26727,
"text": "Xpath is an important component of XSLT standard."
},
{
"code": null,
"e": 26850,
"s": 26777,
"text": "Xpath is used to traverse the element and attributes of an XML document."
},
{
"code": null,
"e": 26947,
"s": 26850,
"text": "Xpath uses different types of expression to retrieve relevant information from the XML document."
},
{
"code": null,
"e": 27153,
"s": 26947,
"text": "Xpath contains a library of standard functions.Example:bookstore/book[1] => Fetches details of first child of bookstore element.bookstore/book[last()] => Fetches details of last child of bookstore element."
},
{
"code": null,
"e": 27227,
"s": 27153,
"text": "bookstore/book[1] => Fetches details of first child of bookstore element."
},
{
"code": null,
"e": 27305,
"s": 27227,
"text": "bookstore/book[last()] => Fetches details of last child of bookstore element."
},
{
"code": null,
"e": 27316,
"s": 27305,
"text": "Templates:"
},
{
"code": null,
"e": 27395,
"s": 27316,
"text": "An XSL stylesheet contains one or more set of rules that are called templates."
},
{
"code": null,
"e": 27476,
"s": 27395,
"text": "A template contains rules that are applied when the specific element is matched."
},
{
"code": null,
"e": 27716,
"s": 27476,
"text": "An XSLT document has the following things:The root element of the stylesheet.A file of extension .xsl .The syntax of XSLT i.e what is allowed and what is not allowed.The standard namespace whose URL is http://www.w3.org/1999/XSL/Transform."
},
{
"code": null,
"e": 27752,
"s": 27716,
"text": "The root element of the stylesheet."
},
{
"code": null,
"e": 27779,
"s": 27752,
"text": "A file of extension .xsl ."
},
{
"code": null,
"e": 27843,
"s": 27779,
"text": "The syntax of XSLT i.e what is allowed and what is not allowed."
},
{
"code": null,
"e": 27917,
"s": 27843,
"text": "The standard namespace whose URL is http://www.w3.org/1999/XSL/Transform."
},
{
"code": null,
"e": 28054,
"s": 27917,
"text": "Example:In this example, creating the XML file that contains the information about five students and displaying the XML file using XSLT."
},
{
"code": null,
"e": 28887,
"s": 28054,
"text": "XML file:Creating Students.xml as:<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/xsl \"href=\"Rule.xsl\" ?> <student> <s> <name> Divyank Singh Sikarwar </name> <branch> CSE</branch> <age>18</age> <city> Agra </city> </s> <s> <name> Aniket Chauhan </name> <branch> CSE</branch> <age> 20</age> <city> Shahjahanpur </city> </s> <s> <name> Simran Agarwal</name> <branch> CSE</branch> <age> 23</age> <city> Buland Shar</city> </s> <s> <name> Abhay Chauhan</name> <branch> CSE</branch> <age> 17</age> <city> Shahjahanpur</city> </s> <s> <name> Himanshu Bhatia</name> <branch> IT</branch> <age> 25</age> <city> Indore</city> </s> </student>In the above example, Students.xml is created and linking it with Rule.xsl which contains the corresponding XSL style sheet rules."
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/xsl \"href=\"Rule.xsl\" ?> <student> <s> <name> Divyank Singh Sikarwar </name> <branch> CSE</branch> <age>18</age> <city> Agra </city> </s> <s> <name> Aniket Chauhan </name> <branch> CSE</branch> <age> 20</age> <city> Shahjahanpur </city> </s> <s> <name> Simran Agarwal</name> <branch> CSE</branch> <age> 23</age> <city> Buland Shar</city> </s> <s> <name> Abhay Chauhan</name> <branch> CSE</branch> <age> 17</age> <city> Shahjahanpur</city> </s> <s> <name> Himanshu Bhatia</name> <branch> IT</branch> <age> 25</age> <city> Indore</city> </s> </student>",
"e": 29556,
"s": 28887,
"text": null
},
{
"code": null,
"e": 29687,
"s": 29556,
"text": "In the above example, Students.xml is created and linking it with Rule.xsl which contains the corresponding XSL style sheet rules."
},
{
"code": null,
"e": 30344,
"s": 29687,
"text": "XSLT Code:Creating Rule.xsl as:<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"/\"> <html> <body> <h1 align=\"center\">Students' Basic Details</h1> <table border=\"3\" align=\"center\" > <tr> <th>Name</th> <th>Branch</th> <th>Age</th> <th>City</th> </tr> <xsl:for-each select=\"student/s\"> <tr> <td><xsl:value-of select=\"name\"/></td> <td><xsl:value-of select=\"branch\"/></td> <td><xsl:value-of select=\"age\"/></td> <td><xsl:value-of select=\"city\"/></td> </tr> </xsl:for-each> </table></body></html></xsl:template></xsl:stylesheet>"
},
{
"code": null,
"e": 30366,
"s": 30344,
"text": "Creating Rule.xsl as:"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"/\"> <html> <body> <h1 align=\"center\">Students' Basic Details</h1> <table border=\"3\" align=\"center\" > <tr> <th>Name</th> <th>Branch</th> <th>Age</th> <th>City</th> </tr> <xsl:for-each select=\"student/s\"> <tr> <td><xsl:value-of select=\"name\"/></td> <td><xsl:value-of select=\"branch\"/></td> <td><xsl:value-of select=\"age\"/></td> <td><xsl:value-of select=\"city\"/></td> </tr> </xsl:for-each> </table></body></html></xsl:template></xsl:stylesheet>",
"e": 30992,
"s": 30366,
"text": null
},
{
"code": null,
"e": 31001,
"s": 30992,
"text": "Output :"
},
{
"code": null,
"e": 31138,
"s": 31001,
"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": 31146,
"s": 31138,
"text": "clintra"
},
{
"code": null,
"e": 31159,
"s": 31146,
"text": "HTML and XML"
},
{
"code": null,
"e": 31189,
"s": 31159,
"text": "Web technologies-HTML and XML"
},
{
"code": null,
"e": 31206,
"s": 31189,
"text": "Web Technologies"
},
{
"code": null,
"e": 31304,
"s": 31206,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31313,
"s": 31304,
"text": "Comments"
},
{
"code": null,
"e": 31326,
"s": 31313,
"text": "Old Comments"
},
{
"code": null,
"e": 31382,
"s": 31326,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 31425,
"s": 31382,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31486,
"s": 31425,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31531,
"s": 31486,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31603,
"s": 31531,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31661,
"s": 31603,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31707,
"s": 31661,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 31752,
"s": 31707,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 31802,
"s": 31752,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
A Deep Dive on Vector Autoregression in R | by Justin Eloriaga | Towards Data Science | Christopher Sims proposed the Vector Autoregression which is a multivariate linear time series model in which the endogenous variables in the system are functions of the lagged values of all endogenous variables. This allows for a simple and flexible alternative to the traditional structural system of equations. A VAR could model macroeconomic data informatively, without imposing very strong restrictions or relationships. Essentially, it is macroeconomic modeling without much of the a-priori expectations getting in the way.
VARs are very useful especially in the field of macroeconomics. It has been used widely in simulating macroeconomic shocks to the real economy and has been used heavily in policy simulations and forecasting. This is the thrust and the main use of the Vector Autoregression. Firstly, it is a sophisticated forecasting tool. We will show how VARs can be much better than standard univariate forecasting models, especially in determining the long-run. The majority of empirical studies on forecasting suggest that the VAR has already eclipsed the traditional univariate forecasting models and theory-based structural equation models.
Apart from forecasting, VARs are also useful tools for structural analysis. We note that VARs can investigate the response to shocks. It can pinpoint sources of fluctuations that traditional univariate models fail at. Moreover, VARs can help distinguish between competing theoretical models.
As we have mentioned previously, the VAR is a multivariate linear time series model where the endogenous variables in the system are functions of the lagged values of all endogenous variables. Said simply, the VAR is essentially a generalization of the univariate autoregressive model. Commonly, we notate a VAR as a VAR(p) where p denotes the number of autoregressive lags in the system. Consider a VAR system with only two variables.
We can also write this in matrix form as
The estimation of a VAR is an Equation by Equation OLS. We essentially run OLS on each equation. What we find is that estimates are consistent as only the lagged values of the endogenous variables are on the right-hand side of the equation. Moreover, estimates are also efficient in that all equations have identical regressors which minimizes the variation in each one. Doing this suggests that it is essentially equivalent to a generalized least squares. The assumption of no-serial correlation also holds in this regard.
We will now apply the numerous concepts learned in VAR in an actual example. In particular, we will be using a framework developed by Sims (1992) using Philippine data. In this model, we will be using four variables. These are the following:
Overnight Reverse Repurchase Rate (RRP) which is set by the Bangko Sentral ng Pilipinas. This is, by all accounts, the main policy rate that the Philippine central bank controls.
M1 Money Supply which can be obtained from the BSP’s website
CPI Inflation Rate which is reported monthly by the Philippine Statistics Authority and measures the relative increase in prices based on a Laspeyres price index.
Industrial Production which measures the value of all goods in the industrial sector.
We will first estimate a standard VAR which reflects a key economic response. It is believed in theory and by Sims that shocks to the nominal interest rate represent monetary policy shocks. A shock to the policy variable affects all other variables contemporaneously. The variable is affected by all the others within the period, and is order last. Lastly, the central bank only observes non-policy variables with a lag.
We start again by installing the required packages and loading them using the library() command. For this part, we need to install the “vars” package which will have a host of commands necessary for us to run the VAR and SVAR and the diagnostic tests and applications to follow. We then see the plots of each variable and judge some initial conditions such as non-stationarity.
As said, we need to install the “vars” package. Use the install.packages(“vars”) command to do this. After this, we will load this package together with our standard suite of packages and libraries for us to continue on the estimation.
install.packages("vars")library(vars)library(mFilter)library(tseries)library(TSstudio)library(forecast)library(tidyverse)
After installation and loading, it is time to load our dataset. We will use the file Sample_VAR.csv which contains the data on all the variables from January 2003 until February 2020. The data is monthly and is publicly available, obtained from the BSP and PSA. We use the read_csv() command to read the dataset and the file.choose() command to open up a dialogue box for us to select our data. In this case, we place the dataset under an object named “mp”. Name it whatever you want, if you’d like. We then use the head() command to see the first few rows of the dataset to inspect if it loaded correctly. The files and code can be found here: https://drive.google.com/drive/u/0/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn
mp <- read_csv(file.choose()) head(mp)
Next, we need to declare each variable in the dataset as a time series using the ts() command. We use the $ symbol to call a variable from the dataset. All variables start in the year 2003 with the same day and month of January 1. We set the frequency to 12 since we are dealing with monthly data.
lnIP <- ts(mp$lnIP, start = c(2003,1,1), frequency = 12)M1 <- ts(mp$M1, start = c(2003,1,1), frequency = 12)CPI <- ts(mp$CPI, start = c(2003,1,1), frequency = 12)RRP <- ts(mp$RRP, start = c(2003,1,1), frequency = 12)
We can also visualize our series using the autoplot() or ts_plot() command. As before, the ts_plot() command is a more interactive version using the plot.ly package as base.
ts_plot(lnIP)ts_plot(M1)ts_plot(CPI)ts_plot(RRP)
Again, it is important to assess whether the variables under study are stationary or not. As we have said, having stationary variables is of an ideal case in our VAR even if we can run it without these. As we have been accustomed to, let us use the tests we are familiar with. For simplicity, we will use the Phillips Perron so we would not need to specify the number of lags.
pp.test(lnIP)pp.test(M1)pp.test(CPI)pp.test(RRP)
In the estimation above, we find that all variables are non-stationary variables. Remember that a rejection of the null hypothesis suggests the data is stationary. Nevertheless, we can still run a VAR estimation using these level data. However, you may opt to difference the data and see if that provides better results and forecasts.
The time has come to formally estimate our VAR. We will first need to bind our VAR variables together to create the system. After this, we will select the optimal lag order behind the VAR we will be using. We will then run an unrestricted VAR estimation and see the results. Lastly, we will run some diagnostics such as tests for autocorrelation, stability, and normality.
The first step is to build the VAR system. This is done through the cbind() command which essentially groups our time series. We will order this in the desired order that we see fit. We will store this in an object called “v1”. We will then rename the variables as the list to follow using the colnames() command.
v1 <- cbind(RRP, lnM1, CPI, lnIP)colnames(v1) <- cbind("RRP","M1","CPI", "lnIP")
After we bind the variables and created the VAR system, we will determine some lag order which we will use. To do this, we use VARselect() command and use the v1 object we just created. We will use a maximum lag order of 15. The command will automatically generate the preferred lag order based on the multivariate iterations of the AIC, SBIC, HQIC and the FPE.
lagselect <- VARselect(v1, lag.max = 15, type = "const")lagselect$selection
Running the commands suggests that the lag order to be used is 2. In the study of Sims, he used 14 lags which may have been more adept in US data as the effects reflect greater persistence.
We will now estimate a model. We estimate the VAR using the VAR() command. The p option refers to the number of lags used. Since we determined that 2 lags is best, we set this to 2. We let it be a typical unrestricted VAR with a constant and we will specify no exogenous variables in the system. The summary() command lists down the results.
Model1 <- VAR(v1, p = 2, type = "const", season = NULL, exog = NULL) summary(Model1)
We do not typically interpret the coefficients of the VAR, we typically interpret the results of the applications. You will see however that we have coefficients there for each lag and each equation in the VAR. Each equation represents an equation in the VAR system.
One assumption is that the residuals should, as much as possible, be non-autocorrelated. This is again on our assumption that the residuals are white noise and thus uncorrelated with the previous periods. To do this, we run the serial.test() command. We store our results in an object Serial1.
Serial1 <- serial.test(Model1, lags.pt = 5, type = "PT.asymptotic")Serial1
In this test, we see that the residuals do not show signs of autocorrelation. However, there is a chance that if we change the maximum lag order, there could be a sign of autocorrelation. As such, it is best to experiment with multiple lag orders.
Another aspect to consider is the presence of heteroscedasticity. In time series, there is what we call ARCH effects which are essentially clustered volatility areas in a time series. This is common is series’ such as stock prices where massive increases or decreases could be seen when an earnings call is released. In that area or window, there could be excessive volatility thereby changing the variance of the residuals, far from our assumption of constant variance. We have models to account for these which are the conditional volatility models which we will discuss in a later section.
Arch1 <- arch.test(Model1, lags.multi = 15, multivariate.only = TRUE)Arch1
Again, the results of the ARCH test signify no degree of heteroscedasticity as we fail to reject the null hypothesis. Therefore, we conclude that there are no ARCH effects in this model. However, like with the autocorrelation test, it is possible to register lag effects at subsequent lag orders.
A soft pre-requisite but a desirable one is the normality of the distribution of the residuals. To test for the normality of the residuals, we use the normality.test() command in R which brings in the Jarque-Bera test, the Kurtosis Test, and the Skewness test.
Norm1 <- normality.test(Model1, multivariate.only = TRUE)Norm1
Based on all the three results, it appears that the residuals of this particular model are not normally distributed.
The stability test is some test for the presence of structural breaks. We know that if we are unable to test for structural breaks and if there happened to be one, the whole estimation may be thrown off. Fortunately, we have a simple test for this which uses a plot of the sum of recursive residuals. If at any point in the graph, the sum goes out of the red critical bounds, then a structural break at that point was seen.
Stability1 <- stability(Model1, type = "OLS-CUSUM")plot(Stability1)
Based on the results of the test, there seems to be no structural breaks evident. As such, our model passes this particular test
We will now move on to policy simulations in a regular VAR. We will do the three main ones, which are the Granger Causality, Forecast Error Variance Decomposition, as well as the Impulse Response Functions.
We will test for an overall Granger causality testing each variable in the system against all the others. As we said, there could be a unidirectional, bidirectional, or no causality relationships between variables.
GrangerRRP<- causality(Model1, cause = "RRP")GrangerRRPGrangerM1 <- causality(Model1, cause = "M1")GrangerM1GrangerCPI <- causality(Model1, cause = "CPI")GrangerCPIGrangerlnIP <- causality(Model1, cause = "lnIP")GrangerlnIP
The command used is suitable for bivariate cases but we will use it in a system of four for now. Some of you may try reducing the VARmodels to two variables to see more straightforward interpretations. To perform the Granger causality test, we use the causality() command. Based on the results, we conclude that CPI Granger causes the other variables but the converse is not seen. Maybe granular variable to variable rather than variable to group relationships would prove more significant.
We will now turn to our impulse response functions. While we can get more impulse response functions than the ones below, we will zero in on the impact of a shock in RRP to the other variables in the system
RRPirf <- irf(Model1, impulse = "RRP", response = "RRP", n.ahead = 20, boot = TRUE)plot(RRPirf, ylab = "RRP", main = "RRP's shock to RRP")M1irf <- irf(Model1, impulse = "RRP", response = "M1", n.ahead = 20, boot = TRUE)plot(M1irf, ylab = "M1", main = "RRP's shock to M1")CPIirf <- irf(Model1, impulse = "RRP", response = "CPI", n.ahead = 20, boot = TRUE)plot(CPIirf, ylab = "CPI", main = "RRP's shock to CPI")lnIPirf <- irf(Model1, impulse = "RRP", response = "lnIP", n.ahead = 20, boot = TRUE)plot(lnIPirf, ylab = "lnIP", main = "RRP's shock to lnIP")
The irf() command generates the IRFs where we need to specify the model, what the impulse series will be, and what the response series will be. We can also specify the number of periods ahead to see how the impact or shock will progress over time. We then use the plot() command to graph this IRF. The results from the IRF are quite puzzling. Remember that such an increase in the RRP cannot be a reaction of the BSP to what is happening the other variables since it was ordered first. As you can see, in (a), the shock to the RRP will of course increase RRP, this would then lead to a slight fall in the money supply (b) and a fall in output (d). What we also find is that prices increase in the short run but decrease moderately thereafter. According to Christopher Sims, this is a puzzling result. The results suggest that prices go up after an RRP hike. If a monetary contraction reduces aggregate demand (lnIP) thereby lowering output, it cannot be associated with inflation. He goes on to say that the VAR could potentially be miss-specified. For instance, there could be a leading indicator for inflation to which the BSP will reach and which was wrongly omitted from the VAR. The BSP could know that inflationary pressures are about to arrive and counteract that by raising the interest rate.
If you recall basic macroeconomics, a contractionary monetary policy like raising the policy rate (interest rate) will lead to a fall in output. That fall in output should generally weigh inflation down and cause prices to decrease. However, what we see in this model is that prices have increased, for the most part, which is puzzling. Supposedly, exogenous movements of the policy interest rate in the previous estimation were not totally exogenous. In other words, the exogenous shocks were not properly identified. To solve this, Sims added commodity prices to the mix.
We now turn our attention to the forecast error variance decomposition. Again, we can trace the development of shocks in our system to explaining the forecast error variances of all the variables in the system. To do this, we use the fevd() command. Like the IRF, we can also specify the number of periods ahead. For this case, let us just zero in on RRP.
FEVD1 <- fevd(Model1, n.ahead = 10)FEVD1plot(FEVD1)
We can clearly see in window (a) that the forecast error of the RRP (column 1) at short horizons is due to itself. This is the case because the RRP was placed first in the ordering and that no other shocks affect RRP contemporaneously. At longer horizons say 10 months, we can see that CPI now accounts for about 16 percent and that money supply accounts for about 2 percent respectively.
As we have said, we can also forecast using VAR. To do this, we use the predict() command and generate something called a fan chart which is commonly used in identifying the confidence level of forecasts igraphically. We will set the forecast horizon to 12 months ahead or a full-year forecast.
forecast <- predict(Model1, n.ahead = 12, ci = 0.95)fanchart(forecast, names = "RRP", main = "Fanchart for RRP", xlab = "Horizon", ylab = "RRP")fanchart(forecast, names = "M1", main = "Fanchart for M1", xlab = "Horizon", ylab = "M1")fanchart(forecast, names = "CPI", main = "Fanchart for CPI", xlab = "Horizon", ylab = "CPI")fanchart(forecast, names = "lnIP", main = "Fanchart for lnIP", xlab = "Horizon", ylab = "lnIP")forecast
The figure shows that RRP is expected to decrease slightly then increase, M1 is expected to decrease and so is IP. CPI is expected to decrease slightly in the first few months then rebound moderately. Take note that this is different from the IRFs simply because we are using VAR as a forecasting tool instead of a policy tool.
All in all, I hope with this example you can see the many use cases of the VAR methodology and why many economists continue to use it for its flexibility. Apart from just a sheer forecasting model, it has many more applications such as policy simulation, linear causality analysis, and forecast error decomposition. Before the creation of the VAR, economics pinned everything on theory and practice and believed that economic variables had to live by their code. In practice, however, we know that economic variables behave in manners that may differ from our preconceived notions. As such, setting prior expectations may have deceived us.
For a more hands-on approach, consider watching the videos I made on this topic which are uploaded on YouTube.
[1] Lütkepohl, H. New introduction to multiple time series analysis.(2005). Springer Science & Business Media.
[2] Enders, W. Applied econometric time series. (2008) John Wiley & Sons. | [
{
"code": null,
"e": 702,
"s": 172,
"text": "Christopher Sims proposed the Vector Autoregression which is a multivariate linear time series model in which the endogenous variables in the system are functions of the lagged values of all endogenous variables. This allows for a simple and flexible alternative to the traditional structural system of equations. A VAR could model macroeconomic data informatively, without imposing very strong restrictions or relationships. Essentially, it is macroeconomic modeling without much of the a-priori expectations getting in the way."
},
{
"code": null,
"e": 1333,
"s": 702,
"text": "VARs are very useful especially in the field of macroeconomics. It has been used widely in simulating macroeconomic shocks to the real economy and has been used heavily in policy simulations and forecasting. This is the thrust and the main use of the Vector Autoregression. Firstly, it is a sophisticated forecasting tool. We will show how VARs can be much better than standard univariate forecasting models, especially in determining the long-run. The majority of empirical studies on forecasting suggest that the VAR has already eclipsed the traditional univariate forecasting models and theory-based structural equation models."
},
{
"code": null,
"e": 1625,
"s": 1333,
"text": "Apart from forecasting, VARs are also useful tools for structural analysis. We note that VARs can investigate the response to shocks. It can pinpoint sources of fluctuations that traditional univariate models fail at. Moreover, VARs can help distinguish between competing theoretical models."
},
{
"code": null,
"e": 2061,
"s": 1625,
"text": "As we have mentioned previously, the VAR is a multivariate linear time series model where the endogenous variables in the system are functions of the lagged values of all endogenous variables. Said simply, the VAR is essentially a generalization of the univariate autoregressive model. Commonly, we notate a VAR as a VAR(p) where p denotes the number of autoregressive lags in the system. Consider a VAR system with only two variables."
},
{
"code": null,
"e": 2102,
"s": 2061,
"text": "We can also write this in matrix form as"
},
{
"code": null,
"e": 2626,
"s": 2102,
"text": "The estimation of a VAR is an Equation by Equation OLS. We essentially run OLS on each equation. What we find is that estimates are consistent as only the lagged values of the endogenous variables are on the right-hand side of the equation. Moreover, estimates are also efficient in that all equations have identical regressors which minimizes the variation in each one. Doing this suggests that it is essentially equivalent to a generalized least squares. The assumption of no-serial correlation also holds in this regard."
},
{
"code": null,
"e": 2868,
"s": 2626,
"text": "We will now apply the numerous concepts learned in VAR in an actual example. In particular, we will be using a framework developed by Sims (1992) using Philippine data. In this model, we will be using four variables. These are the following:"
},
{
"code": null,
"e": 3047,
"s": 2868,
"text": "Overnight Reverse Repurchase Rate (RRP) which is set by the Bangko Sentral ng Pilipinas. This is, by all accounts, the main policy rate that the Philippine central bank controls."
},
{
"code": null,
"e": 3108,
"s": 3047,
"text": "M1 Money Supply which can be obtained from the BSP’s website"
},
{
"code": null,
"e": 3271,
"s": 3108,
"text": "CPI Inflation Rate which is reported monthly by the Philippine Statistics Authority and measures the relative increase in prices based on a Laspeyres price index."
},
{
"code": null,
"e": 3357,
"s": 3271,
"text": "Industrial Production which measures the value of all goods in the industrial sector."
},
{
"code": null,
"e": 3778,
"s": 3357,
"text": "We will first estimate a standard VAR which reflects a key economic response. It is believed in theory and by Sims that shocks to the nominal interest rate represent monetary policy shocks. A shock to the policy variable affects all other variables contemporaneously. The variable is affected by all the others within the period, and is order last. Lastly, the central bank only observes non-policy variables with a lag."
},
{
"code": null,
"e": 4156,
"s": 3778,
"text": "We start again by installing the required packages and loading them using the library() command. For this part, we need to install the “vars” package which will have a host of commands necessary for us to run the VAR and SVAR and the diagnostic tests and applications to follow. We then see the plots of each variable and judge some initial conditions such as non-stationarity."
},
{
"code": null,
"e": 4392,
"s": 4156,
"text": "As said, we need to install the “vars” package. Use the install.packages(“vars”) command to do this. After this, we will load this package together with our standard suite of packages and libraries for us to continue on the estimation."
},
{
"code": null,
"e": 4514,
"s": 4392,
"text": "install.packages(\"vars\")library(vars)library(mFilter)library(tseries)library(TSstudio)library(forecast)library(tidyverse)"
},
{
"code": null,
"e": 5236,
"s": 4514,
"text": "After installation and loading, it is time to load our dataset. We will use the file Sample_VAR.csv which contains the data on all the variables from January 2003 until February 2020. The data is monthly and is publicly available, obtained from the BSP and PSA. We use the read_csv() command to read the dataset and the file.choose() command to open up a dialogue box for us to select our data. In this case, we place the dataset under an object named “mp”. Name it whatever you want, if you’d like. We then use the head() command to see the first few rows of the dataset to inspect if it loaded correctly. The files and code can be found here: https://drive.google.com/drive/u/0/folders/11mAXh0trxjuf1y_yh-AJXgxulHQwcBEn"
},
{
"code": null,
"e": 5275,
"s": 5236,
"text": "mp <- read_csv(file.choose()) head(mp)"
},
{
"code": null,
"e": 5573,
"s": 5275,
"text": "Next, we need to declare each variable in the dataset as a time series using the ts() command. We use the $ symbol to call a variable from the dataset. All variables start in the year 2003 with the same day and month of January 1. We set the frequency to 12 since we are dealing with monthly data."
},
{
"code": null,
"e": 5790,
"s": 5573,
"text": "lnIP <- ts(mp$lnIP, start = c(2003,1,1), frequency = 12)M1 <- ts(mp$M1, start = c(2003,1,1), frequency = 12)CPI <- ts(mp$CPI, start = c(2003,1,1), frequency = 12)RRP <- ts(mp$RRP, start = c(2003,1,1), frequency = 12)"
},
{
"code": null,
"e": 5964,
"s": 5790,
"text": "We can also visualize our series using the autoplot() or ts_plot() command. As before, the ts_plot() command is a more interactive version using the plot.ly package as base."
},
{
"code": null,
"e": 6013,
"s": 5964,
"text": "ts_plot(lnIP)ts_plot(M1)ts_plot(CPI)ts_plot(RRP)"
},
{
"code": null,
"e": 6390,
"s": 6013,
"text": "Again, it is important to assess whether the variables under study are stationary or not. As we have said, having stationary variables is of an ideal case in our VAR even if we can run it without these. As we have been accustomed to, let us use the tests we are familiar with. For simplicity, we will use the Phillips Perron so we would not need to specify the number of lags."
},
{
"code": null,
"e": 6439,
"s": 6390,
"text": "pp.test(lnIP)pp.test(M1)pp.test(CPI)pp.test(RRP)"
},
{
"code": null,
"e": 6774,
"s": 6439,
"text": "In the estimation above, we find that all variables are non-stationary variables. Remember that a rejection of the null hypothesis suggests the data is stationary. Nevertheless, we can still run a VAR estimation using these level data. However, you may opt to difference the data and see if that provides better results and forecasts."
},
{
"code": null,
"e": 7147,
"s": 6774,
"text": "The time has come to formally estimate our VAR. We will first need to bind our VAR variables together to create the system. After this, we will select the optimal lag order behind the VAR we will be using. We will then run an unrestricted VAR estimation and see the results. Lastly, we will run some diagnostics such as tests for autocorrelation, stability, and normality."
},
{
"code": null,
"e": 7461,
"s": 7147,
"text": "The first step is to build the VAR system. This is done through the cbind() command which essentially groups our time series. We will order this in the desired order that we see fit. We will store this in an object called “v1”. We will then rename the variables as the list to follow using the colnames() command."
},
{
"code": null,
"e": 7542,
"s": 7461,
"text": "v1 <- cbind(RRP, lnM1, CPI, lnIP)colnames(v1) <- cbind(\"RRP\",\"M1\",\"CPI\", \"lnIP\")"
},
{
"code": null,
"e": 7904,
"s": 7542,
"text": "After we bind the variables and created the VAR system, we will determine some lag order which we will use. To do this, we use VARselect() command and use the v1 object we just created. We will use a maximum lag order of 15. The command will automatically generate the preferred lag order based on the multivariate iterations of the AIC, SBIC, HQIC and the FPE."
},
{
"code": null,
"e": 7980,
"s": 7904,
"text": "lagselect <- VARselect(v1, lag.max = 15, type = \"const\")lagselect$selection"
},
{
"code": null,
"e": 8170,
"s": 7980,
"text": "Running the commands suggests that the lag order to be used is 2. In the study of Sims, he used 14 lags which may have been more adept in US data as the effects reflect greater persistence."
},
{
"code": null,
"e": 8512,
"s": 8170,
"text": "We will now estimate a model. We estimate the VAR using the VAR() command. The p option refers to the number of lags used. Since we determined that 2 lags is best, we set this to 2. We let it be a typical unrestricted VAR with a constant and we will specify no exogenous variables in the system. The summary() command lists down the results."
},
{
"code": null,
"e": 8597,
"s": 8512,
"text": "Model1 <- VAR(v1, p = 2, type = \"const\", season = NULL, exog = NULL) summary(Model1)"
},
{
"code": null,
"e": 8864,
"s": 8597,
"text": "We do not typically interpret the coefficients of the VAR, we typically interpret the results of the applications. You will see however that we have coefficients there for each lag and each equation in the VAR. Each equation represents an equation in the VAR system."
},
{
"code": null,
"e": 9158,
"s": 8864,
"text": "One assumption is that the residuals should, as much as possible, be non-autocorrelated. This is again on our assumption that the residuals are white noise and thus uncorrelated with the previous periods. To do this, we run the serial.test() command. We store our results in an object Serial1."
},
{
"code": null,
"e": 9233,
"s": 9158,
"text": "Serial1 <- serial.test(Model1, lags.pt = 5, type = \"PT.asymptotic\")Serial1"
},
{
"code": null,
"e": 9481,
"s": 9233,
"text": "In this test, we see that the residuals do not show signs of autocorrelation. However, there is a chance that if we change the maximum lag order, there could be a sign of autocorrelation. As such, it is best to experiment with multiple lag orders."
},
{
"code": null,
"e": 10074,
"s": 9481,
"text": "Another aspect to consider is the presence of heteroscedasticity. In time series, there is what we call ARCH effects which are essentially clustered volatility areas in a time series. This is common is series’ such as stock prices where massive increases or decreases could be seen when an earnings call is released. In that area or window, there could be excessive volatility thereby changing the variance of the residuals, far from our assumption of constant variance. We have models to account for these which are the conditional volatility models which we will discuss in a later section."
},
{
"code": null,
"e": 10149,
"s": 10074,
"text": "Arch1 <- arch.test(Model1, lags.multi = 15, multivariate.only = TRUE)Arch1"
},
{
"code": null,
"e": 10446,
"s": 10149,
"text": "Again, the results of the ARCH test signify no degree of heteroscedasticity as we fail to reject the null hypothesis. Therefore, we conclude that there are no ARCH effects in this model. However, like with the autocorrelation test, it is possible to register lag effects at subsequent lag orders."
},
{
"code": null,
"e": 10707,
"s": 10446,
"text": "A soft pre-requisite but a desirable one is the normality of the distribution of the residuals. To test for the normality of the residuals, we use the normality.test() command in R which brings in the Jarque-Bera test, the Kurtosis Test, and the Skewness test."
},
{
"code": null,
"e": 10770,
"s": 10707,
"text": "Norm1 <- normality.test(Model1, multivariate.only = TRUE)Norm1"
},
{
"code": null,
"e": 10887,
"s": 10770,
"text": "Based on all the three results, it appears that the residuals of this particular model are not normally distributed."
},
{
"code": null,
"e": 11311,
"s": 10887,
"text": "The stability test is some test for the presence of structural breaks. We know that if we are unable to test for structural breaks and if there happened to be one, the whole estimation may be thrown off. Fortunately, we have a simple test for this which uses a plot of the sum of recursive residuals. If at any point in the graph, the sum goes out of the red critical bounds, then a structural break at that point was seen."
},
{
"code": null,
"e": 11379,
"s": 11311,
"text": "Stability1 <- stability(Model1, type = \"OLS-CUSUM\")plot(Stability1)"
},
{
"code": null,
"e": 11508,
"s": 11379,
"text": "Based on the results of the test, there seems to be no structural breaks evident. As such, our model passes this particular test"
},
{
"code": null,
"e": 11715,
"s": 11508,
"text": "We will now move on to policy simulations in a regular VAR. We will do the three main ones, which are the Granger Causality, Forecast Error Variance Decomposition, as well as the Impulse Response Functions."
},
{
"code": null,
"e": 11930,
"s": 11715,
"text": "We will test for an overall Granger causality testing each variable in the system against all the others. As we said, there could be a unidirectional, bidirectional, or no causality relationships between variables."
},
{
"code": null,
"e": 12154,
"s": 11930,
"text": "GrangerRRP<- causality(Model1, cause = \"RRP\")GrangerRRPGrangerM1 <- causality(Model1, cause = \"M1\")GrangerM1GrangerCPI <- causality(Model1, cause = \"CPI\")GrangerCPIGrangerlnIP <- causality(Model1, cause = \"lnIP\")GrangerlnIP"
},
{
"code": null,
"e": 12645,
"s": 12154,
"text": "The command used is suitable for bivariate cases but we will use it in a system of four for now. Some of you may try reducing the VARmodels to two variables to see more straightforward interpretations. To perform the Granger causality test, we use the causality() command. Based on the results, we conclude that CPI Granger causes the other variables but the converse is not seen. Maybe granular variable to variable rather than variable to group relationships would prove more significant."
},
{
"code": null,
"e": 12852,
"s": 12645,
"text": "We will now turn to our impulse response functions. While we can get more impulse response functions than the ones below, we will zero in on the impact of a shock in RRP to the other variables in the system"
},
{
"code": null,
"e": 13405,
"s": 12852,
"text": "RRPirf <- irf(Model1, impulse = \"RRP\", response = \"RRP\", n.ahead = 20, boot = TRUE)plot(RRPirf, ylab = \"RRP\", main = \"RRP's shock to RRP\")M1irf <- irf(Model1, impulse = \"RRP\", response = \"M1\", n.ahead = 20, boot = TRUE)plot(M1irf, ylab = \"M1\", main = \"RRP's shock to M1\")CPIirf <- irf(Model1, impulse = \"RRP\", response = \"CPI\", n.ahead = 20, boot = TRUE)plot(CPIirf, ylab = \"CPI\", main = \"RRP's shock to CPI\")lnIPirf <- irf(Model1, impulse = \"RRP\", response = \"lnIP\", n.ahead = 20, boot = TRUE)plot(lnIPirf, ylab = \"lnIP\", main = \"RRP's shock to lnIP\")"
},
{
"code": null,
"e": 14706,
"s": 13405,
"text": "The irf() command generates the IRFs where we need to specify the model, what the impulse series will be, and what the response series will be. We can also specify the number of periods ahead to see how the impact or shock will progress over time. We then use the plot() command to graph this IRF. The results from the IRF are quite puzzling. Remember that such an increase in the RRP cannot be a reaction of the BSP to what is happening the other variables since it was ordered first. As you can see, in (a), the shock to the RRP will of course increase RRP, this would then lead to a slight fall in the money supply (b) and a fall in output (d). What we also find is that prices increase in the short run but decrease moderately thereafter. According to Christopher Sims, this is a puzzling result. The results suggest that prices go up after an RRP hike. If a monetary contraction reduces aggregate demand (lnIP) thereby lowering output, it cannot be associated with inflation. He goes on to say that the VAR could potentially be miss-specified. For instance, there could be a leading indicator for inflation to which the BSP will reach and which was wrongly omitted from the VAR. The BSP could know that inflationary pressures are about to arrive and counteract that by raising the interest rate."
},
{
"code": null,
"e": 15280,
"s": 14706,
"text": "If you recall basic macroeconomics, a contractionary monetary policy like raising the policy rate (interest rate) will lead to a fall in output. That fall in output should generally weigh inflation down and cause prices to decrease. However, what we see in this model is that prices have increased, for the most part, which is puzzling. Supposedly, exogenous movements of the policy interest rate in the previous estimation were not totally exogenous. In other words, the exogenous shocks were not properly identified. To solve this, Sims added commodity prices to the mix."
},
{
"code": null,
"e": 15636,
"s": 15280,
"text": "We now turn our attention to the forecast error variance decomposition. Again, we can trace the development of shocks in our system to explaining the forecast error variances of all the variables in the system. To do this, we use the fevd() command. Like the IRF, we can also specify the number of periods ahead. For this case, let us just zero in on RRP."
},
{
"code": null,
"e": 15688,
"s": 15636,
"text": "FEVD1 <- fevd(Model1, n.ahead = 10)FEVD1plot(FEVD1)"
},
{
"code": null,
"e": 16077,
"s": 15688,
"text": "We can clearly see in window (a) that the forecast error of the RRP (column 1) at short horizons is due to itself. This is the case because the RRP was placed first in the ordering and that no other shocks affect RRP contemporaneously. At longer horizons say 10 months, we can see that CPI now accounts for about 16 percent and that money supply accounts for about 2 percent respectively."
},
{
"code": null,
"e": 16372,
"s": 16077,
"text": "As we have said, we can also forecast using VAR. To do this, we use the predict() command and generate something called a fan chart which is commonly used in identifying the confidence level of forecasts igraphically. We will set the forecast horizon to 12 months ahead or a full-year forecast."
},
{
"code": null,
"e": 16801,
"s": 16372,
"text": "forecast <- predict(Model1, n.ahead = 12, ci = 0.95)fanchart(forecast, names = \"RRP\", main = \"Fanchart for RRP\", xlab = \"Horizon\", ylab = \"RRP\")fanchart(forecast, names = \"M1\", main = \"Fanchart for M1\", xlab = \"Horizon\", ylab = \"M1\")fanchart(forecast, names = \"CPI\", main = \"Fanchart for CPI\", xlab = \"Horizon\", ylab = \"CPI\")fanchart(forecast, names = \"lnIP\", main = \"Fanchart for lnIP\", xlab = \"Horizon\", ylab = \"lnIP\")forecast"
},
{
"code": null,
"e": 17129,
"s": 16801,
"text": "The figure shows that RRP is expected to decrease slightly then increase, M1 is expected to decrease and so is IP. CPI is expected to decrease slightly in the first few months then rebound moderately. Take note that this is different from the IRFs simply because we are using VAR as a forecasting tool instead of a policy tool."
},
{
"code": null,
"e": 17769,
"s": 17129,
"text": "All in all, I hope with this example you can see the many use cases of the VAR methodology and why many economists continue to use it for its flexibility. Apart from just a sheer forecasting model, it has many more applications such as policy simulation, linear causality analysis, and forecast error decomposition. Before the creation of the VAR, economics pinned everything on theory and practice and believed that economic variables had to live by their code. In practice, however, we know that economic variables behave in manners that may differ from our preconceived notions. As such, setting prior expectations may have deceived us."
},
{
"code": null,
"e": 17880,
"s": 17769,
"text": "For a more hands-on approach, consider watching the videos I made on this topic which are uploaded on YouTube."
},
{
"code": null,
"e": 17992,
"s": 17880,
"text": "[1] Lütkepohl, H. New introduction to multiple time series analysis.(2005). Springer Science & Business Media."
}
] |
asctime() and asctime_s() functions in C with Examples - GeeksforGeeks | 16 Dec, 2021
asctime() function: The asctime() function is defined in time.h header file. This function returns the pointer to the string that contains the information stored in the structure pointed to struct tm type. This function is used to return the local time defined by the system.Syntax:
char *asctime(const struct tm* tm_ptr);
0Parameters: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted.Return Type: This function returns the calendar time in the form “Www Mmm dd hh:mm:ss yyyy”, where:
Www: represents the day in three letter abbreviated (Mon, Tue, Wed.., )
Mmm: represents the month in three letter abbreviated (Jan, Feb, Mar.., )
dd: represents the date in two digits (01, 02, 10, 21, 31.., )
hh: represents the hour (11, 12, 13, 22..., )
mm: represents the minutes (10, 11, 12, 45..., )
ss: represents the seconds (10, 20, 30..., )
yyyy: represents the year in four digits (2000, 2001, 2019, 2020..., )
Below program demonstrate the asctime() function in C:
C
// C program to demonstrate// the asctime() function #include <stdio.h>#include <time.h> int main(){ struct tm* ptr; time_t lt; lt = time(NULL); ptr = localtime(<); // using the asctime() function printf("%s", asctime(ptr)); return 0;}
Wed Aug 14 04:21:25 2019
asctime_s() function:This function is used to convert the given calendar time into a textual representation. We can’t modify the output calendar time in asctime() function whereas we can modify the calendar time in asctime_s() function. The general syntax of asctime_s is “Www Mmm dd hh:mm:ss yyyy“.Syntax:
errno_t asctime_s(char *buf, rsize_t bufsz,
const struct tm *time_ptr)
Parameters: This function accepts three parameters:
time_ptr: pointer to a tm object specifying the time to print
buf: pointer to a user-supplied buffer at least 26 bytes in length
bufsz: size of the user-supplied buffer
Return Value: This function returns pointer to a static null-terminated character string holding the textual representation of date and time. The original calendar time will be obtained from the asctime() function.Note: In some C-compilers asctime_s() won’t be supported. We can use strftime() function instead of asctime_s() function.Below program investigates the asctime_s() function in C:
C
// __STDC_WANT_LIB_EXT1__ is a User defined// standard to get astime_s() function to work#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h>#include <time.h> int main(void){ struct tm tm = *localtime(&(time_t){ time(NULL) }); printf("%s", asctime(&tm)); // Calling C-standard to execute// asctime_s() function#ifdef __STDC_LIB_EXT1__ char str[50]; // Using the asctime_s() function asctime_s(str, sizeof str, &tm); // Print the current time // using the asctime_s() function printf("%s", str);#endif}
Wed Aug 14 04:33:54 2019
Reference: https://en.cppreference.com/w/c/chrono/asctime
gulshankumarar231
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Operators in C / C++
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Input-output system calls in C | Create, Open, Close, Read, Write | [
{
"code": null,
"e": 24128,
"s": 24100,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 24413,
"s": 24128,
"text": "asctime() function: The asctime() function is defined in time.h header file. This function returns the pointer to the string that contains the information stored in the structure pointed to struct tm type. This function is used to return the local time defined by the system.Syntax: "
},
{
"code": null,
"e": 24453,
"s": 24413,
"text": "char *asctime(const struct tm* tm_ptr);"
},
{
"code": null,
"e": 24661,
"s": 24453,
"text": "0Parameters: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted.Return Type: This function returns the calendar time in the form “Www Mmm dd hh:mm:ss yyyy”, where: "
},
{
"code": null,
"e": 24733,
"s": 24661,
"text": "Www: represents the day in three letter abbreviated (Mon, Tue, Wed.., )"
},
{
"code": null,
"e": 24807,
"s": 24733,
"text": "Mmm: represents the month in three letter abbreviated (Jan, Feb, Mar.., )"
},
{
"code": null,
"e": 24870,
"s": 24807,
"text": "dd: represents the date in two digits (01, 02, 10, 21, 31.., )"
},
{
"code": null,
"e": 24916,
"s": 24870,
"text": "hh: represents the hour (11, 12, 13, 22..., )"
},
{
"code": null,
"e": 24965,
"s": 24916,
"text": "mm: represents the minutes (10, 11, 12, 45..., )"
},
{
"code": null,
"e": 25010,
"s": 24965,
"text": "ss: represents the seconds (10, 20, 30..., )"
},
{
"code": null,
"e": 25081,
"s": 25010,
"text": "yyyy: represents the year in four digits (2000, 2001, 2019, 2020..., )"
},
{
"code": null,
"e": 25136,
"s": 25081,
"text": "Below program demonstrate the asctime() function in C:"
},
{
"code": null,
"e": 25138,
"s": 25136,
"text": "C"
},
{
"code": "// C program to demonstrate// the asctime() function #include <stdio.h>#include <time.h> int main(){ struct tm* ptr; time_t lt; lt = time(NULL); ptr = localtime(<); // using the asctime() function printf(\"%s\", asctime(ptr)); return 0;}",
"e": 25397,
"s": 25138,
"text": null
},
{
"code": null,
"e": 25422,
"s": 25397,
"text": "Wed Aug 14 04:21:25 2019"
},
{
"code": null,
"e": 25733,
"s": 25424,
"text": "asctime_s() function:This function is used to convert the given calendar time into a textual representation. We can’t modify the output calendar time in asctime() function whereas we can modify the calendar time in asctime_s() function. The general syntax of asctime_s is “Www Mmm dd hh:mm:ss yyyy“.Syntax: "
},
{
"code": null,
"e": 25823,
"s": 25733,
"text": "errno_t asctime_s(char *buf, rsize_t bufsz, \n const struct tm *time_ptr)"
},
{
"code": null,
"e": 25877,
"s": 25823,
"text": "Parameters: This function accepts three parameters: "
},
{
"code": null,
"e": 25939,
"s": 25877,
"text": "time_ptr: pointer to a tm object specifying the time to print"
},
{
"code": null,
"e": 26006,
"s": 25939,
"text": "buf: pointer to a user-supplied buffer at least 26 bytes in length"
},
{
"code": null,
"e": 26046,
"s": 26006,
"text": "bufsz: size of the user-supplied buffer"
},
{
"code": null,
"e": 26439,
"s": 26046,
"text": "Return Value: This function returns pointer to a static null-terminated character string holding the textual representation of date and time. The original calendar time will be obtained from the asctime() function.Note: In some C-compilers asctime_s() won’t be supported. We can use strftime() function instead of asctime_s() function.Below program investigates the asctime_s() function in C:"
},
{
"code": null,
"e": 26441,
"s": 26439,
"text": "C"
},
{
"code": "// __STDC_WANT_LIB_EXT1__ is a User defined// standard to get astime_s() function to work#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h>#include <time.h> int main(void){ struct tm tm = *localtime(&(time_t){ time(NULL) }); printf(\"%s\", asctime(&tm)); // Calling C-standard to execute// asctime_s() function#ifdef __STDC_LIB_EXT1__ char str[50]; // Using the asctime_s() function asctime_s(str, sizeof str, &tm); // Print the current time // using the asctime_s() function printf(\"%s\", str);#endif}",
"e": 26976,
"s": 26441,
"text": null
},
{
"code": null,
"e": 27001,
"s": 26976,
"text": "Wed Aug 14 04:33:54 2019"
},
{
"code": null,
"e": 27061,
"s": 27003,
"text": "Reference: https://en.cppreference.com/w/c/chrono/asctime"
},
{
"code": null,
"e": 27079,
"s": 27061,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 27091,
"s": 27079,
"text": "C-Functions"
},
{
"code": null,
"e": 27102,
"s": 27091,
"text": "C Language"
},
{
"code": null,
"e": 27200,
"s": 27102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27209,
"s": 27200,
"text": "Comments"
},
{
"code": null,
"e": 27222,
"s": 27209,
"text": "Old Comments"
},
{
"code": null,
"e": 27260,
"s": 27222,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27286,
"s": 27260,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 27306,
"s": 27286,
"text": "Multithreading in C"
},
{
"code": null,
"e": 27328,
"s": 27306,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 27366,
"s": 27328,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27387,
"s": 27366,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 27416,
"s": 27387,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 27458,
"s": 27416,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 27494,
"s": 27458,
"text": "Understanding \"extern\" keyword in C"
}
] |
Combination Sum in Python | Suppose we have a set of candidate numbers (all elements are unique) and a target number. We have to find all unique combinations in candidates where the candidate numbers sum to the given target. The same repeated number may be chosen from candidates unlimited number of times. So if the elements are [2,3,6,7] and the target value is 7, then the possible output will be [[7], [2,2,3]]
Let us see the steps −
We will solve this in recursive manner. The recursive function is named as solve(). This takes an array to store results, one map to keep records, the target value and a list of distinct elements. Initially res array and map is empty. The solve method will work like below −
We will solve this in recursive manner. The recursive function is named as solve(). This takes an array to store results, one map to keep records, the target value and a list of distinct elements. Initially res array and map is empty. The solve method will work like below −
if target is 0, thentemp := a list of elements present in the listtemp1 := temp, then sort tempif temp is not in the map, then insert temp into map and set value as 1, insert temp into resreturnif temp < 0, then returnfor x in range i to length of element list,insert elements[x] into the currentsolve(elements, target – elements[x], res, map, i, current)delete element from current list from index (length of current – 1)
temp := a list of elements present in the list
temp1 := temp, then sort temp
if temp is not in the map, then insert temp into map and set value as 1, insert temp into res
return
if temp < 0, then return
for x in range i to length of element list,insert elements[x] into the currentsolve(elements, target – elements[x], res, map, i, current)delete element from current list from index (length of current – 1)
insert elements[x] into the current
solve(elements, target – elements[x], res, map, i, current)
delete element from current list from index (length of current – 1)
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def combinationSum(self, candidates, target):
result = []
unique={}
candidates = list(set(candidates))
self.solve(candidates,target,result,unique)
return result
def solve(self,candidates,target,result,unique,i = 0,current=[]):
if target == 0:
temp = [i for i in current]
temp1 = temp
temp.sort()
temp = tuple(temp)
if temp not in unique:
unique[temp] = 1
result.append(temp1)
return
if target <0:
return
for x in range(i,len(candidates)):
current.append(candidates[x])
self.solve(candidates,target-candidates[x],result,unique,i,current)
current.pop(len(current)-1)
ob1 = Solution()
print(ob1.combinationSum([2,3,6,7,8],10))
[2,3,6,7,8]
10
[[2, 8], [2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [3, 7]] | [
{
"code": null,
"e": 1449,
"s": 1062,
"text": "Suppose we have a set of candidate numbers (all elements are unique) and a target number. We have to find all unique combinations in candidates where the candidate numbers sum to the given target. The same repeated number may be chosen from candidates unlimited number of times. So if the elements are [2,3,6,7] and the target value is 7, then the possible output will be [[7], [2,2,3]]"
},
{
"code": null,
"e": 1472,
"s": 1449,
"text": "Let us see the steps −"
},
{
"code": null,
"e": 1747,
"s": 1472,
"text": "We will solve this in recursive manner. The recursive function is named as solve(). This takes an array to store results, one map to keep records, the target value and a list of distinct elements. Initially res array and map is empty. The solve method will work like below −"
},
{
"code": null,
"e": 2022,
"s": 1747,
"text": "We will solve this in recursive manner. The recursive function is named as solve(). This takes an array to store results, one map to keep records, the target value and a list of distinct elements. Initially res array and map is empty. The solve method will work like below −"
},
{
"code": null,
"e": 2445,
"s": 2022,
"text": "if target is 0, thentemp := a list of elements present in the listtemp1 := temp, then sort tempif temp is not in the map, then insert temp into map and set value as 1, insert temp into resreturnif temp < 0, then returnfor x in range i to length of element list,insert elements[x] into the currentsolve(elements, target – elements[x], res, map, i, current)delete element from current list from index (length of current – 1)"
},
{
"code": null,
"e": 2492,
"s": 2445,
"text": "temp := a list of elements present in the list"
},
{
"code": null,
"e": 2522,
"s": 2492,
"text": "temp1 := temp, then sort temp"
},
{
"code": null,
"e": 2616,
"s": 2522,
"text": "if temp is not in the map, then insert temp into map and set value as 1, insert temp into res"
},
{
"code": null,
"e": 2623,
"s": 2616,
"text": "return"
},
{
"code": null,
"e": 2648,
"s": 2623,
"text": "if temp < 0, then return"
},
{
"code": null,
"e": 2853,
"s": 2648,
"text": "for x in range i to length of element list,insert elements[x] into the currentsolve(elements, target – elements[x], res, map, i, current)delete element from current list from index (length of current – 1)"
},
{
"code": null,
"e": 2889,
"s": 2853,
"text": "insert elements[x] into the current"
},
{
"code": null,
"e": 2949,
"s": 2889,
"text": "solve(elements, target – elements[x], res, map, i, current)"
},
{
"code": null,
"e": 3017,
"s": 2949,
"text": "delete element from current list from index (length of current – 1)"
},
{
"code": null,
"e": 3087,
"s": 3017,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3098,
"s": 3087,
"text": " Live Demo"
},
{
"code": null,
"e": 3914,
"s": 3098,
"text": "class Solution(object):\n def combinationSum(self, candidates, target):\n result = []\n unique={}\n candidates = list(set(candidates))\n self.solve(candidates,target,result,unique)\n return result\n def solve(self,candidates,target,result,unique,i = 0,current=[]):\n if target == 0:\n temp = [i for i in current]\n temp1 = temp\n temp.sort()\n temp = tuple(temp)\n if temp not in unique:\n unique[temp] = 1\n result.append(temp1)\n return\n if target <0:\n return\n for x in range(i,len(candidates)):\n current.append(candidates[x])\n self.solve(candidates,target-candidates[x],result,unique,i,current)\n current.pop(len(current)-1)\nob1 = Solution()\nprint(ob1.combinationSum([2,3,6,7,8],10))"
},
{
"code": null,
"e": 3929,
"s": 3914,
"text": "[2,3,6,7,8]\n10"
},
{
"code": null,
"e": 3988,
"s": 3929,
"text": "[[2, 8], [2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [3, 7]]"
}
] |
Angular7 - Components | Major part of the development with Angular 7 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters.
The file structure has the app component and it consists of the following files −
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
And if you have selected angular routing during your project setup, files related to routing will also get added and the files are as follows −
app-routing.module.ts
The above files are created by default when we created new project using the angular-cli command.
If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The declarations include the AppComponent variable, which we have already imported. This becomes the parent component.
Now, angular-cli has a command to create your own component. However, the app component which is created by default will always remain the parent and the next components created will form the child components.
Let us now run the command to create the component with the below line of code −
ng g component new-cmp
When you run the above command in the command line, you will receive the following output −
C:\projectA7\angular7-app>ng g component new-cmp
CREATE src/app/new-cmp/new-cmp.component.html (26 bytes)
CREATE src/app/new-cmp/new-cmp.component.spec.ts (629 bytes)
CREATE src/app/new-cmp/new-cmp.component.ts (272 bytes)
CREATE src/app/new-cmp/new-cmp.component.css (0 bytes)
UPDATE src/app/app.module.ts (477 bytes)
Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder.
The following files are created in the new-cmp folder −
new-cmp.component.css − css file for the new component is created.
new-cmp.component.html − html file is created.
new-cmp.component.spec.ts − this can be used for unit testing.
new-cmp.component.ts − here, we can define the module, properties, etc.
Changes are added to the app.module.ts file as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
// includes the new-cmp component we created
@NgModule({
declarations: [
AppComponent,
NewCmpComponent
// here it is added in declarations and will behave as a child component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
//for bootstrap the AppComponent the main app component is given.
})
export class AppModule { }
The new-cmp.component.ts file is generated as follows −,
import { Component, OnInit } from '@angular/core'; // here angular/core is imported.
@Component({
// this is a declarator which starts with @ sign.
// The component word marked in bold needs to be the same.
selector: 'app-new-cmp', // selector to be used inside .html file.
templateUrl: './new-cmp.component.html',
// reference to the html file created in the new component.
styleUrls: ['./new-cmp.component.css'] // reference to the style file.
})
export class NewCmpComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which implements OnInit in which there is a constructor and a method called ngOnInit(). ngOnInit is called by default when the class is executed.
Let us check how the flow works. Now, the app component, which is created by default becomes the parent component. Any component added later becomes the child component.
When we hit the url in the "http://localhost:4200/" browser, it first executes the index.html file which is shown below −
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Angular7App</title>
<base href = "/">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "icon" type = "image/x-icon" href = "favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
The above is the normal html file and we do not see anything that is printed in the browser. We shall take a look at the tag in the body section.
<app-root></app-root>
This is the root tag created by the Angular by default. This tag has the reference in the main.ts file.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));
AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module, which makes the appmodule load.
Let us now see the app.module.ts file −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
@NgModule({
declarations: [
AppComponent,
NewCmpComponent
],
imports: [
BrowserModule,
AppRoutingModule '
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Here, the AppComponent is the name given, i.e., the variable to store the reference of the app.component.ts and the same is given to the bootstrap. Let us now see the app.component.ts file.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
}
Angular core is imported and referred as the Component and the same is used in the Declarator as −
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but the tag which is placed in the index.html file that we saw above.
The class AppComponent has a variable called title, which is displayed in the browser. The @Component uses the templateUrl called app.component.html which is as follows −
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1> Welcome to {{ title }}! </h1>
</div>
It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in the app.component.ts file. This is called binding. We will discuss the concept of binding in the subsequent chapter.
Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file, when the command is run for creating a new component.
app.module.ts has a reference to the new component created.
Let us now check the new files created in new-cmp.
new-cmp.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
Here, we have to import the core too. The reference of the component is used in the declarator.
The declarator has the selector called app-new-cmp and the templateUrl and styleUrl.
The .html called new-cmp.component.html is as follows−
<p>
new-cmp works!
</p>
As seen above, we have the html code, i.e., the p tag. The style file is empty as we do not need any styling at present. But when we run the project, we do not see anything related to the new component getting displayed in the browser.
The browser displays the following screen −
We do not see anything related to the new component being displayed. The new component created has a .html file with following details −
<p>
new-cmp works!
<p>
But we are not getting the same in the browser. Let us now see the changes required to get the new components contents to get displayed in the browser.
The selector 'app-new-cmp' is created for new component from new-cmp.component.ts as shown below −
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
The selector, i.e., app-new-cmp needs to be added in the app.component.html, i.e., the main parent created by default as follows −
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<app-new-cmp7></app-new-cmp>
When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file, i.e., new-cmp.component.html of the new component created will get displayed on the browser along with the parent component data.
Let us add some more details to the new component created and see the display in the browser.
new-cmp.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
newcomponent = "Entered in new component created";
constructor() { }
ngOnInit() { }
}
In the class, we have added one variable called newcomponent and the value is “Entered in new component created”.
The above variable is added in the new-cmp.component.html file as follows −
<p>
{{newcomponent}}
</p>
<p>
new-cmp works!
</p>
Now since we have included the <app-new-cmp></app-new-cmp>selector in the app.component.html which is the .html of the parent component, the content present in the new-cmp.component.html file gets displayed on the browser. We will also add some css for the new component in the new-cmp.component.css file as follows −
p {
color: blue;
font-size: 25px;
}
So we have added blue color and font-size as 25px for the p tags.
Following screen will be displayed in the browser −
Similarly, we can create components and link the same using selector in the app.component.html file as per our requirements.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2320,
"s": 2061,
"text": "Major part of the development with Angular 7 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters."
},
{
"code": null,
"e": 2402,
"s": 2320,
"text": "The file structure has the app component and it consists of the following files −"
},
{
"code": null,
"e": 2420,
"s": 2402,
"text": "app.component.css"
},
{
"code": null,
"e": 2439,
"s": 2420,
"text": "app.component.html"
},
{
"code": null,
"e": 2461,
"s": 2439,
"text": "app.component.spec.ts"
},
{
"code": null,
"e": 2478,
"s": 2461,
"text": "app.component.ts"
},
{
"code": null,
"e": 2492,
"s": 2478,
"text": "app.module.ts"
},
{
"code": null,
"e": 2636,
"s": 2492,
"text": "And if you have selected angular routing during your project setup, files related to routing will also get added and the files are as follows −"
},
{
"code": null,
"e": 2658,
"s": 2636,
"text": "app-routing.module.ts"
},
{
"code": null,
"e": 2756,
"s": 2658,
"text": "The above files are created by default when we created new project using the angular-cli command."
},
{
"code": null,
"e": 2907,
"s": 2756,
"text": "If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows −"
},
{
"code": null,
"e": 3322,
"s": 2907,
"text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; \nimport { AppComponent } from './app.component';\n\n@NgModule({ \n declarations: [ \n AppComponent \n ], \n imports: [ \n BrowserModule, \n AppRoutingModule \n ], \n providers: [],\n bootstrap: [AppComponent] \n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3441,
"s": 3322,
"text": "The declarations include the AppComponent variable, which we have already imported. This becomes the parent component."
},
{
"code": null,
"e": 3651,
"s": 3441,
"text": "Now, angular-cli has a command to create your own component. However, the app component which is created by default will always remain the parent and the next components created will form the child components."
},
{
"code": null,
"e": 3732,
"s": 3651,
"text": "Let us now run the command to create the component with the below line of code −"
},
{
"code": null,
"e": 3756,
"s": 3732,
"text": "ng g component new-cmp\n"
},
{
"code": null,
"e": 3848,
"s": 3756,
"text": "When you run the above command in the command line, you will receive the following output −"
},
{
"code": null,
"e": 4173,
"s": 3848,
"text": "C:\\projectA7\\angular7-app>ng g component new-cmp \nCREATE src/app/new-cmp/new-cmp.component.html (26 bytes) \nCREATE src/app/new-cmp/new-cmp.component.spec.ts (629 bytes) \nCREATE src/app/new-cmp/new-cmp.component.ts (272 bytes) \nCREATE src/app/new-cmp/new-cmp.component.css (0 bytes) \nUPDATE src/app/app.module.ts (477 bytes)\n"
},
{
"code": null,
"e": 4286,
"s": 4173,
"text": "Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder."
},
{
"code": null,
"e": 4342,
"s": 4286,
"text": "The following files are created in the new-cmp folder −"
},
{
"code": null,
"e": 4409,
"s": 4342,
"text": "new-cmp.component.css − css file for the new component is created."
},
{
"code": null,
"e": 4456,
"s": 4409,
"text": "new-cmp.component.html − html file is created."
},
{
"code": null,
"e": 4519,
"s": 4456,
"text": "new-cmp.component.spec.ts − this can be used for unit testing."
},
{
"code": null,
"e": 4591,
"s": 4519,
"text": "new-cmp.component.ts − here, we can define the module, properties, etc."
},
{
"code": null,
"e": 4648,
"s": 4591,
"text": "Changes are added to the app.module.ts file as follows −"
},
{
"code": null,
"e": 5353,
"s": 4648,
"text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component'; \n\n// includes the new-cmp component we created\n@NgModule({ \n declarations: [\n AppComponent, \n NewCmpComponent \n // here it is added in declarations and will behave as a child component \n ], \n imports: [ \n BrowserModule,\n AppRoutingModule \n ], \n providers: [], \n bootstrap: [AppComponent] \n //for bootstrap the AppComponent the main app component is given. \n}) \nexport class AppModule { }"
},
{
"code": null,
"e": 5410,
"s": 5353,
"text": "The new-cmp.component.ts file is generated as follows −,"
},
{
"code": null,
"e": 5981,
"s": 5410,
"text": "import { Component, OnInit } from '@angular/core'; // here angular/core is imported.\n\n@Component({ \n // this is a declarator which starts with @ sign. \n // The component word marked in bold needs to be the same. \n selector: 'app-new-cmp', // selector to be used inside .html file. \n templateUrl: './new-cmp.component.html', \n // reference to the html file created in the new component. \n styleUrls: ['./new-cmp.component.css'] // reference to the style file. \n}) \nexport class NewCmpComponent implements OnInit { \n constructor() { } \n ngOnInit() { } \n}"
},
{
"code": null,
"e": 6222,
"s": 5981,
"text": "If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which implements OnInit in which there is a constructor and a method called ngOnInit(). ngOnInit is called by default when the class is executed."
},
{
"code": null,
"e": 6392,
"s": 6222,
"text": "Let us check how the flow works. Now, the app component, which is created by default becomes the parent component. Any component added later becomes the child component."
},
{
"code": null,
"e": 6514,
"s": 6392,
"text": "When we hit the url in the \"http://localhost:4200/\" browser, it first executes the index.html file which is shown below −"
},
{
"code": null,
"e": 6863,
"s": 6514,
"text": "<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Angular7App</title> \n <base href = \"/\"> \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\"> \n <link rel = \"icon\" type = \"image/x-icon\" href = \"favicon.ico\"> \n </head> \n <body> \n <app-root></app-root>\n </body> \n\n</html>"
},
{
"code": null,
"e": 7009,
"s": 6863,
"text": "The above is the normal html file and we do not see anything that is printed in the browser. We shall take a look at the tag in the body section."
},
{
"code": null,
"e": 7032,
"s": 7009,
"text": "<app-root></app-root>\n"
},
{
"code": null,
"e": 7136,
"s": 7032,
"text": "This is the root tag created by the Angular by default. This tag has the reference in the main.ts file."
},
{
"code": null,
"e": 7507,
"s": 7136,
"text": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { AppModule } from './app/app.module'; \nimport { environment } from './environments/environment';\n\nif (environment.production) { \n enableProdMode(); \n}\nplatformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));"
},
{
"code": null,
"e": 7648,
"s": 7507,
"text": "AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module, which makes the appmodule load."
},
{
"code": null,
"e": 7688,
"s": 7648,
"text": "Let us now see the app.module.ts file −"
},
{
"code": null,
"e": 8191,
"s": 7688,
"text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\n\n@NgModule({ \n declarations: [\n AppComponent, \n NewCmpComponent \n ],\n imports: [ \n BrowserModule, \n AppRoutingModule '\n ], \n providers: [], \n bootstrap: [AppComponent] \n})\nexport class AppModule { }"
},
{
"code": null,
"e": 8381,
"s": 8191,
"text": "Here, the AppComponent is the name given, i.e., the variable to store the reference of the app.component.ts and the same is given to the bootstrap. Let us now see the app.component.ts file."
},
{
"code": null,
"e": 8603,
"s": 8381,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent { \n title = 'Angular 7'; \n}"
},
{
"code": null,
"e": 8702,
"s": 8603,
"text": "Angular core is imported and referred as the Component and the same is used in the Declarator as −"
},
{
"code": null,
"e": 8825,
"s": 8702,
"text": "@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n})"
},
{
"code": null,
"e": 9005,
"s": 8825,
"text": "In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but the tag which is placed in the index.html file that we saw above."
},
{
"code": null,
"e": 9176,
"s": 9005,
"text": "The class AppComponent has a variable called title, which is displayed in the browser. The @Component uses the templateUrl called app.component.html which is as follows −"
},
{
"code": null,
"e": 9326,
"s": 9176,
"text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\"> \n <h1> Welcome to {{ title }}! </h1> \n</div>"
},
{
"code": null,
"e": 9564,
"s": 9326,
"text": "It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in the app.component.ts file. This is called binding. We will discuss the concept of binding in the subsequent chapter."
},
{
"code": null,
"e": 9725,
"s": 9564,
"text": "Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file, when the command is run for creating a new component."
},
{
"code": null,
"e": 9785,
"s": 9725,
"text": "app.module.ts has a reference to the new component created."
},
{
"code": null,
"e": 9836,
"s": 9785,
"text": "Let us now check the new files created in new-cmp."
},
{
"code": null,
"e": 9857,
"s": 9836,
"text": "new-cmp.component.ts"
},
{
"code": null,
"e": 10137,
"s": 9857,
"text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-new-cmp', \n templateUrl: './new-cmp.component.html', \n styleUrls: ['./new-cmp.component.css'] \n}) \nexport class NewCmpComponent implements OnInit { \n constructor() { } \n ngOnInit() { } \n}"
},
{
"code": null,
"e": 10233,
"s": 10137,
"text": "Here, we have to import the core too. The reference of the component is used in the declarator."
},
{
"code": null,
"e": 10318,
"s": 10233,
"text": "The declarator has the selector called app-new-cmp and the templateUrl and styleUrl."
},
{
"code": null,
"e": 10373,
"s": 10318,
"text": "The .html called new-cmp.component.html is as follows−"
},
{
"code": null,
"e": 10402,
"s": 10373,
"text": "<p> \n new-cmp works!\n</p>\n"
},
{
"code": null,
"e": 10638,
"s": 10402,
"text": "As seen above, we have the html code, i.e., the p tag. The style file is empty as we do not need any styling at present. But when we run the project, we do not see anything related to the new component getting displayed in the browser."
},
{
"code": null,
"e": 10682,
"s": 10638,
"text": "The browser displays the following screen −"
},
{
"code": null,
"e": 10819,
"s": 10682,
"text": "We do not see anything related to the new component being displayed. The new component created has a .html file with following details −"
},
{
"code": null,
"e": 10846,
"s": 10819,
"text": "<p>\n new-cmp works!\n<p>\n"
},
{
"code": null,
"e": 10998,
"s": 10846,
"text": "But we are not getting the same in the browser. Let us now see the changes required to get the new components contents to get displayed in the browser."
},
{
"code": null,
"e": 11097,
"s": 10998,
"text": "The selector 'app-new-cmp' is created for new component from new-cmp.component.ts as shown below −"
},
{
"code": null,
"e": 11378,
"s": 11097,
"text": "import { Component, OnInit } from '@angular/core';\n\n@Component({ \n selector: 'app-new-cmp', \n templateUrl: './new-cmp.component.html', \n styleUrls: ['./new-cmp.component.css'] \n}) \nexport class NewCmpComponent implements OnInit { \n constructor() { } \n ngOnInit() { } \n}"
},
{
"code": null,
"e": 11509,
"s": 11378,
"text": "The selector, i.e., app-new-cmp needs to be added in the app.component.html, i.e., the main parent created by default as follows −"
},
{
"code": null,
"e": 11694,
"s": 11509,
"text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{ title }}!\n </h1>\n</div>\n<app-new-cmp7></app-new-cmp>"
},
{
"code": null,
"e": 11914,
"s": 11694,
"text": "When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file, i.e., new-cmp.component.html of the new component created will get displayed on the browser along with the parent component data."
},
{
"code": null,
"e": 12008,
"s": 11914,
"text": "Let us add some more details to the new component created and see the display in the browser."
},
{
"code": null,
"e": 12029,
"s": 12008,
"text": "new-cmp.component.ts"
},
{
"code": null,
"e": 12355,
"s": 12029,
"text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\nexport class NewCmpComponent implements OnInit {\n newcomponent = \"Entered in new component created\";\n constructor() { }\n ngOnInit() { }\n}"
},
{
"code": null,
"e": 12469,
"s": 12355,
"text": "In the class, we have added one variable called newcomponent and the value is “Entered in new component created”."
},
{
"code": null,
"e": 12545,
"s": 12469,
"text": "The above variable is added in the new-cmp.component.html file as follows −"
},
{
"code": null,
"e": 12606,
"s": 12545,
"text": "<p> \n {{newcomponent}} \n</p>\n<p> \n new-cmp works! \n</p>\n"
},
{
"code": null,
"e": 12924,
"s": 12606,
"text": "Now since we have included the <app-new-cmp></app-new-cmp>selector in the app.component.html which is the .html of the parent component, the content present in the new-cmp.component.html file gets displayed on the browser. We will also add some css for the new component in the new-cmp.component.css file as follows −"
},
{
"code": null,
"e": 12970,
"s": 12924,
"text": "p { \n color: blue; \n font-size: 25px; \n}\n"
},
{
"code": null,
"e": 13036,
"s": 12970,
"text": "So we have added blue color and font-size as 25px for the p tags."
},
{
"code": null,
"e": 13088,
"s": 13036,
"text": "Following screen will be displayed in the browser −"
},
{
"code": null,
"e": 13213,
"s": 13088,
"text": "Similarly, we can create components and link the same using selector in the app.component.html file as per our requirements."
},
{
"code": null,
"e": 13248,
"s": 13213,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13262,
"s": 13248,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 13297,
"s": 13262,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13311,
"s": 13297,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 13346,
"s": 13311,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13366,
"s": 13346,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 13401,
"s": 13366,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13418,
"s": 13401,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13451,
"s": 13418,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13463,
"s": 13451,
"text": " Senol Atac"
},
{
"code": null,
"e": 13498,
"s": 13463,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13510,
"s": 13498,
"text": " Senol Atac"
},
{
"code": null,
"e": 13517,
"s": 13510,
"text": " Print"
},
{
"code": null,
"e": 13528,
"s": 13517,
"text": " Add Notes"
}
] |
JSF - Basic Tags | In this chapter, you will learn about various types of basic JSF tags.
JSF provides a standard HTML tag library. These tags get rendered into corresponding html output.
For these tags you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
Following are the important Basic Tags in JSF 2.0.
Renders a HTML input of type="text", text box.
Renders a HTML input of type="password", text box.
Renders a HTML textarea field.
Renders a HTML input of type="hidden".
Renders a single HTML check box.
Renders a group of HTML check boxes.
Renders a single HTML radio button.
Renders a HTML single list box.
Renders a HTML multiple list box.
Renders a HTML combo box.
Renders a HTML text.
Renders a HTML text. It accepts parameters.
Renders an image.
Includes a CSS style sheet in HTML output.
Includes a script in HTML output.
Renders a HTML input of type="submit" button.
Renders a HTML anchor.
Renders a HTML anchor.
Renders a HTML anchor.
Renders an HTML Table in form of grid.
Renders message for a JSF UI Component.
Renders all message for JSF UI Components.
Pass parameters to JSF UI Component.
Pass attribute to a JSF UI Component.
Sets value of a managed bean's property.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2023,
"s": 1952,
"text": "In this chapter, you will learn about various types of basic JSF tags."
},
{
"code": null,
"e": 2121,
"s": 2023,
"text": "JSF provides a standard HTML tag library. These tags get rendered into corresponding html output."
},
{
"code": null,
"e": 2198,
"s": 2121,
"text": "For these tags you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 2294,
"s": 2198,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n"
},
{
"code": null,
"e": 2345,
"s": 2294,
"text": "Following are the important Basic Tags in JSF 2.0."
},
{
"code": null,
"e": 2392,
"s": 2345,
"text": "Renders a HTML input of type=\"text\", text box."
},
{
"code": null,
"e": 2443,
"s": 2392,
"text": "Renders a HTML input of type=\"password\", text box."
},
{
"code": null,
"e": 2474,
"s": 2443,
"text": "Renders a HTML textarea field."
},
{
"code": null,
"e": 2513,
"s": 2474,
"text": "Renders a HTML input of type=\"hidden\"."
},
{
"code": null,
"e": 2546,
"s": 2513,
"text": "Renders a single HTML check box."
},
{
"code": null,
"e": 2583,
"s": 2546,
"text": "Renders a group of HTML check boxes."
},
{
"code": null,
"e": 2619,
"s": 2583,
"text": "Renders a single HTML radio button."
},
{
"code": null,
"e": 2651,
"s": 2619,
"text": "Renders a HTML single list box."
},
{
"code": null,
"e": 2685,
"s": 2651,
"text": "Renders a HTML multiple list box."
},
{
"code": null,
"e": 2711,
"s": 2685,
"text": "Renders a HTML combo box."
},
{
"code": null,
"e": 2732,
"s": 2711,
"text": "Renders a HTML text."
},
{
"code": null,
"e": 2776,
"s": 2732,
"text": "Renders a HTML text. It accepts parameters."
},
{
"code": null,
"e": 2794,
"s": 2776,
"text": "Renders an image."
},
{
"code": null,
"e": 2837,
"s": 2794,
"text": "Includes a CSS style sheet in HTML output."
},
{
"code": null,
"e": 2871,
"s": 2837,
"text": "Includes a script in HTML output."
},
{
"code": null,
"e": 2917,
"s": 2871,
"text": "Renders a HTML input of type=\"submit\" button."
},
{
"code": null,
"e": 2940,
"s": 2917,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 2963,
"s": 2940,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 2986,
"s": 2963,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 3025,
"s": 2986,
"text": "Renders an HTML Table in form of grid."
},
{
"code": null,
"e": 3065,
"s": 3025,
"text": "Renders message for a JSF UI Component."
},
{
"code": null,
"e": 3108,
"s": 3065,
"text": "Renders all message for JSF UI Components."
},
{
"code": null,
"e": 3145,
"s": 3108,
"text": "Pass parameters to JSF UI Component."
},
{
"code": null,
"e": 3183,
"s": 3145,
"text": "Pass attribute to a JSF UI Component."
},
{
"code": null,
"e": 3224,
"s": 3183,
"text": "Sets value of a managed bean's property."
},
{
"code": null,
"e": 3259,
"s": 3224,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3274,
"s": 3259,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3281,
"s": 3274,
"text": " Print"
},
{
"code": null,
"e": 3292,
"s": 3281,
"text": " Add Notes"
}
] |
Pandas - Data Correlations | A great aspect of the Pandas module is the corr() method.
The corr() method calculates the relationship between each column in your data set.
The examples in this page uses a CSV file called: 'data.csv'.
Download data.csv. or Open
data.csv
Show the relationship between the columns:
Duration Pulse Maxpulse Calories
Duration 1.000000 -0.155408 0.009403 0.922721
Pulse -0.155408 1.000000 0.786535 0.025120
Maxpulse 0.009403 0.786535 1.000000 0.203814
Calories 0.922721 0.025120 0.203814 1.000000
Note:
The corr() method ignores "not numeric"
columns.
The Result of the corr() method is a table with a lot of numbers that represents
how well the relationship is between two columns.
The number varies from -1 to 1.
1 means that there is a 1 to 1 relationship (a perfect correlation),
and for this data set, each time a value went up in the first column, the other one went up as well.
0.9 is also a good relationship, and if you increase one value, the other will probably increase as well.
-0.9 would be just as good relationship as 0.9, but if you increase one value, the other will probably go down.
0.2 means NOT a good relationship, meaning that if one value goes up does not mean that the other will.
What is a good correlation?
It depends on the use, but I think it is safe to say you have to have at least 0.6 (or -0.6) to call it a good correlation.
We can see that "Duration" and "Duration" got the number 1.000000, which makes sense,
each column always has a perfect relationship with itself.
"Duration" and "Calories" got a 0.922721 correlation,
which is a very good correlation, and we can predict that the longer you work
out, the more calories you burn, and the other way around: if you burned a lot
of calories, you probably had a long work out.
"Duration" and "Maxpulse" got a 0.009403 correlation,
which is a very bad correlation, meaning that we can not predict the max pulse
by just looking at the duration of the work out, and vice versa.
Insert a correct syntax for finding relationships between columns in a DataFrame.
df.()
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 58,
"s": 0,
"text": "A great aspect of the Pandas module is the corr() method."
},
{
"code": null,
"e": 142,
"s": 58,
"text": "The corr() method calculates the relationship between each column in your data set."
},
{
"code": null,
"e": 204,
"s": 142,
"text": "The examples in this page uses a CSV file called: 'data.csv'."
},
{
"code": null,
"e": 241,
"s": 204,
"text": "Download data.csv. or Open \ndata.csv"
},
{
"code": null,
"e": 284,
"s": 241,
"text": "Show the relationship between the columns:"
},
{
"code": null,
"e": 542,
"s": 284,
"text": "\n Duration Pulse Maxpulse Calories\n Duration 1.000000 -0.155408 0.009403 0.922721\n Pulse -0.155408 1.000000 0.786535 0.025120\n Maxpulse 0.009403 0.786535 1.000000 0.203814\n Calories 0.922721 0.025120 0.203814 1.000000\n\n"
},
{
"code": null,
"e": 610,
"s": 542,
"text": "\nNote:\n The corr() method ignores \"not numeric\" \n columns.\n "
},
{
"code": null,
"e": 741,
"s": 610,
"text": "The Result of the corr() method is a table with a lot of numbers that represents\nhow well the relationship is between two columns."
},
{
"code": null,
"e": 773,
"s": 741,
"text": "The number varies from -1 to 1."
},
{
"code": null,
"e": 943,
"s": 773,
"text": "1 means that there is a 1 to 1 relationship (a perfect correlation),\nand for this data set, each time a value went up in the first column, the other one went up as well."
},
{
"code": null,
"e": 1049,
"s": 943,
"text": "0.9 is also a good relationship, and if you increase one value, the other will probably increase as well."
},
{
"code": null,
"e": 1161,
"s": 1049,
"text": "-0.9 would be just as good relationship as 0.9, but if you increase one value, the other will probably go down."
},
{
"code": null,
"e": 1265,
"s": 1161,
"text": "0.2 means NOT a good relationship, meaning that if one value goes up does not mean that the other will."
},
{
"code": null,
"e": 1425,
"s": 1265,
"text": "\nWhat is a good correlation?\n It depends on the use, but I think it is safe to say you have to have at least 0.6 (or -0.6) to call it a good correlation.\n "
},
{
"code": null,
"e": 1570,
"s": 1425,
"text": "We can see that \"Duration\" and \"Duration\" got the number 1.000000, which makes sense,\neach column always has a perfect relationship with itself."
},
{
"code": null,
"e": 1831,
"s": 1570,
"text": "\"Duration\" and \"Calories\" got a 0.922721 correlation, \nwhich is a very good correlation, and we can predict that the longer you work \nout, the more calories you burn, and the other way around: if you burned a lot \nof calories, you probably had a long work out."
},
{
"code": null,
"e": 2031,
"s": 1831,
"text": "\"Duration\" and \"Maxpulse\" got a 0.009403 correlation, \nwhich is a very bad correlation, meaning that we can not predict the max pulse \nby just looking at the duration of the work out, and vice versa."
},
{
"code": null,
"e": 2113,
"s": 2031,
"text": "Insert a correct syntax for finding relationships between columns in a DataFrame."
},
{
"code": null,
"e": 2120,
"s": 2113,
"text": "df.()\n"
},
{
"code": null,
"e": 2139,
"s": 2120,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2172,
"s": 2139,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2214,
"s": 2172,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2321,
"s": 2214,
"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": 2340,
"s": 2321,
"text": "[email protected]"
}
] |
What is SameSite Cookies and CSRF Protection? - GeeksforGeeks | 15 Sep, 2020
CSRF stands for Cross-Site Request forgery. It allows an attacker to craft a manipulated request via an email or by other means and thereby making state-changing actions in websites that you are currently authenticated as yourself. The intention of CSRF is not to read sensitive data, but to write or make changes to your data for the attackers’ benefit.
For example, you are logged in your net banking website https://mybank.com. The Request URL to make a fund transfer in your net banking application looks like,
https://mybank.com/transferFunds.do?beneficiary=Siva&amount=500
The attacker wants to transact your money to his account. So he crafts an email with the following HTML content,
<img src=’https://mybank.com/transferFunds.do?beneficiary=Attacker&amount=50000′ height=’0px’ width=’0px’ alt=’Logo not available’>
When you open this email, a call is made from your browser where you are logged in to your net banking account to transfer funds to the attacker’s account. Thus, by just opening the email, your account is debited since you are already logged into the banking website. The image may look broken and display alt text but the attacker succeeds in what he expected that is making a state-changing debit account action on your banking website.
Since the attacker can craft and send you the request that executes on your browser, the attacker has no way to read data that is specific to your account. The main intention of CSRF is to perform write actions.
Since CSRF is a serious vulnerability there are multiple protection mechanisms that are tried so far.
Usage of the POST method instead of the GET: There is a misconception that only the GET method is vulnerable to CSRF attacks. It is possible to send a JavaScript controlled HTML form link to a user which when opened auto submits to the target website using the POST method using JavaScript. So the method is not viable protection against CSRF attack.Anti – CSRF token: For every link that is generated by a website, the site also appends an Anti- CSRF token in request parameter or request headers. This should be a strong cryptographic hash that an attacker must not be able to predict or tamper. The site also set this hash in its response cookie. Only if the parameter containing CSRF token matches with CSRF cookie, the request will be allowed to proceed. Otherwise, the request is failed. This CSRF cookie may be generated once per session or once per every request and must be invalidated immediately. The attacker who crafts and sends you the request would not have any idea what is the CSRF cookie for the current session/request. Thus, all state-changing actions with CSRF cookie protection will spoil CSRF attack attempts.
Usage of the POST method instead of the GET: There is a misconception that only the GET method is vulnerable to CSRF attacks. It is possible to send a JavaScript controlled HTML form link to a user which when opened auto submits to the target website using the POST method using JavaScript. So the method is not viable protection against CSRF attack.
Anti – CSRF token: For every link that is generated by a website, the site also appends an Anti- CSRF token in request parameter or request headers. This should be a strong cryptographic hash that an attacker must not be able to predict or tamper. The site also set this hash in its response cookie. Only if the parameter containing CSRF token matches with CSRF cookie, the request will be allowed to proceed. Otherwise, the request is failed. This CSRF cookie may be generated once per session or once per every request and must be invalidated immediately. The attacker who crafts and sends you the request would not have any idea what is the CSRF cookie for the current session/request. Thus, all state-changing actions with CSRF cookie protection will spoil CSRF attack attempts.
For every cookie that is associated with any website, it is possible to set an attribute named SameSite. This is introduced to protect a website against CSRF attacks. Without using a separate cookie to protect a website against CSRF attack, the SameSite attribute can be set a session cookie of a website indicating whether or not the cookie that authorizes a user into a website should be sent only when the link is from the same website, third party website, etc., This attribute controls this cookie passing behavior.
Since it is a common problem for all websites and each website must maintain a mechanism to generate, pass and invalidate CSRF token, Chrome now introduces SameSite cookie which basically aims at CSRF protection.
Almost all site uses Cookie-based user authentication mechanism. Once a user signs in to a website using his/her credentials, the website sets a cookie in the browser session. This is used to respond to further requests from the user to this particular site without having to log in again. This cookie is called session-cookie. Using one of the following values in the SameSite attribute of a session cookie, a website can protect itself from CSRF attack.
All cookies set on a domain can have a SameSite cookie attribute value associated with it. SameSite cookie can take one of the following values,
SameSite : strict
Cookies set with SameSite : strict will disable cookies being sent to all third party websites. Cookies will be sent only if the domain is the same as the path for which the cookie is been set.
SameSite : none
Cookies set with SameSite : none will disable SameSite based protection. The website may use its own CSRF protection mechanisms.
SameSite : Lax
Cookies set with SameSite : Lax will allow cookies to be sent for top-level navigation only. When you didn’t add SameSite attribute, Lax is considered as default behavior.
So if you set session cookie with SameSite : Strict, Even in the absence of a dedicated CSRF cookie, links generated to your website from third-party websites will not have session cookies in them. Thus, it is not possible to perform CSRF attacks on them.
It is becoming more and more common since all modern browsers are considering to implement this behavior to protect its users from CSRF attacks.
Cyber-security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP
Socket Programming in Python
Data encryption standard (DES) | Set 1
Types of Network Topology
UDP Server-Client implementation in C
TCP 3-Way Handshake Process
Types of Transmission Media
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 24478,
"s": 24450,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 24833,
"s": 24478,
"text": "CSRF stands for Cross-Site Request forgery. It allows an attacker to craft a manipulated request via an email or by other means and thereby making state-changing actions in websites that you are currently authenticated as yourself. The intention of CSRF is not to read sensitive data, but to write or make changes to your data for the attackers’ benefit."
},
{
"code": null,
"e": 24993,
"s": 24833,
"text": "For example, you are logged in your net banking website https://mybank.com. The Request URL to make a fund transfer in your net banking application looks like,"
},
{
"code": null,
"e": 25057,
"s": 24993,
"text": "https://mybank.com/transferFunds.do?beneficiary=Siva&amount=500"
},
{
"code": null,
"e": 25170,
"s": 25057,
"text": "The attacker wants to transact your money to his account. So he crafts an email with the following HTML content,"
},
{
"code": null,
"e": 25302,
"s": 25170,
"text": "<img src=’https://mybank.com/transferFunds.do?beneficiary=Attacker&amount=50000′ height=’0px’ width=’0px’ alt=’Logo not available’>"
},
{
"code": null,
"e": 25741,
"s": 25302,
"text": "When you open this email, a call is made from your browser where you are logged in to your net banking account to transfer funds to the attacker’s account. Thus, by just opening the email, your account is debited since you are already logged into the banking website. The image may look broken and display alt text but the attacker succeeds in what he expected that is making a state-changing debit account action on your banking website."
},
{
"code": null,
"e": 25953,
"s": 25741,
"text": "Since the attacker can craft and send you the request that executes on your browser, the attacker has no way to read data that is specific to your account. The main intention of CSRF is to perform write actions."
},
{
"code": null,
"e": 26055,
"s": 25953,
"text": "Since CSRF is a serious vulnerability there are multiple protection mechanisms that are tried so far."
},
{
"code": null,
"e": 27188,
"s": 26055,
"text": "Usage of the POST method instead of the GET: There is a misconception that only the GET method is vulnerable to CSRF attacks. It is possible to send a JavaScript controlled HTML form link to a user which when opened auto submits to the target website using the POST method using JavaScript. So the method is not viable protection against CSRF attack.Anti – CSRF token: For every link that is generated by a website, the site also appends an Anti- CSRF token in request parameter or request headers. This should be a strong cryptographic hash that an attacker must not be able to predict or tamper. The site also set this hash in its response cookie. Only if the parameter containing CSRF token matches with CSRF cookie, the request will be allowed to proceed. Otherwise, the request is failed. This CSRF cookie may be generated once per session or once per every request and must be invalidated immediately. The attacker who crafts and sends you the request would not have any idea what is the CSRF cookie for the current session/request. Thus, all state-changing actions with CSRF cookie protection will spoil CSRF attack attempts."
},
{
"code": null,
"e": 27539,
"s": 27188,
"text": "Usage of the POST method instead of the GET: There is a misconception that only the GET method is vulnerable to CSRF attacks. It is possible to send a JavaScript controlled HTML form link to a user which when opened auto submits to the target website using the POST method using JavaScript. So the method is not viable protection against CSRF attack."
},
{
"code": null,
"e": 28322,
"s": 27539,
"text": "Anti – CSRF token: For every link that is generated by a website, the site also appends an Anti- CSRF token in request parameter or request headers. This should be a strong cryptographic hash that an attacker must not be able to predict or tamper. The site also set this hash in its response cookie. Only if the parameter containing CSRF token matches with CSRF cookie, the request will be allowed to proceed. Otherwise, the request is failed. This CSRF cookie may be generated once per session or once per every request and must be invalidated immediately. The attacker who crafts and sends you the request would not have any idea what is the CSRF cookie for the current session/request. Thus, all state-changing actions with CSRF cookie protection will spoil CSRF attack attempts."
},
{
"code": null,
"e": 28843,
"s": 28322,
"text": "For every cookie that is associated with any website, it is possible to set an attribute named SameSite. This is introduced to protect a website against CSRF attacks. Without using a separate cookie to protect a website against CSRF attack, the SameSite attribute can be set a session cookie of a website indicating whether or not the cookie that authorizes a user into a website should be sent only when the link is from the same website, third party website, etc., This attribute controls this cookie passing behavior."
},
{
"code": null,
"e": 29056,
"s": 28843,
"text": "Since it is a common problem for all websites and each website must maintain a mechanism to generate, pass and invalidate CSRF token, Chrome now introduces SameSite cookie which basically aims at CSRF protection."
},
{
"code": null,
"e": 29512,
"s": 29056,
"text": "Almost all site uses Cookie-based user authentication mechanism. Once a user signs in to a website using his/her credentials, the website sets a cookie in the browser session. This is used to respond to further requests from the user to this particular site without having to log in again. This cookie is called session-cookie. Using one of the following values in the SameSite attribute of a session cookie, a website can protect itself from CSRF attack."
},
{
"code": null,
"e": 29657,
"s": 29512,
"text": "All cookies set on a domain can have a SameSite cookie attribute value associated with it. SameSite cookie can take one of the following values,"
},
{
"code": null,
"e": 29675,
"s": 29657,
"text": "SameSite : strict"
},
{
"code": null,
"e": 29870,
"s": 29675,
"text": "Cookies set with SameSite : strict will disable cookies being sent to all third party websites. Cookies will be sent only if the domain is the same as the path for which the cookie is been set."
},
{
"code": null,
"e": 29886,
"s": 29870,
"text": "SameSite : none"
},
{
"code": null,
"e": 30015,
"s": 29886,
"text": "Cookies set with SameSite : none will disable SameSite based protection. The website may use its own CSRF protection mechanisms."
},
{
"code": null,
"e": 30030,
"s": 30015,
"text": "SameSite : Lax"
},
{
"code": null,
"e": 30202,
"s": 30030,
"text": "Cookies set with SameSite : Lax will allow cookies to be sent for top-level navigation only. When you didn’t add SameSite attribute, Lax is considered as default behavior."
},
{
"code": null,
"e": 30458,
"s": 30202,
"text": "So if you set session cookie with SameSite : Strict, Even in the absence of a dedicated CSRF cookie, links generated to your website from third-party websites will not have session cookies in them. Thus, it is not possible to perform CSRF attacks on them."
},
{
"code": null,
"e": 30603,
"s": 30458,
"text": "It is becoming more and more common since all modern browsers are considering to implement this behavior to protect its users from CSRF attacks."
},
{
"code": null,
"e": 30618,
"s": 30603,
"text": "Cyber-security"
},
{
"code": null,
"e": 30636,
"s": 30618,
"text": "Computer Networks"
},
{
"code": null,
"e": 30654,
"s": 30636,
"text": "Computer Networks"
},
{
"code": null,
"e": 30752,
"s": 30654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30782,
"s": 30752,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 30820,
"s": 30782,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30852,
"s": 30820,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 30881,
"s": 30852,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 30920,
"s": 30881,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 30946,
"s": 30920,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 30984,
"s": 30946,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 31012,
"s": 30984,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 31040,
"s": 31012,
"text": "Types of Transmission Media"
}
] |
Create loops of even and odd values in a binary tree - GeeksforGeeks | 13 May, 2021
Given a binary tree with the node structure containing a data part, left and right pointers, and an arbitrary pointer(abtr). The node’s value can be any positive integer. The problem is to create odd and even loops in a binary tree. An odd loop is a loop that connects all the nodes having odd numbers and similarly even loop is for nodes having even numbers. To create such loops, the abtr pointer of each node is used. An abtr pointer of an odd node(node having an odd number) points to some other odd node in the tree. A loop must be created in such a way that from any node we could traverse all the nodes in the loop to which the node belongs.Examples:
Consider the binary tree given below
1
/ \
2 3
/ \ / \
4 5 6 7
Now with the help of abtr pointers of node,
we connect odd and even nodes as:
Odd loop
1 -> 5 -> 3 -> 7 -> 1(again pointing to first node
in the loop)
Even loop
2 -> 4 -> 6 -> 2(again pointing to first node
in the loop)
Nodes in the respective loop can be arranged in
any order. But from any node in the loop we should
be able to traverse all the nodes in the loop.
Approach: The following steps are:
Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs arrays respectively. Through any tree traversal, we could get the respective node pointers.For both the even_ptrs and odd_ptrs array, perform:As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index.For last element of the array, node->abtr = element at index 0.
Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs arrays respectively. Through any tree traversal, we could get the respective node pointers.
For both the even_ptrs and odd_ptrs array, perform:As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index.For last element of the array, node->abtr = element at index 0.
As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index.
For last element of the array, node->abtr = element at index 0.
CPP
Java
Python3
C#
Javascript
// C++ implementation to create odd and even loops// in a binary tree#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node{ int data; Node *left, *right, *abtr;}; // Utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = node->abtr = NULL; return node;} // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs listvoid preorderTraversal(Node *root, vector<Node*> *even_ptrs, vector<Node*> *odd_ptrs){ if (!root) return; // place node ptr in even_ptrs list if // node contains even number if (root->data % 2 == 0) (*even_ptrs).push_back(root); // else place node ptr in odd_ptrs list else (*odd_ptrs).push_back(root); preorderTraversal(root->left, even_ptrs, odd_ptrs); preorderTraversal(root->right, even_ptrs, odd_ptrs);} // function to create the even and odd loopsvoid createLoops(Node *root){ vector<Node*> even_ptrs, odd_ptrs; preorderTraversal(root, &even_ptrs, &odd_ptrs); int i; // forming even loop for (i=1; i<even_ptrs.size(); i++) even_ptrs[i-1]->abtr = even_ptrs[i]; // for the last element even_ptrs[i-1]->abtr = even_ptrs[0]; // Similarly forming odd loop for (i=1; i<odd_ptrs.size(); i++) odd_ptrs[i-1]->abtr = odd_ptrs[i]; odd_ptrs[i-1]->abtr = odd_ptrs[0];} // traversing the loop from any random// node in the loopvoid traverseLoop(Node *start){ Node *curr = start; do { cout << curr->data << " "; curr = curr->abtr; } while (curr != start);} // Driver program to test aboveint main(){ // Binary tree formation struct Node* root = NULL; root = newNode(1); /* 1 */ root->left = newNode(2); /* / \ */ root->right = newNode(3); /* 2 3 */ root->left->left = newNode(4); /* / \ / \ */ root->left->right = newNode(5); /* 4 5 6 7 */ root->right->left = newNode(6); root->right->right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node cout << "Odd nodes: "; traverseLoop(root->right); cout << endl << "Even nodes: "; // traversing even loop from any // random even node traverseLoop(root->left); return 0;}
// Java implementation to create odd and even loops// in a binary treeimport java.util.*;class GFG{ // structure of a nodestatic class Node{ int data; Node left, right, abtr;}; // Utility function to create a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = node.abtr = null; return node;}static Vector<Node> even_ptrs = new Vector<>();static Vector<Node> odd_ptrs = new Vector<>(); // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs liststatic void preorderTraversal(Node root){ if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).add(root); // else place node ptr in odd_ptrs list else (odd_ptrs).add(root); preorderTraversal(root.left); preorderTraversal(root.right);} // function to create the even and odd loopsstatic void createLoops(Node root){ preorderTraversal(root); int i; // forming even loop for (i = 1; i < even_ptrs.size(); i++) even_ptrs.get(i - 1).abtr = even_ptrs.get(i); // for the last element even_ptrs.get(i - 1).abtr = even_ptrs.get(0); // Similarly forming odd loop for (i = 1; i < odd_ptrs.size(); i++) odd_ptrs.get(i - 1).abtr = odd_ptrs.get(i); odd_ptrs.get(i - 1).abtr = odd_ptrs.get(0);} // traversing the loop from any random// node in the loopstatic void traverseLoop(Node start){ Node curr = start; do { System.out.print(curr.data + " "); curr = curr.abtr; } while (curr != start);} // Driver codepublic static void main(String[] args){ // Binary tree formation Node root = null; root = newNode(1); /* 1 */ root.left = newNode(2); /* / \ */ root.right = newNode(3); /* 2 3 */ root.left.left = newNode(4); /* / \ / \ */ root.left.right = newNode(5); /* 4 5 6 7 */ root.right.left = newNode(6); root.right.right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node System.out.print("Odd nodes: "); traverseLoop(root.right); System.out.print( "\nEven nodes: "); // traversing even loop from any // random even node traverseLoop(root.left); }} // This code is contributed by aashish1995
# Python3 implementation to create odd and even loops# in a binary tree # structure of a nodeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None self.abtr = None even_ptrs = []odd_ptrs = [] # preorder traversal to place the node pointer# in the respective even_ptrs or odd_ptrs listdef preorderTraversal(root): global even_ptrs, odd_ptrs if (not root): return # place node ptr in even_ptrs list if # node contains even number if (root.data % 2 == 0): even_ptrs.append(root) # else place node ptr in odd_ptrs list else: odd_ptrs.append(root) preorderTraversal(root.left) preorderTraversal(root.right) # function to create the even and odd loopsdef createLoops(root): preorderTraversal(root) # forming even loop i = 1 while i < len(even_ptrs): even_ptrs[i - 1].abtr = even_ptrs[i] i += 1 # for the last element even_ptrs[i - 1].abtr = even_ptrs[0] # Similarly forming odd loop i = 1 while i < len(odd_ptrs): odd_ptrs[i - 1].abtr = odd_ptrs[i] i += 1 odd_ptrs[i - 1].abtr = odd_ptrs[0] #traversing the loop from any random#node in the loopdef traverseLoop(start): curr = start while True and curr: print(curr.data, end = " ") curr = curr.abtr if curr == start: break print() # Driver program to test aboveif __name__ == '__main__': # Binary tree formation root = None root = Node(1) #/* 1 */ root.left = Node(2) # /* / \ */ root.right = Node(3) #/* 2 3 */ root.left.left = Node(4) #/* / \ / \ */ root.left.right = Node(5) #/* 4 5 6 7 */ root.right.left = Node(6) root.right.right = Node(7) createLoops(root) # traversing odd loop from any # random odd node print("Odd nodes:", end = " ") traverseLoop(root.right) print("Even nodes:", end = " ") # traversing even loop from any # random even node traverseLoop(root.left) # This code is contributed by mohit kumar 29
// C# implementation to create odd and even loops// in a binary treeusing System;using System.Collections.Generic;class GFG{ // structure of a node public class Node { public int data; public Node left, right, abtr; }; // Utility function to create a new node static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = node.abtr = null; return node; } static List<Node> even_ptrs = new List<Node>(); static List<Node> odd_ptrs = new List<Node>(); // preorder traversal to place the node pointer // in the respective even_ptrs or odd_ptrs list static void preorderTraversal(Node root) { if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).Add(root); // else place node ptr in odd_ptrs list else (odd_ptrs).Add(root); preorderTraversal(root.left); preorderTraversal(root.right); } // function to create the even and odd loops static void createLoops(Node root) { preorderTraversal(root); int i; // forming even loop for (i = 1; i < even_ptrs.Count; i++) even_ptrs[i - 1].abtr = even_ptrs[i]; // for the last element even_ptrs[i - 1].abtr = even_ptrs[0]; // Similarly forming odd loop for (i = 1; i < odd_ptrs.Count; i++) odd_ptrs[i - 1].abtr = odd_ptrs[i]; odd_ptrs[i - 1].abtr = odd_ptrs[0]; } // traversing the loop from any random // node in the loop static void traverseLoop(Node start) { Node curr = start; do { Console.Write(curr.data + " "); curr = curr.abtr; } while (curr != start); } // Driver code public static void Main(String[] args) { // Binary tree formation Node root = null; root = newNode(1); /* 1 */ root.left = newNode(2); /* / \ */ root.right = newNode(3); /* 2 3 */ root.left.left = newNode(4); /* / \ / \ */ root.left.right = newNode(5); /* 4 5 6 7 */ root.right.left = newNode(6); root.right.right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node Console.Write("Odd nodes: "); traverseLoop(root.right); Console.Write( "\nEven nodes: "); // traversing even loop from any // random even node traverseLoop(root.left); }} // This code is contributed by gauravrajput1
<script> // Javascript implementation to// create odd and even loops// in a binary tree // structure of a nodeclass Node{ // Utility function to create a new node constructor(data) { this.data=data; this.left=this.right=this.abtr =null; } } let even_ptrs = [];let odd_ptrs = []; // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs listfunction preorderTraversal(root){ if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).push(root); // else place node ptr in odd_ptrs list else (odd_ptrs).push(root); preorderTraversal(root.left); preorderTraversal(root.right);} // function to create the even and odd loopsfunction createLoops(root){ preorderTraversal(root); let i; // forming even loop for (i = 1; i < even_ptrs.length; i++) even_ptrs[i-1].abtr = even_ptrs[i]; // for the last element even_ptrs[i-1].abtr = even_ptrs[0]; // Similarly forming odd loop for (i = 1; i < odd_ptrs.length; i++) odd_ptrs[i-1].abtr = odd_ptrs[i]; odd_ptrs[i-1].abtr = odd_ptrs[0];} // traversing the loop from any random// node in the loopfunction traverseLoop(start){ let curr = start; do { document.write(curr.data + " "); curr = curr.abtr; } while (curr != start);} // Driver code /* 1 */ /* / \ */ /* 2 3 */ /* / \ / \ */ /* 4 5 6 7 */ // Binary tree formationlet root = null;root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6);root.right.right = new Node(7); createLoops(root); // traversing odd loop from any// random odd nodedocument.write("Odd nodes: ");traverseLoop(root.right); document.write( "<br>Even nodes: "); // traversing even loop from any// random even nodetraverseLoop(root.left); // This code is contributed by patel2127 </script>
Output:
Odd nodes: 3 7 1 5
Even nodes: 2 4 6
Time Complexity: Equal to the time complexity of any recursive tree traversal which is O(n)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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mohit kumar 29
aashish1995
GauravRajput1
patel2127
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Threaded Binary Tree
Find the node with minimum value in a Binary Search Tree
Find maximum (or minimum) in Binary Tree
Iterative Postorder Traversal | Set 2 (Using One Stack)
Top 50 Tree Coding Problems for Interviews
Iterative Preorder Traversal
Construct Complete Binary Tree from its Linked List Representation
Difference between Min Heap and Max Heap | [
{
"code": null,
"e": 24938,
"s": 24910,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 25598,
"s": 24938,
"text": "Given a binary tree with the node structure containing a data part, left and right pointers, and an arbitrary pointer(abtr). The node’s value can be any positive integer. The problem is to create odd and even loops in a binary tree. An odd loop is a loop that connects all the nodes having odd numbers and similarly even loop is for nodes having even numbers. To create such loops, the abtr pointer of each node is used. An abtr pointer of an odd node(node having an odd number) points to some other odd node in the tree. A loop must be created in such a way that from any node we could traverse all the nodes in the loop to which the node belongs.Examples: "
},
{
"code": null,
"e": 26185,
"s": 25598,
"text": "Consider the binary tree given below \n\n 1 \n / \\ \n 2 3 \n / \\ / \\ \n4 5 6 7 \n \nNow with the help of abtr pointers of node, \nwe connect odd and even nodes as:\n\nOdd loop\n1 -> 5 -> 3 -> 7 -> 1(again pointing to first node\n in the loop) \n \nEven loop\n2 -> 4 -> 6 -> 2(again pointing to first node\n in the loop)\n\nNodes in the respective loop can be arranged in\nany order. But from any node in the loop we should \nbe able to traverse all the nodes in the loop."
},
{
"code": null,
"e": 26224,
"s": 26187,
"text": "Approach: The following steps are: "
},
{
"code": null,
"e": 26652,
"s": 26224,
"text": "Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs arrays respectively. Through any tree traversal, we could get the respective node pointers.For both the even_ptrs and odd_ptrs array, perform:As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index.For last element of the array, node->abtr = element at index 0."
},
{
"code": null,
"e": 26824,
"s": 26652,
"text": "Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs arrays respectively. Through any tree traversal, we could get the respective node pointers."
},
{
"code": null,
"e": 27081,
"s": 26824,
"text": "For both the even_ptrs and odd_ptrs array, perform:As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index.For last element of the array, node->abtr = element at index 0."
},
{
"code": null,
"e": 27224,
"s": 27081,
"text": "As the array contains node pointers, consider an element at ith index, let it be node, and the assigned node->abtr = element at (i+1)th index."
},
{
"code": null,
"e": 27288,
"s": 27224,
"text": "For last element of the array, node->abtr = element at index 0."
},
{
"code": null,
"e": 27294,
"s": 27290,
"text": "CPP"
},
{
"code": null,
"e": 27299,
"s": 27294,
"text": "Java"
},
{
"code": null,
"e": 27307,
"s": 27299,
"text": "Python3"
},
{
"code": null,
"e": 27310,
"s": 27307,
"text": "C#"
},
{
"code": null,
"e": 27321,
"s": 27310,
"text": "Javascript"
},
{
"code": "// C++ implementation to create odd and even loops// in a binary tree#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node{ int data; Node *left, *right, *abtr;}; // Utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = node->abtr = NULL; return node;} // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs listvoid preorderTraversal(Node *root, vector<Node*> *even_ptrs, vector<Node*> *odd_ptrs){ if (!root) return; // place node ptr in even_ptrs list if // node contains even number if (root->data % 2 == 0) (*even_ptrs).push_back(root); // else place node ptr in odd_ptrs list else (*odd_ptrs).push_back(root); preorderTraversal(root->left, even_ptrs, odd_ptrs); preorderTraversal(root->right, even_ptrs, odd_ptrs);} // function to create the even and odd loopsvoid createLoops(Node *root){ vector<Node*> even_ptrs, odd_ptrs; preorderTraversal(root, &even_ptrs, &odd_ptrs); int i; // forming even loop for (i=1; i<even_ptrs.size(); i++) even_ptrs[i-1]->abtr = even_ptrs[i]; // for the last element even_ptrs[i-1]->abtr = even_ptrs[0]; // Similarly forming odd loop for (i=1; i<odd_ptrs.size(); i++) odd_ptrs[i-1]->abtr = odd_ptrs[i]; odd_ptrs[i-1]->abtr = odd_ptrs[0];} // traversing the loop from any random// node in the loopvoid traverseLoop(Node *start){ Node *curr = start; do { cout << curr->data << \" \"; curr = curr->abtr; } while (curr != start);} // Driver program to test aboveint main(){ // Binary tree formation struct Node* root = NULL; root = newNode(1); /* 1 */ root->left = newNode(2); /* / \\ */ root->right = newNode(3); /* 2 3 */ root->left->left = newNode(4); /* / \\ / \\ */ root->left->right = newNode(5); /* 4 5 6 7 */ root->right->left = newNode(6); root->right->right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node cout << \"Odd nodes: \"; traverseLoop(root->right); cout << endl << \"Even nodes: \"; // traversing even loop from any // random even node traverseLoop(root->left); return 0;}",
"e": 29843,
"s": 27321,
"text": null
},
{
"code": "// Java implementation to create odd and even loops// in a binary treeimport java.util.*;class GFG{ // structure of a nodestatic class Node{ int data; Node left, right, abtr;}; // Utility function to create a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = node.abtr = null; return node;}static Vector<Node> even_ptrs = new Vector<>();static Vector<Node> odd_ptrs = new Vector<>(); // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs liststatic void preorderTraversal(Node root){ if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).add(root); // else place node ptr in odd_ptrs list else (odd_ptrs).add(root); preorderTraversal(root.left); preorderTraversal(root.right);} // function to create the even and odd loopsstatic void createLoops(Node root){ preorderTraversal(root); int i; // forming even loop for (i = 1; i < even_ptrs.size(); i++) even_ptrs.get(i - 1).abtr = even_ptrs.get(i); // for the last element even_ptrs.get(i - 1).abtr = even_ptrs.get(0); // Similarly forming odd loop for (i = 1; i < odd_ptrs.size(); i++) odd_ptrs.get(i - 1).abtr = odd_ptrs.get(i); odd_ptrs.get(i - 1).abtr = odd_ptrs.get(0);} // traversing the loop from any random// node in the loopstatic void traverseLoop(Node start){ Node curr = start; do { System.out.print(curr.data + \" \"); curr = curr.abtr; } while (curr != start);} // Driver codepublic static void main(String[] args){ // Binary tree formation Node root = null; root = newNode(1); /* 1 */ root.left = newNode(2); /* / \\ */ root.right = newNode(3); /* 2 3 */ root.left.left = newNode(4); /* / \\ / \\ */ root.left.right = newNode(5); /* 4 5 6 7 */ root.right.left = newNode(6); root.right.right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node System.out.print(\"Odd nodes: \"); traverseLoop(root.right); System.out.print( \"\\nEven nodes: \"); // traversing even loop from any // random even node traverseLoop(root.left); }} // This code is contributed by aashish1995",
"e": 32341,
"s": 29843,
"text": null
},
{
"code": "# Python3 implementation to create odd and even loops# in a binary tree # structure of a nodeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None self.abtr = None even_ptrs = []odd_ptrs = [] # preorder traversal to place the node pointer# in the respective even_ptrs or odd_ptrs listdef preorderTraversal(root): global even_ptrs, odd_ptrs if (not root): return # place node ptr in even_ptrs list if # node contains even number if (root.data % 2 == 0): even_ptrs.append(root) # else place node ptr in odd_ptrs list else: odd_ptrs.append(root) preorderTraversal(root.left) preorderTraversal(root.right) # function to create the even and odd loopsdef createLoops(root): preorderTraversal(root) # forming even loop i = 1 while i < len(even_ptrs): even_ptrs[i - 1].abtr = even_ptrs[i] i += 1 # for the last element even_ptrs[i - 1].abtr = even_ptrs[0] # Similarly forming odd loop i = 1 while i < len(odd_ptrs): odd_ptrs[i - 1].abtr = odd_ptrs[i] i += 1 odd_ptrs[i - 1].abtr = odd_ptrs[0] #traversing the loop from any random#node in the loopdef traverseLoop(start): curr = start while True and curr: print(curr.data, end = \" \") curr = curr.abtr if curr == start: break print() # Driver program to test aboveif __name__ == '__main__': # Binary tree formation root = None root = Node(1) #/* 1 */ root.left = Node(2) # /* / \\ */ root.right = Node(3) #/* 2 3 */ root.left.left = Node(4) #/* / \\ / \\ */ root.left.right = Node(5) #/* 4 5 6 7 */ root.right.left = Node(6) root.right.right = Node(7) createLoops(root) # traversing odd loop from any # random odd node print(\"Odd nodes:\", end = \" \") traverseLoop(root.right) print(\"Even nodes:\", end = \" \") # traversing even loop from any # random even node traverseLoop(root.left) # This code is contributed by mohit kumar 29",
"e": 34479,
"s": 32341,
"text": null
},
{
"code": "// C# implementation to create odd and even loops// in a binary treeusing System;using System.Collections.Generic;class GFG{ // structure of a node public class Node { public int data; public Node left, right, abtr; }; // Utility function to create a new node static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = node.abtr = null; return node; } static List<Node> even_ptrs = new List<Node>(); static List<Node> odd_ptrs = new List<Node>(); // preorder traversal to place the node pointer // in the respective even_ptrs or odd_ptrs list static void preorderTraversal(Node root) { if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).Add(root); // else place node ptr in odd_ptrs list else (odd_ptrs).Add(root); preorderTraversal(root.left); preorderTraversal(root.right); } // function to create the even and odd loops static void createLoops(Node root) { preorderTraversal(root); int i; // forming even loop for (i = 1; i < even_ptrs.Count; i++) even_ptrs[i - 1].abtr = even_ptrs[i]; // for the last element even_ptrs[i - 1].abtr = even_ptrs[0]; // Similarly forming odd loop for (i = 1; i < odd_ptrs.Count; i++) odd_ptrs[i - 1].abtr = odd_ptrs[i]; odd_ptrs[i - 1].abtr = odd_ptrs[0]; } // traversing the loop from any random // node in the loop static void traverseLoop(Node start) { Node curr = start; do { Console.Write(curr.data + \" \"); curr = curr.abtr; } while (curr != start); } // Driver code public static void Main(String[] args) { // Binary tree formation Node root = null; root = newNode(1); /* 1 */ root.left = newNode(2); /* / \\ */ root.right = newNode(3); /* 2 3 */ root.left.left = newNode(4); /* / \\ / \\ */ root.left.right = newNode(5); /* 4 5 6 7 */ root.right.left = newNode(6); root.right.right = newNode(7); createLoops(root); // traversing odd loop from any // random odd node Console.Write(\"Odd nodes: \"); traverseLoop(root.right); Console.Write( \"\\nEven nodes: \"); // traversing even loop from any // random even node traverseLoop(root.left); }} // This code is contributed by gauravrajput1",
"e": 36998,
"s": 34479,
"text": null
},
{
"code": "<script> // Javascript implementation to// create odd and even loops// in a binary tree // structure of a nodeclass Node{ // Utility function to create a new node constructor(data) { this.data=data; this.left=this.right=this.abtr =null; } } let even_ptrs = [];let odd_ptrs = []; // preorder traversal to place the node pointer// in the respective even_ptrs or odd_ptrs listfunction preorderTraversal(root){ if (root == null) return; // place node ptr in even_ptrs list if // node contains even number if (root.data % 2 == 0) (even_ptrs).push(root); // else place node ptr in odd_ptrs list else (odd_ptrs).push(root); preorderTraversal(root.left); preorderTraversal(root.right);} // function to create the even and odd loopsfunction createLoops(root){ preorderTraversal(root); let i; // forming even loop for (i = 1; i < even_ptrs.length; i++) even_ptrs[i-1].abtr = even_ptrs[i]; // for the last element even_ptrs[i-1].abtr = even_ptrs[0]; // Similarly forming odd loop for (i = 1; i < odd_ptrs.length; i++) odd_ptrs[i-1].abtr = odd_ptrs[i]; odd_ptrs[i-1].abtr = odd_ptrs[0];} // traversing the loop from any random// node in the loopfunction traverseLoop(start){ let curr = start; do { document.write(curr.data + \" \"); curr = curr.abtr; } while (curr != start);} // Driver code /* 1 */ /* / \\ */ /* 2 3 */ /* / \\ / \\ */ /* 4 5 6 7 */ // Binary tree formationlet root = null;root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6);root.right.right = new Node(7); createLoops(root); // traversing odd loop from any// random odd nodedocument.write(\"Odd nodes: \");traverseLoop(root.right); document.write( \"<br>Even nodes: \"); // traversing even loop from any// random even nodetraverseLoop(root.left); // This code is contributed by patel2127 </script>",
"e": 39214,
"s": 36998,
"text": null
},
{
"code": null,
"e": 39224,
"s": 39214,
"text": "Output: "
},
{
"code": null,
"e": 39261,
"s": 39224,
"text": "Odd nodes: 3 7 1 5\nEven nodes: 2 4 6"
},
{
"code": null,
"e": 39773,
"s": 39261,
"text": "Time Complexity: Equal to the time complexity of any recursive tree traversal which is O(n)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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39788,
"s": 39773,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 39800,
"s": 39788,
"text": "aashish1995"
},
{
"code": null,
"e": 39814,
"s": 39800,
"text": "GauravRajput1"
},
{
"code": null,
"e": 39824,
"s": 39814,
"text": "patel2127"
},
{
"code": null,
"e": 39829,
"s": 39824,
"text": "Tree"
},
{
"code": null,
"e": 39834,
"s": 39829,
"text": "Tree"
},
{
"code": null,
"e": 39932,
"s": 39834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39941,
"s": 39932,
"text": "Comments"
},
{
"code": null,
"e": 39954,
"s": 39941,
"text": "Old Comments"
},
{
"code": null,
"e": 39990,
"s": 39954,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 40030,
"s": 39990,
"text": "DFS traversal of a tree using recursion"
},
{
"code": null,
"e": 40051,
"s": 40030,
"text": "Threaded Binary Tree"
},
{
"code": null,
"e": 40108,
"s": 40051,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 40149,
"s": 40108,
"text": "Find maximum (or minimum) in Binary Tree"
},
{
"code": null,
"e": 40205,
"s": 40149,
"text": "Iterative Postorder Traversal | Set 2 (Using One Stack)"
},
{
"code": null,
"e": 40248,
"s": 40205,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 40277,
"s": 40248,
"text": "Iterative Preorder Traversal"
},
{
"code": null,
"e": 40344,
"s": 40277,
"text": "Construct Complete Binary Tree from its Linked List Representation"
}
] |
5 Ways to add a new column in a PySpark Dataframe | by Rahul Agarwal | Towards Data Science | Too much data is getting generated day by day.
Although sometimes we can manage our big data using tools like Rapids or Parallelization, Spark is an excellent tool to have in your repertoire if you are working with Terabytes of data.
In my last post on Spark, I explained how to work with PySpark RDDs and Dataframes.
Although this post explains a lot on how to work with RDDs and basic Dataframe operations, I missed quite a lot when it comes to working with PySpark Dataframes.
And it is only when I required more functionality that I read up and came up with multiple solutions to do one single thing.
How to create a new column in spark?
Now, this might sound trivial, but believe me, it isn’t. With so much you might want to do with your data, I am pretty sure you will end up using most of these column creation processes in your workflow. Sometimes to utilize Pandas functionality, or occasionally to use RDDs based partitioning or sometimes to make use of the mature python ecosystem.
This post is going to be about — “Multiple ways to create a new column in Pyspark Dataframe.”
If you have PySpark installed, you can skip the Getting Started section below.
I know that a lot of you won’t have spark installed in your system to try and learn. But installing Spark is a headache of its own.
Since we want to understand how it works and work with it, I would suggest that you use Spark on Databricks here online with the community edition. Don’t worry, it is free, albeit fewer resources, but that works for us right now for learning purposes.
Once you register and login will be presented with the following screen.
You can start a new notebook here.
Select the Python notebook and give any name to your notebook.
Once you start a new notebook and try to execute any command, the notebook will ask you if you want to start a new cluster. Do it.
The next step will be to check if the sparkcontext is present. To check if the sparkcontext is present, you have to run this command:
sc
This means that we are set up with a notebook where we can run Spark.
Here, I will work on the Movielens ml-100k.zip dataset. 100,000 ratings from 1000 users on 1700 movies. In this zipped folder, the file we will specifically work with is the rating file. This filename is kept as “u.data”
If you want to upload this data or any data, you can click on the Data tab in the left and then Add Data by using the GUI provided.
We can then load the data using the following commands:
ratings = spark.read.load("/FileStore/tables/u.data",format="csv", sep="\t", inferSchema="true", header="false")ratings = ratings.toDF(*['user_id', 'movie_id', 'rating', 'unix_timestamp'])
Here is how it looks:
ratings.show()
Ok, so now we are set up to begin the part we are interested in finally. How to create a new column in PySpark Dataframe?
The most pysparkish way to create a new column in a PySpark DataFrame is by using built-in functions. This is the most performant programmatical way to create a new column, so this is the first place I go whenever I want to do some column manipulation.
We can use .withcolumn along with PySpark SQL functions to create a new column. In essence, you can find String functions, Date functions, and Math functions already implemented using Spark functions. We can import spark functions as:
import pyspark.sql.functions as F
Our first function, the F.col function gives us access to the column. So if we wanted to multiply a column by 2, we could use F.col as:
ratings_with_scale10 = ratings.withColumn("ScaledRating", 2*F.col("rating"))ratings_with_scale10.show()
We can also use math functions like F.exp function:
ratings_with_exp = ratings.withColumn("expRating", 2*F.exp("rating"))ratings_with_exp.show()
There are a lot of other functions provided in this module, which are enough for most simple use cases. You can check out the functions list here.
Sometimes we want to do complicated things to a column or multiple columns. This could be thought of as a map operation on a PySpark Dataframe to a single column or multiple columns. While Spark SQL functions do solve many use cases when it comes to column creation, I use Spark UDF whenever I want to use the more matured Python functionality.
To use Spark UDFs, we need to use the F.udf function to convert a regular python function to a Spark UDF. We also need to specify the return type of the function. In this example the return type is StringType()
import pyspark.sql.functions as Ffrom pyspark.sql.types import *def somefunc(value): if value < 3: return 'low' else: return 'high'#convert to a UDF Function by passing in the function and return type of functionudfsomefunc = F.udf(somefunc, StringType())ratings_with_high_low = ratings.withColumn("high_low", udfsomefunc("rating"))ratings_with_high_low.show()
Sometimes both the spark UDFs and SQL Functions are not enough for a particular use-case. You might want to utilize the better partitioning that you get with spark RDDs. Or you may want to use group functions in Spark RDDs. You can use this one, mainly when you need access to all the columns in the spark data frame inside a python function.
Whatever the case be, I find this way of using RDD to create new columns pretty useful for people who have experience working with RDDs that is the basic building block in the Spark ecosystem.
The process below makes use of the functionality to convert between Row and pythondict objects. We convert a row object to a dictionary. Work with the dictionary as we are used to and convert that dictionary back to row again.
import mathfrom pyspark.sql import Rowdef rowwise_function(row): # convert row to dict: row_dict = row.asDict() # Add a new key in the dictionary with the new column name and value. row_dict['Newcol'] = math.exp(row_dict['rating']) # convert dict to row: newrow = Row(**row_dict) # return new row return newrow# convert ratings dataframe to RDDratings_rdd = ratings.rdd# apply our function to RDDratings_rdd_new = ratings_rdd.map(lambda row: rowwise_function(row))# Convert RDD Back to DataFrameratings_new_df = sqlContext.createDataFrame(ratings_rdd_new)ratings_new_df.show()
This functionality was introduced in the Spark version 2.3.1. And this allows you to use pandas functionality with Spark. I generally use it when I have to run a groupby operation on a Spark dataframe or whenever I need to create rolling features and want to use Pandas rolling functions/window functions.
The way we use it is by using the F.pandas_udf decorator. We assume here that the input to the function will be a pandas data frame. And we need to return a pandas dataframe in turn from this function.
The only complexity here is that we have to provide a schema for the output Dataframe. We can make that using the format below.
# Declare the schema for the output of our functionoutSchema = StructType([StructField('user_id',IntegerType(),True),StructField('movie_id',IntegerType(),True),StructField('rating',IntegerType(),True),StructField('unix_timestamp',IntegerType(),True),StructField('normalized_rating',DoubleType(),True)])# decorate our function with pandas_udf [email protected]_udf(outSchema, F.PandasUDFType.GROUPED_MAP)def subtract_mean(pdf): # pdf is a pandas.DataFrame v = pdf.rating v = v - v.mean() pdf['normalized_rating'] =v return pdfrating_groupwise_normalization = ratings.groupby("movie_id").apply(subtract_mean)rating_groupwise_normalization.show()
We can also make use of this to train multiple individual models on each spark node. For that, we replicate our data and give each replication a key and some training params like max_depth, etc. Our function then takes the pandas Dataframe, runs the required model, and returns the result. The structure would look something like below.
# 0. Declare the schema for the output of our functionoutSchema = StructType([StructField('replication_id',IntegerType(),True),StructField('RMSE',DoubleType(),True)])# decorate our function with pandas_udf [email protected]_udf(outSchema, F.PandasUDFType.GROUPED_MAP)def run_model(pdf): # 1. Get hyperparam values num_trees = pdf.num_trees.values[0] depth = pdf.depth.values[0] replication_id = pdf.replication_id.values[0] # 2. Train test split Xtrain,Xcv,ytrain,ycv = train_test_split..... # 3. Create model using the pandas dataframe clf = RandomForestRegressor(max_depth = depth, num_trees=num_trees,....) clf.fit(Xtrain,ytrain) # 4. Evaluate the model rmse = RMSE(clf.predict(Xcv,ycv) # 5. return results as pandas DF res =pd.DataFrame({'replication_id':replication_id,'RMSE':rmse}) return res results = replicated_data.groupby("replication_id").apply(run_model)
Above is just an idea and not a working code. Though it should work with minor modifications.
For people who like SQL, there is a way even to create columns using SQL. For this, we need to register a temporary SQL table and then use simple select queries with an additional column. One might also use it to do joins.
ratings.registerTempTable('ratings_table')newDF = sqlContext.sql('select *, 2*rating as newCol from ratings_table')newDF.show()
And that is the end of this column(pun intended)
Hopefully, I’ve covered the column creation process well to help you with your Spark problems. If you need to learn more of spark basics, take a look at:
towardsdatascience.com
You can find all the code for this post at the GitHub repository or the published notebook on databricks.
Also, if you want to learn more about Spark and Spark DataFrames, I would like to call out an excellent course on Big Data Essentials, which is part of the Big Data Specialization provided by Yandex.
Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz
Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea. | [
{
"code": null,
"e": 219,
"s": 172,
"text": "Too much data is getting generated day by day."
},
{
"code": null,
"e": 406,
"s": 219,
"text": "Although sometimes we can manage our big data using tools like Rapids or Parallelization, Spark is an excellent tool to have in your repertoire if you are working with Terabytes of data."
},
{
"code": null,
"e": 490,
"s": 406,
"text": "In my last post on Spark, I explained how to work with PySpark RDDs and Dataframes."
},
{
"code": null,
"e": 652,
"s": 490,
"text": "Although this post explains a lot on how to work with RDDs and basic Dataframe operations, I missed quite a lot when it comes to working with PySpark Dataframes."
},
{
"code": null,
"e": 777,
"s": 652,
"text": "And it is only when I required more functionality that I read up and came up with multiple solutions to do one single thing."
},
{
"code": null,
"e": 814,
"s": 777,
"text": "How to create a new column in spark?"
},
{
"code": null,
"e": 1165,
"s": 814,
"text": "Now, this might sound trivial, but believe me, it isn’t. With so much you might want to do with your data, I am pretty sure you will end up using most of these column creation processes in your workflow. Sometimes to utilize Pandas functionality, or occasionally to use RDDs based partitioning or sometimes to make use of the mature python ecosystem."
},
{
"code": null,
"e": 1259,
"s": 1165,
"text": "This post is going to be about — “Multiple ways to create a new column in Pyspark Dataframe.”"
},
{
"code": null,
"e": 1338,
"s": 1259,
"text": "If you have PySpark installed, you can skip the Getting Started section below."
},
{
"code": null,
"e": 1470,
"s": 1338,
"text": "I know that a lot of you won’t have spark installed in your system to try and learn. But installing Spark is a headache of its own."
},
{
"code": null,
"e": 1722,
"s": 1470,
"text": "Since we want to understand how it works and work with it, I would suggest that you use Spark on Databricks here online with the community edition. Don’t worry, it is free, albeit fewer resources, but that works for us right now for learning purposes."
},
{
"code": null,
"e": 1795,
"s": 1722,
"text": "Once you register and login will be presented with the following screen."
},
{
"code": null,
"e": 1830,
"s": 1795,
"text": "You can start a new notebook here."
},
{
"code": null,
"e": 1893,
"s": 1830,
"text": "Select the Python notebook and give any name to your notebook."
},
{
"code": null,
"e": 2024,
"s": 1893,
"text": "Once you start a new notebook and try to execute any command, the notebook will ask you if you want to start a new cluster. Do it."
},
{
"code": null,
"e": 2158,
"s": 2024,
"text": "The next step will be to check if the sparkcontext is present. To check if the sparkcontext is present, you have to run this command:"
},
{
"code": null,
"e": 2161,
"s": 2158,
"text": "sc"
},
{
"code": null,
"e": 2231,
"s": 2161,
"text": "This means that we are set up with a notebook where we can run Spark."
},
{
"code": null,
"e": 2452,
"s": 2231,
"text": "Here, I will work on the Movielens ml-100k.zip dataset. 100,000 ratings from 1000 users on 1700 movies. In this zipped folder, the file we will specifically work with is the rating file. This filename is kept as “u.data”"
},
{
"code": null,
"e": 2584,
"s": 2452,
"text": "If you want to upload this data or any data, you can click on the Data tab in the left and then Add Data by using the GUI provided."
},
{
"code": null,
"e": 2640,
"s": 2584,
"text": "We can then load the data using the following commands:"
},
{
"code": null,
"e": 2829,
"s": 2640,
"text": "ratings = spark.read.load(\"/FileStore/tables/u.data\",format=\"csv\", sep=\"\\t\", inferSchema=\"true\", header=\"false\")ratings = ratings.toDF(*['user_id', 'movie_id', 'rating', 'unix_timestamp'])"
},
{
"code": null,
"e": 2851,
"s": 2829,
"text": "Here is how it looks:"
},
{
"code": null,
"e": 2866,
"s": 2851,
"text": "ratings.show()"
},
{
"code": null,
"e": 2988,
"s": 2866,
"text": "Ok, so now we are set up to begin the part we are interested in finally. How to create a new column in PySpark Dataframe?"
},
{
"code": null,
"e": 3241,
"s": 2988,
"text": "The most pysparkish way to create a new column in a PySpark DataFrame is by using built-in functions. This is the most performant programmatical way to create a new column, so this is the first place I go whenever I want to do some column manipulation."
},
{
"code": null,
"e": 3476,
"s": 3241,
"text": "We can use .withcolumn along with PySpark SQL functions to create a new column. In essence, you can find String functions, Date functions, and Math functions already implemented using Spark functions. We can import spark functions as:"
},
{
"code": null,
"e": 3510,
"s": 3476,
"text": "import pyspark.sql.functions as F"
},
{
"code": null,
"e": 3646,
"s": 3510,
"text": "Our first function, the F.col function gives us access to the column. So if we wanted to multiply a column by 2, we could use F.col as:"
},
{
"code": null,
"e": 3750,
"s": 3646,
"text": "ratings_with_scale10 = ratings.withColumn(\"ScaledRating\", 2*F.col(\"rating\"))ratings_with_scale10.show()"
},
{
"code": null,
"e": 3802,
"s": 3750,
"text": "We can also use math functions like F.exp function:"
},
{
"code": null,
"e": 3895,
"s": 3802,
"text": "ratings_with_exp = ratings.withColumn(\"expRating\", 2*F.exp(\"rating\"))ratings_with_exp.show()"
},
{
"code": null,
"e": 4042,
"s": 3895,
"text": "There are a lot of other functions provided in this module, which are enough for most simple use cases. You can check out the functions list here."
},
{
"code": null,
"e": 4387,
"s": 4042,
"text": "Sometimes we want to do complicated things to a column or multiple columns. This could be thought of as a map operation on a PySpark Dataframe to a single column or multiple columns. While Spark SQL functions do solve many use cases when it comes to column creation, I use Spark UDF whenever I want to use the more matured Python functionality."
},
{
"code": null,
"e": 4598,
"s": 4387,
"text": "To use Spark UDFs, we need to use the F.udf function to convert a regular python function to a Spark UDF. We also need to specify the return type of the function. In this example the return type is StringType()"
},
{
"code": null,
"e": 4974,
"s": 4598,
"text": "import pyspark.sql.functions as Ffrom pyspark.sql.types import *def somefunc(value): if value < 3: return 'low' else: return 'high'#convert to a UDF Function by passing in the function and return type of functionudfsomefunc = F.udf(somefunc, StringType())ratings_with_high_low = ratings.withColumn(\"high_low\", udfsomefunc(\"rating\"))ratings_with_high_low.show()"
},
{
"code": null,
"e": 5317,
"s": 4974,
"text": "Sometimes both the spark UDFs and SQL Functions are not enough for a particular use-case. You might want to utilize the better partitioning that you get with spark RDDs. Or you may want to use group functions in Spark RDDs. You can use this one, mainly when you need access to all the columns in the spark data frame inside a python function."
},
{
"code": null,
"e": 5510,
"s": 5317,
"text": "Whatever the case be, I find this way of using RDD to create new columns pretty useful for people who have experience working with RDDs that is the basic building block in the Spark ecosystem."
},
{
"code": null,
"e": 5737,
"s": 5510,
"text": "The process below makes use of the functionality to convert between Row and pythondict objects. We convert a row object to a dictionary. Work with the dictionary as we are used to and convert that dictionary back to row again."
},
{
"code": null,
"e": 6323,
"s": 5737,
"text": "import mathfrom pyspark.sql import Rowdef rowwise_function(row): # convert row to dict: row_dict = row.asDict() # Add a new key in the dictionary with the new column name and value. row_dict['Newcol'] = math.exp(row_dict['rating']) # convert dict to row: newrow = Row(**row_dict) # return new row return newrow# convert ratings dataframe to RDDratings_rdd = ratings.rdd# apply our function to RDDratings_rdd_new = ratings_rdd.map(lambda row: rowwise_function(row))# Convert RDD Back to DataFrameratings_new_df = sqlContext.createDataFrame(ratings_rdd_new)ratings_new_df.show()"
},
{
"code": null,
"e": 6629,
"s": 6323,
"text": "This functionality was introduced in the Spark version 2.3.1. And this allows you to use pandas functionality with Spark. I generally use it when I have to run a groupby operation on a Spark dataframe or whenever I need to create rolling features and want to use Pandas rolling functions/window functions."
},
{
"code": null,
"e": 6831,
"s": 6629,
"text": "The way we use it is by using the F.pandas_udf decorator. We assume here that the input to the function will be a pandas data frame. And we need to return a pandas dataframe in turn from this function."
},
{
"code": null,
"e": 6959,
"s": 6831,
"text": "The only complexity here is that we have to provide a schema for the output Dataframe. We can make that using the format below."
},
{
"code": null,
"e": 7619,
"s": 6959,
"text": "# Declare the schema for the output of our functionoutSchema = StructType([StructField('user_id',IntegerType(),True),StructField('movie_id',IntegerType(),True),StructField('rating',IntegerType(),True),StructField('unix_timestamp',IntegerType(),True),StructField('normalized_rating',DoubleType(),True)])# decorate our function with pandas_udf [email protected]_udf(outSchema, F.PandasUDFType.GROUPED_MAP)def subtract_mean(pdf): # pdf is a pandas.DataFrame v = pdf.rating v = v - v.mean() pdf['normalized_rating'] =v return pdfrating_groupwise_normalization = ratings.groupby(\"movie_id\").apply(subtract_mean)rating_groupwise_normalization.show()"
},
{
"code": null,
"e": 7956,
"s": 7619,
"text": "We can also make use of this to train multiple individual models on each spark node. For that, we replicate our data and give each replication a key and some training params like max_depth, etc. Our function then takes the pandas Dataframe, runs the required model, and returns the result. The structure would look something like below."
},
{
"code": null,
"e": 8882,
"s": 7956,
"text": "# 0. Declare the schema for the output of our functionoutSchema = StructType([StructField('replication_id',IntegerType(),True),StructField('RMSE',DoubleType(),True)])# decorate our function with pandas_udf [email protected]_udf(outSchema, F.PandasUDFType.GROUPED_MAP)def run_model(pdf): # 1. Get hyperparam values num_trees = pdf.num_trees.values[0] depth = pdf.depth.values[0] replication_id = pdf.replication_id.values[0] # 2. Train test split Xtrain,Xcv,ytrain,ycv = train_test_split..... # 3. Create model using the pandas dataframe clf = RandomForestRegressor(max_depth = depth, num_trees=num_trees,....) clf.fit(Xtrain,ytrain) # 4. Evaluate the model rmse = RMSE(clf.predict(Xcv,ycv) # 5. return results as pandas DF res =pd.DataFrame({'replication_id':replication_id,'RMSE':rmse}) return res results = replicated_data.groupby(\"replication_id\").apply(run_model)"
},
{
"code": null,
"e": 8976,
"s": 8882,
"text": "Above is just an idea and not a working code. Though it should work with minor modifications."
},
{
"code": null,
"e": 9199,
"s": 8976,
"text": "For people who like SQL, there is a way even to create columns using SQL. For this, we need to register a temporary SQL table and then use simple select queries with an additional column. One might also use it to do joins."
},
{
"code": null,
"e": 9327,
"s": 9199,
"text": "ratings.registerTempTable('ratings_table')newDF = sqlContext.sql('select *, 2*rating as newCol from ratings_table')newDF.show()"
},
{
"code": null,
"e": 9376,
"s": 9327,
"text": "And that is the end of this column(pun intended)"
},
{
"code": null,
"e": 9530,
"s": 9376,
"text": "Hopefully, I’ve covered the column creation process well to help you with your Spark problems. If you need to learn more of spark basics, take a look at:"
},
{
"code": null,
"e": 9553,
"s": 9530,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9659,
"s": 9553,
"text": "You can find all the code for this post at the GitHub repository or the published notebook on databricks."
},
{
"code": null,
"e": 9859,
"s": 9659,
"text": "Also, if you want to learn more about Spark and Spark DataFrames, I would like to call out an excellent course on Big Data Essentials, which is part of the Big Data Specialization provided by Yandex."
},
{
"code": null,
"e": 10122,
"s": 9859,
"text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz"
}
] |
Difference between TypeScript and JavaScript | As we know that both Typescript and JavaScript are the programming language usually used at client end for processing the server request and rendering data on UI. However, both are scripting language but Typescript supports some additional features than Javascript due to which we can state it as the superset of Javascript.
The following are the important differences between TypeScript and JavaScript.
JavaTester.js
<script type="text/javascript">
document.write("Hello World");
</script>
Hello World
JavaTester.ts
var hello: string = "Hello";
var world: string = "World";
console.log(hello + " from " + world);
Hello from World | [
{
"code": null,
"e": 1387,
"s": 1062,
"text": "As we know that both Typescript and JavaScript are the programming language usually used at client end for processing the server request and rendering data on UI. However, both are scripting language but Typescript supports some additional features than Javascript due to which we can state it as the superset of Javascript."
},
{
"code": null,
"e": 1466,
"s": 1387,
"text": "The following are the important differences between TypeScript and JavaScript."
},
{
"code": null,
"e": 1480,
"s": 1466,
"text": "JavaTester.js"
},
{
"code": null,
"e": 1556,
"s": 1480,
"text": "<script type=\"text/javascript\">\n document.write(\"Hello World\");\n</script>"
},
{
"code": null,
"e": 1568,
"s": 1556,
"text": "Hello World"
},
{
"code": null,
"e": 1582,
"s": 1568,
"text": "JavaTester.ts"
},
{
"code": null,
"e": 1679,
"s": 1582,
"text": "var hello: string = \"Hello\";\nvar world: string = \"World\";\nconsole.log(hello + \" from \" + world);"
},
{
"code": null,
"e": 1696,
"s": 1679,
"text": "Hello from World"
}
] |
\underline - Tex Command | \underline - Used to create underline symbol under the argument.
{ \underline #1}
\underline command creates underline symbol under the argument.
\underline{AB}
AB_
\underline a
a_
\underline{\text{a long argument}}
a long argument_
\underline{AB}
AB_
\underline{AB}
\underline a
a_
\underline a
\underline{\text{a long argument}}
a long argument_
\underline{\text{a long argument}}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8051,
"s": 7986,
"text": "\\underline - Used to create underline symbol under the argument."
},
{
"code": null,
"e": 8068,
"s": 8051,
"text": "{ \\underline #1}"
},
{
"code": null,
"e": 8132,
"s": 8068,
"text": "\\underline command creates underline symbol under the argument."
},
{
"code": null,
"e": 8230,
"s": 8132,
"text": "\n\\underline{AB}\n\nAB_\n\n\n\\underline a\n\na_\n\n\n\\underline{\\text{a long argument}}\n\na long argument_\n\n\n"
},
{
"code": null,
"e": 8252,
"s": 8230,
"text": "\\underline{AB}\n\nAB_\n\n"
},
{
"code": null,
"e": 8267,
"s": 8252,
"text": "\\underline{AB}"
},
{
"code": null,
"e": 8286,
"s": 8267,
"text": "\\underline a\n\na_\n\n"
},
{
"code": null,
"e": 8299,
"s": 8286,
"text": "\\underline a"
},
{
"code": null,
"e": 8354,
"s": 8299,
"text": "\\underline{\\text{a long argument}}\n\na long argument_\n\n"
},
{
"code": null,
"e": 8389,
"s": 8354,
"text": "\\underline{\\text{a long argument}}"
},
{
"code": null,
"e": 8421,
"s": 8389,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8434,
"s": 8421,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8467,
"s": 8434,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8480,
"s": 8467,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8512,
"s": 8480,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8548,
"s": 8512,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8583,
"s": 8548,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8600,
"s": 8583,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8633,
"s": 8600,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8647,
"s": 8633,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8679,
"s": 8647,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8694,
"s": 8679,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8701,
"s": 8694,
"text": " Print"
},
{
"code": null,
"e": 8712,
"s": 8701,
"text": " Add Notes"
}
] |
How to access the pointer to structure in C language? | Pointer to structure holds the address of an entire structure.
Mainly, these are used to create the complex data structures such as linked lists, trees, graphs and so on.
The members of the structure can be accessed by using a special operator called arrow operator ( -> ).
Following is the declaration for pointer to structure −
struct tagname *ptr;
For example, struct student *s;
You can access pointer to structure by using the following −
Ptr-> membername;
For example, s->sno, s->sname, s->marks;
Following is the C program to access the pointer to structure −
#include<stdio.h>
struct classroom{
int students[7];
};
int main(){
struct classroom clr = {2, 3, 5, 7, 11, 13};
int *ptr;
ptr = (int *)&clr;
printf("%d",*(ptr + 4));
return 0;
}
When the above program is executed, it produces the following result −
11
Here, a pointer variable ptr holds the address of a first value 2 of an object clr. Then, the address of the pointer variable is incremented by 4 and finally, the value is displayed.
For example,
*(ptr + 0) = 2
*(ptr + 1) = 3
*(ptr + 2) = 5
*(ptr + 3) = 7
*(ptr + 4) = 11
*(ptr + 5) = 13
Consider another simple example to know about pointer to structures −
struct student{
int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks :");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are\n");
printf ("Number = %d\n", st ->sno);
printf ("name = %s\n", st->sname);
printf ("marks =%f", st->marks);
getch ( );
}
When the above program is executed, it produces the following result −
enter sno, sname, marks :1 bhanu 69
details of the student are
Number = 1
name = bhanu
marks =69.000000 | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Pointer to structure holds the address of an entire structure."
},
{
"code": null,
"e": 1233,
"s": 1125,
"text": "Mainly, these are used to create the complex data structures such as linked lists, trees, graphs and so on."
},
{
"code": null,
"e": 1336,
"s": 1233,
"text": "The members of the structure can be accessed by using a special operator called arrow operator ( -> )."
},
{
"code": null,
"e": 1392,
"s": 1336,
"text": "Following is the declaration for pointer to structure −"
},
{
"code": null,
"e": 1413,
"s": 1392,
"text": "struct tagname *ptr;"
},
{
"code": null,
"e": 1445,
"s": 1413,
"text": "For example, struct student *s;"
},
{
"code": null,
"e": 1506,
"s": 1445,
"text": "You can access pointer to structure by using the following −"
},
{
"code": null,
"e": 1524,
"s": 1506,
"text": "Ptr-> membername;"
},
{
"code": null,
"e": 1565,
"s": 1524,
"text": "For example, s->sno, s->sname, s->marks;"
},
{
"code": null,
"e": 1629,
"s": 1565,
"text": "Following is the C program to access the pointer to structure −"
},
{
"code": null,
"e": 1826,
"s": 1629,
"text": "#include<stdio.h>\nstruct classroom{\n int students[7];\n};\nint main(){\n struct classroom clr = {2, 3, 5, 7, 11, 13};\n int *ptr;\n ptr = (int *)&clr;\n printf(\"%d\",*(ptr + 4));\n return 0;\n}"
},
{
"code": null,
"e": 1897,
"s": 1826,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 1900,
"s": 1897,
"text": "11"
},
{
"code": null,
"e": 2083,
"s": 1900,
"text": "Here, a pointer variable ptr holds the address of a first value 2 of an object clr. Then, the address of the pointer variable is incremented by 4 and finally, the value is displayed."
},
{
"code": null,
"e": 2096,
"s": 2083,
"text": "For example,"
},
{
"code": null,
"e": 2188,
"s": 2096,
"text": "*(ptr + 0) = 2\n*(ptr + 1) = 3\n*(ptr + 2) = 5\n*(ptr + 3) = 7\n*(ptr + 4) = 11\n*(ptr + 5) = 13"
},
{
"code": null,
"e": 2258,
"s": 2188,
"text": "Consider another simple example to know about pointer to structures −"
},
{
"code": null,
"e": 2653,
"s": 2258,
"text": "struct student{\n int sno;\n char sname[30];\n float marks;\n};\nmain ( ){\n struct student s;\n struct student *st;\n printf(\"enter sno, sname, marks :\");\n scanf (\"%d%s%f\", & s.sno, s.sname, &s. marks);\n st = &s;\n printf (\"details of the student are\\n\");\n printf (\"Number = %d\\n\", st ->sno);\n printf (\"name = %s\\n\", st->sname);\n printf (\"marks =%f\", st->marks);\n getch ( );\n}"
},
{
"code": null,
"e": 2724,
"s": 2653,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2828,
"s": 2724,
"text": "enter sno, sname, marks :1 bhanu 69\ndetails of the student are\nNumber = 1\nname = bhanu\nmarks =69.000000"
}
] |
Bootstrap 4 | Collapse - GeeksforGeeks | 04 Mar, 2022
Bootstrap 4 offers different classes for creating collapsible elements. A collapsible element is used to hide or show a large amount of content. When clicking a button it targets a collapsible element, the class transition takes place as follows:
.collapse: It hides the content.
.collapsing: It applied during transitions.
.collapse.show: It shows the content.
Basic Collapsible: The .collapse class indicates a collapsible element i.e. the content that will be shown or hidden with a click of a button. To control (show/hide) the collapsible content, add data-toggle = “collapse” attribute to an anchor or a button element. Then add data-target = “#collapseExample” attribute to connect the button with the collapsible content.Example:
HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <head> <body> <div class="container"> <!-- Button trigger modal --> <h2 class="mb-1" style="padding-bottom: 15px;"> Toggle Collapse </h2> <p> <a class="btn btn-success" data-toggle="collapse" href="#example_1" role="button" aria-expanded="false" aria-controls="example_1"> GeeksforGeeks </a> <button class="btn btn-success" type="button" data-toggle="collapse" data-target="#example_2" aria-expanded="false" aria-controls="example_2"> Bootstrap </button> </p> <div class="collapse" id="example_1"> <div class="card card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> <div class="collapse" id="example_2"> <div class="card card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div></body></html>
Output:
Multi Toggle Collapsible: A button or anchor tag can show or hide multiple elements by referencing them with a JQuery selector in its href or data-target attribute. Multiple button or anchor tag can show and hide an element if they can reference it with their href or data-target attribute.Example:
HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <head> <body> <div class="container"> <h2 class="mb-1" style="padding-bottom: 15px;"> Toggle Collapse </h2> <p> <a class="btn btn-success" data-toggle="collapse" href="#collapse1" role="button" aria-expanded="false" aria-controls="collapse1"> Toggle GeeksforGeeks </a> <button class="btn btn-success" type="button" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2"> Toggle Bootstrap </button> <button class="btn btn-success" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="collapse1 collapse2"> Toggle both </button> </p> <div class="collapse multi-collapse" id="collapse1"> <div class="card card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> <div class="collapse multi-collapse" id="collapse2"> <div class="card card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div></body> </html>
Accordion: The following example shows a simple accordion by extending the panel component. The use of data-parent attribute to makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible items is shown.Example:
HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px;"> Accordion </h2> <div id="accordion"> <div class = "card"> <div class = "card-header"> <a class = "card-link" data-toggle = "collapse" href = "#description1"> GeeksforGeeks </a> </div> <div id = "description1" class = "collapse show" data-parent = "#accordion"> <div class = "card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class = "card"> <div class = "card-header"> <a class = "collapsed card-link" data-toggle = "collapse" href = "#description2"> Bootstrap </a> </div> <div id = "description2" class = "collapse" data-parent = "#accordion"> <div class = "card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div> <div class = "card"> <div class = "card-header"> <a class = "collapsed card-link" data-toggle = "collapse" href = "#description3"> HTML </a> </div> <div id = "description3" class = "collapse" data-parent = "#accordion"> <div class = "card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. </div> </div> </div> </div> </div></body> </html>
Output:
germanshephered48
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to change the background color of the active nav-item?
Create a Homepage for Restaurant using HTML , CSS and Bootstrap
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25534,
"s": 25506,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 25783,
"s": 25534,
"text": "Bootstrap 4 offers different classes for creating collapsible elements. A collapsible element is used to hide or show a large amount of content. When clicking a button it targets a collapsible element, the class transition takes place as follows: "
},
{
"code": null,
"e": 25816,
"s": 25783,
"text": ".collapse: It hides the content."
},
{
"code": null,
"e": 25860,
"s": 25816,
"text": ".collapsing: It applied during transitions."
},
{
"code": null,
"e": 25898,
"s": 25860,
"text": ".collapse.show: It shows the content."
},
{
"code": null,
"e": 26276,
"s": 25898,
"text": "Basic Collapsible: The .collapse class indicates a collapsible element i.e. the content that will be shown or hidden with a click of a button. To control (show/hide) the collapsible content, add data-toggle = “collapse” attribute to an anchor or a button element. Then add data-target = “#collapseExample” attribute to connect the button with the collapsible content.Example: "
},
{
"code": null,
"e": 26281,
"s": 26276,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <head> <body> <div class=\"container\"> <!-- Button trigger modal --> <h2 class=\"mb-1\" style=\"padding-bottom: 15px;\"> Toggle Collapse </h2> <p> <a class=\"btn btn-success\" data-toggle=\"collapse\" href=\"#example_1\" role=\"button\" aria-expanded=\"false\" aria-controls=\"example_1\"> GeeksforGeeks </a> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\"#example_2\" aria-expanded=\"false\" aria-controls=\"example_2\"> Bootstrap </button> </p> <div class=\"collapse\" id=\"example_1\"> <div class=\"card card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> <div class=\"collapse\" id=\"example_2\"> <div class=\"card card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div></body></html>",
"e": 28271,
"s": 26281,
"text": null
},
{
"code": null,
"e": 28281,
"s": 28271,
"text": "Output: "
},
{
"code": null,
"e": 28582,
"s": 28281,
"text": "Multi Toggle Collapsible: A button or anchor tag can show or hide multiple elements by referencing them with a JQuery selector in its href or data-target attribute. Multiple button or anchor tag can show and hide an element if they can reference it with their href or data-target attribute.Example: "
},
{
"code": null,
"e": 28587,
"s": 28582,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <head> <body> <div class=\"container\"> <h2 class=\"mb-1\" style=\"padding-bottom: 15px;\"> Toggle Collapse </h2> <p> <a class=\"btn btn-success\" data-toggle=\"collapse\" href=\"#collapse1\" role=\"button\" aria-expanded=\"false\" aria-controls=\"collapse1\"> Toggle GeeksforGeeks </a> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapse2\" aria-expanded=\"false\" aria-controls=\"collapse2\"> Toggle Bootstrap </button> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\".multi-collapse\" aria-expanded=\"false\" aria-controls=\"collapse1 collapse2\"> Toggle both </button> </p> <div class=\"collapse multi-collapse\" id=\"collapse1\"> <div class=\"card card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> <div class=\"collapse multi-collapse\" id=\"collapse2\"> <div class=\"card card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div></body> </html>",
"e": 30849,
"s": 28587,
"text": null
},
{
"code": null,
"e": 31114,
"s": 30849,
"text": "Accordion: The following example shows a simple accordion by extending the panel component. The use of data-parent attribute to makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible items is shown.Example: "
},
{
"code": null,
"e": 31119,
"s": 31114,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px;\"> Accordion </h2> <div id=\"accordion\"> <div class = \"card\"> <div class = \"card-header\"> <a class = \"card-link\" data-toggle = \"collapse\" href = \"#description1\"> GeeksforGeeks </a> </div> <div id = \"description1\" class = \"collapse show\" data-parent = \"#accordion\"> <div class = \"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class = \"card\"> <div class = \"card-header\"> <a class = \"collapsed card-link\" data-toggle = \"collapse\" href = \"#description2\"> Bootstrap </a> </div> <div id = \"description2\" class = \"collapse\" data-parent = \"#accordion\"> <div class = \"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. </div> </div> </div> <div class = \"card\"> <div class = \"card-header\"> <a class = \"collapsed card-link\" data-toggle = \"collapse\" href = \"#description3\"> HTML </a> </div> <div id = \"description3\" class = \"collapse\" data-parent = \"#accordion\"> <div class = \"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. </div> </div> </div> </div> </div></body> </html>",
"e": 34389,
"s": 31119,
"text": null
},
{
"code": null,
"e": 34399,
"s": 34389,
"text": "Output: "
},
{
"code": null,
"e": 34419,
"s": 34401,
"text": "germanshephered48"
},
{
"code": null,
"e": 34426,
"s": 34419,
"text": "Picked"
},
{
"code": null,
"e": 34436,
"s": 34426,
"text": "Bootstrap"
},
{
"code": null,
"e": 34453,
"s": 34436,
"text": "Web Technologies"
},
{
"code": null,
"e": 34551,
"s": 34453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34560,
"s": 34551,
"text": "Comments"
},
{
"code": null,
"e": 34573,
"s": 34560,
"text": "Old Comments"
},
{
"code": null,
"e": 34614,
"s": 34573,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 34677,
"s": 34614,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 34718,
"s": 34677,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 34777,
"s": 34718,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 34841,
"s": 34777,
"text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap"
},
{
"code": null,
"e": 34883,
"s": 34841,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 34916,
"s": 34883,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34959,
"s": 34916,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 35021,
"s": 34959,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Spring AOP - Proxy | So far, we've declared aspects using <aop:config> or < aop:aspectj-autoproxy>. We can create a proxy programmatically as well as invoke the aspects programmatically using the proxy object.
//Create object to be proxied
Student student = new Student();
//Create the Proxy Factory
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);
//Add Aspect class to the factory
proxyFactory.addAspect(Logging.class);
//Get the proxy object
Student proxyStudent = proxyFactory.getProxy();
//Invoke the proxied method.
proxyStudent.getAge();
Where,
AspectJProxyFactory − Factory class to create a proxy object.
AspectJProxyFactory − Factory class to create a proxy object.
Logging.class − Class of the Aspect containing advices.
Logging.class − Class of the Aspect containing advices.
Student − Business class to be advised.
Student − Business class to be advised.
To understand the above-mentioned concepts related to proxy, let us write an example which will implement proxy. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.PointCut;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Logging {
/** Following is the definition for a PointCut to select
* all the methods available. So advice will be called
* for all the methods.
*/
@PointCut("execution(* com.tutorialspoint.Student.getAge(..))")
private void selectGetAge(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
@Before("selectGetAge()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
//Create the Proxy Factory
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);
//Add Aspect class to the factory
proxyFactory.addAspect(Logging.class);
//Get the proxy object
Student proxyStudent = proxyFactory.getProxy();
//Invoke the proxied method.
proxyStudent.getAge();
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- Definition for student bean -->
<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Age : 11
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2458,
"s": 2269,
"text": "So far, we've declared aspects using <aop:config> or < aop:aspectj-autoproxy>. We can create a proxy programmatically as well as invoke the aspects programmatically using the proxy object."
},
{
"code": null,
"e": 2817,
"s": 2458,
"text": "//Create object to be proxied\nStudent student = new Student();\n\n//Create the Proxy Factory\nAspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);\n\n//Add Aspect class to the factory\nproxyFactory.addAspect(Logging.class);\n\n//Get the proxy object\nStudent proxyStudent = proxyFactory.getProxy();\n\n//Invoke the proxied method.\nproxyStudent.getAge();"
},
{
"code": null,
"e": 2824,
"s": 2817,
"text": "Where,"
},
{
"code": null,
"e": 2886,
"s": 2824,
"text": "AspectJProxyFactory − Factory class to create a proxy object."
},
{
"code": null,
"e": 2948,
"s": 2886,
"text": "AspectJProxyFactory − Factory class to create a proxy object."
},
{
"code": null,
"e": 3004,
"s": 2948,
"text": "Logging.class − Class of the Aspect containing advices."
},
{
"code": null,
"e": 3060,
"s": 3004,
"text": "Logging.class − Class of the Aspect containing advices."
},
{
"code": null,
"e": 3100,
"s": 3060,
"text": "Student − Business class to be advised."
},
{
"code": null,
"e": 3140,
"s": 3100,
"text": "Student − Business class to be advised."
},
{
"code": null,
"e": 3396,
"s": 3140,
"text": "To understand the above-mentioned concepts related to proxy, let us write an example which will implement proxy. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −"
},
{
"code": null,
"e": 3545,
"s": 3396,
"text": "Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points."
},
{
"code": null,
"e": 4240,
"s": 3545,
"text": "package com.tutorialspoint;\n\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.PointCut;\nimport org.aspectj.lang.annotation.Before;\n\n@Aspect\npublic class Logging {\n /** Following is the definition for a PointCut to select\n * all the methods available. So advice will be called\n * for all the methods.\n */\n @PointCut(\"execution(* com.tutorialspoint.Student.getAge(..))\")\n private void selectGetAge(){}\n\n /** \n * This is the method which I would like to execute\n * before a selected method execution.\n */\n @Before(\"selectGetAge()\")\n public void beforeAdvice(){\n System.out.println(\"Going to setup student profile.\");\n } \n}"
},
{
"code": null,
"e": 4291,
"s": 4240,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 4531,
"s": 4291,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n System.out.println(\"Age : \" + age );\n return age;\n } \n}"
},
{
"code": null,
"e": 4582,
"s": 4531,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 5378,
"s": 4582,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.springframework.aop.aspectj.annotation.AspectJProxyFactory;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n Student student = (Student) context.getBean(\"student\");\n\n //Create the Proxy Factory\n AspectJProxyFactory proxyFactory = new AspectJProxyFactory(student);\n\n //Add Aspect class to the factory\n proxyFactory.addAspect(Logging.class);\n\n //Get the proxy object\n Student proxyStudent = proxyFactory.getProxy();\n\n //Invoke the proxied method.\n proxyStudent.getAge();\n }\n}"
},
{
"code": null,
"e": 5425,
"s": 5378,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 6180,
"s": 5425,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/aop \n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \">\n\n <!-- Definition for student bean -->\n <bean id = \"student\" class = \"com.tutorialspoint.Student\">\n <property name = \"age\" value = \"11\"/> \n </bean>\n\n <!-- Definition for logging aspect -->\n <bean id = \"logging\" class = \"com.tutorialspoint.Logging\"/> \n</beans>"
},
{
"code": null,
"e": 6435,
"s": 6180,
"text": "Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 6477,
"s": 6435,
"text": "Going to setup student profile.\nAge : 11\n"
},
{
"code": null,
"e": 6484,
"s": 6477,
"text": " Print"
},
{
"code": null,
"e": 6495,
"s": 6484,
"text": " Add Notes"
}
] |
Word2vec Made Easy. This post is a simplified yet in-depth... | by Munesh Lakhey | Towards Data Science | This post is a simplified yet in-depth guide to word2vec. In this article, we will implement word2vec model from scratch and see how embedding help to find similar/dissimilar words.
Word2Vec is the foundation of NLP( Natural Language Processing). Tomas Mikolov and the team of researchers developed the technique in 2013 at Google. Their approach first published in the paper ‘Efficient Estimation of Word Representations in Vector Space’. They refined their models to improve the quality of representation and speed of computation by using techniques like sub-sampling of frequent words and adopting negative sampling. This work was published in the paper ‘Distributed Representations of Words and Phrases and their Compositionality’.
Word2Vec is an efficient and effective way of representing words as vectors. The whole body of the text is encapsulated in some space of much lower dimension. In this space, all vectors have certain orientation and it is possible to explicitly define their relationship with each other. The distributed representation of words as embedding vectors opens up many possibilities to find the words in ways that suits many applications in NLP.
We will keep the corpus simple as it helps us to understand each step with ease plus we can visualize the relationship clearly to make it more concrete. CBOW (Continuous Bag Of Words) and Skip-Gram are two most popular frames for word embedding. In CBOW the words occurring in context (surrounding words) of a selected word are used as inputs and middle or selected word as the target. Its the other way round in Skip-Gram, here the middle word tries to predict the words coming before and after it.
Consider a text consisting of characters from ‘a’ to ‘z’ sequentially [a, b,c, d, e, f, g, h, i, j, k,l, m, n, o, p, q, r,s, t, u, v, w, x, y, z], further let integers 0 to 25 represent the respective letters. Implementing CBOW keeping the window size of 2, we can see that ‘a’ is related to ‘b’ and ‘c’, ‘b’ to ‘a’, ‘c’ and’ ‘d’ and so forth. It follows that one hot vector representing input words will be of dimension [26, 1]. With the help of the model we will find the dense and distributed vector of size [10, 1]. The size of the embedding vector is selected arbitrarily.
The diagram below illustrates the context and target words.
It is easy to visualize the pattern of relationship. When they occur together within a span of 2 characters they are related or co-occurrence is true. The pattern is depicted in table and map below.
Word2Vec is a probabilistic model. Key components of this model are 2 weight matrices. The rows of the first matrix (w1) and the columns of the second matrix (w2) embed the input words and target words respectively. The product of these two word vectors is then used to get the probabilities for being a target word, given the selected input word. Upon training these embedding vectors are optimized using gradient descent such that probabilities for true targets are maximized. It is obvious that the matrices w1 and w2 are factorization a probability matrix which closely resembles the co-occurrence matrix.
Model is illustrated and explained in the figures below.
As evident from above the network is light and um ambiguous. Here we just need to create one-hot vectors for each letter and pair with all its targets. For example letter ‘a’ is [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.] (reshaped to size 26, 1) as one-hot vector and it’s targets indices are 1 and 2 (‘b’ and ‘c’).
The network has 2 fully connected layers which compute hidden and output layers. No bias is used as they are redundant for similarity measures. Softmax is the only activation and it converts the output scores to probabilities. Here the loss criterion (nn.CrossEntropyLoss) implements the Softmax and computes the loss. Adam optimizer is selected while optimizing the weights.
#Dependenciesimport torchimport torch.optim as optimimport matplotlib.pyplot as plt#Generating desired pair of inputs and targets#Empty list that collects input and target in pairsinp_target_list = [] for i in range(26): temp = [] a, b, c, d = i- 2, i - 1, i + 1, i + 2 #targets for input i temp.extend([a, b, c, d])#keep targets within range of 0 to 25 for j in range(4): if temp[j] >=0 and temp[j] <=25: inp_target_list.append([i, temp[j]])print(inp_target_list[:5])#[[0, 1], [0, 2], [1, 0], [1, 2], [1, 3]]#Get one hot vectors for all inputs#Initiate tensor with 0’s that holds all inputs in inp_target pairsinp_tensor= torch.zeros(len(inp_target_list), 26)#Substitute 1 for 0, at position indicated by respective input for i in range(len(inp_tensor)): inp_tensor[i, np.array(inp_target_list)[i, 0]] =1#One_hot for 0 or letter 'a'print(inp_tensor[0]) #tensor([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0.])#Create Network #2 fully connected layers with NO bias#Embedding dimension is 10#Softmax is implemented using loss criterion (nn.CrossEntropyLoss())fc1 = nn.Linear(26, 10, bias = False)fc2 = nn.Linear(10, 26, bias = False)params = list(fc1.parameters()) + list(fc2.parameters())LR = 0.001 #Learning ratecriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(params, lr = LR)#Train#Define inputs and target tensorsinp_tensor = inp_tensortarget_tensor = torch.tensor(inp_target_list)[:, 1]losses = []for i in range(10000): out_1 = fc1(torch.Tensor(inp_tensor)) #hidden layer out_2 = fc2(out_1) #Score matrix optimizer.zero_grad() #Flushing gradients loss = criterion(out_2, target_tensor.long().view(out_2.shape[0],))#Apply Softmax, get loss loss.backward() #Getting grads optimizer.step() #Correcting parameters if i % 1000 == 0: losses.append(loss.item()) print(loss.data)#Loss printedtensor(3.2619) tensor(3.0980) tensor(2.7768) tensor(2.4193) tensor(2.1216) tensor(1.8937) tensor(1.7242)tensor(1.6007) tensor(1.5130) tensor(1.4526) tensor(1.4121) .........
Here we will review a series of matrices. It is much easier to interpret pictures/patterns which give us a clear idea of about the numbers spread throughout the matrix.
The content of each heat map below is discussed and interpreted in the respective captions. Each row in Score matrix is the product of the embedding vector for word as input and word as the target. The products are seen as probabilities in the probability matrix. Neighboring characters within a window of 2 characters have higher values and dense probabilities.
The distance matrix is the cosine distances from each embedding vector for input word to all the vectors embedding vectors for words as input including itself. Hot diagonal values are the product with itself and have distances of 1. Values close to diagonal are warm indicating they are close neighbors to each diagonal element. This pattern is much enhanced when the matrix is plotted as 1, positive and negative distances from each other as in smoothed distances.
#Note: As there is no transposition of weight matrices in forward #propagation columns represent the embedding vectors#Score Matrixplt.matshow((fc1.weight.t() @ fc2.weight.t()).detach().numpy())#Probability Matrixplt.matshow(nn.Softmax(dim = 1)(fc1.weight.t() @ fc2.weight.t()).detach().numpy())#Distance Matrixdist_matrix = torch.zeros(26, 26)for i in range(26): for j in range(26): dist = torch.nn.functional.cosine_similarity(fc1.weight.t()[i, :], fc1.weight.t()[j, :], dim = 0, eps = 1e-8) dist_matrix[i, j] = dist#Smoothed distances if dist_matrix[i, j] ==1 --> 1if dist_matrix[i, j] < 0 --> -0.5if dist_matrix[i, j] 0 to 0.99 --> 0.5
Embedding vectors
First, let’s see the embedding for ‘a’ in w1 and ‘b’ in w2 representing input/surrounding and target/middle words respectively. The vector product between ‘a’ — as input and ‘b’ — as a target is 18.217, a relatively large positive number whereas for all other characters it is small or negative (except for ‘c’). Which implies ‘b’ (and ‘c’) will have a much higher probability. On the other hand, taking both vectors from w1, the cosine similarity between vector ‘a’ -as input and ‘b’ — as input is 0.4496 or about 63 degrees implying some similarity.
#Embedding for ‘a’ and ‘b’vec_a = fc1.weight.t()[0].data #select 'a' from w1vec_b = fc1.weight.t()[1].data #select 'b' from w1vec_b_as_target = fc2.weight[1].data #select 'b' from w2#vec_a [1.7211128, -1.8706707, 0.15043418, -1.7761097, 0.25396731, 0.17291844, 0.11687599, -2.0173464, 1.4879528, -1.6174731],#vec_b[-1.8015, -0.6789, -1.3880, -1.6618, 1.5363, -1.8415, 1.9647, -1.5331, 2.0684, -1.7526]#vec_b_as_target[1.9113195, -1.9370987, 1.349203, -1.5565106, 1.1705781, -0.78464353, -1.7225869, -1.7434344, 1.9383335, -1.2209699]#Cosine similarity between two characterstorch.nn.functional.cosine_similarity(vec_a_as_input, vec_b_as_input, dim = 0, eps = 1e-8) #0.4496 or 63 degrees#vector product between input and target vectors --> raw scorevec_a@vec_b_as_target #18.217
Cosine Similarity
Among different distance metrics, cosine similarity is more intuitive and most used in word2vec. It is normalized dot product of 2 vectors and this ratio defines the angle between them. Two vectors with the same orientation have a cosine similarity of 1, two vectors at 90° have a similarity of 0, and two vectors diametrically opposed have a similarity of -1, independent of their magnitude.
Vector combination and finding it’s neighbors
Once the words are represented by vectors, the task of finding similar or dissimilar words becomes easier. Any combination vectors result in a new vector and the cosine distances or other similarity measures can be used as before. These operations underlie the famous equation ‘king -man + woman = queen’.
t-SNE for dimensionality reduction
t-SNE ( t-distributed Stochastic Neighbor Embedding) is helpful to further reduce the dimensions of the vectors down to 2 or 3 dimensions making it possible to visualize the vectors and their spatial arrangement or distribution. The code below is an example of a t-SNE transformation of the embedding vectors from 10 dimensions to 2.
from sklearn.manifold import TSNEtsne_2d = TSNE(n_components=2).fit_transform(fc1.weight.t().detach().numpy())#First five 2d vectorsprint(tsne_2d[:5])array([[-1.11534159e-04, 1.24468185e-04], [-8.66758155e-05, -1.63095172e-04], [-5.46419301e-05, 6.82841112e-05], [ 1.30452306e-04, 1.16242307e-04], [-2.39734325e-05, 1.93809960e-04]])
The key to the implementation of word2vec is the construction of 2 complimentary weight matrices to represent words as input and as context or targets. Embedding dimension could be any arbitrary dimension depending upon vocabulary size. The output or prediction of the model is different from the similarity or distances. While the model learns to map from the input to output the embedding capture their relative position with each other. Softmax works well for smaller corpus but it becomes inefficient as the size of vocabulary grows due to the fact that it involves summing scores across the whole length of vocabulary. Skip gram with negative sampling is the preferred algorithm.Finally, Gensim is a popular and freely available library which we can employ readily for word embedding and text analysis. But knowing the underlying principles makes it much clear and easier to use these tools.
Notations and Equations:
x: One hot vector input (size: vocab, 1)
w1: Weight matrix 1 (size: vocab, embedding dim)
h: hidden layer (size: embedding dim, 1)
Vc: Vector embedding for word input(In CBOW input word is context word)
w2: Wight matrix 2 (size: embedding dim, vocab)
Vw_i: Vector embedding for i’th target word (In CBOW the middle word we are trying to predict given the selected surrounding word). Size(embedding dim, 1)
S and S_i : S_i is vector product of h (or Vc or selected row of w1) and Vw_i (or i’th column of w2). S represents scores resulting from Vc with each Vw. (size: S_i is scalar quantity and S has as many scores as vocab)
Y_i: Softmax converts the score S_i to probability Y_i (or probability of i’th target word). Doing so Softmax needs to sum across all scores(S)
Vw_prime: Sum across all target words
P(w|c): Probability of target word given context or input word
L(theta): Likelihood of parameters (theta represents the w1 and w2 which in turn collection of Vc and Vw for all the words in corpus)
l(theta): Log likelihood of theta
rho: Learning rate
Note: Equations below use one character or one word vector at a time (except during Softmax normalization) but a batch or whole of vocabulary processed while implementing in algorithm.
Forward propagation
Likelihood and back-propagation
References:
[1] Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean, Efficient Estimation of Word Representations in Vector Space (2013), arXiv:1301.3781 [cs.CL]
[2] Mikolov, Tomas, Ilya Sutskever, Kai Chen, Gregory S. Corrado and Jeffrey Dean. “Distributed Representations of Words and Phrases and their Compositionality.” NIPS(2013).
Also check out: Ali Ghodsi, Lec 13: Word2Vec Skip-Gram
Do connect via:
mail: [email protected] or | [
{
"code": null,
"e": 229,
"s": 47,
"text": "This post is a simplified yet in-depth guide to word2vec. In this article, we will implement word2vec model from scratch and see how embedding help to find similar/dissimilar words."
},
{
"code": null,
"e": 783,
"s": 229,
"text": "Word2Vec is the foundation of NLP( Natural Language Processing). Tomas Mikolov and the team of researchers developed the technique in 2013 at Google. Their approach first published in the paper ‘Efficient Estimation of Word Representations in Vector Space’. They refined their models to improve the quality of representation and speed of computation by using techniques like sub-sampling of frequent words and adopting negative sampling. This work was published in the paper ‘Distributed Representations of Words and Phrases and their Compositionality’."
},
{
"code": null,
"e": 1222,
"s": 783,
"text": "Word2Vec is an efficient and effective way of representing words as vectors. The whole body of the text is encapsulated in some space of much lower dimension. In this space, all vectors have certain orientation and it is possible to explicitly define their relationship with each other. The distributed representation of words as embedding vectors opens up many possibilities to find the words in ways that suits many applications in NLP."
},
{
"code": null,
"e": 1722,
"s": 1222,
"text": "We will keep the corpus simple as it helps us to understand each step with ease plus we can visualize the relationship clearly to make it more concrete. CBOW (Continuous Bag Of Words) and Skip-Gram are two most popular frames for word embedding. In CBOW the words occurring in context (surrounding words) of a selected word are used as inputs and middle or selected word as the target. Its the other way round in Skip-Gram, here the middle word tries to predict the words coming before and after it."
},
{
"code": null,
"e": 2300,
"s": 1722,
"text": "Consider a text consisting of characters from ‘a’ to ‘z’ sequentially [a, b,c, d, e, f, g, h, i, j, k,l, m, n, o, p, q, r,s, t, u, v, w, x, y, z], further let integers 0 to 25 represent the respective letters. Implementing CBOW keeping the window size of 2, we can see that ‘a’ is related to ‘b’ and ‘c’, ‘b’ to ‘a’, ‘c’ and’ ‘d’ and so forth. It follows that one hot vector representing input words will be of dimension [26, 1]. With the help of the model we will find the dense and distributed vector of size [10, 1]. The size of the embedding vector is selected arbitrarily."
},
{
"code": null,
"e": 2360,
"s": 2300,
"text": "The diagram below illustrates the context and target words."
},
{
"code": null,
"e": 2559,
"s": 2360,
"text": "It is easy to visualize the pattern of relationship. When they occur together within a span of 2 characters they are related or co-occurrence is true. The pattern is depicted in table and map below."
},
{
"code": null,
"e": 3169,
"s": 2559,
"text": "Word2Vec is a probabilistic model. Key components of this model are 2 weight matrices. The rows of the first matrix (w1) and the columns of the second matrix (w2) embed the input words and target words respectively. The product of these two word vectors is then used to get the probabilities for being a target word, given the selected input word. Upon training these embedding vectors are optimized using gradient descent such that probabilities for true targets are maximized. It is obvious that the matrices w1 and w2 are factorization a probability matrix which closely resembles the co-occurrence matrix."
},
{
"code": null,
"e": 3226,
"s": 3169,
"text": "Model is illustrated and explained in the figures below."
},
{
"code": null,
"e": 3604,
"s": 3226,
"text": "As evident from above the network is light and um ambiguous. Here we just need to create one-hot vectors for each letter and pair with all its targets. For example letter ‘a’ is [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.] (reshaped to size 26, 1) as one-hot vector and it’s targets indices are 1 and 2 (‘b’ and ‘c’)."
},
{
"code": null,
"e": 3980,
"s": 3604,
"text": "The network has 2 fully connected layers which compute hidden and output layers. No bias is used as they are redundant for similarity measures. Softmax is the only activation and it converts the output scores to probabilities. Here the loss criterion (nn.CrossEntropyLoss) implements the Softmax and computes the loss. Adam optimizer is selected while optimizing the weights."
},
{
"code": null,
"e": 6194,
"s": 3980,
"text": "#Dependenciesimport torchimport torch.optim as optimimport matplotlib.pyplot as plt#Generating desired pair of inputs and targets#Empty list that collects input and target in pairsinp_target_list = [] for i in range(26): temp = [] a, b, c, d = i- 2, i - 1, i + 1, i + 2 #targets for input i temp.extend([a, b, c, d])#keep targets within range of 0 to 25 for j in range(4): if temp[j] >=0 and temp[j] <=25: inp_target_list.append([i, temp[j]])print(inp_target_list[:5])#[[0, 1], [0, 2], [1, 0], [1, 2], [1, 3]]#Get one hot vectors for all inputs#Initiate tensor with 0’s that holds all inputs in inp_target pairsinp_tensor= torch.zeros(len(inp_target_list), 26)#Substitute 1 for 0, at position indicated by respective input for i in range(len(inp_tensor)): inp_tensor[i, np.array(inp_target_list)[i, 0]] =1#One_hot for 0 or letter 'a'print(inp_tensor[0]) #tensor([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0.])#Create Network #2 fully connected layers with NO bias#Embedding dimension is 10#Softmax is implemented using loss criterion (nn.CrossEntropyLoss())fc1 = nn.Linear(26, 10, bias = False)fc2 = nn.Linear(10, 26, bias = False)params = list(fc1.parameters()) + list(fc2.parameters())LR = 0.001 #Learning ratecriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(params, lr = LR)#Train#Define inputs and target tensorsinp_tensor = inp_tensortarget_tensor = torch.tensor(inp_target_list)[:, 1]losses = []for i in range(10000): out_1 = fc1(torch.Tensor(inp_tensor)) #hidden layer out_2 = fc2(out_1) #Score matrix optimizer.zero_grad() #Flushing gradients loss = criterion(out_2, target_tensor.long().view(out_2.shape[0],))#Apply Softmax, get loss loss.backward() #Getting grads optimizer.step() #Correcting parameters if i % 1000 == 0: losses.append(loss.item()) print(loss.data)#Loss printedtensor(3.2619) tensor(3.0980) tensor(2.7768) tensor(2.4193) tensor(2.1216) tensor(1.8937) tensor(1.7242)tensor(1.6007) tensor(1.5130) tensor(1.4526) tensor(1.4121) ........."
},
{
"code": null,
"e": 6363,
"s": 6194,
"text": "Here we will review a series of matrices. It is much easier to interpret pictures/patterns which give us a clear idea of about the numbers spread throughout the matrix."
},
{
"code": null,
"e": 6726,
"s": 6363,
"text": "The content of each heat map below is discussed and interpreted in the respective captions. Each row in Score matrix is the product of the embedding vector for word as input and word as the target. The products are seen as probabilities in the probability matrix. Neighboring characters within a window of 2 characters have higher values and dense probabilities."
},
{
"code": null,
"e": 7192,
"s": 6726,
"text": "The distance matrix is the cosine distances from each embedding vector for input word to all the vectors embedding vectors for words as input including itself. Hot diagonal values are the product with itself and have distances of 1. Values close to diagonal are warm indicating they are close neighbors to each diagonal element. This pattern is much enhanced when the matrix is plotted as 1, positive and negative distances from each other as in smoothed distances."
},
{
"code": null,
"e": 7849,
"s": 7192,
"text": "#Note: As there is no transposition of weight matrices in forward #propagation columns represent the embedding vectors#Score Matrixplt.matshow((fc1.weight.t() @ fc2.weight.t()).detach().numpy())#Probability Matrixplt.matshow(nn.Softmax(dim = 1)(fc1.weight.t() @ fc2.weight.t()).detach().numpy())#Distance Matrixdist_matrix = torch.zeros(26, 26)for i in range(26): for j in range(26): dist = torch.nn.functional.cosine_similarity(fc1.weight.t()[i, :], fc1.weight.t()[j, :], dim = 0, eps = 1e-8) dist_matrix[i, j] = dist#Smoothed distances if dist_matrix[i, j] ==1 --> 1if dist_matrix[i, j] < 0 --> -0.5if dist_matrix[i, j] 0 to 0.99 --> 0.5"
},
{
"code": null,
"e": 7867,
"s": 7849,
"text": "Embedding vectors"
},
{
"code": null,
"e": 8419,
"s": 7867,
"text": "First, let’s see the embedding for ‘a’ in w1 and ‘b’ in w2 representing input/surrounding and target/middle words respectively. The vector product between ‘a’ — as input and ‘b’ — as a target is 18.217, a relatively large positive number whereas for all other characters it is small or negative (except for ‘c’). Which implies ‘b’ (and ‘c’) will have a much higher probability. On the other hand, taking both vectors from w1, the cosine similarity between vector ‘a’ -as input and ‘b’ — as input is 0.4496 or about 63 degrees implying some similarity."
},
{
"code": null,
"e": 9268,
"s": 8419,
"text": "#Embedding for ‘a’ and ‘b’vec_a = fc1.weight.t()[0].data #select 'a' from w1vec_b = fc1.weight.t()[1].data #select 'b' from w1vec_b_as_target = fc2.weight[1].data #select 'b' from w2#vec_a [1.7211128, -1.8706707, 0.15043418, -1.7761097, 0.25396731, 0.17291844, 0.11687599, -2.0173464, 1.4879528, -1.6174731],#vec_b[-1.8015, -0.6789, -1.3880, -1.6618, 1.5363, -1.8415, 1.9647, -1.5331, 2.0684, -1.7526]#vec_b_as_target[1.9113195, -1.9370987, 1.349203, -1.5565106, 1.1705781, -0.78464353, -1.7225869, -1.7434344, 1.9383335, -1.2209699]#Cosine similarity between two characterstorch.nn.functional.cosine_similarity(vec_a_as_input, vec_b_as_input, dim = 0, eps = 1e-8) #0.4496 or 63 degrees#vector product between input and target vectors --> raw scorevec_a@vec_b_as_target #18.217"
},
{
"code": null,
"e": 9286,
"s": 9268,
"text": "Cosine Similarity"
},
{
"code": null,
"e": 9679,
"s": 9286,
"text": "Among different distance metrics, cosine similarity is more intuitive and most used in word2vec. It is normalized dot product of 2 vectors and this ratio defines the angle between them. Two vectors with the same orientation have a cosine similarity of 1, two vectors at 90° have a similarity of 0, and two vectors diametrically opposed have a similarity of -1, independent of their magnitude."
},
{
"code": null,
"e": 9725,
"s": 9679,
"text": "Vector combination and finding it’s neighbors"
},
{
"code": null,
"e": 10031,
"s": 9725,
"text": "Once the words are represented by vectors, the task of finding similar or dissimilar words becomes easier. Any combination vectors result in a new vector and the cosine distances or other similarity measures can be used as before. These operations underlie the famous equation ‘king -man + woman = queen’."
},
{
"code": null,
"e": 10066,
"s": 10031,
"text": "t-SNE for dimensionality reduction"
},
{
"code": null,
"e": 10400,
"s": 10066,
"text": "t-SNE ( t-distributed Stochastic Neighbor Embedding) is helpful to further reduce the dimensions of the vectors down to 2 or 3 dimensions making it possible to visualize the vectors and their spatial arrangement or distribution. The code below is an example of a t-SNE transformation of the embedding vectors from 10 dimensions to 2."
},
{
"code": null,
"e": 10766,
"s": 10400,
"text": "from sklearn.manifold import TSNEtsne_2d = TSNE(n_components=2).fit_transform(fc1.weight.t().detach().numpy())#First five 2d vectorsprint(tsne_2d[:5])array([[-1.11534159e-04, 1.24468185e-04], [-8.66758155e-05, -1.63095172e-04], [-5.46419301e-05, 6.82841112e-05], [ 1.30452306e-04, 1.16242307e-04], [-2.39734325e-05, 1.93809960e-04]])"
},
{
"code": null,
"e": 11663,
"s": 10766,
"text": "The key to the implementation of word2vec is the construction of 2 complimentary weight matrices to represent words as input and as context or targets. Embedding dimension could be any arbitrary dimension depending upon vocabulary size. The output or prediction of the model is different from the similarity or distances. While the model learns to map from the input to output the embedding capture their relative position with each other. Softmax works well for smaller corpus but it becomes inefficient as the size of vocabulary grows due to the fact that it involves summing scores across the whole length of vocabulary. Skip gram with negative sampling is the preferred algorithm.Finally, Gensim is a popular and freely available library which we can employ readily for word embedding and text analysis. But knowing the underlying principles makes it much clear and easier to use these tools."
},
{
"code": null,
"e": 11688,
"s": 11663,
"text": "Notations and Equations:"
},
{
"code": null,
"e": 11729,
"s": 11688,
"text": "x: One hot vector input (size: vocab, 1)"
},
{
"code": null,
"e": 11778,
"s": 11729,
"text": "w1: Weight matrix 1 (size: vocab, embedding dim)"
},
{
"code": null,
"e": 11819,
"s": 11778,
"text": "h: hidden layer (size: embedding dim, 1)"
},
{
"code": null,
"e": 11891,
"s": 11819,
"text": "Vc: Vector embedding for word input(In CBOW input word is context word)"
},
{
"code": null,
"e": 11939,
"s": 11891,
"text": "w2: Wight matrix 2 (size: embedding dim, vocab)"
},
{
"code": null,
"e": 12094,
"s": 11939,
"text": "Vw_i: Vector embedding for i’th target word (In CBOW the middle word we are trying to predict given the selected surrounding word). Size(embedding dim, 1)"
},
{
"code": null,
"e": 12313,
"s": 12094,
"text": "S and S_i : S_i is vector product of h (or Vc or selected row of w1) and Vw_i (or i’th column of w2). S represents scores resulting from Vc with each Vw. (size: S_i is scalar quantity and S has as many scores as vocab)"
},
{
"code": null,
"e": 12457,
"s": 12313,
"text": "Y_i: Softmax converts the score S_i to probability Y_i (or probability of i’th target word). Doing so Softmax needs to sum across all scores(S)"
},
{
"code": null,
"e": 12495,
"s": 12457,
"text": "Vw_prime: Sum across all target words"
},
{
"code": null,
"e": 12558,
"s": 12495,
"text": "P(w|c): Probability of target word given context or input word"
},
{
"code": null,
"e": 12692,
"s": 12558,
"text": "L(theta): Likelihood of parameters (theta represents the w1 and w2 which in turn collection of Vc and Vw for all the words in corpus)"
},
{
"code": null,
"e": 12726,
"s": 12692,
"text": "l(theta): Log likelihood of theta"
},
{
"code": null,
"e": 12745,
"s": 12726,
"text": "rho: Learning rate"
},
{
"code": null,
"e": 12930,
"s": 12745,
"text": "Note: Equations below use one character or one word vector at a time (except during Softmax normalization) but a batch or whole of vocabulary processed while implementing in algorithm."
},
{
"code": null,
"e": 12950,
"s": 12930,
"text": "Forward propagation"
},
{
"code": null,
"e": 12982,
"s": 12950,
"text": "Likelihood and back-propagation"
},
{
"code": null,
"e": 12994,
"s": 12982,
"text": "References:"
},
{
"code": null,
"e": 13144,
"s": 12994,
"text": "[1] Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean, Efficient Estimation of Word Representations in Vector Space (2013), arXiv:1301.3781 [cs.CL]"
},
{
"code": null,
"e": 13318,
"s": 13144,
"text": "[2] Mikolov, Tomas, Ilya Sutskever, Kai Chen, Gregory S. Corrado and Jeffrey Dean. “Distributed Representations of Words and Phrases and their Compositionality.” NIPS(2013)."
},
{
"code": null,
"e": 13373,
"s": 13318,
"text": "Also check out: Ali Ghodsi, Lec 13: Word2Vec Skip-Gram"
},
{
"code": null,
"e": 13389,
"s": 13373,
"text": "Do connect via:"
}
] |
TreeSet remove() Method in Java - GeeksforGeeks | 26 Nov, 2018
The Java.util.TreeSet.remove(Object O) method is to remove a particular element from a Tree set.
Syntax:
TreeSet.remove(Object O)
Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set.
Return Value: This method returns True if the element specified in the parameter is initially present in the Set and is successfully removed otherwise it returns False.
Below program illustrate the Java.util.TreeSet.remove() method:
// Java code to illustrate remove()import java.util.*;import java.util.TreeSet; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty TreeSet TreeSet<String> tree = new TreeSet<String>(); // Use add() method to add elements into the Set tree.add("Welcome"); tree.add("To"); tree.add("Geeks"); tree.add("4"); tree.add("Geeks"); tree.add("TreeSet"); // Displaying the TreeSet System.out.println("TreeSet: " + tree); // Removing elements using remove() method tree.remove("Geeks"); tree.remove("4"); tree.remove("TreeSet"); // Displaying the TreeSet after removal System.out.println("New TreeSet: " + tree); }}
TreeSet: [4, Geeks, To, TreeSet, Welcome]
New TreeSet: [To, Welcome]
Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Overriding in Java | [
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 24487,
"s": 24390,
"text": "The Java.util.TreeSet.remove(Object O) method is to remove a particular element from a Tree set."
},
{
"code": null,
"e": 24495,
"s": 24487,
"text": "Syntax:"
},
{
"code": null,
"e": 24520,
"s": 24495,
"text": "TreeSet.remove(Object O)"
},
{
"code": null,
"e": 24629,
"s": 24520,
"text": "Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set."
},
{
"code": null,
"e": 24798,
"s": 24629,
"text": "Return Value: This method returns True if the element specified in the parameter is initially present in the Set and is successfully removed otherwise it returns False."
},
{
"code": null,
"e": 24862,
"s": 24798,
"text": "Below program illustrate the Java.util.TreeSet.remove() method:"
},
{
"code": "// Java code to illustrate remove()import java.util.*;import java.util.TreeSet; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty TreeSet TreeSet<String> tree = new TreeSet<String>(); // Use add() method to add elements into the Set tree.add(\"Welcome\"); tree.add(\"To\"); tree.add(\"Geeks\"); tree.add(\"4\"); tree.add(\"Geeks\"); tree.add(\"TreeSet\"); // Displaying the TreeSet System.out.println(\"TreeSet: \" + tree); // Removing elements using remove() method tree.remove(\"Geeks\"); tree.remove(\"4\"); tree.remove(\"TreeSet\"); // Displaying the TreeSet after removal System.out.println(\"New TreeSet: \" + tree); }}",
"e": 25642,
"s": 24862,
"text": null
},
{
"code": null,
"e": 25712,
"s": 25642,
"text": "TreeSet: [4, Geeks, To, TreeSet, Welcome]\nNew TreeSet: [To, Welcome]\n"
},
{
"code": null,
"e": 25732,
"s": 25712,
"text": "Java - util package"
},
{
"code": null,
"e": 25749,
"s": 25732,
"text": "Java-Collections"
},
{
"code": null,
"e": 25764,
"s": 25749,
"text": "Java-Functions"
},
{
"code": null,
"e": 25777,
"s": 25764,
"text": "java-treeset"
},
{
"code": null,
"e": 25782,
"s": 25777,
"text": "Java"
},
{
"code": null,
"e": 25787,
"s": 25782,
"text": "Java"
},
{
"code": null,
"e": 25804,
"s": 25787,
"text": "Java-Collections"
},
{
"code": null,
"e": 25902,
"s": 25804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25934,
"s": 25902,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25985,
"s": 25934,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26004,
"s": 25985,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26035,
"s": 26004,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26053,
"s": 26035,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26085,
"s": 26053,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26105,
"s": 26085,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26120,
"s": 26105,
"text": "Stream In Java"
},
{
"code": null,
"e": 26144,
"s": 26120,
"text": "Singleton Class in Java"
}
] |
C# program to count the occurrences of each character | Firstly, set the string −
string str = "Website";
Console.WriteLine("String: "+str);
Check for every character in the string and increment a variable that would count the number of occurrences of that character −
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
cal++;
}
}
You can try to run the following code to count the occurrences of each character.
Live Demo
using System;
public class Demo {
public static void Main() {
string str = "Website";
Console.WriteLine("String: "+str);
while (str.Length > 0) {
Console.Write(str[0] + " = ");
int cal = 0;
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
cal++;
}
}
Console.WriteLine(cal);
str = str.Replace(str[0].ToString(), string.Empty);
}
Console.ReadLine();
}
}
String: Website
W = 1
e = 2
b = 1
s = 1
i = 1
t = 1 | [
{
"code": null,
"e": 1088,
"s": 1062,
"text": "Firstly, set the string −"
},
{
"code": null,
"e": 1147,
"s": 1088,
"text": "string str = \"Website\";\nConsole.WriteLine(\"String: \"+str);"
},
{
"code": null,
"e": 1275,
"s": 1147,
"text": "Check for every character in the string and increment a variable that would count the number of occurrences of that character −"
},
{
"code": null,
"e": 1361,
"s": 1275,
"text": "for (int j = 0; j < str.Length; j++) {\n if (str[0] == str[j]) {\n cal++;\n }\n}"
},
{
"code": null,
"e": 1443,
"s": 1361,
"text": "You can try to run the following code to count the occurrences of each character."
},
{
"code": null,
"e": 1453,
"s": 1443,
"text": "Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1453,
"text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"Website\";\n Console.WriteLine(\"String: \"+str);\n while (str.Length > 0) {\n Console.Write(str[0] + \" = \");\n int cal = 0;\n for (int j = 0; j < str.Length; j++) {\n if (str[0] == str[j]) {\n cal++;\n }\n }\n Console.WriteLine(cal);\n str = str.Replace(str[0].ToString(), string.Empty);\n }\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 2000,
"s": 1948,
"text": "String: Website\nW = 1\ne = 2\nb = 1\ns = 1\ni = 1\nt = 1"
}
] |
A Beginner's Guide to 30 Days of Google Cloud Program - GeeksforGeeks | 17 Jan, 2021
Google Cloud in collaboration with Developer Students Club (DSC) provides an opportunity to students to start their journey in cloud programming with hands-on labs on Google Cloud Platform that powers apps like Google Search, Gmail, and YouTube. Along the way, you will learn and practice cloud concepts like computing, big data, application developments, and machine learning. It usually takes place in October every year, as the name suggests the duration of this program is 30 days. It consists of several quests (collection of labs) that need to be completed in a stipulated time.
The program is divided into 2 tracks:
Cloud Engineering Track: It consists of 6 skills each represented as badges as follows:
Getting Started: Create & Manage Cloud Resources.Perform Foundational Infrastructure Tasks in Google Cloud.Setup & Configure Cloud Environments in Google Cloud.Deploy & Manage Cloud Environments with Google Cloud.Build & Secure Networks in Google Cloud.Deploy to Kubernetes in Google Cloud.
Getting Started: Create & Manage Cloud Resources.
Perform Foundational Infrastructure Tasks in Google Cloud.
Setup & Configure Cloud Environments in Google Cloud.
Deploy & Manage Cloud Environments with Google Cloud.
Build & Secure Networks in Google Cloud.
Deploy to Kubernetes in Google Cloud.
Data Science & Machine Learning Track: It consists of 6 skill represented as badges as shown below:
Getting Started: Create & Manage Cloud Resources.Perform Foundational Data, ML, and AI Tasks in Google Cloud.Insights from Data with BigQuery.Engineer Data in Google Cloud.Integrate with Machine Learning APIs.Explore Machine Learning Models with Explainable AI.
Getting Started: Create & Manage Cloud Resources.
Perform Foundational Data, ML, and AI Tasks in Google Cloud.
Insights from Data with BigQuery.
Engineer Data in Google Cloud.
Integrate with Machine Learning APIs.
Explore Machine Learning Models with Explainable AI.
On average there are around 6 labs in each skill badge. That makes it a total of 30-35 labs and at the end of each skill badge, you will need to give a test based on your learning so far.
Qwiklabs is the platform to complete the labs of the 30 days of Google Cloud. You will first need to create an account on the platform. To start with each lab you will require credits which you would get for free after successfully registering for the program.
Follow the below steps to start working on labs and exercises provided by the program:
Step 1: Head over to your Qwiklabs account, search the quest mentioned, and then click on Enroll in this Quest.
Step 2: After that, you just need to select the lab and then click on the Start Lab button to unlock the lab by using your credits.
All the labs are fixed as you click on Start Lab a timer starts within which you need to complete the lab.
Step 3: Click on Open Google Console and verify your credentials in the below-shown section.
Step 4: Click on Accept and then on Confirm.
Step 5: Then click on Agree and Continue.
Step 6: Click on the icon of cloud shell to activate the cloud shell which is in the top-right corner.
Qwiklabs is a beginner-friendly platform and there is a step-by-step detailed process that needs to be followed.
Step 7: As you can see in the image below, there is an input command (which needs to be copied and should be pasted in the cloud shell terminal. After the input there is an output and also an example output, so you get to know when you are going wrong.
Pro Tip: Sometimes 'refreshing' your window can solve your problem
in case you are not getting the desired output.
Step 8: Just follow the instructions properly and click on the End Lab button when the scoreboard shows 100/100
Pro Tip: It is suggested that the entire task of Qwiklabs
should be done in incognito mode. As to complete
each lab you are given unique credentials for a
temporary Google account so by using incognito window
you would not mess it up with your original Google account.
Just click on the scoreboard on the right-hand side and a message will pop up mentioning what you have missed.
There is an option of ‘Qwiklabs Chat Support‘ where you can ask for help whenever you are facing any problem and you would be helped within minutes.
There is also a ‘Campus Facilitator’ from each college to guide the students throughout.
Pro Tip: You are given a maximum of 5 attempts to complete a lab so do it carefully.
It is a total gain situation as this entire program is free of cost.
Get hands-on practice of Google self-placed labs.
Get to learn how Google cloud computing, Google Assistant works, and also learn trending skills such as Machine Learning, AI, Kubernetes, and many more.
Get an amazing Google cloud certificate on successful completion of the program.
Get a skill badge after the completion of every quest which you can share on your social media account.
The best part is you get a chance to win really cool Google cloud goodies (This is the reason why majority of the students enroll in this program)
Google-Cloud-Platform
Technical Scripter 2020
Advanced Computer Subject
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
OpenCV - Overview
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
Mounting a Volume Inside Docker Container
Q-Learning in Python
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman | [
{
"code": null,
"e": 23861,
"s": 23833,
"text": "\n17 Jan, 2021"
},
{
"code": null,
"e": 24446,
"s": 23861,
"text": "Google Cloud in collaboration with Developer Students Club (DSC) provides an opportunity to students to start their journey in cloud programming with hands-on labs on Google Cloud Platform that powers apps like Google Search, Gmail, and YouTube. Along the way, you will learn and practice cloud concepts like computing, big data, application developments, and machine learning. It usually takes place in October every year, as the name suggests the duration of this program is 30 days. It consists of several quests (collection of labs) that need to be completed in a stipulated time."
},
{
"code": null,
"e": 24484,
"s": 24446,
"text": "The program is divided into 2 tracks:"
},
{
"code": null,
"e": 24572,
"s": 24484,
"text": "Cloud Engineering Track: It consists of 6 skills each represented as badges as follows:"
},
{
"code": null,
"e": 24863,
"s": 24572,
"text": "Getting Started: Create & Manage Cloud Resources.Perform Foundational Infrastructure Tasks in Google Cloud.Setup & Configure Cloud Environments in Google Cloud.Deploy & Manage Cloud Environments with Google Cloud.Build & Secure Networks in Google Cloud.Deploy to Kubernetes in Google Cloud."
},
{
"code": null,
"e": 24913,
"s": 24863,
"text": "Getting Started: Create & Manage Cloud Resources."
},
{
"code": null,
"e": 24972,
"s": 24913,
"text": "Perform Foundational Infrastructure Tasks in Google Cloud."
},
{
"code": null,
"e": 25026,
"s": 24972,
"text": "Setup & Configure Cloud Environments in Google Cloud."
},
{
"code": null,
"e": 25080,
"s": 25026,
"text": "Deploy & Manage Cloud Environments with Google Cloud."
},
{
"code": null,
"e": 25121,
"s": 25080,
"text": "Build & Secure Networks in Google Cloud."
},
{
"code": null,
"e": 25159,
"s": 25121,
"text": "Deploy to Kubernetes in Google Cloud."
},
{
"code": null,
"e": 25259,
"s": 25159,
"text": "Data Science & Machine Learning Track: It consists of 6 skill represented as badges as shown below:"
},
{
"code": null,
"e": 25521,
"s": 25259,
"text": "Getting Started: Create & Manage Cloud Resources.Perform Foundational Data, ML, and AI Tasks in Google Cloud.Insights from Data with BigQuery.Engineer Data in Google Cloud.Integrate with Machine Learning APIs.Explore Machine Learning Models with Explainable AI."
},
{
"code": null,
"e": 25571,
"s": 25521,
"text": "Getting Started: Create & Manage Cloud Resources."
},
{
"code": null,
"e": 25632,
"s": 25571,
"text": "Perform Foundational Data, ML, and AI Tasks in Google Cloud."
},
{
"code": null,
"e": 25666,
"s": 25632,
"text": "Insights from Data with BigQuery."
},
{
"code": null,
"e": 25697,
"s": 25666,
"text": "Engineer Data in Google Cloud."
},
{
"code": null,
"e": 25735,
"s": 25697,
"text": "Integrate with Machine Learning APIs."
},
{
"code": null,
"e": 25788,
"s": 25735,
"text": "Explore Machine Learning Models with Explainable AI."
},
{
"code": null,
"e": 25976,
"s": 25788,
"text": "On average there are around 6 labs in each skill badge. That makes it a total of 30-35 labs and at the end of each skill badge, you will need to give a test based on your learning so far."
},
{
"code": null,
"e": 26238,
"s": 25976,
"text": "Qwiklabs is the platform to complete the labs of the 30 days of Google Cloud. You will first need to create an account on the platform. To start with each lab you will require credits which you would get for free after successfully registering for the program."
},
{
"code": null,
"e": 26325,
"s": 26238,
"text": "Follow the below steps to start working on labs and exercises provided by the program:"
},
{
"code": null,
"e": 26437,
"s": 26325,
"text": "Step 1: Head over to your Qwiklabs account, search the quest mentioned, and then click on Enroll in this Quest."
},
{
"code": null,
"e": 26569,
"s": 26437,
"text": "Step 2: After that, you just need to select the lab and then click on the Start Lab button to unlock the lab by using your credits."
},
{
"code": null,
"e": 26678,
"s": 26569,
"text": " All the labs are fixed as you click on Start Lab a timer starts within which you need to complete the lab. "
},
{
"code": null,
"e": 26771,
"s": 26678,
"text": "Step 3: Click on Open Google Console and verify your credentials in the below-shown section."
},
{
"code": null,
"e": 26816,
"s": 26771,
"text": "Step 4: Click on Accept and then on Confirm."
},
{
"code": null,
"e": 26858,
"s": 26816,
"text": "Step 5: Then click on Agree and Continue."
},
{
"code": null,
"e": 26961,
"s": 26858,
"text": "Step 6: Click on the icon of cloud shell to activate the cloud shell which is in the top-right corner."
},
{
"code": null,
"e": 27074,
"s": 26961,
"text": "Qwiklabs is a beginner-friendly platform and there is a step-by-step detailed process that needs to be followed."
},
{
"code": null,
"e": 27327,
"s": 27074,
"text": "Step 7: As you can see in the image below, there is an input command (which needs to be copied and should be pasted in the cloud shell terminal. After the input there is an output and also an example output, so you get to know when you are going wrong."
},
{
"code": null,
"e": 27451,
"s": 27327,
"text": "Pro Tip: Sometimes 'refreshing' your window can solve your problem\n in case you are not getting the desired output."
},
{
"code": null,
"e": 27563,
"s": 27451,
"text": "Step 8: Just follow the instructions properly and click on the End Lab button when the scoreboard shows 100/100"
},
{
"code": null,
"e": 27868,
"s": 27563,
"text": "Pro Tip: It is suggested that the entire task of Qwiklabs\n should be done in incognito mode. As to complete\n each lab you are given unique credentials for a\n temporary Google account so by using incognito window\n you would not mess it up with your original Google account."
},
{
"code": null,
"e": 27979,
"s": 27868,
"text": "Just click on the scoreboard on the right-hand side and a message will pop up mentioning what you have missed."
},
{
"code": null,
"e": 28128,
"s": 27979,
"text": "There is an option of ‘Qwiklabs Chat Support‘ where you can ask for help whenever you are facing any problem and you would be helped within minutes."
},
{
"code": null,
"e": 28217,
"s": 28128,
"text": "There is also a ‘Campus Facilitator’ from each college to guide the students throughout."
},
{
"code": null,
"e": 28302,
"s": 28217,
"text": "Pro Tip: You are given a maximum of 5 attempts to complete a lab so do it carefully."
},
{
"code": null,
"e": 28371,
"s": 28302,
"text": "It is a total gain situation as this entire program is free of cost."
},
{
"code": null,
"e": 28421,
"s": 28371,
"text": "Get hands-on practice of Google self-placed labs."
},
{
"code": null,
"e": 28574,
"s": 28421,
"text": "Get to learn how Google cloud computing, Google Assistant works, and also learn trending skills such as Machine Learning, AI, Kubernetes, and many more."
},
{
"code": null,
"e": 28655,
"s": 28574,
"text": "Get an amazing Google cloud certificate on successful completion of the program."
},
{
"code": null,
"e": 28759,
"s": 28655,
"text": "Get a skill badge after the completion of every quest which you can share on your social media account."
},
{
"code": null,
"e": 28906,
"s": 28759,
"text": "The best part is you get a chance to win really cool Google cloud goodies (This is the reason why majority of the students enroll in this program)"
},
{
"code": null,
"e": 28928,
"s": 28906,
"text": "Google-Cloud-Platform"
},
{
"code": null,
"e": 28952,
"s": 28928,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28978,
"s": 28952,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28997,
"s": 28978,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29095,
"s": 28997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29104,
"s": 29095,
"text": "Comments"
},
{
"code": null,
"e": 29117,
"s": 29104,
"text": "Old Comments"
},
{
"code": null,
"e": 29161,
"s": 29117,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 29202,
"s": 29161,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29229,
"s": 29202,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 29247,
"s": 29229,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 29310,
"s": 29247,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 29345,
"s": 29310,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 29387,
"s": 29345,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 29408,
"s": 29387,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 29456,
"s": 29408,
"text": "How to create a REST API using Java Spring Boot"
}
] |
forward_list::push_front() and forward_list::pop_front() in C++ STL - GeeksforGeeks | 06 Oct, 2021
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements.
push_front() function is used to push elements into a Forward list from the front. The new value is inserted into the Forward list at the beginning, before the current first element and the container size is increased by 1.Syntax :
forwardlistname.push_front(value)
Parameters :
The value to be added in the front is
passed as the parameter
Result :
Adds the value mentioned as the parameter to the
front of the forward list named as forwardlistname
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.push_front(6);
Output : 6, 1, 2, 3, 4, 5
Input : forward_list forwardlist{5, 4, 3, 2, 1};
forwardlist.push_front(6);
Output :6, 5, 4, 3, 2, 1
Errors and Exceptions1. Strong exception guarantee – if an exception is thrown, there are no changes in the container. 2. If the value passed as argument is not supported by the forward list, it shows undefined behavior.
CPP
// CPP program to illustrate// push_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; myforwardlist.push_front(6); // Forward list becomes 6, 1, 2, 3, 4, 5 for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}
Output:
6 1 2 3 4 5
Application : Input an empty forward list with the following numbers and order using push_front() function and sort the given forward list.
Input : 7, 89, 45, 6, 24, 58, 43
Output : 6, 7, 24, 43, 45, 58, 89
CPP
// CPP program to illustrate// application Of push_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}; myforwardlist.push_front(43); myforwardlist.push_front(58); myforwardlist.push_front(24); myforwardlist.push_front(6); myforwardlist.push_front(45); myforwardlist.push_front(89); myforwardlist.push_front(7); // Forward list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function myforwardlist.sort(); for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}
Output
6 7 24 43 45 58 89
pop_front() function is used to pop or remove elements from a forward list from the front. The value is removed from the list from the beginning, and the container size is decreased by 1.Syntax :
forwardlistname.pop_front()
Parameters :
No parameter is passed as the parameter.
Result :
Removes the value present at the front
of the given forward list named as forwardlistname
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.pop_front();
Output :2, 3, 4, 5
Input : forward_list forwardlist{5, 4, 3, 2, 1};
forwardlist.pop_front();
Output :4, 3, 2, 1
Errors and Exceptions1. No-Throw-Guarantee – if an exception is thrown, there are no changes in the container. 2. If the list is empty, it shows undefined behaviour.
CPP
// CPP program to illustrate// pop_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; myforwardlist.pop_front(); // forward list becomes 2, 3, 4, 5 for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}
Output:
2 3 4 5
Application : Input an empty forward list with the following numbers and order using push_front() function and print the reverse of the list.
Input : 1, 2, 3, 4, 5, 6, 7, 8
Output: 8, 7, 6, 5, 4, 3, 2, 1
CPP
// CPP program to illustrate// application Of pop_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}, newforwardlist{}; myforwardlist.push_front(8); myforwardlist.push_front(7); myforwardlist.push_front(6); myforwardlist.push_front(5); myforwardlist.push_front(4); myforwardlist.push_front(3); myforwardlist.push_front(2); myforwardlist.push_front(1); // Forward list becomes 1, 2, 3, 4, 5, 6, 7, 8 while (!myforwardlist.empty()) { newforwardlist.push_front(myforwardlist.front()); myforwardlist.pop_front(); } for (auto it = newforwardlist.begin(); it != newforwardlist.end(); ++it) cout << ' ' << *it;}
Output
8 7 6 5 4 3 2 1
hritikbhatnagar2182
cpp-containers-library
CPP-forward-list
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples | [
{
"code": null,
"e": 24216,
"s": 24188,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24607,
"s": 24216,
"text": "Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements. "
},
{
"code": null,
"e": 24841,
"s": 24607,
"text": "push_front() function is used to push elements into a Forward list from the front. The new value is inserted into the Forward list at the beginning, before the current first element and the container size is increased by 1.Syntax : "
},
{
"code": null,
"e": 25060,
"s": 24841,
"text": "forwardlistname.push_front(value)\nParameters :\nThe value to be added in the front is \npassed as the parameter\nResult :\nAdds the value mentioned as the parameter to the\nfront of the forward list named as forwardlistname"
},
{
"code": null,
"e": 25072,
"s": 25060,
"text": "Examples: "
},
{
"code": null,
"e": 25292,
"s": 25072,
"text": "Input : forward_list forwardlist{1, 2, 3, 4, 5};\n forwardlist.push_front(6);\nOutput : 6, 1, 2, 3, 4, 5\n\nInput : forward_list forwardlist{5, 4, 3, 2, 1};\n forwardlist.push_front(6);\nOutput :6, 5, 4, 3, 2, 1"
},
{
"code": null,
"e": 25514,
"s": 25292,
"text": "Errors and Exceptions1. Strong exception guarantee – if an exception is thrown, there are no changes in the container. 2. If the value passed as argument is not supported by the forward list, it shows undefined behavior. "
},
{
"code": null,
"e": 25518,
"s": 25514,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// push_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; myforwardlist.push_front(6); // Forward list becomes 6, 1, 2, 3, 4, 5 for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}",
"e": 25878,
"s": 25518,
"text": null
},
{
"code": null,
"e": 25888,
"s": 25878,
"text": "Output: "
},
{
"code": null,
"e": 25900,
"s": 25888,
"text": "6 1 2 3 4 5"
},
{
"code": null,
"e": 26042,
"s": 25900,
"text": "Application : Input an empty forward list with the following numbers and order using push_front() function and sort the given forward list. "
},
{
"code": null,
"e": 26110,
"s": 26042,
"text": "Input : 7, 89, 45, 6, 24, 58, 43\nOutput : 6, 7, 24, 43, 45, 58, 89"
},
{
"code": null,
"e": 26116,
"s": 26112,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// application Of push_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}; myforwardlist.push_front(43); myforwardlist.push_front(58); myforwardlist.push_front(24); myforwardlist.push_front(6); myforwardlist.push_front(45); myforwardlist.push_front(89); myforwardlist.push_front(7); // Forward list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function myforwardlist.sort(); for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}",
"e": 26730,
"s": 26116,
"text": null
},
{
"code": null,
"e": 26739,
"s": 26730,
"text": "Output "
},
{
"code": null,
"e": 26758,
"s": 26739,
"text": "6 7 24 43 45 58 89"
},
{
"code": null,
"e": 26958,
"s": 26760,
"text": "pop_front() function is used to pop or remove elements from a forward list from the front. The value is removed from the list from the beginning, and the container size is decreased by 1.Syntax : "
},
{
"code": null,
"e": 27140,
"s": 26958,
"text": "forwardlistname.pop_front()\nParameters :\nNo parameter is passed as the parameter.\nResult :\nRemoves the value present at the front \nof the given forward list named as forwardlistname"
},
{
"code": null,
"e": 27152,
"s": 27140,
"text": "Examples: "
},
{
"code": null,
"e": 27355,
"s": 27152,
"text": "Input : forward_list forwardlist{1, 2, 3, 4, 5};\n forwardlist.pop_front();\nOutput :2, 3, 4, 5\n\nInput : forward_list forwardlist{5, 4, 3, 2, 1};\n forwardlist.pop_front();\nOutput :4, 3, 2, 1"
},
{
"code": null,
"e": 27522,
"s": 27355,
"text": "Errors and Exceptions1. No-Throw-Guarantee – if an exception is thrown, there are no changes in the container. 2. If the list is empty, it shows undefined behaviour. "
},
{
"code": null,
"e": 27526,
"s": 27522,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// pop_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; myforwardlist.pop_front(); // forward list becomes 2, 3, 4, 5 for (auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it;}",
"e": 27877,
"s": 27526,
"text": null
},
{
"code": null,
"e": 27887,
"s": 27877,
"text": "Output: "
},
{
"code": null,
"e": 27895,
"s": 27887,
"text": "2 3 4 5"
},
{
"code": null,
"e": 28039,
"s": 27895,
"text": "Application : Input an empty forward list with the following numbers and order using push_front() function and print the reverse of the list. "
},
{
"code": null,
"e": 28101,
"s": 28039,
"text": "Input : 1, 2, 3, 4, 5, 6, 7, 8\nOutput: 8, 7, 6, 5, 4, 3, 2, 1"
},
{
"code": null,
"e": 28107,
"s": 28103,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// application Of pop_front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}, newforwardlist{}; myforwardlist.push_front(8); myforwardlist.push_front(7); myforwardlist.push_front(6); myforwardlist.push_front(5); myforwardlist.push_front(4); myforwardlist.push_front(3); myforwardlist.push_front(2); myforwardlist.push_front(1); // Forward list becomes 1, 2, 3, 4, 5, 6, 7, 8 while (!myforwardlist.empty()) { newforwardlist.push_front(myforwardlist.front()); myforwardlist.pop_front(); } for (auto it = newforwardlist.begin(); it != newforwardlist.end(); ++it) cout << ' ' << *it;}",
"e": 28848,
"s": 28107,
"text": null
},
{
"code": null,
"e": 28857,
"s": 28848,
"text": "Output "
},
{
"code": null,
"e": 28873,
"s": 28857,
"text": "8 7 6 5 4 3 2 1"
},
{
"code": null,
"e": 28895,
"s": 28875,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 28918,
"s": 28895,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 28935,
"s": 28918,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 28947,
"s": 28935,
"text": "CPP-Library"
},
{
"code": null,
"e": 28951,
"s": 28947,
"text": "STL"
},
{
"code": null,
"e": 28955,
"s": 28951,
"text": "C++"
},
{
"code": null,
"e": 28959,
"s": 28955,
"text": "STL"
},
{
"code": null,
"e": 28963,
"s": 28959,
"text": "CPP"
},
{
"code": null,
"e": 29061,
"s": 28963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29080,
"s": 29061,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29123,
"s": 29080,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29147,
"s": 29123,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29174,
"s": 29147,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29202,
"s": 29174,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29222,
"s": 29202,
"text": "Constructors in C++"
},
{
"code": null,
"e": 29250,
"s": 29222,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 29274,
"s": 29250,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 29309,
"s": 29274,
"text": "Multidimensional Arrays in C / C++"
}
] |
DATE_SUB() Function in MySQL - GeeksforGeeks | 03 Dec, 2020
DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date.
Syntax :
DATE_SUB(date, INTERVAL value addunit)
Parameter: This function accepts two parameters which are illustrated below :
date – Specified date to be modified
value addunit – Here the value is date or time interval to subtract. This value can be both positive and negative. And here the addunit is the type of interval to subtract such as SECOND, MINUTE, HOUR, DAY, YEAR, MONTH etc.
Returns :It returns the new date after subtraction of specified time or date.
Example-1 :Getting a new date of “2017-11-22” after the subtraction of 3 year to the specified date “2020-11-22”.
SELECT DATE_SUB("2020-11-22", INTERVAL 3 YEAR);
Output :
2017-11-22
Example-2 :Getting a new date of “2020-9-22” after the subtraction of 2 month to the specified date “2020-11-22”.
SELECT DATE_SUB("2020-11-22", INTERVAL 2 MONTH);
Output :
2020-09-22
Example-3 :Getting a new date of “2020-11-12” after the subtraction of 10 days to the specified date “2020-11-22”.
SELECT DATE_SUB("2020-11-22", INTERVAL 10 DAY);
Output :
2020-11-12
Example-4 :Getting a new date of “2020-11-22 06:12:10” after the subtraction of 3 hours to the specified date “2020-11-22 09:12:10”.
SELECT DATE_SUB("2020-11-22 09:12:10", INTERVAL 3 HOUR);
Output :
2020-11-22 06:12:10
Example-5 :Getting a new date of “2020-11-22 09:06:10” after the subtraction of 3 minutes to the specified date “2020-11-22 09:09:10”.
SELECT DATE_SUB("2020-11-22 09:09:10", INTERVAL 3 MINUTE);
Output :
2020-11-22 09:06:10
Example-6 :Getting a new date of “2020-11-22 09:09:05” after the subtraction of 5 seconds to the specified date “2020-11-22 09:09:10”.
SELECT DATE_SUB("2020-11-22 09:09:10", INTERVAL 5 SECOND);
Output :
2020-11-22 09:09:05
Application :This function is used to subtract a specified time or date interval to a specified date and then returns the date.
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
How to Select Data Between Two Dates and Times in SQL Server?
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Delete Duplicate Rows | [
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 24398,
"s": 24268,
"text": "DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date."
},
{
"code": null,
"e": 24407,
"s": 24398,
"text": "Syntax :"
},
{
"code": null,
"e": 24447,
"s": 24407,
"text": "DATE_SUB(date, INTERVAL value addunit)\n"
},
{
"code": null,
"e": 24525,
"s": 24447,
"text": "Parameter: This function accepts two parameters which are illustrated below :"
},
{
"code": null,
"e": 24562,
"s": 24525,
"text": "date – Specified date to be modified"
},
{
"code": null,
"e": 24786,
"s": 24562,
"text": "value addunit – Here the value is date or time interval to subtract. This value can be both positive and negative. And here the addunit is the type of interval to subtract such as SECOND, MINUTE, HOUR, DAY, YEAR, MONTH etc."
},
{
"code": null,
"e": 24864,
"s": 24786,
"text": "Returns :It returns the new date after subtraction of specified time or date."
},
{
"code": null,
"e": 24978,
"s": 24864,
"text": "Example-1 :Getting a new date of “2017-11-22” after the subtraction of 3 year to the specified date “2020-11-22”."
},
{
"code": null,
"e": 25027,
"s": 24978,
"text": "SELECT DATE_SUB(\"2020-11-22\", INTERVAL 3 YEAR);\n"
},
{
"code": null,
"e": 25036,
"s": 25027,
"text": "Output :"
},
{
"code": null,
"e": 25047,
"s": 25036,
"text": "2017-11-22"
},
{
"code": null,
"e": 25161,
"s": 25047,
"text": "Example-2 :Getting a new date of “2020-9-22” after the subtraction of 2 month to the specified date “2020-11-22”."
},
{
"code": null,
"e": 25211,
"s": 25161,
"text": "SELECT DATE_SUB(\"2020-11-22\", INTERVAL 2 MONTH);\n"
},
{
"code": null,
"e": 25220,
"s": 25211,
"text": "Output :"
},
{
"code": null,
"e": 25231,
"s": 25220,
"text": "2020-09-22"
},
{
"code": null,
"e": 25346,
"s": 25231,
"text": "Example-3 :Getting a new date of “2020-11-12” after the subtraction of 10 days to the specified date “2020-11-22”."
},
{
"code": null,
"e": 25395,
"s": 25346,
"text": "SELECT DATE_SUB(\"2020-11-22\", INTERVAL 10 DAY);\n"
},
{
"code": null,
"e": 25404,
"s": 25395,
"text": "Output :"
},
{
"code": null,
"e": 25415,
"s": 25404,
"text": "2020-11-12"
},
{
"code": null,
"e": 25548,
"s": 25415,
"text": "Example-4 :Getting a new date of “2020-11-22 06:12:10” after the subtraction of 3 hours to the specified date “2020-11-22 09:12:10”."
},
{
"code": null,
"e": 25606,
"s": 25548,
"text": "SELECT DATE_SUB(\"2020-11-22 09:12:10\", INTERVAL 3 HOUR);\n"
},
{
"code": null,
"e": 25615,
"s": 25606,
"text": "Output :"
},
{
"code": null,
"e": 25635,
"s": 25615,
"text": "2020-11-22 06:12:10"
},
{
"code": null,
"e": 25770,
"s": 25635,
"text": "Example-5 :Getting a new date of “2020-11-22 09:06:10” after the subtraction of 3 minutes to the specified date “2020-11-22 09:09:10”."
},
{
"code": null,
"e": 25830,
"s": 25770,
"text": "SELECT DATE_SUB(\"2020-11-22 09:09:10\", INTERVAL 3 MINUTE);\n"
},
{
"code": null,
"e": 25839,
"s": 25830,
"text": "Output :"
},
{
"code": null,
"e": 25859,
"s": 25839,
"text": "2020-11-22 09:06:10"
},
{
"code": null,
"e": 25994,
"s": 25859,
"text": "Example-6 :Getting a new date of “2020-11-22 09:09:05” after the subtraction of 5 seconds to the specified date “2020-11-22 09:09:10”."
},
{
"code": null,
"e": 26054,
"s": 25994,
"text": "SELECT DATE_SUB(\"2020-11-22 09:09:10\", INTERVAL 5 SECOND);\n"
},
{
"code": null,
"e": 26063,
"s": 26054,
"text": "Output :"
},
{
"code": null,
"e": 26083,
"s": 26063,
"text": "2020-11-22 09:09:05"
},
{
"code": null,
"e": 26211,
"s": 26083,
"text": "Application :This function is used to subtract a specified time or date interval to a specified date and then returns the date."
},
{
"code": null,
"e": 26220,
"s": 26211,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26226,
"s": 26220,
"text": "mysql"
},
{
"code": null,
"e": 26230,
"s": 26226,
"text": "SQL"
},
{
"code": null,
"e": 26234,
"s": 26230,
"text": "SQL"
},
{
"code": null,
"e": 26332,
"s": 26234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26398,
"s": 26332,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26430,
"s": 26398,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26508,
"s": 26430,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26525,
"s": 26508,
"text": "SQL using Python"
},
{
"code": null,
"e": 26540,
"s": 26525,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26606,
"s": 26540,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26642,
"s": 26606,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26704,
"s": 26642,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 26757,
"s": 26704,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
jQuery - find( selector ) Method | The find( selector ) method searches for descendant elements that match the specified selector.
Here is the simple syntax to use this method −
selector.find( selector )
Here is the description of all the parameters used by this method −
selector − The selector can be written using CSS 1-3 selector syntax.
selector − The selector can be written using CSS 1-3 selector syntax.
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
</div>
</body>
</html>
This will produce following result −
Hello, how are you?
Me? I'm good.
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<p><span class = "selected">Hello</span>, how are you?</p>
<p>Me? I'm <span class = "selected">good</span>.</p>
</div>
</body>
</html>
This will produce following result −
Hello, how are you?
Me? I'm good.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2418,
"s": 2322,
"text": "The find( selector ) method searches for descendant elements that match the specified selector."
},
{
"code": null,
"e": 2465,
"s": 2418,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2492,
"s": 2465,
"text": "selector.find( selector )\n"
},
{
"code": null,
"e": 2560,
"s": 2492,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2630,
"s": 2560,
"text": "selector − The selector can be written using CSS 1-3 selector syntax."
},
{
"code": null,
"e": 2700,
"s": 2630,
"text": "selector − The selector can be written using CSS 1-3 selector syntax."
},
{
"code": null,
"e": 2773,
"s": 2700,
"text": "Following is a simple example a simple showing the usage of this method."
},
{
"code": null,
"e": 3384,
"s": 2773,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p\").find(\"span\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <p><span>Hello</span>, how are you?</p>\n <p>Me? I'm <span>good</span>.</p>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3421,
"s": 3384,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3441,
"s": 3421,
"text": "Hello, how are you?"
},
{
"code": null,
"e": 3455,
"s": 3441,
"text": "Me? I'm good."
},
{
"code": null,
"e": 3528,
"s": 3455,
"text": "Following is a simple example a simple showing the usage of this method."
},
{
"code": null,
"e": 4177,
"s": 3528,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p\").find(\"span\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <p><span class = \"selected\">Hello</span>, how are you?</p>\n <p>Me? I'm <span class = \"selected\">good</span>.</p>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4214,
"s": 4177,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4234,
"s": 4214,
"text": "Hello, how are you?"
},
{
"code": null,
"e": 4248,
"s": 4234,
"text": "Me? I'm good."
},
{
"code": null,
"e": 4281,
"s": 4248,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4295,
"s": 4281,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4330,
"s": 4295,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4344,
"s": 4330,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4379,
"s": 4344,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4396,
"s": 4379,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4429,
"s": 4396,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4457,
"s": 4429,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4490,
"s": 4457,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4511,
"s": 4490,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4543,
"s": 4511,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4560,
"s": 4543,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4567,
"s": 4560,
"text": " Print"
},
{
"code": null,
"e": 4578,
"s": 4567,
"text": " Add Notes"
}
] |
Count of elements in given Array divisible by all elements in their prefix - GeeksforGeeks | 24 Jan, 2022
Given an array arr[] containing N positive integers, the task is to find the total number of elements in the array that are divisible by all the elements present before them.
Examples:
Input: arr[] = {10, 6, 60, 120, 30, 360}Output: 3Explanation: 60, 120 and 360 are the required elements.
Input: arr[] = {2, 6, 5, 60}Output: 2Explanation: 6 and 60 are the elements.
Approach: As known, that any number X is divided by {X1, X2, X3, X4, . . ., Xn}, if X is divided by LCM of {X1, X2, X3, X4, ..., Xn). And LCM of any number A, B is [(A*B)/gcd(A, B)]. Now to solve this problem, follow the below steps:
Create a variable ans which stores the final answer and initialize it with 0.Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element.Print ans as the final answer to this problem.
Create a variable ans which stores the final answer and initialize it with 0.
Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].
Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element.
Print ans as the final answer to this problem.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to return total number of// elements which are divisible by// all their previous elementsint countElements(int arr[], int N){ int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans;} // Driver codeint main(){ int arr[] = { 10, 6, 60, 120, 30, 360 }; int N = sizeof(arr) / sizeof(int); cout << countElements(arr, N); return 0;}
// Java program for the above approachimport java.util.*;public class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements static int countElements(int arr[], int N) { int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } public static void main(String args[]) { int arr[] = { 10, 6, 60, 120, 30, 360 }; int N = arr.length; System.out.print(countElements(arr, N)); }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Recursive function to return gcd of a and bdef __gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return __gcd(a - b, b); return __gcd(a, b - a); # Function to return total number of# elements which are divisible by# all their previous elementsdef countElements(arr, N): ans = 0; lcm = arr[0]; for i in range(1, N): # To check if number is divisible # by lcm of all previous elements if (arr[i] % lcm == 0): ans += 1 # Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); return ans; # Driver codearr = [10, 6, 60, 120, 30, 360]; N = len(arr)print(countElements(arr, N)); # This code is contributed by Saurabh Jaiswal
// C#program for the above approachusing System; public class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements static int countElements(int[] arr, int N) { int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } public static void Main() { int[] arr = { 10, 6, 60, 120, 30, 360 }; int N = arr.Length; Console.Write(countElements(arr, N)); }} // This code is contributed by ukasp.
<script> // JavaScript code for the above approach // Recursive function to return gcd of a and b function __gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements function countElements(arr, N) { let ans = 0; let lcm = arr[0]; for (let i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } // Driver code let arr = [10, 6, 60, 120, 30, 360]; let N = arr.length document.write(countElements(arr, N)); // This code is contributed by Potta Lokesh </script>
3
Time complexity: O(N * logD) where D is the maximum array elementAuxiliary Space: O(N)
lokeshpotta20
_saurabh_jaiswal
samim2000
ukasp
GCD-LCM
prefix
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 24971,
"s": 24796,
"text": "Given an array arr[] containing N positive integers, the task is to find the total number of elements in the array that are divisible by all the elements present before them."
},
{
"code": null,
"e": 24981,
"s": 24971,
"text": "Examples:"
},
{
"code": null,
"e": 25086,
"s": 24981,
"text": "Input: arr[] = {10, 6, 60, 120, 30, 360}Output: 3Explanation: 60, 120 and 360 are the required elements."
},
{
"code": null,
"e": 25163,
"s": 25086,
"text": "Input: arr[] = {2, 6, 5, 60}Output: 2Explanation: 6 and 60 are the elements."
},
{
"code": null,
"e": 25397,
"s": 25163,
"text": "Approach: As known, that any number X is divided by {X1, X2, X3, X4, . . ., Xn}, if X is divided by LCM of {X1, X2, X3, X4, ..., Xn). And LCM of any number A, B is [(A*B)/gcd(A, B)]. Now to solve this problem, follow the below steps:"
},
{
"code": null,
"e": 25823,
"s": 25397,
"text": "Create a variable ans which stores the final answer and initialize it with 0.Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0].Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element.Print ans as the final answer to this problem."
},
{
"code": null,
"e": 25901,
"s": 25823,
"text": "Create a variable ans which stores the final answer and initialize it with 0."
},
{
"code": null,
"e": 26031,
"s": 25901,
"text": "Create another variable lcm which stores LCM up to the ith element while iterating through the array. Initialize lcm with arr[0]."
},
{
"code": null,
"e": 26205,
"s": 26031,
"text": "Iterate over the array from i = 1 to i = N, and in each iteration, check if arr[i] is divided by lcm. If yes increment ans by 1. Also, update lcm with lcm up to ith element."
},
{
"code": null,
"e": 26252,
"s": 26205,
"text": "Print ans as the final answer to this problem."
},
{
"code": null,
"e": 26303,
"s": 26252,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26307,
"s": 26303,
"text": "C++"
},
{
"code": null,
"e": 26312,
"s": 26307,
"text": "Java"
},
{
"code": null,
"e": 26320,
"s": 26312,
"text": "Python3"
},
{
"code": null,
"e": 26323,
"s": 26320,
"text": "C#"
},
{
"code": null,
"e": 26334,
"s": 26323,
"text": "Javascript"
},
{
"code": "// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to return total number of// elements which are divisible by// all their previous elementsint countElements(int arr[], int N){ int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans;} // Driver codeint main(){ int arr[] = { 10, 6, 60, 120, 30, 360 }; int N = sizeof(arr) / sizeof(int); cout << countElements(arr, N); return 0;}",
"e": 27026,
"s": 26334,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements static int countElements(int arr[], int N) { int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } public static void main(String args[]) { int arr[] = { 10, 6, 60, 120, 30, 360 }; int N = arr.length; System.out.print(countElements(arr, N)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 28076,
"s": 27026,
"text": null
},
{
"code": "# Python code for the above approach # Recursive function to return gcd of a and bdef __gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return __gcd(a - b, b); return __gcd(a, b - a); # Function to return total number of# elements which are divisible by# all their previous elementsdef countElements(arr, N): ans = 0; lcm = arr[0]; for i in range(1, N): # To check if number is divisible # by lcm of all previous elements if (arr[i] % lcm == 0): ans += 1 # Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); return ans; # Driver codearr = [10, 6, 60, 120, 30, 360]; N = len(arr)print(countElements(arr, N)); # This code is contributed by Saurabh Jaiswal",
"e": 28946,
"s": 28076,
"text": null
},
{
"code": "// C#program for the above approachusing System; public class GFG { // Recursive function to return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements static int countElements(int[] arr, int N) { int ans = 0; int lcm = arr[0]; for (int i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } public static void Main() { int[] arr = { 10, 6, 60, 120, 30, 360 }; int N = arr.Length; Console.Write(countElements(arr, N)); }} // This code is contributed by ukasp.",
"e": 29957,
"s": 28946,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Recursive function to return gcd of a and b function __gcd(a, b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Function to return total number of // elements which are divisible by // all their previous elements function countElements(arr, N) { let ans = 0; let lcm = arr[0]; for (let i = 1; i < N; i++) { // To check if number is divisible // by lcm of all previous elements if (arr[i] % lcm == 0) { ans++; } // Updating LCM lcm = (lcm * arr[i]) / __gcd(lcm, arr[i]); } return ans; } // Driver code let arr = [10, 6, 60, 120, 30, 360]; let N = arr.length document.write(countElements(arr, N)); // This code is contributed by Potta Lokesh </script>",
"e": 31139,
"s": 29957,
"text": null
},
{
"code": null,
"e": 31144,
"s": 31142,
"text": "3"
},
{
"code": null,
"e": 31233,
"s": 31146,
"text": "Time complexity: O(N * logD) where D is the maximum array elementAuxiliary Space: O(N)"
},
{
"code": null,
"e": 31249,
"s": 31235,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31266,
"s": 31249,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31276,
"s": 31266,
"text": "samim2000"
},
{
"code": null,
"e": 31282,
"s": 31276,
"text": "ukasp"
},
{
"code": null,
"e": 31290,
"s": 31282,
"text": "GCD-LCM"
},
{
"code": null,
"e": 31297,
"s": 31290,
"text": "prefix"
},
{
"code": null,
"e": 31304,
"s": 31297,
"text": "Arrays"
},
{
"code": null,
"e": 31317,
"s": 31304,
"text": "Mathematical"
},
{
"code": null,
"e": 31324,
"s": 31317,
"text": "Arrays"
},
{
"code": null,
"e": 31337,
"s": 31324,
"text": "Mathematical"
},
{
"code": null,
"e": 31435,
"s": 31337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31460,
"s": 31435,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31480,
"s": 31460,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 31518,
"s": 31480,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31543,
"s": 31518,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 31628,
"s": 31543,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 31658,
"s": 31628,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31718,
"s": 31658,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31733,
"s": 31718,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31776,
"s": 31733,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
alarm() - Unix, Linux System Call | Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <unistd.h>
unsigned int alarm(unsigned int seconds);
unsigned int alarm(unsigned int seconds);
alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds.
If seconds is zero, no new alarm() is scheduled.
In any event any previously set alarm() is cancelled.
alarm() returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
alarm() and setitimer() share the same timer; calls to one will interfere with use of the other.
sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.
Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.
SVr4, POSIX.1-2001, 4.3BSD
gettimeofday (2)
gettimeofday (2)
pause (2)
pause (2)
select (2)
select (2)
setitimer (2)
setitimer (2)
sigaction (2)
sigaction (2)
signal (2)
signal (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2385,
"s": 2319,
"text": "#include <unistd.h> \n\nunsigned int alarm(unsigned int seconds); \n"
},
{
"code": null,
"e": 2428,
"s": 2385,
"text": "unsigned int alarm(unsigned int seconds); "
},
{
"code": null,
"e": 2517,
"s": 2428,
"text": "alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds."
},
{
"code": null,
"e": 2566,
"s": 2517,
"text": "If seconds is zero, no new alarm() is scheduled."
},
{
"code": null,
"e": 2620,
"s": 2566,
"text": "In any event any previously set alarm() is cancelled."
},
{
"code": null,
"e": 2782,
"s": 2620,
"text": "alarm() returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm."
},
{
"code": null,
"e": 2879,
"s": 2782,
"text": "alarm() and setitimer() share the same timer; calls to one will interfere with use of the other."
},
{
"code": null,
"e": 2972,
"s": 2879,
"text": "sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea."
},
{
"code": null,
"e": 3085,
"s": 2972,
"text": "Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time."
},
{
"code": null,
"e": 3112,
"s": 3085,
"text": "SVr4, POSIX.1-2001, 4.3BSD"
},
{
"code": null,
"e": 3129,
"s": 3112,
"text": "gettimeofday (2)"
},
{
"code": null,
"e": 3146,
"s": 3129,
"text": "gettimeofday (2)"
},
{
"code": null,
"e": 3156,
"s": 3146,
"text": "pause (2)"
},
{
"code": null,
"e": 3166,
"s": 3156,
"text": "pause (2)"
},
{
"code": null,
"e": 3177,
"s": 3166,
"text": "select (2)"
},
{
"code": null,
"e": 3188,
"s": 3177,
"text": "select (2)"
},
{
"code": null,
"e": 3202,
"s": 3188,
"text": "setitimer (2)"
},
{
"code": null,
"e": 3216,
"s": 3202,
"text": "setitimer (2)"
},
{
"code": null,
"e": 3230,
"s": 3216,
"text": "sigaction (2)"
},
{
"code": null,
"e": 3244,
"s": 3230,
"text": "sigaction (2)"
},
{
"code": null,
"e": 3255,
"s": 3244,
"text": "signal (2)"
},
{
"code": null,
"e": 3266,
"s": 3255,
"text": "signal (2)"
},
{
"code": null,
"e": 3283,
"s": 3266,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 3318,
"s": 3283,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 3346,
"s": 3318,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3380,
"s": 3346,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3397,
"s": 3380,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3430,
"s": 3397,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3441,
"s": 3430,
"text": " Pradeep D"
},
{
"code": null,
"e": 3476,
"s": 3441,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3492,
"s": 3476,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 3525,
"s": 3492,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3537,
"s": 3525,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3569,
"s": 3537,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3577,
"s": 3569,
"text": " Uplatz"
},
{
"code": null,
"e": 3584,
"s": 3577,
"text": " Print"
},
{
"code": null,
"e": 3595,
"s": 3584,
"text": " Add Notes"
}
] |
How to copy a file's content from Linux terminal? - GeeksforGeeks | 11 Jul, 2019
This article shows the alternative method to copy the content of the file onto the clipboard, via the Linux terminal. In OSX, the commands pbcopy and pbpaste are available by default. Thus, to copy a file onto the clipboard via OSX terminal, type:
pbcopy < 'path of the file'
Since, in Ubuntu, pbcopy and pbpaste commands are not available by default, installing xclip will serve our purpose.
The next step is to open the bash_aliases file.
Next, type in the following inside bash_aliases file and save it.
#using pbcopy and pbpaste for copy-paste a file's contents
alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'
This will set pbcopy and pbpaste as the aliases for xclip’s copy and paste commands respectively. Now we are ready to test the commands in the terminal. Let’s create a file named ‘file.txt’ and add some content into it.
Save the file and exit from the text editor. Let’s try copying and pasting its content from the terminal with our pbcopy and pbpaste commands.
Thus, now we are able to copy and paste the contents of our file using the terminal.
Note: One can use pbcopy command in the terminal to copy the c++/python template file used for competitive programming. Instead of the opening and copying the template file every time you attempt a question, just run the command in the terminal to get the work done and save time.
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples | [
{
"code": null,
"e": 24432,
"s": 24404,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 24680,
"s": 24432,
"text": "This article shows the alternative method to copy the content of the file onto the clipboard, via the Linux terminal. In OSX, the commands pbcopy and pbpaste are available by default. Thus, to copy a file onto the clipboard via OSX terminal, type:"
},
{
"code": null,
"e": 24708,
"s": 24680,
"text": "pbcopy < 'path of the file'"
},
{
"code": null,
"e": 24825,
"s": 24708,
"text": "Since, in Ubuntu, pbcopy and pbpaste commands are not available by default, installing xclip will serve our purpose."
},
{
"code": null,
"e": 24873,
"s": 24825,
"text": "The next step is to open the bash_aliases file."
},
{
"code": null,
"e": 24939,
"s": 24873,
"text": "Next, type in the following inside bash_aliases file and save it."
},
{
"code": null,
"e": 25088,
"s": 24939,
"text": "#using pbcopy and pbpaste for copy-paste a file's contents\n\nalias pbcopy='xclip -selection clipboard'\nalias pbpaste='xclip -selection clipboard -o'\n"
},
{
"code": null,
"e": 25308,
"s": 25088,
"text": "This will set pbcopy and pbpaste as the aliases for xclip’s copy and paste commands respectively. Now we are ready to test the commands in the terminal. Let’s create a file named ‘file.txt’ and add some content into it."
},
{
"code": null,
"e": 25451,
"s": 25308,
"text": "Save the file and exit from the text editor. Let’s try copying and pasting its content from the terminal with our pbcopy and pbpaste commands."
},
{
"code": null,
"e": 25536,
"s": 25451,
"text": "Thus, now we are able to copy and paste the contents of our file using the terminal."
},
{
"code": null,
"e": 25817,
"s": 25536,
"text": "Note: One can use pbcopy command in the terminal to copy the c++/python template file used for competitive programming. Instead of the opening and copying the template file every time you attempt a question, just run the command in the terminal to get the work done and save time."
},
{
"code": null,
"e": 25831,
"s": 25817,
"text": "linux-command"
},
{
"code": null,
"e": 25842,
"s": 25831,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25940,
"s": 25842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25977,
"s": 25940,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26012,
"s": 25977,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26038,
"s": 26012,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26072,
"s": 26038,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26109,
"s": 26072,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26138,
"s": 26109,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26164,
"s": 26138,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26204,
"s": 26164,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26239,
"s": 26204,
"text": "Basic Operators in Shell Scripting"
}
] |
Stop Using Pandas get_dummies() for Feature Encoding | by Satyam Kumar | Towards Data Science | Machine learning algorithms require the input data source in a specific format of numerical vectors. Feature engineering is an important component of a data science model development life cycle, which refers to converting the raw data to numerical format fit for training a robust model.
A data scientist spends about 80% of the time on data preparation and feature engineering. The performance of the model depends on the feature engineering strategies. The raw dataset contains various data types of features including numerical, categorical, date time, etc. There are various feature-engineering techniques that convert different data types of data features to numerical vectors.
Dummy Encoding refers to an encoding strategy to convert a categorical feature to a numerical vector format. There are various other techniques to encode a categorical feature including Count Encoder, One Hot Encoder, Tf-Idf Encoder, etc.
pd.get_dummies() is a function from Pandas that performs dummy encoding in a single line of code. Data scientists mostly use this for feature encoding, but it’s not recommended to use it in production or Kaggle competitions. In this article, we will discuss the reason behind it and what the best choice is for the get_dummies() function.
The get_dummies() function from the Pandas library can be used to convert a categorical variable into dummy/indicator variables. It is in a way a static technique for encoding in its behavior.
We will take a random dataset with 2 numerical and 1 categorical feature (‘color’) for further demostration. The ‘color’ categorical variable has 3 unique categories: green, red, blue.
You can observe the encoded results for pd.get_dummies() . The usage of this function is not recommended in production or on Kaggle as it is in a way static in nature in its behavior. It cannot learn the characteristics from the training data and hence is unable to propagate its findings onto the test dataset.
The categorical feature color has 3 feature values: green, red, blue. In the training sample that causes encoding the color feature into 3 feature categories. But the test data may or may not have all the feature values, which may cause data mismatch issues while modeling.
The blue feature value is missing in the color feature, which causes the absence of the blue feature column in the encoded data. This is caused because pd.get_dummies does not learn the characteristics of training data and will further cause feature mismatch while prediction.
#to print the encoded features for train datapd.get_dummies(X_train)#to print the encoded features for test datapd.get_dummies(X_test)
The only advantage of pd.get_dummies() is its easy interpretability, and the fact that it returns a pandas data frame with clean column names.
One-hot Encoder is a popular feature encoding strategy that performs similar to pd.get_dummies() with added advantages. It encodes a nominal or categorical feature by assigning one binary column per category per categorical feature. Scikit-learn comes with the implementation of the one-hot encoder.
From the above results of One hot encoder for training and test data, one can observe that the characteristics of encoding are saved while encoding the categorical variable for training data and its finding or feature values are propagated while encoding the test data.
Although the blue feature values were not present in the test data, one hot encoder created a feature column for the blue category, as it was present in the training pipeline.
from sklearn.preprocessing import OneHotEncoder# one hot encodingenc = OneHotEncoder(sparse=False)color_onehot = enc.fit_transform(X_train[['color']])#to print the encoded features for train datapd.DataFrame(color_onehot, columns=list(enc.categories_[0]))# tranform encoding for test datatest_onehot = enc.transform(X_test[['color']])#to print the encoded features for train datapd.DataFrame(test_onehot, columns=list(enc.categories_[0]))
pd.get_dummies() returns a pandas data frame with clean column names after feature encoding, still, it's not recommended to use it for production or in Kaggle competitions. One-hot encoded or Count Vectorizer strategies should be preferred as it carries the characteristics of feature values for each categorical features.
New feature categories can also be handled using handle_unknown=’ignore’ parameter for One hot encoder, which can further cause data mismatch issues in pd.get_dummies()
[1] Scikit-learn documentation: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
Thank You for Reading | [
{
"code": null,
"e": 335,
"s": 47,
"text": "Machine learning algorithms require the input data source in a specific format of numerical vectors. Feature engineering is an important component of a data science model development life cycle, which refers to converting the raw data to numerical format fit for training a robust model."
},
{
"code": null,
"e": 730,
"s": 335,
"text": "A data scientist spends about 80% of the time on data preparation and feature engineering. The performance of the model depends on the feature engineering strategies. The raw dataset contains various data types of features including numerical, categorical, date time, etc. There are various feature-engineering techniques that convert different data types of data features to numerical vectors."
},
{
"code": null,
"e": 969,
"s": 730,
"text": "Dummy Encoding refers to an encoding strategy to convert a categorical feature to a numerical vector format. There are various other techniques to encode a categorical feature including Count Encoder, One Hot Encoder, Tf-Idf Encoder, etc."
},
{
"code": null,
"e": 1308,
"s": 969,
"text": "pd.get_dummies() is a function from Pandas that performs dummy encoding in a single line of code. Data scientists mostly use this for feature encoding, but it’s not recommended to use it in production or Kaggle competitions. In this article, we will discuss the reason behind it and what the best choice is for the get_dummies() function."
},
{
"code": null,
"e": 1501,
"s": 1308,
"text": "The get_dummies() function from the Pandas library can be used to convert a categorical variable into dummy/indicator variables. It is in a way a static technique for encoding in its behavior."
},
{
"code": null,
"e": 1686,
"s": 1501,
"text": "We will take a random dataset with 2 numerical and 1 categorical feature (‘color’) for further demostration. The ‘color’ categorical variable has 3 unique categories: green, red, blue."
},
{
"code": null,
"e": 1998,
"s": 1686,
"text": "You can observe the encoded results for pd.get_dummies() . The usage of this function is not recommended in production or on Kaggle as it is in a way static in nature in its behavior. It cannot learn the characteristics from the training data and hence is unable to propagate its findings onto the test dataset."
},
{
"code": null,
"e": 2272,
"s": 1998,
"text": "The categorical feature color has 3 feature values: green, red, blue. In the training sample that causes encoding the color feature into 3 feature categories. But the test data may or may not have all the feature values, which may cause data mismatch issues while modeling."
},
{
"code": null,
"e": 2549,
"s": 2272,
"text": "The blue feature value is missing in the color feature, which causes the absence of the blue feature column in the encoded data. This is caused because pd.get_dummies does not learn the characteristics of training data and will further cause feature mismatch while prediction."
},
{
"code": null,
"e": 2684,
"s": 2549,
"text": "#to print the encoded features for train datapd.get_dummies(X_train)#to print the encoded features for test datapd.get_dummies(X_test)"
},
{
"code": null,
"e": 2827,
"s": 2684,
"text": "The only advantage of pd.get_dummies() is its easy interpretability, and the fact that it returns a pandas data frame with clean column names."
},
{
"code": null,
"e": 3127,
"s": 2827,
"text": "One-hot Encoder is a popular feature encoding strategy that performs similar to pd.get_dummies() with added advantages. It encodes a nominal or categorical feature by assigning one binary column per category per categorical feature. Scikit-learn comes with the implementation of the one-hot encoder."
},
{
"code": null,
"e": 3397,
"s": 3127,
"text": "From the above results of One hot encoder for training and test data, one can observe that the characteristics of encoding are saved while encoding the categorical variable for training data and its finding or feature values are propagated while encoding the test data."
},
{
"code": null,
"e": 3573,
"s": 3397,
"text": "Although the blue feature values were not present in the test data, one hot encoder created a feature column for the blue category, as it was present in the training pipeline."
},
{
"code": null,
"e": 4012,
"s": 3573,
"text": "from sklearn.preprocessing import OneHotEncoder# one hot encodingenc = OneHotEncoder(sparse=False)color_onehot = enc.fit_transform(X_train[['color']])#to print the encoded features for train datapd.DataFrame(color_onehot, columns=list(enc.categories_[0]))# tranform encoding for test datatest_onehot = enc.transform(X_test[['color']])#to print the encoded features for train datapd.DataFrame(test_onehot, columns=list(enc.categories_[0]))"
},
{
"code": null,
"e": 4335,
"s": 4012,
"text": "pd.get_dummies() returns a pandas data frame with clean column names after feature encoding, still, it's not recommended to use it for production or in Kaggle competitions. One-hot encoded or Count Vectorizer strategies should be preferred as it carries the characteristics of feature values for each categorical features."
},
{
"code": null,
"e": 4504,
"s": 4335,
"text": "New feature categories can also be handled using handle_unknown=’ignore’ parameter for One hot encoder, which can further cause data mismatch issues in pd.get_dummies()"
},
{
"code": null,
"e": 4627,
"s": 4504,
"text": "[1] Scikit-learn documentation: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.