title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Parallel Neural Networks and Transfer Learning | by Himanshu Aswani | Towards Data Science
Hey there! This is my first ever article on medium. I have been planning to write this article for a while now. My main motivation is to help simplify and even maybe provide a template for taking the next step in building complex neural networks that involve parallel neurons in addition to those in a certain architecture you may have already built. This is so as although it may seem simple on paper, building, saving, loading and refining (training at a later time) neural nets do form a stumbling block when we actually begin to code them up. Hopefully, this article helps you understand issues related to those a bit better too and help you in solving those minor hiccups that you face from time to time when you are getting started with deep learning. With that, let’s begin our journey. For those who are beginning to learn or are practicing neural nets, you may have observed that most of the neural network architectures we work with are usually feed-forward i.e. tensors flow from one layer to the next sequentially. Let’s say we want to explore what happens if we increase the number of neurons in one layer after we have built and trained our architecture to some degree of satisfaction. This would usually mean starting all over from scratch again and possibly wasting a few hours training. Just to see the effect of adding a few neurons in a particular layer, it seems unreasonable to begin all over from scratch. This is where transfer learning comes in. What it means, in simple terms, is the fact that you want to transfer what you have learnt while learning a particular task to another task. In the paradigm of neural networks, what we learn is represented by the weight values obtained after training. When we begin to learn more about how to utilize transfer learning, most of the in-built functions have fixed neural architectures as well as subsume code utilized for reloading weights and updating them in a new context. To figure out the specifics of applying it to your custom model will most probably take a few hours or days of hair scratching and pondering over multiple examples available online. I have done that myself and believe consolidating what I have learnt, all in one place, will definitely help anyone wanting to become more hands-on with transfer learning as well as exploring another alternative to augmenting neural networks. With that, let’s begin our example. I shall assume you are familiar with the tutorial available on building neural nets in PyTorch available at the link: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html. To learn the basics of transfer learning for existing popular architectures, do refer the link: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html. I strongly encourage you to visit these links and others available there to practice as well as form a well-rounded idea of training neural network architectures. Let’s say we now want to create a copy of the network described in the CIFAR 10 tutorial and place it in parallel with our trained version create a bigger network for the same problem of image classification. Our current model looks like this conceptually: A TensorBoard depiction of the graph reveals the following: Our goal now is to construct a neural network architecture that looks like this: We also want that the upper sub-part of this new structure contain the same weights as that obtained by executing the tutorial. Let’s look at the code that helps us realize such a structure: import torchimport torchvisionimport torchvision.transforms as transformstransform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=0)testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=0)classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')import matplotlib.pyplot as pltimport numpy as np# functions to show an imagedef imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show()# get some random training imagesdataiter = iter(trainloader)images, labels = dataiter.next()# show imagesimshow(torchvision.utils.make_grid(images))# print labelsprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net()PATH = './cifar_net.pth'net.load_state_dict(torch.load(PATH)) Till now, we have recreated our model learnt from the tutorial that we had trained and loaded the weights for us to copy into our new network. The following code constructs our required architecture. class SideNet(nn.Module): def __init__(self): super(SideNet, self).__init__() self.pool = nn.MaxPool2d(2, 2) self.conv11 = nn.Conv2d(3, 6, 5) self.conv12 = nn.Conv2d(6, 16, 5) self.conv11.weight.data.copy_( net.conv1.weight.data) self.conv12.weight.data.copy_(net.conv2.weight.data) self.conv21 = nn.Conv2d(3, 6, 5) self.conv22 = nn.Conv2d(6, 16, 5) self.fc11 = nn.Linear(16 * 5 * 5, 120) self.fc12 = nn.Linear(120, 84) self.fc11.weight.data.copy_(net.fc1.weight.data) self.fc12.weight.data.copy_(net.fc2.weight.data) self.fc21 = nn.Linear(16 * 5 * 5, 120) self.fc22 = nn.Linear(120, 84) self.fc3 = nn.Linear(168,10) def forward(self, x): y = self.pool(F.relu(self.conv11(x))) y = self.pool(F.relu(self.conv12(y))) y = y.view(-1, 16 * 5 * 5) y = F.relu(self.fc11(y)) y = F.relu(self.fc12(y)) x = self.pool(F.relu(self.conv21(x))) x = self.pool(F.relu(self.conv22(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) out = self.fc3(torch.cat((x,y),dim=1)) return out# create a new modelnet1 = SideNet() We have now created our network architecture and defined the flow of tensors in our network in the forward function of class SideNet(). self.conv11.weight.data.copy_( net.conv1.weight.data)self.conv12.weight.data.copy_(net.conv2.weight.data)self.fc11.weight.data.copy_(net.fc1.weight.data)self.fc12.weight.data.copy_(net.fc2.weight.data) This code snippet is key in many aspects. One may instantly recognize what is going on here as this is what fundamentally takes place in transfer learning. We have just copied the weights of our trained network into the upper sub-part of our new structure. Voila! We may now choose to keep those weights as it is, by setting requires_grad = False (essentially freezing the weights for those layers whose weights have been copied from our trained network) or update them while training our new architecture. As I trained the tutorial’s network only for a few epochs, I will train the weights of both sub parts of our architecture. The reason for training initially for only a single epoch shall be clear later on. #check weightsprint(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)#for param in net.parameters():# param.requires_grad = Falsefrom torch.utils.tensorboard import SummaryWriter# default `log_dir` is "runs" - we'll be more specific herewriter = SummaryWriter('runs/temp')# write model to tensorboardwriter.add_graph(net1, images)writer.close()# train the new modelimport torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net1.parameters(), lr=0.01)for epoch in range(1): # loop over the dataset multiple timesrunning_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data# zero the parameter gradients optimizer.zero_grad()# forward + backward + optimize outputs = net1(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')correct = 0total = 0with torch.no_grad(): for data in testloader: images, labels = data outputs = net1(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))#check weightsprint(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data) Here, the optimizer’s parameters has been set as follows: learning rate = 0.01 and no momentum has been used. I have used the same parameters for training the initial network. This is so as when we view the weights for our new network and our initial network side-by-side, we need to check that the old network’s weights are copied, the new network’s weights have been appropriately initialized and while the new network’s weights are trained, the initial network’s weights do not change. The last phrase is key, there are many ways to achieve the first two phrases in the previous sentence but they usually result in modifying the initial network’s weights too! An example of this is if the following code snippet is used: self.conv11.weight.data = net.conv1.weight.dataself.conv12.weight.data = net.conv2.weight.dataself.fc11.weight.data = net.fc1.weight.dataself.fc12.weight.data = net.fc2.weight.data Let’s have a look at the structure TensorBoard has inferred: It does match what we are trying to build. Great! As a verification step let us print the weight values of layer FC2(fully connected 2, for those of you wondering) for both of our networks: print(net.fc2.weight.data) # before traintensor([[-2.5432e-03, -6.9285e-02, 7.7019e-02, ..., 2.8243e-02, 4.9399e-02, -8.7909e-05], [-7.2035e-02, -1.2313e-03, -8.9993e-02, ..., 1.8121e-02, -6.1479e-02, -3.8699e-02], [-6.3147e-02, 5.5815e-02, -6.0806e-02, ..., 3.3566e-02, 7.6486e-02, 7.3699e-02], ..., [ 1.9772e-03, -1.8449e-02, 6.8946e-02, ..., -2.1011e-02, 7.5202e-02, 4.1823e-02], [ 2.9912e-02, -7.9396e-02, -8.7561e-02, ..., 4.6011e-02, -9.0685e-02, 4.1302e-02], [-1.8297e-02, -7.3356e-02, 4.7250e-02, ..., -7.5147e-02, -6.4722e-02, 6.0243e-02]])print(net.fc2.weight.data) # after traintensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])In our new model code, before train,print(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[ 0.0864, 0.0843, 0.0060, ..., 0.0325, -0.0519, -0.0048], [ 0.0394, -0.0486, -0.0258, ..., 0.0515, 0.0077, -0.0702], [ 0.0570, -0.0178, 0.0411, ..., -0.0026, -0.0385, 0.0893], ..., [-0.0760, 0.0237, 0.0782, ..., 0.0338, 0.0055, -0.0830], [-0.0755, -0.0767, 0.0308, ..., -0.0234, -0.0403, 0.0812], [ 0.0057, -0.0511, -0.0834, ..., 0.0028, 0.0834, -0.0340]])After training,print(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[-0.0322, -0.0377, 0.0366, ..., 0.0290, 0.0322, 0.0069], [-0.0749, -0.0033, -0.0902, ..., 0.0179, -0.0650, -0.0402], [-0.0362, 0.0748, -0.1354, ..., 0.0352, 0.0715, 0.1009], ..., [ 0.0244, -0.0192, -0.0326, ..., -0.0220, 0.0661, 0.0834], [ 0.0304, -0.0785, -0.0976, ..., 0.0461, -0.0911, 0.0529], [-0.0225, -0.0737, 0.0275, ..., -0.0747, -0.0805, 0.1130]])tensor([[ 0.0864, 0.0843, 0.0060, ..., 0.0325, -0.0519, -0.0048], [ 0.0390, -0.0469, -0.0283, ..., 0.0506, 0.0030, -0.0723], [ 0.0571, -0.0178, 0.0411, ..., -0.0027, -0.0389, 0.0893], ..., [-0.0763, 0.0230, 0.0792, ..., 0.0337, 0.0065, -0.0802], [-0.0756, -0.0769, 0.0306, ..., -0.0235, -0.0413, 0.0810], [ 0.0048, -0.0525, -0.0822, ..., 0.0019, 0.0785, -0.0313]]) Thus, we can observe that our initial model’s parameters weights are copied but not changed while the new model is training. Also, the layer that had the weights copied, had its weights changed after training, thereby validating our sanity check. We have now built a more complex model and are able to reuse our weights in parallel. Of course, if you want parallelism in between, you just need to change the flow of tensors in the forward function of class SideNet(). For example, let’s say we want to keep our convolution layers but introduce two parallel routes after that. We want: The class SideNet() now looks as follows: class SideNet(nn.Module): def __init__(self): super(SideNet, self).__init__() self.pool = nn.MaxPool2d(2, 2)self.conv11 = nn.Conv2d(3, 6, 5) self.conv12 = nn.Conv2d(6, 16, 5) self.conv11.weight.data.copy_(net.conv1.weight.data) self.conv12.weight.data.copy_(net.conv2.weight.data) self.fc11 = nn.Linear(16 * 5 * 5, 120) self.fc12 = nn.Linear(120, 84) self.fc11.weight.data.copy_(net.fc1.weight.data) self.fc12.weight.data.copy_(net.fc2.weight.data) self.fc21 = nn.Linear(16 * 5 * 5, 120) self.fc22 = nn.Linear(120, 84) self.fc3 = nn.Linear(168,10)def forward(self, x): y = self.pool(F.relu(self.conv11(x))) y = self.pool(F.relu(self.conv12(y))) z = y.view(-1, 16 * 5 * 5) y = F.relu(self.fc11(z)) y = F.relu(self.fc12(y)) x = F.relu(self.fc21(z)) x = F.relu(self.fc22(x)) out = self.fc3(torch.cat((x,y),dim=1)) return out# create a new modelnet1 = SideNet() The TensorBoard depiction confirms what we were aspiring to build: I hope all these examples give you confidence on coding up complex neural networks as well as serve as a key stepping stone in your journey in machine learning. Thanks for reading :)
[ { "code": null, "e": 965, "s": 171, "text": "Hey there! This is my first ever article on medium. I have been planning to write this article for a while now. My main motivation is to help simplify and even maybe provide a template for taking the next step in building complex neural networks that involve parallel neurons in addition to those in a certain architecture you may have already built. This is so as although it may seem simple on paper, building, saving, loading and refining (training at a later time) neural nets do form a stumbling block when we actually begin to code them up. Hopefully, this article helps you understand issues related to those a bit better too and help you in solving those minor hiccups that you face from time to time when you are getting started with deep learning. With that, let’s begin our journey." }, { "code": null, "e": 1893, "s": 965, "text": "For those who are beginning to learn or are practicing neural nets, you may have observed that most of the neural network architectures we work with are usually feed-forward i.e. tensors flow from one layer to the next sequentially. Let’s say we want to explore what happens if we increase the number of neurons in one layer after we have built and trained our architecture to some degree of satisfaction. This would usually mean starting all over from scratch again and possibly wasting a few hours training. Just to see the effect of adding a few neurons in a particular layer, it seems unreasonable to begin all over from scratch. This is where transfer learning comes in. What it means, in simple terms, is the fact that you want to transfer what you have learnt while learning a particular task to another task. In the paradigm of neural networks, what we learn is represented by the weight values obtained after training." }, { "code": null, "e": 2576, "s": 1893, "text": "When we begin to learn more about how to utilize transfer learning, most of the in-built functions have fixed neural architectures as well as subsume code utilized for reloading weights and updating them in a new context. To figure out the specifics of applying it to your custom model will most probably take a few hours or days of hair scratching and pondering over multiple examples available online. I have done that myself and believe consolidating what I have learnt, all in one place, will definitely help anyone wanting to become more hands-on with transfer learning as well as exploring another alternative to augmenting neural networks. With that, let’s begin our example." }, { "code": null, "e": 3093, "s": 2576, "text": "I shall assume you are familiar with the tutorial available on building neural nets in PyTorch available at the link: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html. To learn the basics of transfer learning for existing popular architectures, do refer the link: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html. I strongly encourage you to visit these links and others available there to practice as well as form a well-rounded idea of training neural network architectures." }, { "code": null, "e": 3350, "s": 3093, "text": "Let’s say we now want to create a copy of the network described in the CIFAR 10 tutorial and place it in parallel with our trained version create a bigger network for the same problem of image classification. Our current model looks like this conceptually:" }, { "code": null, "e": 3410, "s": 3350, "text": "A TensorBoard depiction of the graph reveals the following:" }, { "code": null, "e": 3491, "s": 3410, "text": "Our goal now is to construct a neural network architecture that looks like this:" }, { "code": null, "e": 3619, "s": 3491, "text": "We also want that the upper sub-part of this new structure contain the same weights as that obtained by executing the tutorial." }, { "code": null, "e": 3682, "s": 3619, "text": "Let’s look at the code that helps us realize such a structure:" }, { "code": null, "e": 5647, "s": 3682, "text": "import torchimport torchvisionimport torchvision.transforms as transformstransform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=0)testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=0)classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')import matplotlib.pyplot as pltimport numpy as np# functions to show an imagedef imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show()# get some random training imagesdataiter = iter(trainloader)images, labels = dataiter.next()# show imagesimshow(torchvision.utils.make_grid(images))# print labelsprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net()PATH = './cifar_net.pth'net.load_state_dict(torch.load(PATH))" }, { "code": null, "e": 5790, "s": 5647, "text": "Till now, we have recreated our model learnt from the tutorial that we had trained and loaded the weights for us to copy into our new network." }, { "code": null, "e": 5847, "s": 5790, "text": "The following code constructs our required architecture." }, { "code": null, "e": 7129, "s": 5847, "text": "class SideNet(nn.Module): def __init__(self): super(SideNet, self).__init__() self.pool = nn.MaxPool2d(2, 2) self.conv11 = nn.Conv2d(3, 6, 5) self.conv12 = nn.Conv2d(6, 16, 5) self.conv11.weight.data.copy_( net.conv1.weight.data) self.conv12.weight.data.copy_(net.conv2.weight.data) self.conv21 = nn.Conv2d(3, 6, 5) self.conv22 = nn.Conv2d(6, 16, 5) self.fc11 = nn.Linear(16 * 5 * 5, 120) self.fc12 = nn.Linear(120, 84) self.fc11.weight.data.copy_(net.fc1.weight.data) self.fc12.weight.data.copy_(net.fc2.weight.data) self.fc21 = nn.Linear(16 * 5 * 5, 120) self.fc22 = nn.Linear(120, 84) self.fc3 = nn.Linear(168,10) def forward(self, x): y = self.pool(F.relu(self.conv11(x))) y = self.pool(F.relu(self.conv12(y))) y = y.view(-1, 16 * 5 * 5) y = F.relu(self.fc11(y)) y = F.relu(self.fc12(y)) x = self.pool(F.relu(self.conv21(x))) x = self.pool(F.relu(self.conv22(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc21(x)) x = F.relu(self.fc22(x)) out = self.fc3(torch.cat((x,y),dim=1)) return out# create a new modelnet1 = SideNet()" }, { "code": null, "e": 7265, "s": 7129, "text": "We have now created our network architecture and defined the flow of tensors in our network in the forward function of class SideNet()." }, { "code": null, "e": 7467, "s": 7265, "text": "self.conv11.weight.data.copy_( net.conv1.weight.data)self.conv12.weight.data.copy_(net.conv2.weight.data)self.fc11.weight.data.copy_(net.fc1.weight.data)self.fc12.weight.data.copy_(net.fc2.weight.data)" }, { "code": null, "e": 7731, "s": 7467, "text": "This code snippet is key in many aspects. One may instantly recognize what is going on here as this is what fundamentally takes place in transfer learning. We have just copied the weights of our trained network into the upper sub-part of our new structure. Voila!" }, { "code": null, "e": 8180, "s": 7731, "text": "We may now choose to keep those weights as it is, by setting requires_grad = False (essentially freezing the weights for those layers whose weights have been copied from our trained network) or update them while training our new architecture. As I trained the tutorial’s network only for a few epochs, I will train the weights of both sub parts of our architecture. The reason for training initially for only a single epoch shall be clear later on." }, { "code": null, "e": 9829, "s": 8180, "text": "#check weightsprint(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)#for param in net.parameters():# param.requires_grad = Falsefrom torch.utils.tensorboard import SummaryWriter# default `log_dir` is \"runs\" - we'll be more specific herewriter = SummaryWriter('runs/temp')# write model to tensorboardwriter.add_graph(net1, images)writer.close()# train the new modelimport torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net1.parameters(), lr=0.01)for epoch in range(1): # loop over the dataset multiple timesrunning_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data# zero the parameter gradients optimizer.zero_grad()# forward + backward + optimize outputs = net1(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')correct = 0total = 0with torch.no_grad(): for data in testloader: images, labels = data outputs = net1(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))#check weightsprint(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)" }, { "code": null, "e": 10553, "s": 9829, "text": "Here, the optimizer’s parameters has been set as follows: learning rate = 0.01 and no momentum has been used. I have used the same parameters for training the initial network. This is so as when we view the weights for our new network and our initial network side-by-side, we need to check that the old network’s weights are copied, the new network’s weights have been appropriately initialized and while the new network’s weights are trained, the initial network’s weights do not change. The last phrase is key, there are many ways to achieve the first two phrases in the previous sentence but they usually result in modifying the initial network’s weights too! An example of this is if the following code snippet is used:" }, { "code": null, "e": 10734, "s": 10553, "text": "self.conv11.weight.data = net.conv1.weight.dataself.conv12.weight.data = net.conv2.weight.dataself.fc11.weight.data = net.fc1.weight.dataself.fc12.weight.data = net.fc2.weight.data" }, { "code": null, "e": 10795, "s": 10734, "text": "Let’s have a look at the structure TensorBoard has inferred:" }, { "code": null, "e": 10845, "s": 10795, "text": "It does match what we are trying to build. Great!" }, { "code": null, "e": 10985, "s": 10845, "text": "As a verification step let us print the weight values of layer FC2(fully connected 2, for those of you wondering) for both of our networks:" }, { "code": null, "e": 14890, "s": 10985, "text": "print(net.fc2.weight.data) # before traintensor([[-2.5432e-03, -6.9285e-02, 7.7019e-02, ..., 2.8243e-02, 4.9399e-02, -8.7909e-05], [-7.2035e-02, -1.2313e-03, -8.9993e-02, ..., 1.8121e-02, -6.1479e-02, -3.8699e-02], [-6.3147e-02, 5.5815e-02, -6.0806e-02, ..., 3.3566e-02, 7.6486e-02, 7.3699e-02], ..., [ 1.9772e-03, -1.8449e-02, 6.8946e-02, ..., -2.1011e-02, 7.5202e-02, 4.1823e-02], [ 2.9912e-02, -7.9396e-02, -8.7561e-02, ..., 4.6011e-02, -9.0685e-02, 4.1302e-02], [-1.8297e-02, -7.3356e-02, 4.7250e-02, ..., -7.5147e-02, -6.4722e-02, 6.0243e-02]])print(net.fc2.weight.data) # after traintensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])In our new model code, before train,print(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[ 0.0864, 0.0843, 0.0060, ..., 0.0325, -0.0519, -0.0048], [ 0.0394, -0.0486, -0.0258, ..., 0.0515, 0.0077, -0.0702], [ 0.0570, -0.0178, 0.0411, ..., -0.0026, -0.0385, 0.0893], ..., [-0.0760, 0.0237, 0.0782, ..., 0.0338, 0.0055, -0.0830], [-0.0755, -0.0767, 0.0308, ..., -0.0234, -0.0403, 0.0812], [ 0.0057, -0.0511, -0.0834, ..., 0.0028, 0.0834, -0.0340]])After training,print(net.fc2.weight.data)print(net1.fc12.weight.data)print(net1.fc22.weight.data)tensor([[-0.0151, -0.0470, 0.1057, ..., 0.0288, 0.0280, 0.0171], [-0.0720, -0.0029, -0.0907, ..., 0.0181, -0.0630, -0.0408], [-0.0417, 0.0548, -0.1226, ..., 0.0335, 0.0679, 0.0900], ..., [ 0.0074, -0.0028, 0.0292, ..., -0.0218, 0.0754, 0.0473], [ 0.0307, -0.0784, -0.0875, ..., 0.0460, -0.0903, 0.0510], [-0.0252, -0.0824, 0.0380, ..., -0.0744, -0.0741, 0.1009]])tensor([[-0.0322, -0.0377, 0.0366, ..., 0.0290, 0.0322, 0.0069], [-0.0749, -0.0033, -0.0902, ..., 0.0179, -0.0650, -0.0402], [-0.0362, 0.0748, -0.1354, ..., 0.0352, 0.0715, 0.1009], ..., [ 0.0244, -0.0192, -0.0326, ..., -0.0220, 0.0661, 0.0834], [ 0.0304, -0.0785, -0.0976, ..., 0.0461, -0.0911, 0.0529], [-0.0225, -0.0737, 0.0275, ..., -0.0747, -0.0805, 0.1130]])tensor([[ 0.0864, 0.0843, 0.0060, ..., 0.0325, -0.0519, -0.0048], [ 0.0390, -0.0469, -0.0283, ..., 0.0506, 0.0030, -0.0723], [ 0.0571, -0.0178, 0.0411, ..., -0.0027, -0.0389, 0.0893], ..., [-0.0763, 0.0230, 0.0792, ..., 0.0337, 0.0065, -0.0802], [-0.0756, -0.0769, 0.0306, ..., -0.0235, -0.0413, 0.0810], [ 0.0048, -0.0525, -0.0822, ..., 0.0019, 0.0785, -0.0313]])" }, { "code": null, "e": 15137, "s": 14890, "text": "Thus, we can observe that our initial model’s parameters weights are copied but not changed while the new model is training. Also, the layer that had the weights copied, had its weights changed after training, thereby validating our sanity check." }, { "code": null, "e": 15358, "s": 15137, "text": "We have now built a more complex model and are able to reuse our weights in parallel. Of course, if you want parallelism in between, you just need to change the flow of tensors in the forward function of class SideNet()." }, { "code": null, "e": 15475, "s": 15358, "text": "For example, let’s say we want to keep our convolution layers but introduce two parallel routes after that. We want:" }, { "code": null, "e": 15517, "s": 15475, "text": "The class SideNet() now looks as follows:" }, { "code": null, "e": 16593, "s": 15517, "text": "class SideNet(nn.Module): def __init__(self): super(SideNet, self).__init__() self.pool = nn.MaxPool2d(2, 2)self.conv11 = nn.Conv2d(3, 6, 5) self.conv12 = nn.Conv2d(6, 16, 5) self.conv11.weight.data.copy_(net.conv1.weight.data) self.conv12.weight.data.copy_(net.conv2.weight.data) self.fc11 = nn.Linear(16 * 5 * 5, 120) self.fc12 = nn.Linear(120, 84) self.fc11.weight.data.copy_(net.fc1.weight.data) self.fc12.weight.data.copy_(net.fc2.weight.data) self.fc21 = nn.Linear(16 * 5 * 5, 120) self.fc22 = nn.Linear(120, 84) self.fc3 = nn.Linear(168,10)def forward(self, x): y = self.pool(F.relu(self.conv11(x))) y = self.pool(F.relu(self.conv12(y))) z = y.view(-1, 16 * 5 * 5) y = F.relu(self.fc11(z)) y = F.relu(self.fc12(y)) x = F.relu(self.fc21(z)) x = F.relu(self.fc22(x)) out = self.fc3(torch.cat((x,y),dim=1)) return out# create a new modelnet1 = SideNet()" }, { "code": null, "e": 16660, "s": 16593, "text": "The TensorBoard depiction confirms what we were aspiring to build:" } ]
AVG() Function in MySQL - GeeksforGeeks
21 Jan, 2021 AVG() function : This function in MySQL is used to return the average value of the specified expression. Features : This function is used to find the average value of the specified expression. This function comes under Numeric Functions. This function accepts only one parameter namely expression. This function ignores NULL values. Syntax : AVG(expression) Parameter : This method accepts only one parameter as follows. expression –The specified numeric value may be either a stated field or a stated formula. Returns : It returns the average value of the specified expression. Example-1 : Using AVG() function and getting the output. Creating table – CREATE TABLE item13 ( user_id int, product01 VARCHAR(4), product02 VARCHAR(10), price int ); Inserting data – INSERT item13(product01, price) VALUES ('rice', 500); INSERT item13(product02, price) VALUES ('grains', 700); Reading Data – SELECT AVG(price) FROM item13; Output : 600 Here, the average of the first product’s price and the second product’s price is returned. Example-2 : Using AVG() function and getting the average of float values. Creating table – CREATE TABLE floats ( user_id int, float_val float ); Inserting Data – INSERT floats(float_val) VALUES (3.5); INSERT floats(float_val) VALUES (2.5); Reading Data – SELECT AVG(float_val) FROM floats; Output : 3 Example-3 : Using AVG() function and getting the output where MRP is greater than the average MRP of the products. Creating table – CREATE TABLE package01 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, PRIMARY KEY(user_id) ); Inserting Data – INSERT package01(item, mrp) VALUES ('book1', 250); INSERT package01(item, mrp) VALUES ('book2', 350); INSERT package01(item, mrp) VALUES ('book3', 400); Reading Data – SELECT * FROM package01 WHERE mrp > (SELECT AVG(mrp) FROM package01); Output : Example-4 : Using AVG() function and getting the average of the (MRP-sales price). Creating table – CREATE TABLE package011 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10) NOT NULL, mrp int NOT NULL, sp int NOT NULL, PRIMARY KEY(user_id) ); Inserting Data – INSERT package011(item, mrp, sp) VALUES ('book1', 250, 240); INSERT package011(item, mrp, sp) VALUES ('book2', 350, 320); INSERT package011(item, mrp, sp) VALUES ('book3', 400, 350); Reading Data – SELECT AVG(mrp-sp) FROM package011; Output : 30 Application : This function is used to find the average of the expression specified. DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? SQL | DROP, TRUNCATE Composite Key in SQL SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL indexes SQL | Date functions What is Temporary Table in SQL? Window functions in SQL SQL | ALTER (ADD, DROP, MODIFY)
[ { "code": null, "e": 24188, "s": 24160, "text": "\n21 Jan, 2021" }, { "code": null, "e": 24205, "s": 24188, "text": "AVG() function :" }, { "code": null, "e": 24293, "s": 24205, "text": "This function in MySQL is used to return the average value of the specified expression." }, { "code": null, "e": 24304, "s": 24293, "text": "Features :" }, { "code": null, "e": 24381, "s": 24304, "text": "This function is used to find the average value of the specified expression." }, { "code": null, "e": 24426, "s": 24381, "text": "This function comes under Numeric Functions." }, { "code": null, "e": 24486, "s": 24426, "text": "This function accepts only one parameter namely expression." }, { "code": null, "e": 24521, "s": 24486, "text": "This function ignores NULL values." }, { "code": null, "e": 24530, "s": 24521, "text": "Syntax :" }, { "code": null, "e": 24546, "s": 24530, "text": "AVG(expression)" }, { "code": null, "e": 24558, "s": 24546, "text": "Parameter :" }, { "code": null, "e": 24609, "s": 24558, "text": "This method accepts only one parameter as follows." }, { "code": null, "e": 24699, "s": 24609, "text": "expression –The specified numeric value may be either a stated field or a stated formula." }, { "code": null, "e": 24709, "s": 24699, "text": "Returns :" }, { "code": null, "e": 24767, "s": 24709, "text": "It returns the average value of the specified expression." }, { "code": null, "e": 24779, "s": 24767, "text": "Example-1 :" }, { "code": null, "e": 24824, "s": 24779, "text": "Using AVG() function and getting the output." }, { "code": null, "e": 24841, "s": 24824, "text": "Creating table –" }, { "code": null, "e": 24942, "s": 24841, "text": "CREATE TABLE item13\n( \nuser_id int, \nproduct01 VARCHAR(4),\nproduct02 VARCHAR(10),\nprice int \n);" }, { "code": null, "e": 24959, "s": 24942, "text": "Inserting data –" }, { "code": null, "e": 25074, "s": 24959, "text": "INSERT item13(product01, price) \nVALUES ('rice', 500);\n\nINSERT item13(product02, price) \nVALUES ('grains', 700);" }, { "code": null, "e": 25089, "s": 25074, "text": "Reading Data –" }, { "code": null, "e": 25120, "s": 25089, "text": "SELECT AVG(price) FROM item13;" }, { "code": null, "e": 25129, "s": 25120, "text": "Output :" }, { "code": null, "e": 25133, "s": 25129, "text": "600" }, { "code": null, "e": 25224, "s": 25133, "text": "Here, the average of the first product’s price and the second product’s price is returned." }, { "code": null, "e": 25236, "s": 25224, "text": "Example-2 :" }, { "code": null, "e": 25298, "s": 25236, "text": "Using AVG() function and getting the average of float values." }, { "code": null, "e": 25315, "s": 25298, "text": "Creating table –" }, { "code": null, "e": 25371, "s": 25315, "text": "CREATE TABLE floats\n( \nuser_id int,\nfloat_val float\n);" }, { "code": null, "e": 25388, "s": 25371, "text": "Inserting Data –" }, { "code": null, "e": 25471, "s": 25388, "text": "INSERT floats(float_val) \nVALUES (3.5);\n\nINSERT floats(float_val) \nVALUES (2.5);" }, { "code": null, "e": 25486, "s": 25471, "text": "Reading Data –" }, { "code": null, "e": 25521, "s": 25486, "text": "SELECT AVG(float_val) FROM floats;" }, { "code": null, "e": 25530, "s": 25521, "text": "Output :" }, { "code": null, "e": 25532, "s": 25530, "text": "3" }, { "code": null, "e": 25544, "s": 25532, "text": "Example-3 :" }, { "code": null, "e": 25647, "s": 25544, "text": "Using AVG() function and getting the output where MRP is greater than the average MRP of the products." }, { "code": null, "e": 25664, "s": 25647, "text": "Creating table –" }, { "code": null, "e": 25784, "s": 25664, "text": "CREATE TABLE package01\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nitem VARCHAR(10),\nmrp int, \nPRIMARY KEY(user_id) \n);" }, { "code": null, "e": 25801, "s": 25784, "text": "Inserting Data –" }, { "code": null, "e": 25962, "s": 25801, "text": "INSERT package01(item, mrp) \nVALUES ('book1', 250);\n\nINSERT package01(item, mrp) \nVALUES ('book2', 350);\n\nINSERT package01(item, mrp) \nVALUES ('book3', 400);" }, { "code": null, "e": 25977, "s": 25962, "text": "Reading Data –" }, { "code": null, "e": 26047, "s": 25977, "text": "SELECT * FROM package01\nWHERE mrp > (SELECT AVG(mrp) FROM package01);" }, { "code": null, "e": 26056, "s": 26047, "text": "Output :" }, { "code": null, "e": 26068, "s": 26056, "text": "Example-4 :" }, { "code": null, "e": 26139, "s": 26068, "text": "Using AVG() function and getting the average of the (MRP-sales price)." }, { "code": null, "e": 26156, "s": 26139, "text": "Creating table –" }, { "code": null, "e": 26311, "s": 26156, "text": "CREATE TABLE package011\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nitem VARCHAR(10) NOT NULL,\nmrp int NOT NULL,\nsp int NOT NULL,\nPRIMARY KEY(user_id) \n);" }, { "code": null, "e": 26328, "s": 26311, "text": "Inserting Data –" }, { "code": null, "e": 26519, "s": 26328, "text": "INSERT package011(item, mrp, sp) \nVALUES ('book1', 250, 240);\n\nINSERT package011(item, mrp, sp) \nVALUES ('book2', 350, 320);\n\nINSERT package011(item, mrp, sp) \nVALUES ('book3', 400, 350);" }, { "code": null, "e": 26534, "s": 26519, "text": "Reading Data –" }, { "code": null, "e": 26570, "s": 26534, "text": "SELECT AVG(mrp-sp) FROM package011;" }, { "code": null, "e": 26579, "s": 26570, "text": "Output :" }, { "code": null, "e": 26582, "s": 26579, "text": "30" }, { "code": null, "e": 26596, "s": 26582, "text": "Application :" }, { "code": null, "e": 26667, "s": 26596, "text": "This function is used to find the average of the expression specified." }, { "code": null, "e": 26676, "s": 26667, "text": "DBMS-SQL" }, { "code": null, "e": 26682, "s": 26676, "text": "mysql" }, { "code": null, "e": 26686, "s": 26682, "text": "SQL" }, { "code": null, "e": 26690, "s": 26686, "text": "SQL" }, { "code": null, "e": 26788, "s": 26690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26797, "s": 26788, "text": "Comments" }, { "code": null, "e": 26810, "s": 26797, "text": "Old Comments" }, { "code": null, "e": 26876, "s": 26810, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26897, "s": 26876, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 26918, "s": 26897, "text": "Composite Key in SQL" }, { "code": null, "e": 26996, "s": 26918, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27013, "s": 26996, "text": "SQL using Python" }, { "code": null, "e": 27025, "s": 27013, "text": "SQL indexes" }, { "code": null, "e": 27046, "s": 27025, "text": "SQL | Date functions" }, { "code": null, "e": 27078, "s": 27046, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27102, "s": 27078, "text": "Window functions in SQL" } ]
Python Trading Toolbox: Weighted and Exponential Moving Averages | by Stefano Basurto | Towards Data Science
In the first post of the Financial Trading Toolbox series (Building a Financial Trading Toolbox in Python: Simple Moving Average), we discussed how to calculate a simple moving average, add it to a price series chart, and use it for investment and trading decisions. The Simple Moving Average is only one of several moving averages available that can be applied to price series to build trading systems or investment decision frameworks. Among those, two other moving averages are commonly used among financial market : Weighted Moving Average (WMA) Exponential Moving Average (EMA) In this article, we will explore how to calculate those two averages and how to ensure that the results match the definitions that we need to implement. In some applications, one of the limitations of the simple moving average is that it gives equal weight to each of the daily prices included in the window. E.g., in a 10-day moving average, the most recent day receives the same weight as the first day in the window: each price receives a 10% weighting. Compared to the Simple Moving Average, the Linearly Weighted Moving Average (or simply Weighted Moving Average, WMA), gives more weight to the most recent price and gradually less as we look back in time. On a 10-day weighted average, the price of the 10th day would be multiplied by 10, that of the 9th day by 9, the 8th day by 8 and so on. The total will then be divided by the sum of the weights (in this case: 55). In this specific example, the most recent price receives about 18.2% of the total weight, the second more recent 16.4%, and so on until the oldest price in the window that receives 0.02% of the weight. Let’s put that in practice with an example in Python. In addition to pandas and Matplotlib, we are going to make use of NumPy: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib as mpl We apply a style for our charts. If you’re using Jupyter it’s a good idea to add the %matplotlib inline instruction (and skip plt.show() when creating charts): plt.style.use('fivethirtyeight') For the next examples, we are going to use price data from a StockCharts.com article. It’s an excellent educational article on moving averages and I recommend reading it. The price series used in that article could belong to any stock or financial instrument and will serve our purposes for illustration. I modified the original Excel sheet by including calculations for the 10-day WMA since the calculation for the EMA is already included. You can access my Google Sheets file and download the data in CSV format here. It is always a good practice, when modeling data, to start with a simple implementation of our model that we can use to make sure that the results from our final implementation are correct. We start by loading the data into a data frame: datafile = 'cs-movavg.csv'data = pd.read_csv(datafile, index_col = 'Date')data.index = pd.to_datetime(data.index)# We can drop the old index column:data = data.drop(columns='Unnamed: 0')data We are going to consider only the Price and 10-Day WMA columns for now and move to the EMA later on. When it comes to linearly weighted moving averages, the pandas library does not have a ready off-the-shelf method to calculate them. It offers, however, a very powerful and flexible method: .apply() This method allows us to create and pass any custom function to a rolling window: that is how we are going to calculate our Weighted Moving Average. To calculate a 10-Day WMA, we start by creating an array of weights - whole numbers from 1 to 10: weights = np.arange(1,11) #this creates an array with integers 1 to 10 includedweights Which looks like: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Next, using the .apply() method we pass our own function (a lambda function) to compute the dot product of weights and prices in our rolling window (prices in the window will be multiplied by the corresponding weight, then summed), then dividing it by the sum of the weights: wma10 = data['Price'].rolling(10).apply(lambda prices: np.dot(prices, weights)/weights.sum(), raw=True)wma10.head(20) Which gives: Now, we want to compare our WMA to the one obtained with the spreadsheet. To do so, we can add an ‘Our 10-day WMA’ column to the dataframe. To make the visual comparison easier, we can round the WMA series to three decimals using the.round() method from NumPy. Then, we select the price and WMA columns to be displayed: data['Our 10-day WMA'] = np.round(wma10, decimals=3)data[['Price', '10-day WMA', 'Our 10-day WMA']].head(20) Showing: The two WMA columns look the same. There are a few differences in the third decimal place, but we can put that down to rounding error and conclude that our implementation of the WMA is correct. In a real-life application, if we want to be more rigorous we should compute the differences between the two columns and check that they are not too large. For now, we keep things simple and we can be satisfied with the visual inspection. It would be interesting to compare in a plot our newly created WMA with the familiar SMA: sma10 = data['Price'].rolling(10).mean()plt.figure(figsize = (12,6))plt.plot(data['Price'], label="Price")plt.plot(wma10, label="10-Day WMA")plt.plot(sma10, label="10-Day SMA")plt.xlabel("Date")plt.ylabel("Price")plt.legend()plt.show() This shows: As we can see, both averages smooth out the price movement. The WMA is more reactive and follows the price closer than the SMA: we expect that since the WMA gives more weight to the most recent price observations. Also, both moving average series start on day 10: the first day with enough available data to compute the averages. The Weighted Moving Average may be lesser known than its Exponential sibling. However, it can be an additional item in our toolbox when we try to build original solutions. Implementing the WMA in Python forced us to search for a way to create customized moving averages using .apply(): this technique can be used to implement new and original moving averages as well. Similarly to the Weighted Moving Average, the Exponential Moving Average (EMA) assigns a greater weight to the most recent price observations. While it assigns lesser weight to past data, it is based on a recursive formula that includes in its calculation all the past data in our price series. The EMA at time t is calculated as the current price multiplied by a smoothing factor alpha (a positive number less than 1) plus the EMA at time t−1 multiplied by 1 minus alpha. It is basically a value between the previous EMA and the current price: The smoothing factor α ( alpha ) is defined as: where n is the number of days in our span. Therefore, a 10-day EMA will have a smoothing factor: Pandas includes a method to compute the EMA moving average of any time series: .ewm(). Will this method respond to our needs and compute an average that matches our definition? Let's test it: ema10 = data['Price'].ewm(span=10).mean()ema10.head(10) Which gives: We want to compare this EMA series with the one obtained in the spreadsheet: data['Our 10-day EMA'] = np.round(ema10, decimals=3)data[['Price', '10-day EMA', 'Our 10-day EMA']].head(20) Which results: As you have already noticed, we have a problem here: the 10-day EMA that we just calculated does not correspond to the one calculated in the downloaded spreadsheet. One starts on day 10, while the other starts on day 1. Also, the values do not match exactly. Is our calculation wrong? Or is the calculation in the provided spreadsheet wrong? Neither: those two series correspond to two different definitions of EMA. To be more specific, the formula used to compute the EMA is the same. What changes is just the use of the initial values. If we look carefully at the definition of Exponential Moving Average on the StockCharts.com web page we can notice one important detail: they start calculating a 10-day moving average on day 10, disregarding the previous days and replacing the price on day 10 with its 10-day SMA. It’s a different definition than the one applied when we calculated the EMA using the .ewm() method directly. The following lines of code create a new modified price series where the first 9 prices (when the SMA is not available) are replaced by NaN and the price on the 10th date becomes its 10-Day SMA: modPrice = data['Price'].copy()modPrice.iloc[0:10] = sma10[0:10]modPrice.head(20) We can use this modified price series to calculate a second version of the EWM. By looking at the documentation, we can note that the .ewm() method has an adjust parameter that defaults to True. This parameter adjusts the weights to account for the imbalance in the beginning periods (if you need more detail, see the Exponentially weighted windows section in the pandas documentation). If we want to emulate the EMA as in our spreadsheet using our modified price series, we don’t need this adjustment. We then set adjust=False: ema10alt = modPrice.ewm(span=10, adjust=False).mean() Will this newly calculated EMA match the one calculated in the spreadsheet? Let’s have a look: data['Our 2nd 10-Day EMA'] = np.round(ema10alt, decimals=3)data[['Price', '10-day EMA', 'Our 10-day EMA', 'Our 2nd 10-Day EMA']].head(20) Now, we are doing much better. We have obtained an EMA series that matches the one calculated in the spreadsheet. We ended up with two different versions of EMA in our hands: ema10: This version uses the plain .ewm() method, starts at the beginning of our price history but does not match the definition used in the spreadsheet.ema10alt: This version starts on day 10 (with an initial value equal to the 10-day SMA) and matches the definition on our spreadsheet. ema10: This version uses the plain .ewm() method, starts at the beginning of our price history but does not match the definition used in the spreadsheet. ema10alt: This version starts on day 10 (with an initial value equal to the 10-day SMA) and matches the definition on our spreadsheet. Which one is the best to use? The answer is: it depends on what we need for our application and to build our system. If we need an EMA series that starts from day 1, then we should choose the first one. On the other hand, if we need to use our average in combination with other averages that have no values for the initial days (such as the SMA), then the second is probably the best one. The second EMA is widely used among financial market analysts: if we need to implement an already existing system, we need to be careful to use the correct definition. Otherwise, the results may not be what is expected from us and may put the accuracy of all of our work into question. In any case, the numeric difference between those two averages is minimal, with an impact on our trading or investment decision system limited to the initial days. Let’s look at all the moving averages we have used so far in a chart: plt.figure(figsize = (12,6))plt.plot(data['Price'], label="Price")plt.plot(wma10, label="10-Day WMA")plt.plot(sma10, label="10-Day SMA")plt.plot(ema10, label="10-Day EMA-1")plt.plot(ema10alt, label="10-Day EMA-2")plt.xlabel("Date")plt.ylabel("Price")plt.legend()plt.show() Of all the moving averages, the WMA appears the one that is more responsive and tags the price more closely, while the SMA is the one that responds with some more lag. The two versions of the EMA tend to overlap each other, mainly in the last days. I hope you found this post useful. Introducing the Weighted Moving Average helped us to learn and implement a custom average based on a specific definition. Working with the Exponential Moving Average gave us the chance to highlight how important it is to ensure that any function we are using to work on price series matches the definition that we have for any given task. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 567, "s": 47, "text": "In the first post of the Financial Trading Toolbox series (Building a Financial Trading Toolbox in Python: Simple Moving Average), we discussed how to calculate a simple moving average, add it to a price series chart, and use it for investment and trading decisions. The Simple Moving Average is only one of several moving averages available that can be applied to price series to build trading systems or investment decision frameworks. Among those, two other moving averages are commonly used among financial market :" }, { "code": null, "e": 597, "s": 567, "text": "Weighted Moving Average (WMA)" }, { "code": null, "e": 630, "s": 597, "text": "Exponential Moving Average (EMA)" }, { "code": null, "e": 783, "s": 630, "text": "In this article, we will explore how to calculate those two averages and how to ensure that the results match the definitions that we need to implement." }, { "code": null, "e": 1087, "s": 783, "text": "In some applications, one of the limitations of the simple moving average is that it gives equal weight to each of the daily prices included in the window. E.g., in a 10-day moving average, the most recent day receives the same weight as the first day in the window: each price receives a 10% weighting." }, { "code": null, "e": 1708, "s": 1087, "text": "Compared to the Simple Moving Average, the Linearly Weighted Moving Average (or simply Weighted Moving Average, WMA), gives more weight to the most recent price and gradually less as we look back in time. On a 10-day weighted average, the price of the 10th day would be multiplied by 10, that of the 9th day by 9, the 8th day by 8 and so on. The total will then be divided by the sum of the weights (in this case: 55). In this specific example, the most recent price receives about 18.2% of the total weight, the second more recent 16.4%, and so on until the oldest price in the window that receives 0.02% of the weight." }, { "code": null, "e": 1835, "s": 1708, "text": "Let’s put that in practice with an example in Python. In addition to pandas and Matplotlib, we are going to make use of NumPy:" }, { "code": null, "e": 1928, "s": 1835, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib as mpl" }, { "code": null, "e": 2088, "s": 1928, "text": "We apply a style for our charts. If you’re using Jupyter it’s a good idea to add the %matplotlib inline instruction (and skip plt.show() when creating charts):" }, { "code": null, "e": 2121, "s": 2088, "text": "plt.style.use('fivethirtyeight')" }, { "code": null, "e": 2426, "s": 2121, "text": "For the next examples, we are going to use price data from a StockCharts.com article. It’s an excellent educational article on moving averages and I recommend reading it. The price series used in that article could belong to any stock or financial instrument and will serve our purposes for illustration." }, { "code": null, "e": 2641, "s": 2426, "text": "I modified the original Excel sheet by including calculations for the 10-day WMA since the calculation for the EMA is already included. You can access my Google Sheets file and download the data in CSV format here." }, { "code": null, "e": 2831, "s": 2641, "text": "It is always a good practice, when modeling data, to start with a simple implementation of our model that we can use to make sure that the results from our final implementation are correct." }, { "code": null, "e": 2879, "s": 2831, "text": "We start by loading the data into a data frame:" }, { "code": null, "e": 3070, "s": 2879, "text": "datafile = 'cs-movavg.csv'data = pd.read_csv(datafile, index_col = 'Date')data.index = pd.to_datetime(data.index)# We can drop the old index column:data = data.drop(columns='Unnamed: 0')data" }, { "code": null, "e": 3171, "s": 3070, "text": "We are going to consider only the Price and 10-Day WMA columns for now and move to the EMA later on." }, { "code": null, "e": 3617, "s": 3171, "text": "When it comes to linearly weighted moving averages, the pandas library does not have a ready off-the-shelf method to calculate them. It offers, however, a very powerful and flexible method: .apply() This method allows us to create and pass any custom function to a rolling window: that is how we are going to calculate our Weighted Moving Average. To calculate a 10-Day WMA, we start by creating an array of weights - whole numbers from 1 to 10:" }, { "code": null, "e": 3704, "s": 3617, "text": "weights = np.arange(1,11) #this creates an array with integers 1 to 10 includedweights" }, { "code": null, "e": 3722, "s": 3704, "text": "Which looks like:" }, { "code": null, "e": 3770, "s": 3722, "text": "array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])" }, { "code": null, "e": 4046, "s": 3770, "text": "Next, using the .apply() method we pass our own function (a lambda function) to compute the dot product of weights and prices in our rolling window (prices in the window will be multiplied by the corresponding weight, then summed), then dividing it by the sum of the weights:" }, { "code": null, "e": 4164, "s": 4046, "text": "wma10 = data['Price'].rolling(10).apply(lambda prices: np.dot(prices, weights)/weights.sum(), raw=True)wma10.head(20)" }, { "code": null, "e": 4177, "s": 4164, "text": "Which gives:" }, { "code": null, "e": 4497, "s": 4177, "text": "Now, we want to compare our WMA to the one obtained with the spreadsheet. To do so, we can add an ‘Our 10-day WMA’ column to the dataframe. To make the visual comparison easier, we can round the WMA series to three decimals using the.round() method from NumPy. Then, we select the price and WMA columns to be displayed:" }, { "code": null, "e": 4606, "s": 4497, "text": "data['Our 10-day WMA'] = np.round(wma10, decimals=3)data[['Price', '10-day WMA', 'Our 10-day WMA']].head(20)" }, { "code": null, "e": 4615, "s": 4606, "text": "Showing:" }, { "code": null, "e": 5048, "s": 4615, "text": "The two WMA columns look the same. There are a few differences in the third decimal place, but we can put that down to rounding error and conclude that our implementation of the WMA is correct. In a real-life application, if we want to be more rigorous we should compute the differences between the two columns and check that they are not too large. For now, we keep things simple and we can be satisfied with the visual inspection." }, { "code": null, "e": 5138, "s": 5048, "text": "It would be interesting to compare in a plot our newly created WMA with the familiar SMA:" }, { "code": null, "e": 5374, "s": 5138, "text": "sma10 = data['Price'].rolling(10).mean()plt.figure(figsize = (12,6))plt.plot(data['Price'], label=\"Price\")plt.plot(wma10, label=\"10-Day WMA\")plt.plot(sma10, label=\"10-Day SMA\")plt.xlabel(\"Date\")plt.ylabel(\"Price\")plt.legend()plt.show()" }, { "code": null, "e": 5386, "s": 5374, "text": "This shows:" }, { "code": null, "e": 5716, "s": 5386, "text": "As we can see, both averages smooth out the price movement. The WMA is more reactive and follows the price closer than the SMA: we expect that since the WMA gives more weight to the most recent price observations. Also, both moving average series start on day 10: the first day with enough available data to compute the averages." }, { "code": null, "e": 6084, "s": 5716, "text": "The Weighted Moving Average may be lesser known than its Exponential sibling. However, it can be an additional item in our toolbox when we try to build original solutions. Implementing the WMA in Python forced us to search for a way to create customized moving averages using .apply(): this technique can be used to implement new and original moving averages as well." }, { "code": null, "e": 6379, "s": 6084, "text": "Similarly to the Weighted Moving Average, the Exponential Moving Average (EMA) assigns a greater weight to the most recent price observations. While it assigns lesser weight to past data, it is based on a recursive formula that includes in its calculation all the past data in our price series." }, { "code": null, "e": 6629, "s": 6379, "text": "The EMA at time t is calculated as the current price multiplied by a smoothing factor alpha (a positive number less than 1) plus the EMA at time t−1 multiplied by 1 minus alpha. It is basically a value between the previous EMA and the current price:" }, { "code": null, "e": 6677, "s": 6629, "text": "The smoothing factor α ( alpha ) is defined as:" }, { "code": null, "e": 6774, "s": 6677, "text": "where n is the number of days in our span. Therefore, a 10-day EMA will have a smoothing factor:" }, { "code": null, "e": 6966, "s": 6774, "text": "Pandas includes a method to compute the EMA moving average of any time series: .ewm(). Will this method respond to our needs and compute an average that matches our definition? Let's test it:" }, { "code": null, "e": 7022, "s": 6966, "text": "ema10 = data['Price'].ewm(span=10).mean()ema10.head(10)" }, { "code": null, "e": 7035, "s": 7022, "text": "Which gives:" }, { "code": null, "e": 7112, "s": 7035, "text": "We want to compare this EMA series with the one obtained in the spreadsheet:" }, { "code": null, "e": 7221, "s": 7112, "text": "data['Our 10-day EMA'] = np.round(ema10, decimals=3)data[['Price', '10-day EMA', 'Our 10-day EMA']].head(20)" }, { "code": null, "e": 7236, "s": 7221, "text": "Which results:" }, { "code": null, "e": 7495, "s": 7236, "text": "As you have already noticed, we have a problem here: the 10-day EMA that we just calculated does not correspond to the one calculated in the downloaded spreadsheet. One starts on day 10, while the other starts on day 1. Also, the values do not match exactly." }, { "code": null, "e": 7774, "s": 7495, "text": "Is our calculation wrong? Or is the calculation in the provided spreadsheet wrong? Neither: those two series correspond to two different definitions of EMA. To be more specific, the formula used to compute the EMA is the same. What changes is just the use of the initial values." }, { "code": null, "e": 8165, "s": 7774, "text": "If we look carefully at the definition of Exponential Moving Average on the StockCharts.com web page we can notice one important detail: they start calculating a 10-day moving average on day 10, disregarding the previous days and replacing the price on day 10 with its 10-day SMA. It’s a different definition than the one applied when we calculated the EMA using the .ewm() method directly." }, { "code": null, "e": 8360, "s": 8165, "text": "The following lines of code create a new modified price series where the first 9 prices (when the SMA is not available) are replaced by NaN and the price on the 10th date becomes its 10-Day SMA:" }, { "code": null, "e": 8442, "s": 8360, "text": "modPrice = data['Price'].copy()modPrice.iloc[0:10] = sma10[0:10]modPrice.head(20)" }, { "code": null, "e": 8829, "s": 8442, "text": "We can use this modified price series to calculate a second version of the EWM. By looking at the documentation, we can note that the .ewm() method has an adjust parameter that defaults to True. This parameter adjusts the weights to account for the imbalance in the beginning periods (if you need more detail, see the Exponentially weighted windows section in the pandas documentation)." }, { "code": null, "e": 8971, "s": 8829, "text": "If we want to emulate the EMA as in our spreadsheet using our modified price series, we don’t need this adjustment. We then set adjust=False:" }, { "code": null, "e": 9025, "s": 8971, "text": "ema10alt = modPrice.ewm(span=10, adjust=False).mean()" }, { "code": null, "e": 9120, "s": 9025, "text": "Will this newly calculated EMA match the one calculated in the spreadsheet? Let’s have a look:" }, { "code": null, "e": 9258, "s": 9120, "text": "data['Our 2nd 10-Day EMA'] = np.round(ema10alt, decimals=3)data[['Price', '10-day EMA', 'Our 10-day EMA', 'Our 2nd 10-Day EMA']].head(20)" }, { "code": null, "e": 9372, "s": 9258, "text": "Now, we are doing much better. We have obtained an EMA series that matches the one calculated in the spreadsheet." }, { "code": null, "e": 9433, "s": 9372, "text": "We ended up with two different versions of EMA in our hands:" }, { "code": null, "e": 9721, "s": 9433, "text": "ema10: This version uses the plain .ewm() method, starts at the beginning of our price history but does not match the definition used in the spreadsheet.ema10alt: This version starts on day 10 (with an initial value equal to the 10-day SMA) and matches the definition on our spreadsheet." }, { "code": null, "e": 9875, "s": 9721, "text": "ema10: This version uses the plain .ewm() method, starts at the beginning of our price history but does not match the definition used in the spreadsheet." }, { "code": null, "e": 10010, "s": 9875, "text": "ema10alt: This version starts on day 10 (with an initial value equal to the 10-day SMA) and matches the definition on our spreadsheet." }, { "code": null, "e": 10399, "s": 10010, "text": "Which one is the best to use? The answer is: it depends on what we need for our application and to build our system. If we need an EMA series that starts from day 1, then we should choose the first one. On the other hand, if we need to use our average in combination with other averages that have no values for the initial days (such as the SMA), then the second is probably the best one." }, { "code": null, "e": 10849, "s": 10399, "text": "The second EMA is widely used among financial market analysts: if we need to implement an already existing system, we need to be careful to use the correct definition. Otherwise, the results may not be what is expected from us and may put the accuracy of all of our work into question. In any case, the numeric difference between those two averages is minimal, with an impact on our trading or investment decision system limited to the initial days." }, { "code": null, "e": 10919, "s": 10849, "text": "Let’s look at all the moving averages we have used so far in a chart:" }, { "code": null, "e": 11192, "s": 10919, "text": "plt.figure(figsize = (12,6))plt.plot(data['Price'], label=\"Price\")plt.plot(wma10, label=\"10-Day WMA\")plt.plot(sma10, label=\"10-Day SMA\")plt.plot(ema10, label=\"10-Day EMA-1\")plt.plot(ema10alt, label=\"10-Day EMA-2\")plt.xlabel(\"Date\")plt.ylabel(\"Price\")plt.legend()plt.show()" }, { "code": null, "e": 11441, "s": 11192, "text": "Of all the moving averages, the WMA appears the one that is more responsive and tags the price more closely, while the SMA is the one that responds with some more lag. The two versions of the EMA tend to overlap each other, mainly in the last days." }, { "code": null, "e": 11815, "s": 11441, "text": "I hope you found this post useful. Introducing the Weighted Moving Average helped us to learn and implement a custom average based on a specific definition. Working with the Exponential Moving Average gave us the chance to highlight how important it is to ensure that any function we are using to work on price series matches the definition that we have for any given task." } ]
Count of different groups using Graph - GeeksforGeeks
18 Oct, 2021 Given a graph with N nodes having values either P or M. Also given K pairs of integers as (x, y) representing the edges in the graph such that if a is connected to b and b is connected to c then a and c will also be connected. A single connected component is called a group. The group can have both P and M values. If the P values are more than the M values this group is called P influenced and similarly for M. If the number of P’s and M’s are equal then it is called a neutral group. The task is to find the number of P influenced, M influenced and, Neutral groups. Examples: Input: Nodes[] = {P, M, P, M, P}, edges[][] = { {1, 3}, {4, 5}, {3, 5}} Output: P = 1 M = 1 N = 0 There will be two groups of indexes {1, 3, 4, 5} and {2}. The first group is P influenced and the second one is M influenced. Input: Nodes[] = {P, M, P, M, P}, edges[][] = { {1, 3}, {4, 5}} Output: P = 1 M = 2 N = 0 Approach: It is easier to construct a graph with adjacency list and loop from 1 to N and do DFS and check the count of P and M. Another way is to use DSU with a little modification that size array will be of pair so that it can maintain the count of both M and P. In this approach, there is no need to construct the graph as the merge operation will take care of the connected component. Note that you should have the knowledge of DSU by size/rank for optimization. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the parents// of the current nodevector<int> par; // To store the size of M and Pvector<pair<int, int> > sz; // Function for initializationvoid init(vector<char>& nodes){ // Size of the graph int n = (int)nodes.size(); par.clear(); sz.clear(); par.resize(n + 1); sz.resize(n + 1); for (int i = 0; i <= n; ++i) { par[i] = i; if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') sz[i] = { 0, 1 }; // If the node is M else sz[i] = { 1, 0 }; } }} // To find the parent of// the current nodeint parent(int i){ while (par[i] != i) i = par[i]; return i;} // Merge functionvoid union(int a, int b){ a = parent(a); b = parent(b); if (a == b) return; // Total size by adding number of M and P int sz_a = sz[a].first + sz[a].second; int sz_b = sz[b].first + sz[b].second; if (sz_a < sz_b) swap(a, b); par[b] = a; sz[a].first += sz[b].first; sz[a].second += sz[b].second; return;} // Function to calculate the influenced valuevoid influenced(vector<char>& nodes, vector<pair<int, int> > connect){ // Number of nodes int n = (int)nodes.size(); // Initialization function init(nodes); // Size of the connected vector int k = connect.size(); // Performing union operation for (int i = 0; i < k; ++i) { union(connect[i].first, connect[i].second); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for (int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz[i].first == sz[i].second) { ne++; } else if (sz[i].first > sz[i].second) { ma++; } else { pe++; } } } cout << "P = " << pe << "\nM = " << ma << "\nN = " << ne << "\n";} // Driver codeint main(){ // Nodes at each index ( 1 - base indexing ) vector<char> nodes = { 'P', 'M', 'P', 'M', 'P' }; // Connected Pairs vector<pair<int, int> > connect = { { 1, 3 }, { 3, 5 }, { 4, 5 } }; influenced(nodes, connect); return 0;} // Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // To store the parents// of the current nodestatic ArrayList<Integer> par = new ArrayList<Integer>(); // To store the size of M and Pstatic ArrayList< ArrayList<Integer>> sz = new ArrayList< ArrayList<Integer>>(); // Function for initializationstatic void init(ArrayList<Character> nodes){ // Size of the graph int n = nodes.size(); for(int i = 0; i <= n; ++i) { par.add(i); if (i == 0) { sz.add(new ArrayList<Integer>( Arrays.asList(0, 0))); } if (i > 0) { // If the node is P if (nodes.get(i - 1) == 'P') { sz.add(new ArrayList<Integer>( Arrays.asList(0, 1))); } // If the node is M else { sz.add(new ArrayList<Integer>( Arrays.asList(1, 0))); } } }} // To find the parent of// the current nodestatic int parent(int i){ while (par.get(i) != i) { i = par.get(i); } return i;} // Merge functionstatic void union(int a, int b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P int sz_a = sz.get(a).get(0) + sz.get(a).get(1); int sz_b = sz.get(b).get(0) + sz.get(b).get(1); if (sz_a < sz_b) { int temp = a; a = b; b = temp; } par.set(b, a); sz.get(a).set(0, sz.get(a).get(0) + sz.get(b).get(0)); sz.get(a).set(1, sz.get(a).get(1) + sz.get(b).get(1)); return;} // Function to calculate the influenced valuestatic void influenced(ArrayList<Character> nodes, ArrayList<ArrayList<Integer>> connect){ // Number of nodes int n = nodes.size(); // Initialization function init(nodes); // Size of the connected vector int k = connect.size(); // Performing union operation for(int i = 0; i < k; ++i) { union(connect.get(i).get(0), connect.get(i).get(1)); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for(int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz.get(i).get(0) == sz.get(i).get(1)) { ne++; } else if (sz.get(i).get(0) > sz.get(i).get(1)) { ma++; } else { pe++; } } } System.out.println("P = " + pe + "\nM = " + ma + "\nN = " + ne);} // Driver codepublic static void main(String[] args){ // Nodes at each index ( 1 - base indexing ) ArrayList<Character> nodes = new ArrayList<Character>(); nodes.add('P'); nodes.add('M'); nodes.add('P'); nodes.add('M'); nodes.add('P'); // Connected Pairs ArrayList< ArrayList<Integer>> connect = new ArrayList< ArrayList<Integer>>(); connect.add(new ArrayList<Integer>( Arrays.asList(1, 3))); connect.add(new ArrayList<Integer>( Arrays.asList(3, 5))); connect.add(new ArrayList<Integer>( Arrays.asList(4, 5))); influenced(nodes, connect);}} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of the approach # To store the parents# of the current nodepar = [] # To store the size of M and Psz = [] # Function for initializationdef init(nodes): # Size of the graph n = len(nodes) for i in range(n + 1): par.append(0) sz.append(0) for i in range(n + 1): par[i] = i if (i > 0): # If the node is P if (nodes[i - 1] == 'P'): sz[i] = [0, 1] # If the node is M else: sz[i] = [1, 0] # To find the parent of# the current nodedef parent(i): while (par[i] != i): i = par[i] return i # Merge functiondef union(a, b): a = parent(a) b = parent(b) if (a == b): return # Total size by adding number of M and P sz_a = sz[a][0] + sz[a][1] sz_b = sz[b][0] + sz[b][1] if (sz_a < sz_b): a, b = b, a par[b] = a sz[a][0] += sz[b][0] sz[a][1] += sz[b][1] return # Function to calculate the influenced valuedef influenced(nodes,connect): # Number of nodes n = len(nodes) # Initialization function init(nodes) # Size of the connected vector k = len(connect) # Performing union operation for i in range(k): union(connect[i][0], connect[i][1]) # ne = Number of neutal groups # ma = Number of M influenced groups # pe = Number of P influenced groups ne = 0 ma = 0 pe = 0 for i in range(1, n + 1): x = parent(i) if (x == i): if (sz[i][0] == sz[i][1]): ne += 1 elif (sz[i][0] > sz[i][1]): ma += 1 else: pe += 1 print("P =",pe,"\nM =",ma,"\nN =",ne) # Driver code # Nodes at each index ( 1 - base indexing )nodes = [ 'P', 'M', 'P', 'M', 'P' ] # Connected Pairsconnect = [ [ 1, 3 ], [ 3, 5 ], [ 4, 5 ] ] influenced(nodes, connect) # This code is contributed by mohit kumar 29 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the parents// of the current nodestatic List<int> par = new List<int>(); // To store the size of M and Pstatic List<List<int>> sz = new List<List<int>>(); // Function for initializationstatic void init(List<char> nodes){ // Size of the graph int n = nodes.Count; for(int i = 0; i <= n; ++i) { par.Add(i); if (i == 0) { sz.Add(new List<int>(){0, 0}); } if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') { sz.Add(new List<int>(){0, 1}); } // If the node is M else { sz.Add(new List<int>(){1, 0}); } } }} // To find the parent of// the current nodestatic int parent(int i){ while (par[i] != i) { i = par[i]; } return i;} // Merge functionstatic void union(int a, int b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P int sz_a = sz[a][0] + sz[a][1]; int sz_b = sz[b][0] + sz[b][1]; if (sz_a < sz_b) { int temp = a; a = b; b = temp; } par[b] = a; sz[a][0] += sz[b][0]; sz[a][1] += sz[b][1]; return;} // Function to calculate the influenced valuestatic void influenced(List<char> nodes, List<List<int>> connect){ // Number of nodes int n = nodes.Count; // Initialization function init(nodes); // Size of the connected vector int k = connect.Count; // Performing union operation for(int i = 0; i < k; ++i) { union(connect[i][0], connect[i][1]); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for(int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz[i][0] == sz[i][1]) { ne++; } else if (sz[i][0] > sz[i][1]) { ma++; } else { pe++; } } } Console.WriteLine("P = " + pe + "\nM = " + ma + "\nN = " + ne);} // Driver codestatic public void Main(){ // Nodes at each index ( 1 - base indexing ) List<char> nodes = new List<char>(){'P', 'M', 'P', 'M', 'P'}; // Connected Pairs List<List<int>> connect = new List<List<int>>(); connect.Add(new List<int>(){1, 3}); connect.Add(new List<int>(){3, 5}); connect.Add(new List<int>(){4, 5}); influenced(nodes, connect);}} // This code is contributed by rag2127 <script>// Javascript implementation of the approach // To store the parents// of the current nodelet par = []; // To store the size of M and Plet sz = []; // Function for initializationfunction init(nodes){ // Size of the graph let n = nodes.length; for(let i = 0; i <= n; ++i) { par.push(i); if (i == 0) { sz.push([0,0]); } if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') { sz.push([0,1]); } // If the node is M else { sz.push([1,0]); } } }} // To find the parent of// the current nodefunction parent(i){ while (par[i] != i) { i = par[i]; } return i;} // Merge functionfunction union(a,b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P let sz_a = sz[a][0] + sz[a][1]; let sz_b = sz[b][0] + sz[b][1]; if (sz_a < sz_b) { let temp = a; a = b; b = temp; } par[b] = a; sz[a][0] = sz[a][0] + sz[b][0]; sz[a][1] = sz[a][1] + sz[b][1]; return;} // Function to calculate the influenced valuefunction influenced(nodes,connect){ // Number of nodes let n = nodes.length; // Initialization function init(nodes); // Size of the connected vector let k = connect.length; // Performing union operation for(let i = 0; i < k; ++i) { union(connect[i][0], connect[i][1]); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups let ne = 0, ma = 0, pe = 0; for(let i = 1; i <= n; ++i) { let x = parent(i); if (x == i) { if (sz[i][0] == sz[i][1]) { ne++; } else if (sz[i][0] > sz[i][1]) { ma++; } else { pe++; } } } document.write("P = " + pe + "<br>M = " + ma + "<br>N = " + ne);} // Driver code// Nodes at each index ( 1 - base indexing )let nodes =[];nodes.push('P');nodes.push('M');nodes.push('P');nodes.push('M');nodes.push('P'); // Connected Pairslet connect = [];connect.push([1,3]);connect.push([3,5]);connect.push([4,5]); influenced(nodes, connect); // This code is contributed by patel2127</script> P = 1 M = 1 N = 0 Time Complexity: O(N).Auxiliary Space: O(N). mohit kumar 29 Akanksha_Rai avanitrachhadiya2155 rag2127 patel2127 pankajsharmagfg rajeev0719singh singghakshay DFS disjoint-set Advanced Data Structure Algorithms Data Structures Graph Data Structures DFS Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Difference between Backtracking and Branch-N-Bound technique SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS A* Search Algorithm
[ { "code": null, "e": 25707, "s": 25679, "text": "\n18 Oct, 2021" }, { "code": null, "e": 25935, "s": 25707, "text": "Given a graph with N nodes having values either P or M. Also given K pairs of integers as (x, y) representing the edges in the graph such that if a is connected to b and b is connected to c then a and c will also be connected. " }, { "code": null, "e": 26277, "s": 25935, "text": "A single connected component is called a group. The group can have both P and M values. If the P values are more than the M values this group is called P influenced and similarly for M. If the number of P’s and M’s are equal then it is called a neutral group. The task is to find the number of P influenced, M influenced and, Neutral groups." }, { "code": null, "e": 26289, "s": 26277, "text": "Examples: " }, { "code": null, "e": 26513, "s": 26289, "text": "Input: Nodes[] = {P, M, P, M, P}, edges[][] = { {1, 3}, {4, 5}, {3, 5}} Output: P = 1 M = 1 N = 0 There will be two groups of indexes {1, 3, 4, 5} and {2}. The first group is P influenced and the second one is M influenced." }, { "code": null, "e": 26604, "s": 26513, "text": "Input: Nodes[] = {P, M, P, M, P}, edges[][] = { {1, 3}, {4, 5}} Output: P = 1 M = 2 N = 0 " }, { "code": null, "e": 27070, "s": 26604, "text": "Approach: It is easier to construct a graph with adjacency list and loop from 1 to N and do DFS and check the count of P and M. Another way is to use DSU with a little modification that size array will be of pair so that it can maintain the count of both M and P. In this approach, there is no need to construct the graph as the merge operation will take care of the connected component. Note that you should have the knowledge of DSU by size/rank for optimization." }, { "code": null, "e": 27123, "s": 27070, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27127, "s": 27123, "text": "C++" }, { "code": null, "e": 27132, "s": 27127, "text": "Java" }, { "code": null, "e": 27140, "s": 27132, "text": "Python3" }, { "code": null, "e": 27143, "s": 27140, "text": "C#" }, { "code": null, "e": 27154, "s": 27143, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the parents// of the current nodevector<int> par; // To store the size of M and Pvector<pair<int, int> > sz; // Function for initializationvoid init(vector<char>& nodes){ // Size of the graph int n = (int)nodes.size(); par.clear(); sz.clear(); par.resize(n + 1); sz.resize(n + 1); for (int i = 0; i <= n; ++i) { par[i] = i; if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') sz[i] = { 0, 1 }; // If the node is M else sz[i] = { 1, 0 }; } }} // To find the parent of// the current nodeint parent(int i){ while (par[i] != i) i = par[i]; return i;} // Merge functionvoid union(int a, int b){ a = parent(a); b = parent(b); if (a == b) return; // Total size by adding number of M and P int sz_a = sz[a].first + sz[a].second; int sz_b = sz[b].first + sz[b].second; if (sz_a < sz_b) swap(a, b); par[b] = a; sz[a].first += sz[b].first; sz[a].second += sz[b].second; return;} // Function to calculate the influenced valuevoid influenced(vector<char>& nodes, vector<pair<int, int> > connect){ // Number of nodes int n = (int)nodes.size(); // Initialization function init(nodes); // Size of the connected vector int k = connect.size(); // Performing union operation for (int i = 0; i < k; ++i) { union(connect[i].first, connect[i].second); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for (int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz[i].first == sz[i].second) { ne++; } else if (sz[i].first > sz[i].second) { ma++; } else { pe++; } } } cout << \"P = \" << pe << \"\\nM = \" << ma << \"\\nN = \" << ne << \"\\n\";} // Driver codeint main(){ // Nodes at each index ( 1 - base indexing ) vector<char> nodes = { 'P', 'M', 'P', 'M', 'P' }; // Connected Pairs vector<pair<int, int> > connect = { { 1, 3 }, { 3, 5 }, { 4, 5 } }; influenced(nodes, connect); return 0;}", "e": 29562, "s": 27154, "text": null }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // To store the parents// of the current nodestatic ArrayList<Integer> par = new ArrayList<Integer>(); // To store the size of M and Pstatic ArrayList< ArrayList<Integer>> sz = new ArrayList< ArrayList<Integer>>(); // Function for initializationstatic void init(ArrayList<Character> nodes){ // Size of the graph int n = nodes.size(); for(int i = 0; i <= n; ++i) { par.add(i); if (i == 0) { sz.add(new ArrayList<Integer>( Arrays.asList(0, 0))); } if (i > 0) { // If the node is P if (nodes.get(i - 1) == 'P') { sz.add(new ArrayList<Integer>( Arrays.asList(0, 1))); } // If the node is M else { sz.add(new ArrayList<Integer>( Arrays.asList(1, 0))); } } }} // To find the parent of// the current nodestatic int parent(int i){ while (par.get(i) != i) { i = par.get(i); } return i;} // Merge functionstatic void union(int a, int b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P int sz_a = sz.get(a).get(0) + sz.get(a).get(1); int sz_b = sz.get(b).get(0) + sz.get(b).get(1); if (sz_a < sz_b) { int temp = a; a = b; b = temp; } par.set(b, a); sz.get(a).set(0, sz.get(a).get(0) + sz.get(b).get(0)); sz.get(a).set(1, sz.get(a).get(1) + sz.get(b).get(1)); return;} // Function to calculate the influenced valuestatic void influenced(ArrayList<Character> nodes, ArrayList<ArrayList<Integer>> connect){ // Number of nodes int n = nodes.size(); // Initialization function init(nodes); // Size of the connected vector int k = connect.size(); // Performing union operation for(int i = 0; i < k; ++i) { union(connect.get(i).get(0), connect.get(i).get(1)); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for(int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz.get(i).get(0) == sz.get(i).get(1)) { ne++; } else if (sz.get(i).get(0) > sz.get(i).get(1)) { ma++; } else { pe++; } } } System.out.println(\"P = \" + pe + \"\\nM = \" + ma + \"\\nN = \" + ne);} // Driver codepublic static void main(String[] args){ // Nodes at each index ( 1 - base indexing ) ArrayList<Character> nodes = new ArrayList<Character>(); nodes.add('P'); nodes.add('M'); nodes.add('P'); nodes.add('M'); nodes.add('P'); // Connected Pairs ArrayList< ArrayList<Integer>> connect = new ArrayList< ArrayList<Integer>>(); connect.add(new ArrayList<Integer>( Arrays.asList(1, 3))); connect.add(new ArrayList<Integer>( Arrays.asList(3, 5))); connect.add(new ArrayList<Integer>( Arrays.asList(4, 5))); influenced(nodes, connect);}} // This code is contributed by avanitrachhadiya2155", "e": 33284, "s": 29562, "text": null }, { "code": "# Python3 implementation of the approach # To store the parents# of the current nodepar = [] # To store the size of M and Psz = [] # Function for initializationdef init(nodes): # Size of the graph n = len(nodes) for i in range(n + 1): par.append(0) sz.append(0) for i in range(n + 1): par[i] = i if (i > 0): # If the node is P if (nodes[i - 1] == 'P'): sz[i] = [0, 1] # If the node is M else: sz[i] = [1, 0] # To find the parent of# the current nodedef parent(i): while (par[i] != i): i = par[i] return i # Merge functiondef union(a, b): a = parent(a) b = parent(b) if (a == b): return # Total size by adding number of M and P sz_a = sz[a][0] + sz[a][1] sz_b = sz[b][0] + sz[b][1] if (sz_a < sz_b): a, b = b, a par[b] = a sz[a][0] += sz[b][0] sz[a][1] += sz[b][1] return # Function to calculate the influenced valuedef influenced(nodes,connect): # Number of nodes n = len(nodes) # Initialization function init(nodes) # Size of the connected vector k = len(connect) # Performing union operation for i in range(k): union(connect[i][0], connect[i][1]) # ne = Number of neutal groups # ma = Number of M influenced groups # pe = Number of P influenced groups ne = 0 ma = 0 pe = 0 for i in range(1, n + 1): x = parent(i) if (x == i): if (sz[i][0] == sz[i][1]): ne += 1 elif (sz[i][0] > sz[i][1]): ma += 1 else: pe += 1 print(\"P =\",pe,\"\\nM =\",ma,\"\\nN =\",ne) # Driver code # Nodes at each index ( 1 - base indexing )nodes = [ 'P', 'M', 'P', 'M', 'P' ] # Connected Pairsconnect = [ [ 1, 3 ], [ 3, 5 ], [ 4, 5 ] ] influenced(nodes, connect) # This code is contributed by mohit kumar 29", "e": 35220, "s": 33284, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the parents// of the current nodestatic List<int> par = new List<int>(); // To store the size of M and Pstatic List<List<int>> sz = new List<List<int>>(); // Function for initializationstatic void init(List<char> nodes){ // Size of the graph int n = nodes.Count; for(int i = 0; i <= n; ++i) { par.Add(i); if (i == 0) { sz.Add(new List<int>(){0, 0}); } if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') { sz.Add(new List<int>(){0, 1}); } // If the node is M else { sz.Add(new List<int>(){1, 0}); } } }} // To find the parent of// the current nodestatic int parent(int i){ while (par[i] != i) { i = par[i]; } return i;} // Merge functionstatic void union(int a, int b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P int sz_a = sz[a][0] + sz[a][1]; int sz_b = sz[b][0] + sz[b][1]; if (sz_a < sz_b) { int temp = a; a = b; b = temp; } par[b] = a; sz[a][0] += sz[b][0]; sz[a][1] += sz[b][1]; return;} // Function to calculate the influenced valuestatic void influenced(List<char> nodes, List<List<int>> connect){ // Number of nodes int n = nodes.Count; // Initialization function init(nodes); // Size of the connected vector int k = connect.Count; // Performing union operation for(int i = 0; i < k; ++i) { union(connect[i][0], connect[i][1]); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups int ne = 0, ma = 0, pe = 0; for(int i = 1; i <= n; ++i) { int x = parent(i); if (x == i) { if (sz[i][0] == sz[i][1]) { ne++; } else if (sz[i][0] > sz[i][1]) { ma++; } else { pe++; } } } Console.WriteLine(\"P = \" + pe + \"\\nM = \" + ma + \"\\nN = \" + ne);} // Driver codestatic public void Main(){ // Nodes at each index ( 1 - base indexing ) List<char> nodes = new List<char>(){'P', 'M', 'P', 'M', 'P'}; // Connected Pairs List<List<int>> connect = new List<List<int>>(); connect.Add(new List<int>(){1, 3}); connect.Add(new List<int>(){3, 5}); connect.Add(new List<int>(){4, 5}); influenced(nodes, connect);}} // This code is contributed by rag2127", "e": 38106, "s": 35220, "text": null }, { "code": "<script>// Javascript implementation of the approach // To store the parents// of the current nodelet par = []; // To store the size of M and Plet sz = []; // Function for initializationfunction init(nodes){ // Size of the graph let n = nodes.length; for(let i = 0; i <= n; ++i) { par.push(i); if (i == 0) { sz.push([0,0]); } if (i > 0) { // If the node is P if (nodes[i - 1] == 'P') { sz.push([0,1]); } // If the node is M else { sz.push([1,0]); } } }} // To find the parent of// the current nodefunction parent(i){ while (par[i] != i) { i = par[i]; } return i;} // Merge functionfunction union(a,b){ a = parent(a); b = parent(b); if (a == b) { return; } // Total size by adding number // of M and P let sz_a = sz[a][0] + sz[a][1]; let sz_b = sz[b][0] + sz[b][1]; if (sz_a < sz_b) { let temp = a; a = b; b = temp; } par[b] = a; sz[a][0] = sz[a][0] + sz[b][0]; sz[a][1] = sz[a][1] + sz[b][1]; return;} // Function to calculate the influenced valuefunction influenced(nodes,connect){ // Number of nodes let n = nodes.length; // Initialization function init(nodes); // Size of the connected vector let k = connect.length; // Performing union operation for(let i = 0; i < k; ++i) { union(connect[i][0], connect[i][1]); } // ne = Number of neutal groups // ma = Number of M influenced groups // pe = Number of P influenced groups let ne = 0, ma = 0, pe = 0; for(let i = 1; i <= n; ++i) { let x = parent(i); if (x == i) { if (sz[i][0] == sz[i][1]) { ne++; } else if (sz[i][0] > sz[i][1]) { ma++; } else { pe++; } } } document.write(\"P = \" + pe + \"<br>M = \" + ma + \"<br>N = \" + ne);} // Driver code// Nodes at each index ( 1 - base indexing )let nodes =[];nodes.push('P');nodes.push('M');nodes.push('P');nodes.push('M');nodes.push('P'); // Connected Pairslet connect = [];connect.push([1,3]);connect.push([3,5]);connect.push([4,5]); influenced(nodes, connect); // This code is contributed by patel2127</script>", "e": 40804, "s": 38106, "text": null }, { "code": null, "e": 40822, "s": 40804, "text": "P = 1\nM = 1\nN = 0" }, { "code": null, "e": 40870, "s": 40824, "text": "Time Complexity: O(N).Auxiliary Space: O(N). " }, { "code": null, "e": 40885, "s": 40870, "text": "mohit kumar 29" }, { "code": null, "e": 40898, "s": 40885, "text": "Akanksha_Rai" }, { "code": null, "e": 40919, "s": 40898, "text": "avanitrachhadiya2155" }, { "code": null, "e": 40927, "s": 40919, "text": "rag2127" }, { "code": null, "e": 40937, "s": 40927, "text": "patel2127" }, { "code": null, "e": 40953, "s": 40937, "text": "pankajsharmagfg" }, { "code": null, "e": 40969, "s": 40953, "text": "rajeev0719singh" }, { "code": null, "e": 40982, "s": 40969, "text": "singghakshay" }, { "code": null, "e": 40986, "s": 40982, "text": "DFS" }, { "code": null, "e": 40999, "s": 40986, "text": "disjoint-set" }, { "code": null, "e": 41023, "s": 40999, "text": "Advanced Data Structure" }, { "code": null, "e": 41034, "s": 41023, "text": "Algorithms" }, { "code": null, "e": 41050, "s": 41034, "text": "Data Structures" }, { "code": null, "e": 41056, "s": 41050, "text": "Graph" }, { "code": null, "e": 41072, "s": 41056, "text": "Data Structures" }, { "code": null, "e": 41076, "s": 41072, "text": "DFS" }, { "code": null, "e": 41082, "s": 41076, "text": "Graph" }, { "code": null, "e": 41093, "s": 41082, "text": "Algorithms" }, { "code": null, "e": 41191, "s": 41093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41220, "s": 41191, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 41262, "s": 41220, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 41308, "s": 41262, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 41344, "s": 41308, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 41405, "s": 41344, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 41454, "s": 41405, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 41498, "s": 41454, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 41523, "s": 41498, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 41554, "s": 41523, "text": "Difference between BFS and DFS" } ]
Minimum operations to convert array A to B | Practice | GeeksforGeeks
Given two Arrays A[] and B[] of length N and M respectively. Find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical. Note: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not necessarily at end. Example 1: Input: N = 5, M = 3 A[] = {1, 2, 5, 3, 1} B[] = {1, 3, 5} Output: 4 Explanation: We need to delete 2 and replace it with 3. This costs 2 steps. Further, we will have to delete the last two elements from A to obtain an identical array to B. Overall, it results in 4 steps. Input: N = 2, M = 2 A[] = {1, 4} B[] = {1, 4} Output : 0 Explanation: Both the Arrays are already identical. Your Task: You don't need to read input or print anything. Your task is to complete the function minInsAndDel() which takes two integers N and M, and two arrays A of size N and B of size M respectively as input and returns the minimum insertions and deletions required. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 1 ≤ A[i], B[i] ≤ 105 0 beheraalokmaya2 weeks ago hi this is the converting class Solution { public: int minInsAndDel(int A[], int B[], int N, int M) { vector<int> lis; unordered_set<int> s; for(int i = 0; i < M ;i++){ s.insert(B[i]); } for(int i = 0; i < N ;i++){ if(s.find(A[i])!=s.end()){ auto it = lower_bound(lis.begin(),lis.end(),A[i]); if(it==lis.end()){ lis.push_back(A[i]); }else{ *it = A[i]; } } } return N+M-2*lis.size(); }}; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int N,M; cin>>N>>M; int A[N], B[M]; for(int i=0; i<N; i++) cin>>A[i]; for(int i=0; i<M; i++) cin>>B[i]; Solution ob; cout << ob.minInsAndDel(A,B,N,M) << endl; } return 0;} 0 karthiksamineni1112 months ago 4 31 4 2 51 2 4 this input is giving 3 as output plz explain. 0 ksandeep27072 months ago C++ code:- int minInsAndDel(int a[], int b[], int n, int m) { map<int,int> mp; for(int i=0;i<m;i++) mp[b[i]]++; vector<int> v; for(int i=0;i<n;i++) { if(mp[a[i]]) { auto it=lower_bound(v.begin(),v.end(),a[i]); if(it==v.end()) v.push_back(a[i]); else (*it)=a[i]; } } int ans=n+m-2*v.size(); return ans; } 0 araj2920183 months ago class Solution { public: //method of finding LCS using binary search int LCS(vector<int> co){ vector<int>lcs; for(int i=0;i<co.size();i++){ auto j=lower_bound(lcs.begin(),lcs.end(),co[i]); if(j!=lcs.end()){ *j=co[i]; } else{ lcs.push_back(co[i]); } } return lcs.size(); } int minInsAndDel(int A[], int B[], int N, int M) { vector<int>co; unordered_set<int>s; for(int i=0;i<M;i++){ s.insert(B[i]); } for(int i=0;i<N;i++){ if(s.find(A[i])!=s.end()){ co.push_back(A[i]); } } return N+M-(2*LCS(co)); }}; +5 neuron093 months ago Trivial solution would be to use 2-D DP(simialar to https://leetcode.com/problems/edit-distance/) but since N could be upto 100K it will give TLE. First delete the nums in A which are not in B Now we need to find LCS between A and B, and keep those elements in A and delete rest, and also add remaining numbers in B which don't occur in the LCS to make it equal to B To find the LCS(longest common subsequence) with trivial 2-D DP will give TLE, but since B is already sorted, Longest increasing subsequence in A will be the LCS which can be found in O(N*LogN) time(similar to https://leetcode.com/problems/longest-increasing-subsequence/), Time: O(NlogN), Space: O(N) class Solution { public: const int INF = 1e9 + 5; int lis(vector<int> a) { int n = a.size(); vector<int> len; for(int i = 0; i < n; i++) { auto lb = lower_bound(len.begin(), len.end(), a[i]); if(lb != len.end()) { *lb = min(*lb, a[i]); } else { len.push_back(a[i]); } } return len.size(); } int minInsAndDel(int a[], int b[], int n, int m) { unordered_set<int> b_set; for(int i = 0; i < m; i++) b_set.insert(b[i]); vector<int> a_updated; int steps = 0; for(int i = 0; i < n; i++) { if(b_set.find(a[i]) != b_set.end()) { a_updated.push_back(a[i]); } else { steps++; } } int lis_size = lis(a_updated); return steps + (a_updated.size() - lis_size) + (m-lis_size); } }; 0 shashikantsolanki0423 months ago Hint : First try to solve longest increasing subsequence problem. class Solution { public: int solve(vector<int>vec){ vector<int>res; for(int i=0; i<vec.size(); i++){ auto it = lower_bound(res.begin(),res.end(),vec[i]); if(it == res.end()){ res.push_back(vec[i]); } else{ *it = vec[i]; } } return res.size(); } int minInsAndDel(int A[], int B[], int N, int M) { // code here unordered_map<int,int>mp; for(int i=0; i<M; i++){ mp[B[i]]++; } vector<int>vec; for(int i=0; i<N; i++){ if(mp.find(A[i]) != mp.end()){ vec.push_back(A[i]); } } return (N+M) - 2*solve(vec); } }; +2 shadyboy6 months ago class Solution { public: int minInsAndDel(int A[], int B[], int N, int M) { vector<int> lis;// store longest increasing subsequence in nlogn time unordered_set<int> s; for(int i = 0; i < M ;i++){ s.insert(B[i]); } for(int i = 0; i < N ;i++){ if(s.find(A[i])!=s.end()){ auto it = lower_bound(lis.begin(),lis.end(),A[i]); if(it==lis.end()){ lis.push_back(A[i]); }else{ *it = A[i]; } } } return N+M-2*lis.size(); } }; 0 divyanshchaudhri6 months ago Can someone plz explain the question According to my understanding i wrote a code but one test case is not passing don't know why test case is- 7 7 1 9 7 4 9 8 9 1 2 4 7 8 9 10 and the code is- class Solution: def minInsAndDel(self, A, B, N, M): # code here if(N>M): x=N-M c=0 for i in range(M): if A[i]!=B[i]: if B[i] in A: ind=A.index(B[i]) temp=A[i] A[i]=A[ind] A[ind]=temp c+=2 else: A[i]=B[i] c+=2 return x+c else: x=M-N c=0 for i in range(N): if A[i]!=B[i]: if B[i] in A: ind=A.index(B[i]) temp=A[i] A[i]=A[ind] A[ind]=temp c+=2 else: A[i]=B[i] c+=2 return x+c 0 shivanshushukla10246 months ago why i am getting error in this approach While submitting: class Solution: def minInsAndDel(self, A, B, N, M): # code here count = 0 if(N == 0 and M == 0): return count for i in range(M): if(A[i] != B[i]): A.pop(i) count += 1 A.insert(i, B[i]) count += 1 count += N-M return count 0 itsanshika6 months ago Find length of LIS of elements of A which are present in B We need to delete all elements of A which are not in LIS and need to insert all elements of B which are not in LIS Hence ans = N + M - 2*LIS_length Thus we only need length of longest increasing subsequence of elements of A which are present in B int LIS(vector<int> A, int N){ if(A.empty()) return 0; vector<int> tail(N, 0); int len = 1; tail[0] = A[0]; for (int i = 1; i < N; i++) { if (A[i] < tail[0]) tail[0] = A[i]; else if (A[i] > tail[len - 1]) tail[len++] = A[i]; else { int pos = lower_bound(tail.begin(), tail.begin()+len, A[i])-tail.begin(); tail[pos] = A[i]; } } return len; } int minInsAndDel(int A[], int B[], int N, int M) { vector<int> arr; map<int,int> m; for(int i = 0; i < M; i++) m[B[i]]++; for(int i = 0; i < N; i++){ if(m.find(A[i]) != m.end()) arr.push_back(A[i]); } int len = LIS(arr, arr.size()); return N+M-2*len; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 527, "s": 226, "text": "Given two Arrays A[] and B[] of length N and M respectively. Find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical.\nNote: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not necessarily at end." }, { "code": null, "e": 540, "s": 529, "text": "Example 1:" }, { "code": null, "e": 813, "s": 540, "text": "Input:\nN = 5, M = 3\nA[] = {1, 2, 5, 3, 1}\nB[] = {1, 3, 5}\nOutput:\n4\nExplanation:\nWe need to delete 2 and replace it with 3.\nThis costs 2 steps. Further, we will have to\ndelete the last two elements from A to\nobtain an identical array to B. Overall, it\nresults in 4 steps.\n" }, { "code": null, "e": 923, "s": 813, "text": "Input:\nN = 2, M = 2\nA[] = {1, 4}\nB[] = {1, 4}\nOutput :\n0\nExplanation:\nBoth the Arrays are already identical.\n" }, { "code": null, "e": 1196, "s": 923, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function minInsAndDel() which takes two integers N and M, and two arrays A of size N and B of size M respectively as input and returns the minimum insertions and deletions required." }, { "code": null, "e": 1263, "s": 1196, "text": "\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1310, "s": 1263, "text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ A[i], B[i] ≤ 105" }, { "code": null, "e": 1312, "s": 1310, "text": "0" }, { "code": null, "e": 1338, "s": 1312, "text": "beheraalokmaya2 weeks ago" }, { "code": null, "e": 1364, "s": 1338, "text": "hi this is the converting" }, { "code": null, "e": 1923, "s": 1366, "text": "class Solution { public: int minInsAndDel(int A[], int B[], int N, int M) { vector<int> lis; unordered_set<int> s; for(int i = 0; i < M ;i++){ s.insert(B[i]); } for(int i = 0; i < N ;i++){ if(s.find(A[i])!=s.end()){ auto it = lower_bound(lis.begin(),lis.end(),A[i]); if(it==lis.end()){ lis.push_back(A[i]); }else{ *it = A[i]; } } } return N+M-2*lis.size(); }};" }, { "code": null, "e": 1948, "s": 1923, "text": "// { Driver Code Starts." }, { "code": null, "e": 2159, "s": 1948, "text": "int main() { int t; cin >> t; while (t--) { int N,M; cin>>N>>M; int A[N], B[M]; for(int i=0; i<N; i++) cin>>A[i]; for(int i=0; i<M; i++) cin>>B[i];" }, { "code": null, "e": 2246, "s": 2159, "text": " Solution ob; cout << ob.minInsAndDel(A,B,N,M) << endl; } return 0;} " }, { "code": null, "e": 2248, "s": 2246, "text": "0" }, { "code": null, "e": 2279, "s": 2248, "text": "karthiksamineni1112 months ago" }, { "code": null, "e": 2295, "s": 2279, "text": "4 31 4 2 51 2 4" }, { "code": null, "e": 2342, "s": 2295, "text": "this input is giving 3 as output plz explain." }, { "code": null, "e": 2344, "s": 2342, "text": "0" }, { "code": null, "e": 2369, "s": 2344, "text": "ksandeep27072 months ago" }, { "code": null, "e": 2380, "s": 2369, "text": "C++ code:-" }, { "code": null, "e": 2877, "s": 2380, "text": "int minInsAndDel(int a[], int b[], int n, int m) \n {\n map<int,int> mp;\n for(int i=0;i<m;i++)\n mp[b[i]]++;\n vector<int> v;\n \n for(int i=0;i<n;i++)\n {\n if(mp[a[i]])\n {\n auto it=lower_bound(v.begin(),v.end(),a[i]);\n if(it==v.end())\n v.push_back(a[i]);\n else\n (*it)=a[i];\n }\n\n }\n \n int ans=n+m-2*v.size();\n return ans;\n }" }, { "code": null, "e": 2879, "s": 2877, "text": "0" }, { "code": null, "e": 2902, "s": 2879, "text": "araj2920183 months ago" }, { "code": null, "e": 3629, "s": 2902, "text": "class Solution { public: //method of finding LCS using binary search int LCS(vector<int> co){ vector<int>lcs; for(int i=0;i<co.size();i++){ auto j=lower_bound(lcs.begin(),lcs.end(),co[i]); if(j!=lcs.end()){ *j=co[i]; } else{ lcs.push_back(co[i]); } } return lcs.size(); } int minInsAndDel(int A[], int B[], int N, int M) { vector<int>co; unordered_set<int>s; for(int i=0;i<M;i++){ s.insert(B[i]); } for(int i=0;i<N;i++){ if(s.find(A[i])!=s.end()){ co.push_back(A[i]); } } return N+M-(2*LCS(co)); }};" }, { "code": null, "e": 3632, "s": 3629, "text": "+5" }, { "code": null, "e": 3653, "s": 3632, "text": "neuron093 months ago" }, { "code": null, "e": 3800, "s": 3653, "text": "Trivial solution would be to use 2-D DP(simialar to https://leetcode.com/problems/edit-distance/) but since N could be upto 100K it will give TLE." }, { "code": null, "e": 3847, "s": 3800, "text": " First delete the nums in A which are not in B" }, { "code": null, "e": 4021, "s": 3847, "text": "Now we need to find LCS between A and B, and keep those elements in A and delete rest, and also add remaining numbers in B which don't occur in the LCS to make it equal to B" }, { "code": null, "e": 4295, "s": 4021, "text": "To find the LCS(longest common subsequence) with trivial 2-D DP will give TLE, but since B is already sorted, Longest increasing subsequence in A will be the LCS which can be found in O(N*LogN) time(similar to https://leetcode.com/problems/longest-increasing-subsequence/)," }, { "code": null, "e": 4324, "s": 4295, "text": " Time: O(NlogN), Space: O(N)" }, { "code": null, "e": 5301, "s": 4324, "text": "class Solution {\n public:\n const int INF = 1e9 + 5;\n int lis(vector<int> a) {\n int n = a.size();\n vector<int> len;\n for(int i = 0; i < n; i++) {\n auto lb = lower_bound(len.begin(), len.end(), a[i]);\n if(lb != len.end()) {\n *lb = min(*lb, a[i]);\n }\n else {\n len.push_back(a[i]);\n }\n }\n return len.size();\n }\n int minInsAndDel(int a[], int b[], int n, int m) {\n unordered_set<int> b_set;\n for(int i = 0; i < m; i++) \n b_set.insert(b[i]);\n vector<int> a_updated;\n int steps = 0;\n for(int i = 0; i < n; i++) {\n if(b_set.find(a[i]) != b_set.end()) {\n a_updated.push_back(a[i]);\n }\n else {\n steps++;\n }\n }\n int lis_size = lis(a_updated);\n return steps + (a_updated.size() - lis_size) + (m-lis_size);\n }\n};" }, { "code": null, "e": 5303, "s": 5301, "text": "0" }, { "code": null, "e": 5336, "s": 5303, "text": "shashikantsolanki0423 months ago" }, { "code": null, "e": 5402, "s": 5336, "text": "Hint : First try to solve longest increasing subsequence problem." }, { "code": null, "e": 6165, "s": 5404, "text": "class Solution {\n public:\n int solve(vector<int>vec){\n vector<int>res;\n for(int i=0; i<vec.size(); i++){\n auto it = lower_bound(res.begin(),res.end(),vec[i]);\n if(it == res.end()){\n res.push_back(vec[i]);\n }\n else{\n *it = vec[i];\n }\n }\n return res.size();\n }\n int minInsAndDel(int A[], int B[], int N, int M) {\n // code here\n unordered_map<int,int>mp;\n for(int i=0; i<M; i++){\n mp[B[i]]++;\n }\n vector<int>vec;\n for(int i=0; i<N; i++){\n if(mp.find(A[i]) != mp.end()){\n vec.push_back(A[i]);\n }\n }\n return (N+M) - 2*solve(vec);\n }\n};" }, { "code": null, "e": 6168, "s": 6165, "text": "+2" }, { "code": null, "e": 6189, "s": 6168, "text": "shadyboy6 months ago" }, { "code": null, "e": 6846, "s": 6189, "text": "class Solution {\n public:\n int minInsAndDel(int A[], int B[], int N, int M) {\n vector<int> lis;// store longest increasing subsequence in nlogn time\n \n unordered_set<int> s;\n for(int i = 0; i < M ;i++){\n s.insert(B[i]);\n }\n \n \n for(int i = 0; i < N ;i++){\n if(s.find(A[i])!=s.end()){\n auto it = lower_bound(lis.begin(),lis.end(),A[i]);\n if(it==lis.end()){\n lis.push_back(A[i]);\n }else{\n *it = A[i];\n }\n }\n }\n \n return N+M-2*lis.size();\n }\n};" }, { "code": null, "e": 6848, "s": 6846, "text": "0" }, { "code": null, "e": 6877, "s": 6848, "text": "divyanshchaudhri6 months ago" }, { "code": null, "e": 6915, "s": 6877, "text": "Can someone plz explain the question " }, { "code": null, "e": 7008, "s": 6915, "text": "According to my understanding i wrote a code but one test case is not passing don't know why" }, { "code": null, "e": 7022, "s": 7008, "text": "test case is-" }, { "code": null, "e": 7027, "s": 7022, "text": "7 7 " }, { "code": null, "e": 7042, "s": 7027, "text": "1 9 7 4 9 8 9 " }, { "code": null, "e": 7057, "s": 7042, "text": "1 2 4 7 8 9 10" }, { "code": null, "e": 7074, "s": 7057, "text": "and the code is-" }, { "code": null, "e": 8007, "s": 7074, "text": "class Solution: def minInsAndDel(self, A, B, N, M): # code here if(N>M): x=N-M c=0 for i in range(M): if A[i]!=B[i]: if B[i] in A: ind=A.index(B[i]) temp=A[i] A[i]=A[ind] A[ind]=temp c+=2 else: A[i]=B[i] c+=2 return x+c else: x=M-N c=0 for i in range(N): if A[i]!=B[i]: if B[i] in A: ind=A.index(B[i]) temp=A[i] A[i]=A[ind] A[ind]=temp c+=2 else: A[i]=B[i] c+=2 return x+c " }, { "code": null, "e": 8011, "s": 8009, "text": "0" }, { "code": null, "e": 8043, "s": 8011, "text": "shivanshushukla10246 months ago" }, { "code": null, "e": 8101, "s": 8043, "text": "why i am getting error in this approach While submitting:" }, { "code": null, "e": 8440, "s": 8103, "text": "class Solution: def minInsAndDel(self, A, B, N, M): # code here count = 0 if(N == 0 and M == 0): return count for i in range(M): if(A[i] != B[i]): A.pop(i) count += 1 A.insert(i, B[i]) count += 1 count += N-M return count" }, { "code": null, "e": 8442, "s": 8440, "text": "0" }, { "code": null, "e": 8465, "s": 8442, "text": "itsanshika6 months ago" }, { "code": null, "e": 8524, "s": 8465, "text": "Find length of LIS of elements of A which are present in B" }, { "code": null, "e": 8639, "s": 8524, "text": "We need to delete all elements of A which are not in LIS and need to insert all elements of B which are not in LIS" }, { "code": null, "e": 8672, "s": 8639, "text": "Hence ans = N + M - 2*LIS_length" }, { "code": null, "e": 8771, "s": 8672, "text": "Thus we only need length of longest increasing subsequence of elements of A which are present in B" }, { "code": null, "e": 9584, "s": 8771, "text": "int LIS(vector<int> A, int N){\n if(A.empty()) return 0;\n vector<int> tail(N, 0);\n int len = 1; tail[0] = A[0];\n for (int i = 1; i < N; i++) {\n if (A[i] < tail[0]) tail[0] = A[i];\n else if (A[i] > tail[len - 1]) tail[len++] = A[i];\n else {\n int pos = lower_bound(tail.begin(), tail.begin()+len, A[i])-tail.begin();\n tail[pos] = A[i];\n }\n }\n return len;\n }\n \n \n int minInsAndDel(int A[], int B[], int N, int M) {\n vector<int> arr;\n map<int,int> m;\n for(int i = 0; i < M; i++) m[B[i]]++;\n for(int i = 0; i < N; i++){\n if(m.find(A[i]) != m.end()) arr.push_back(A[i]);\n }\n int len = LIS(arr, arr.size());\n return N+M-2*len;\n }" }, { "code": null, "e": 9730, "s": 9584, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9766, "s": 9730, "text": " Login to access your submissions. " }, { "code": null, "e": 9776, "s": 9766, "text": "\nProblem\n" }, { "code": null, "e": 9786, "s": 9776, "text": "\nContest\n" }, { "code": null, "e": 9849, "s": 9786, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9997, "s": 9849, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 10205, "s": 9997, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 10311, "s": 10205, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Get all array elements with true values in Julia | Array findall() Method - GeeksforGeeks
23 Mar, 2020 The findall() is an inbuilt function in julia which is used to return a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on. Syntax:findall(A)orfindall(f::Function, A) Parameters: A: Specified array Function: Determines whether something is true or false based on the specified arguments Returns: It returns a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array. Example 1: # Julia program to illustrate # the use of Array findall() method # Finding index of all true values from # the 1D array AA = [false, true, true, false]println(findall(A)) # Finding index of all true values from # the 2D array B of size 2 * 2B = [false false; true false]println(findall(B)) # Finding index of all true values from # the 3D array C of size 2 * 2*2C = cat([false false; true false], [false true; true false], [true false; true true], dims = 3)println(findall(C)) Output: Example 2: # Julia program to illustrate # the use of Array findall() method # Finding index of all even values from # the 1D array AA = [1, 2, 5, 7]println(findall(iseven, A)) # Finding index of all odd values from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findall(isodd, B)) # Finding index of all odd values from # the 3D array C of size 2 * 2*2C = cat([6 2; 6 4], [5 6; 2 8], [2 10; 11 1], dims = 3)println(findall(isodd, C)) Output: Julia Array-functions Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Storing Output on a File in Julia Reshaping array dimensions in Julia | Array reshape() Method Manipulating matrices in Julia Comments in Julia while loop in Julia Formatting of Strings in Julia Tuples in Julia Searching in Array for a given element in Julia
[ { "code": null, "e": 24266, "s": 24238, "text": "\n23 Mar, 2020" }, { "code": null, "e": 24602, "s": 24266, "text": "The findall() is an inbuilt function in julia which is used to return a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on." }, { "code": null, "e": 24645, "s": 24602, "text": "Syntax:findall(A)orfindall(f::Function, A)" }, { "code": null, "e": 24657, "s": 24645, "text": "Parameters:" }, { "code": null, "e": 24676, "s": 24657, "text": "A: Specified array" }, { "code": null, "e": 24765, "s": 24676, "text": "Function: Determines whether something is true or false based on the specified arguments" }, { "code": null, "e": 24937, "s": 24765, "text": "Returns: It returns a vector of indices or keys of the all true values from the specified array A. If such true values are not present in the array, return an empty array." }, { "code": null, "e": 24948, "s": 24937, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of Array findall() method # Finding index of all true values from # the 1D array AA = [false, true, true, false]println(findall(A)) # Finding index of all true values from # the 2D array B of size 2 * 2B = [false false; true false]println(findall(B)) # Finding index of all true values from # the 3D array C of size 2 * 2*2C = cat([false false; true false], [false true; true false], [true false; true true], dims = 3)println(findall(C))", "e": 25447, "s": 24948, "text": null }, { "code": null, "e": 25455, "s": 25447, "text": "Output:" }, { "code": null, "e": 25466, "s": 25455, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of Array findall() method # Finding index of all even values from # the 1D array AA = [1, 2, 5, 7]println(findall(iseven, A)) # Finding index of all odd values from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findall(isodd, B)) # Finding index of all odd values from # the 3D array C of size 2 * 2*2C = cat([6 2; 6 4], [5 6; 2 8], [2 10; 11 1], dims = 3)println(findall(isodd, C))", "e": 25909, "s": 25466, "text": null }, { "code": null, "e": 25917, "s": 25909, "text": "Output:" }, { "code": null, "e": 25939, "s": 25917, "text": "Julia Array-functions" }, { "code": null, "e": 25945, "s": 25939, "text": "Julia" }, { "code": null, "e": 26043, "s": 25945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26060, "s": 26043, "text": "Vectors in Julia" }, { "code": null, "e": 26120, "s": 26060, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 26154, "s": 26120, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 26215, "s": 26154, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 26246, "s": 26215, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 26264, "s": 26246, "text": "Comments in Julia" }, { "code": null, "e": 26284, "s": 26264, "text": "while loop in Julia" }, { "code": null, "e": 26315, "s": 26284, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 26331, "s": 26315, "text": "Tuples in Julia" } ]
Implement Canny Edge Detector in Python using OpenCV - GeeksforGeeks
22 Feb, 2022 In this article, we will learn the working of the popular Canny edge detection algorithm developed by John F. Canny in 1986. Usually, in Matlab and OpenCV we use the canny edge detection for many popular tasks in edge detection such as lane detection, sketching, border removal, now we will learn the internal working and implementation of this algorithm from scratch. The basic steps involved in this algorithm are: Noise reduction using Gaussian filter Gradient calculation along the horizontal and vertical axis Non-Maximum suppression of false edges Double thresholding for segregating strong and weak edges Edge tracking by hysteresis Now let us understand these concepts in detail: This step is of utmost importance in the Canny edge detection. It uses a Gaussian filter for the removal of noise from the image, it is because this noise can be assumed as edges due to sudden intensity change by the edge detector. The sum of the elements in the Gaussian kernel is 1, so, the kernel should be normalized before applying as convolution to the image. In this tutorial, we will use a kernel of size 5 X 5 and sigma = 1.4, which will blur the image and remove the noise from it. The equation for Gaussian filter kernel is When the image is smoothed, the derivatives Ix and Iy are calculated w.r.t x and y axis. It can be implemented by using the Sobel-Feldman kernels convolution with image as given: Sobel Kernels after applying these kernel we can use the gradient magnitudes and the angle to further process this step. The magnitude and angle can be calculated as Gradient magnitude and angle This step aims at reducing the duplicate merging pixels along the edges to make them uneven. For each pixel find two neighbors in the positive and negative gradient directions, supposing that each neighbor occupies the angle of pi /4, and 0 is the direction straight to the right. If the magnitude of the current pixel is greater than the magnitude of the neighbors, nothing changes, otherwise, the magnitude of the current pixel is set to zero. The gradient magnitudes are compared with two specified threshold values, the first one is lower than the second. The gradients that are smaller than the low threshold value are suppressed, the gradients higher than the high threshold value are marked as strong ones and the corresponding pixels are included in the final edge map. All the rest gradients are marked as weak ones and pixels corresponding to these gradients are considered in the next step. Since a weak edge pixel caused by true edges will be connected to a strong edge pixel, pixel W with weak gradient is marked as edge and included in the final edge map if and only if it is involved in the same connected component as some pixel S with strong gradient. In other words, there should be a chain of neighbor weak pixels connecting W and S (the neighbors are 8 pixels around the considered one). We will make up and implement an algorithm that finds all the connected components of the gradient map considering each pixel only once. After that, you can decide which pixels will be included in the final edge map.Below is the implementation. Python3 import numpy as npimport osimport cv2import matplotlib.pyplot as plt # defining the canny detector function # here weak_th and strong_th are thresholds for# double thresholding stepdef Canny_detector(img, weak_th = None, strong_th = None): # conversion of image to grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Noise reduction step img = cv2.GaussianBlur(img, (5, 5), 1.4) # Calculating the gradients gx = cv2.Sobel(np.float32(img), cv2.CV_64F, 1, 0, 3) gy = cv2.Sobel(np.float32(img), cv2.CV_64F, 0, 1, 3) # Conversion of Cartesian coordinates to polar mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees = True) # setting the minimum and maximum thresholds # for double thresholding mag_max = np.max(mag) if not weak_th:weak_th = mag_max * 0.1 if not strong_th:strong_th = mag_max * 0.5 # getting the dimensions of the input image height, width = img.shape # Looping through every pixel of the grayscale # image for i_x in range(width): for i_y in range(height): grad_ang = ang[i_y, i_x] grad_ang = abs(grad_ang-180) if abs(grad_ang)>180 else abs(grad_ang) # selecting the neighbours of the target pixel # according to the gradient direction # In the x axis direction if grad_ang<= 22.5: neighb_1_x, neighb_1_y = i_x-1, i_y neighb_2_x, neighb_2_y = i_x + 1, i_y # top right (diagonal-1) direction elif grad_ang>22.5 and grad_ang<=(22.5 + 45): neighb_1_x, neighb_1_y = i_x-1, i_y-1 neighb_2_x, neighb_2_y = i_x + 1, i_y + 1 # In y-axis direction elif grad_ang>(22.5 + 45) and grad_ang<=(22.5 + 90): neighb_1_x, neighb_1_y = i_x, i_y-1 neighb_2_x, neighb_2_y = i_x, i_y + 1 # top left (diagonal-2) direction elif grad_ang>(22.5 + 90) and grad_ang<=(22.5 + 135): neighb_1_x, neighb_1_y = i_x-1, i_y + 1 neighb_2_x, neighb_2_y = i_x + 1, i_y-1 # Now it restarts the cycle elif grad_ang>(22.5 + 135) and grad_ang<=(22.5 + 180): neighb_1_x, neighb_1_y = i_x-1, i_y neighb_2_x, neighb_2_y = i_x + 1, i_y # Non-maximum suppression step if width>neighb_1_x>= 0 and height>neighb_1_y>= 0: if mag[i_y, i_x]<mag[neighb_1_y, neighb_1_x]: mag[i_y, i_x]= 0 continue if width>neighb_2_x>= 0 and height>neighb_2_y>= 0: if mag[i_y, i_x]<mag[neighb_2_y, neighb_2_x]: mag[i_y, i_x]= 0 weak_ids = np.zeros_like(img) strong_ids = np.zeros_like(img) ids = np.zeros_like(img) # double thresholding step for i_x in range(width): for i_y in range(height): grad_mag = mag[i_y, i_x] if grad_mag<weak_th: mag[i_y, i_x]= 0 elif strong_th>grad_mag>= weak_th: ids[i_y, i_x]= 1 else: ids[i_y, i_x]= 2 # finally returning the magnitude of # gradients of edges return mag frame = cv2.imread('food.jpeg') # calling the designed function for# finding edgescanny_img = Canny_detector(frame) # Displaying the input and output image plt.figure()f, plots = plt.subplots(2, 1) plots[0].imshow(frame)plots[1].imshow(canny_img) Input image Output image adnanirshad158 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24720, "s": 24692, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25090, "s": 24720, "text": "In this article, we will learn the working of the popular Canny edge detection algorithm developed by John F. Canny in 1986. Usually, in Matlab and OpenCV we use the canny edge detection for many popular tasks in edge detection such as lane detection, sketching, border removal, now we will learn the internal working and implementation of this algorithm from scratch. " }, { "code": null, "e": 25140, "s": 25090, "text": "The basic steps involved in this algorithm are: " }, { "code": null, "e": 25180, "s": 25140, "text": "Noise reduction using Gaussian filter " }, { "code": null, "e": 25242, "s": 25180, "text": "Gradient calculation along the horizontal and vertical axis " }, { "code": null, "e": 25283, "s": 25242, "text": "Non-Maximum suppression of false edges " }, { "code": null, "e": 25343, "s": 25283, "text": "Double thresholding for segregating strong and weak edges " }, { "code": null, "e": 25371, "s": 25343, "text": "Edge tracking by hysteresis" }, { "code": null, "e": 25421, "s": 25371, "text": "Now let us understand these concepts in detail: " }, { "code": null, "e": 25957, "s": 25421, "text": "This step is of utmost importance in the Canny edge detection. It uses a Gaussian filter for the removal of noise from the image, it is because this noise can be assumed as edges due to sudden intensity change by the edge detector. The sum of the elements in the Gaussian kernel is 1, so, the kernel should be normalized before applying as convolution to the image. In this tutorial, we will use a kernel of size 5 X 5 and sigma = 1.4, which will blur the image and remove the noise from it. The equation for Gaussian filter kernel is " }, { "code": null, "e": 26139, "s": 25959, "text": "When the image is smoothed, the derivatives Ix and Iy are calculated w.r.t x and y axis. It can be implemented by using the Sobel-Feldman kernels convolution with image as given: " }, { "code": null, "e": 26153, "s": 26139, "text": "Sobel Kernels" }, { "code": null, "e": 26306, "s": 26153, "text": "after applying these kernel we can use the gradient magnitudes and the angle to further process this step. The magnitude and angle can be calculated as " }, { "code": null, "e": 26335, "s": 26306, "text": "Gradient magnitude and angle" }, { "code": null, "e": 26784, "s": 26337, "text": "This step aims at reducing the duplicate merging pixels along the edges to make them uneven. For each pixel find two neighbors in the positive and negative gradient directions, supposing that each neighbor occupies the angle of pi /4, and 0 is the direction straight to the right. If the magnitude of the current pixel is greater than the magnitude of the neighbors, nothing changes, otherwise, the magnitude of the current pixel is set to zero. " }, { "code": null, "e": 27241, "s": 26784, "text": "The gradient magnitudes are compared with two specified threshold values, the first one is lower than the second. The gradients that are smaller than the low threshold value are suppressed, the gradients higher than the high threshold value are marked as strong ones and the corresponding pixels are included in the final edge map. All the rest gradients are marked as weak ones and pixels corresponding to these gradients are considered in the next step. " }, { "code": null, "e": 27894, "s": 27241, "text": "Since a weak edge pixel caused by true edges will be connected to a strong edge pixel, pixel W with weak gradient is marked as edge and included in the final edge map if and only if it is involved in the same connected component as some pixel S with strong gradient. In other words, there should be a chain of neighbor weak pixels connecting W and S (the neighbors are 8 pixels around the considered one). We will make up and implement an algorithm that finds all the connected components of the gradient map considering each pixel only once. After that, you can decide which pixels will be included in the final edge map.Below is the implementation. " }, { "code": null, "e": 27902, "s": 27894, "text": "Python3" }, { "code": "import numpy as npimport osimport cv2import matplotlib.pyplot as plt # defining the canny detector function # here weak_th and strong_th are thresholds for# double thresholding stepdef Canny_detector(img, weak_th = None, strong_th = None): # conversion of image to grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Noise reduction step img = cv2.GaussianBlur(img, (5, 5), 1.4) # Calculating the gradients gx = cv2.Sobel(np.float32(img), cv2.CV_64F, 1, 0, 3) gy = cv2.Sobel(np.float32(img), cv2.CV_64F, 0, 1, 3) # Conversion of Cartesian coordinates to polar mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees = True) # setting the minimum and maximum thresholds # for double thresholding mag_max = np.max(mag) if not weak_th:weak_th = mag_max * 0.1 if not strong_th:strong_th = mag_max * 0.5 # getting the dimensions of the input image height, width = img.shape # Looping through every pixel of the grayscale # image for i_x in range(width): for i_y in range(height): grad_ang = ang[i_y, i_x] grad_ang = abs(grad_ang-180) if abs(grad_ang)>180 else abs(grad_ang) # selecting the neighbours of the target pixel # according to the gradient direction # In the x axis direction if grad_ang<= 22.5: neighb_1_x, neighb_1_y = i_x-1, i_y neighb_2_x, neighb_2_y = i_x + 1, i_y # top right (diagonal-1) direction elif grad_ang>22.5 and grad_ang<=(22.5 + 45): neighb_1_x, neighb_1_y = i_x-1, i_y-1 neighb_2_x, neighb_2_y = i_x + 1, i_y + 1 # In y-axis direction elif grad_ang>(22.5 + 45) and grad_ang<=(22.5 + 90): neighb_1_x, neighb_1_y = i_x, i_y-1 neighb_2_x, neighb_2_y = i_x, i_y + 1 # top left (diagonal-2) direction elif grad_ang>(22.5 + 90) and grad_ang<=(22.5 + 135): neighb_1_x, neighb_1_y = i_x-1, i_y + 1 neighb_2_x, neighb_2_y = i_x + 1, i_y-1 # Now it restarts the cycle elif grad_ang>(22.5 + 135) and grad_ang<=(22.5 + 180): neighb_1_x, neighb_1_y = i_x-1, i_y neighb_2_x, neighb_2_y = i_x + 1, i_y # Non-maximum suppression step if width>neighb_1_x>= 0 and height>neighb_1_y>= 0: if mag[i_y, i_x]<mag[neighb_1_y, neighb_1_x]: mag[i_y, i_x]= 0 continue if width>neighb_2_x>= 0 and height>neighb_2_y>= 0: if mag[i_y, i_x]<mag[neighb_2_y, neighb_2_x]: mag[i_y, i_x]= 0 weak_ids = np.zeros_like(img) strong_ids = np.zeros_like(img) ids = np.zeros_like(img) # double thresholding step for i_x in range(width): for i_y in range(height): grad_mag = mag[i_y, i_x] if grad_mag<weak_th: mag[i_y, i_x]= 0 elif strong_th>grad_mag>= weak_th: ids[i_y, i_x]= 1 else: ids[i_y, i_x]= 2 # finally returning the magnitude of # gradients of edges return mag frame = cv2.imread('food.jpeg') # calling the designed function for# finding edgescanny_img = Canny_detector(frame) # Displaying the input and output image plt.figure()f, plots = plt.subplots(2, 1) plots[0].imshow(frame)plots[1].imshow(canny_img)", "e": 31537, "s": 27902, "text": null }, { "code": null, "e": 31549, "s": 31537, "text": "Input image" }, { "code": null, "e": 31562, "s": 31549, "text": "Output image" }, { "code": null, "e": 31577, "s": 31562, "text": "adnanirshad158" }, { "code": null, "e": 31591, "s": 31577, "text": "Python-OpenCV" }, { "code": null, "e": 31598, "s": 31591, "text": "Python" }, { "code": null, "e": 31696, "s": 31598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31714, "s": 31696, "text": "Python Dictionary" }, { "code": null, "e": 31736, "s": 31714, "text": "Enumerate() in Python" }, { "code": null, "e": 31768, "s": 31736, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31798, "s": 31768, "text": "Iterate over a list in Python" }, { "code": null, "e": 31840, "s": 31798, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31866, "s": 31840, "text": "Python String | replace()" }, { "code": null, "e": 31903, "s": 31866, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 31947, "s": 31903, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 31972, "s": 31947, "text": "sum() function in Python" } ]
MySQL search if more than one string contains special characters?
To search if strings contain special characters, you can use REGEXP. Following is the syntax − select * from yourTableName where yourColumnName REGEXP '[^a-zA-Z0-9]'; Let us first create a table − mysql> create table specialCharactersDemo -> ( -> StudentId varchar(100) -> ); Query OK, 0 rows affected (0.58 sec) Insert records in the table using insert command. Following is the query − mysql> insert into specialCharactersDemo values('STU_1234'); Query OK, 1 row affected (0.15 sec) mysql> insert into specialCharactersDemo values('STU567'); Query OK, 1 row affected (0.14 sec) mysql> insert into specialCharactersDemo values('STU#1234'); Query OK, 1 row affected (0.13 sec) mysql> insert into specialCharactersDemo values('STU897$'); Query OK, 1 row affected (0.18 sec) mysql> insert into specialCharactersDemo values('STU999'); Query OK, 1 row affected (0.43 sec) mysql> insert into specialCharactersDemo values('STU1010'); Query OK, 1 row affected (0.14 sec Following is the query to display all records from the table using select statement − mysql> select *from specialCharactersDemo; This will produce the following output − +-----------+ | StudentId | +-----------+ | STU_1234 | | STU567 | | STU#1234 | | STU897$ | | STU999 | | STU1010 | +-----------+ 6 rows in set (0.00 sec) Here is the query to search if a string contains special characters − mysql> select *from specialCharactersDemo -> where StudentId REGEXP '[^a-zA-Z0-9]'; This will produce the following output − +-----------+ | StudentId | +-----------+ | STU_1234 | | STU#1234 | | STU897$ | +-----------+ 3 rows in set (0.02 sec) You can use another syntax for the above result. Following is the query − mysql> select *from specialCharactersDemo -> where StudentId REGEXP'[^[:alnum:]]'; This will produce the following output − +-----------+ | StudentId | +-----------+ | STU_1234 | | STU#1234 | | STU897$ | +-----------+ 3 rows in set (0.05 sec)
[ { "code": null, "e": 1157, "s": 1062, "text": "To search if strings contain special characters, you can use REGEXP. Following is the syntax −" }, { "code": null, "e": 1229, "s": 1157, "text": "select * from yourTableName\nwhere yourColumnName REGEXP '[^a-zA-Z0-9]';" }, { "code": null, "e": 1259, "s": 1229, "text": "Let us first create a table −" }, { "code": null, "e": 1384, "s": 1259, "text": "mysql> create table specialCharactersDemo\n -> (\n -> StudentId varchar(100)\n -> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1459, "s": 1384, "text": "Insert records in the table using insert command. Following is the query −" }, { "code": null, "e": 2034, "s": 1459, "text": "mysql> insert into specialCharactersDemo values('STU_1234');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into specialCharactersDemo values('STU567');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into specialCharactersDemo values('STU#1234');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into specialCharactersDemo values('STU897$');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into specialCharactersDemo values('STU999');\nQuery OK, 1 row affected (0.43 sec)\nmysql> insert into specialCharactersDemo values('STU1010');\nQuery OK, 1 row affected (0.14 sec" }, { "code": null, "e": 2120, "s": 2034, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 2163, "s": 2120, "text": "mysql> select *from specialCharactersDemo;" }, { "code": null, "e": 2204, "s": 2163, "text": "This will produce the following output −" }, { "code": null, "e": 2369, "s": 2204, "text": "+-----------+\n| StudentId |\n+-----------+\n| STU_1234 |\n| STU567 |\n| STU#1234 |\n| STU897$ |\n| STU999 |\n| STU1010 |\n+-----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2439, "s": 2369, "text": "Here is the query to search if a string contains special characters −" }, { "code": null, "e": 2526, "s": 2439, "text": "mysql> select *from specialCharactersDemo\n -> where StudentId REGEXP '[^a-zA-Z0-9]';" }, { "code": null, "e": 2567, "s": 2526, "text": "This will produce the following output −" }, { "code": null, "e": 2690, "s": 2567, "text": "+-----------+\n| StudentId |\n+-----------+\n| STU_1234 |\n| STU#1234 |\n| STU897$ |\n+-----------+\n3 rows in set (0.02 sec)" }, { "code": null, "e": 2764, "s": 2690, "text": "You can use another syntax for the above result. Following is the query −" }, { "code": null, "e": 2850, "s": 2764, "text": "mysql> select *from specialCharactersDemo\n -> where StudentId REGEXP'[^[:alnum:]]';" }, { "code": null, "e": 2891, "s": 2850, "text": "This will produce the following output −" }, { "code": null, "e": 3014, "s": 2891, "text": "+-----------+\n| StudentId |\n+-----------+\n| STU_1234 |\n| STU#1234 |\n| STU897$ |\n+-----------+\n3 rows in set (0.05 sec)" } ]
finally keyword in Python - GeeksforGeeks
29 Apr, 2019 Prerequisites: Exception Handling, try and except in Python In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on.So, in order to handle these situations, Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Syntax: try: # Some Code.... except: # optional block # Handling of exception (if required) finally: # Some code .....(always executed) Important Points – finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block. finally block is used to deallocate the system resources. One can use finally just after try without using except block, but no exception is handled in that case. Example #1: # Python program to demonstrate finally # No exception Exception raised in try blocktry: k = 5//0 # raises divide by zero exception. print(k) # handles zerodivision exception except ZeroDivisionError: print("Can't divide by zero") finally: # this block is always executed # regardless of exception generation. print('This is always executed') Output: Can't divide by zero This is always executed Example #2: # Python program to demonstrate finally try: k = 5//1 # No exception raised print(k) # intends to handle zerodivision exception except ZeroDivisionError: print("Can't divide by zero") finally: # this block is always executed # regardless of exception generation. print('This is always executed') Output: 5 This is always executed Example #3: # Python program to demonstrate finally # Exception is not handledtry: k = 5//0 # exception raised print(k) finally: # this block is always executed # regardless of exception generation. print('This is always executed') Output: This is always executed Runtime Error – Unhandled Exception k=5//0 #No exception raised ZeroDivisionError: integer division or modulo by zero Explanation:In above code, the exception is generated integer division or modulo by zero, which was not handled. The exception was re-raised after execution of finally block. This shows that finally block is executed regardless of exception is handled or not. Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24313, "s": 24285, "text": "\n29 Apr, 2019" }, { "code": null, "e": 24373, "s": 24313, "text": "Prerequisites: Exception Handling, try and except in Python" }, { "code": null, "e": 24856, "s": 24373, "text": "In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on.So, in order to handle these situations, Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception." }, { "code": null, "e": 24864, "s": 24856, "text": "Syntax:" }, { "code": null, "e": 25030, "s": 24864, "text": "try:\n # Some Code.... \n\nexcept:\n # optional block\n # Handling of exception (if required)\n\nfinally:\n # Some code .....(always executed) \n\n" }, { "code": null, "e": 25049, "s": 25030, "text": "Important Points –" }, { "code": null, "e": 25224, "s": 25049, "text": "finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block." }, { "code": null, "e": 25282, "s": 25224, "text": "finally block is used to deallocate the system resources." }, { "code": null, "e": 25387, "s": 25282, "text": "One can use finally just after try without using except block, but no exception is handled in that case." }, { "code": null, "e": 25399, "s": 25387, "text": "Example #1:" }, { "code": "# Python program to demonstrate finally # No exception Exception raised in try blocktry: k = 5//0 # raises divide by zero exception. print(k) # handles zerodivision exception except ZeroDivisionError: print(\"Can't divide by zero\") finally: # this block is always executed # regardless of exception generation. print('This is always executed') ", "e": 25775, "s": 25399, "text": null }, { "code": null, "e": 25783, "s": 25775, "text": "Output:" }, { "code": null, "e": 25828, "s": 25783, "text": "Can't divide by zero\nThis is always executed" }, { "code": null, "e": 25841, "s": 25828, "text": " Example #2:" }, { "code": "# Python program to demonstrate finally try: k = 5//1 # No exception raised print(k) # intends to handle zerodivision exception except ZeroDivisionError: print(\"Can't divide by zero\") finally: # this block is always executed # regardless of exception generation. print('This is always executed') ", "e": 26170, "s": 25841, "text": null }, { "code": null, "e": 26178, "s": 26170, "text": "Output:" }, { "code": null, "e": 26205, "s": 26178, "text": "5\nThis is always executed\n" }, { "code": null, "e": 26218, "s": 26205, "text": " Example #3:" }, { "code": "# Python program to demonstrate finally # Exception is not handledtry: k = 5//0 # exception raised print(k) finally: # this block is always executed # regardless of exception generation. print('This is always executed') ", "e": 26461, "s": 26218, "text": null }, { "code": null, "e": 26469, "s": 26461, "text": "Output:" }, { "code": null, "e": 26494, "s": 26469, "text": "This is always executed\n" }, { "code": null, "e": 26510, "s": 26494, "text": "Runtime Error –" }, { "code": null, "e": 26617, "s": 26510, "text": "Unhandled Exception \n k=5//0 #No exception raised\nZeroDivisionError: integer division or modulo by zero" }, { "code": null, "e": 26877, "s": 26617, "text": "Explanation:In above code, the exception is generated integer division or modulo by zero, which was not handled. The exception was re-raised after execution of finally block. This shows that finally block is executed regardless of exception is handled or not." }, { "code": null, "e": 26895, "s": 26877, "text": "Python-exceptions" }, { "code": null, "e": 26902, "s": 26895, "text": "Python" }, { "code": null, "e": 27000, "s": 26902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27018, "s": 27000, "text": "Python Dictionary" }, { "code": null, "e": 27040, "s": 27018, "text": "Enumerate() in Python" }, { "code": null, "e": 27072, "s": 27040, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27102, "s": 27072, "text": "Iterate over a list in Python" }, { "code": null, "e": 27144, "s": 27102, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27170, "s": 27144, "text": "Python String | replace()" }, { "code": null, "e": 27207, "s": 27170, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27250, "s": 27207, "text": "Python program to convert a list to string" }, { "code": null, "e": 27275, "s": 27250, "text": "sum() function in Python" } ]
String Similarity Matching for Big Data using Distributed Cloud Computations | by Georgios Ntanakas | Towards Data Science
Our story — like most stories — starts with an ambitious undertaking! We are offered two large data-sets (coming from two tables in BigQuery). One consists of all the app names from the Google Play and iOS App Stores — about 14 million entries— which we shall call the “clean” app names. The other contains about 5K “dirty” app names. Dirtiness refers to missing words, misspelling of certain words, additional words referring to the OS or other info etc. Examples can be found by looking at the section “Putting everything together and running it”. Along with the data-sets we are offered a blue and a red pill. We think we are brave enough, decide to take the red pill, accept the challenge and seek the brutal truth. The request is to match entries from the “dirty” data-set to entries in the “clean” one and then store the results as a lookup table. Before becoming a man and facing t̶h̶e̶ ̶r̶e̶a̶l̶ ̶w̶o̶r̶l̶d̶ production, a boy needs to develop his skills in the playground. A fancy one is Google Colaboratory, a Jupyter notebook hosted on the cloud, offering free, powerful computing resources (including GPUs/TPUs) and that’s where the first tests were run. A computer scientist would classify our problem as an approximate string matching problem. Traditional solutions to these problems use different string metrics to come up with a distance between two given sequences of characters. Examples are the Jaro–Winkler distance and the Levenshtein distance. Our first attempt was to employ fuzzy wuzzy, a Python library that implements the Levenshtein distance. (Please take the rough numbers that follow — rather than an appropriate bench-marking — with a pinch of salt. The final differences are so significant that perfect precision is of little importance.) Fuzzy wuzzy needed about 15 min to compute the distance between a single entry from the “dirty” data-set and all the entries from the “clean” data-set. Repeating the process 5K times translates to about 52 days, which is slightly more than we would like for a process that runs at least once daily. If time is money, we would be broke by now! To avoid crippling loans and bankruptcy, a slightly different approach was employed: increasing performance through the power of numbers. The string data-sets are transformed into vectors based on tf–idf in order to use the cosine similarity. The core of the algorithm has been used before for similar problems here, here and here. A few modifications are introduced in this article to enable running the computations distributed on a cloud Dask client in order to further improve performance. Why Dask?/What is Dask? Dask is a library that provides ways to scale Pandas, Scikit-Learn, and Numpy workflows natively, with minimal rewriting. Thus, ordinary Python operations can be distributed/parallelized between different nodes/CPU cores. It also can (but doesn’t have to) run on a distributed cluster. I.e., Dask is doing nothing more than providing the infrastructure to split data, such as a Pandas DataFrame, into different nodes and then perform operations using multiple cores and ensuring communication between the split data. Note: Below the clean and dirty name conventions are used for the baseline and the to-be-matched data-set respectively. Here is a list of the basic libraries that were used for this project: To get data from BigQuery, we are using the BigQuery Client Library for Python. The data is loaded into a Pandas DataFrame by the client, which is immediately transformed into a Dask DataFrame. The Dask DataFrame is nothing more than a composition of Pandas DataFrames distributed over a number of partitions (npartitions), depending on the CPU architecture. Transforming the DataFrames from strings to vectors using tf-idf needs literally 3 lines of code: The vectorizing function is initialized using the TfidfVectorizer function from Scikit-Learn and by defining the analyzer function (see info below). The clean DataFrame is used to define the feature vector (based on the analyzer) and compute the clean tf-idf matrix at the same time (fit_transform) and then the dirty tf-idf matrix is computed (transform). The analyzer is the function that is used to split each app name (string) into smaller bits. Gathering all these smaller bits from all entries of the clean DataFrame defines the feature vector. If a specific app name contains this bit, then when transforming into a vector it will get a float value at the corresponding position — if not a 0. The float value depends on the number of times this bit appears within the app name and the value is modified so that the vector for this app name is normalized (vector norm equal to 1 unit). To give an example: If the analyzer is defined as below and the clean DataFrame is simply the following, then the feature vector has this form: ['ACE', 'AGR', 'BOO', 'CEB', 'EBO', 'FAC', 'GRA', 'INS', 'NST', 'OOK', 'RAM', 'STA', 'TAG'] and the clean DataFrame is transformed to the following vector matrix (the output matrix is given in sparse matrix (CSR) format but displayed as an array here) [[0.40824829 0. 0.40824829 0.40824829 0.40824829 0.40824829 0. 0. 0. 0.40824829 0. 0. 0. ] [0. 0.37796447 0. 0. 0. 0. 0.37796447 0.37796447 0.37796447 0. 0.37796447 0.37796447 0.37796447]] As soon as clean and dirty data-sets are in vector mode, we can proceed with getting the cosine similarity scores matrix. Performing the dot product between the clean and dirty vectorized matrices is enough to give us the cosine since the vectors are normalized. I.e., the dot product coincides with the cosine (similarity). To do so, the following code is used: Here, the sparse_dot_topn package is used, which provides a fast way to perform a sparse matrix multiplication followed by top-n multiplication result selection using Cython. The cosine similarities will be given in a sparse matrix form with rows corresponding to the dirty data-set and columns to the clean one. Using this similarity matrix, we can extract the entries matched between clean and dirty and their similarity score using: Last but not least, we need to upload the result of our matching process back to BiqQuery as a lookup table. The code to do so looks like this: Would you prefer a picture rather than a thousand words of the algorithm? Here is a simplified diagram of it: Section written by Gaiar Baimuratov Dask is such a versatile tool that can benefit you even by running it locally using its drop-in Pandas API support. However, it shows it’s full power when it runs on a distributed system — aka cluster. In collaboration with the DevOps engineers, we got access to a managed Kubernetes (k8s) cluster deployed on Google Cloud Platform (GCP). In most cases, after getting access to the cluster, Dask can easily be deployed on k8s using the helm package manager by running the command: helm install —name my-dask stable/dask After a while, you’ll get 5 pods deployed: the scheduler — main Dask task manager 3 workers — to process data and apply operations the Jupyter pod —a pre-setup Jupiter Lab pod as a nice way to interact with Dask To get the list of the pods, once deployed, we’ve created a simple shell script. Run it and it will show the list of IP addresses for all freshly created pods: In case you don’t need it anymore or you broke something and want a fresh start you can run: helm delete dask —purge Does it look too easy to be true? You’re right; universal solutions rarely work. Here comes a bit of customization to make it work for our needs. After the initial test, we’ve discovered a couple of issues when using Dask helm as-is. It had several bugs. Luckily all fixes existed as pending pull requests (PRs) in the official repo but were not merged.Default images were missing for some of the packages we needed.One package didn’t have a binary version in pip and was failing at pip install ... part.Default pod configuration wasn’t beefy enough to process our large DataFrames. It had several bugs. Luckily all fixes existed as pending pull requests (PRs) in the official repo but were not merged. Default images were missing for some of the packages we needed. One package didn’t have a binary version in pip and was failing at pip install ... part. Default pod configuration wasn’t beefy enough to process our large DataFrames. Moving on to the solutions: 1. Bugs in helm configurationFortunately, the bugs were fixed already in the official repo via pending PRs. To apply them, we had to make a local clone of the repo and merge all the PRs with the solutions as patches. That is certainly not the ideal solution but it is a quick way to make it work.Another problem was that the Jupyter Lab version defined in the repo had some UI troubles. To overcome them, it had to be upgraded by specifying the package version. The way to do it is included in the solution of the 2nd issue. 2. Missing packagesAs our data pipeline is based on GCP, we needed to include the SDK packages and some other libraries. Fortunately, Dask helm chart supports the usage of a YAML config file. Thus, it can be specified which pip or conda packages to be included, how much RAM to allocate to workers and much more than that.In our case, we’ve added the following: Most of the packages will be installed via conda using the channels conda-forge and gaiar(see below why this channel is needed too). The rest is installed via pip. 3. Missing binary package versionFor speeding up the sparse matrix multiplication, we are using sparse_dot_topn, as mentioned in the algorithm section, which relies on Cython. Packages like this are usually supplied in two ways: either as binary, pre-compiled packages or when library compiles some of it is parts on installation host. In our case, we were missing the binary distribution and this meant that we should add compilation tools in our already “not-so-light” image. Instead, we chose another way. I’ve already had experience in building and maintaining conda packages in my own channel. A significant advantage of conda is that it ships packages in a binary way and that’s exactly what we needed.Defining the YAML file with conda recipe based on the pip distribution is relatively easy: With that recipe, you run the conda build command and upload the package to the channel you have access to. Then, the package can be installed with conda -c CHANNEL_NAME PACKAGE_NAME or in our case conda -c gaiar sparse_dot_topn. I prepared two versions of it — one for Linux and another for MacOS (as it also had some troubles with the installation). 4. Limited resources for podsThis part is case specific and depends on what kind of tasks Dask is running and which are the constraints. In our case, we needed more RAM and wanted to define also the upper limit that every pod can consume. This is done again via a config YAML file: This translates to: the lower limit for every worker is 3G, but it can request up to 6G if it needs to. Here is a simple demo of Dask working on k8s on GCP: Combining the algorithm and the deployment mentioned above, our code performs the matching process in about 20–30 mins; quite a significant speed up compared to the original 52 days. 😆 Here is a small part from the output table of one of our runs: This table and the execution time needed to obtain it is an indication that the red pill might have been the wiser decision this time. Let’s try to give it in one sentence: Tf-idf vectorization and cosine similarity combined with efficient sparse matrix computations and parallel execution of operations using the distribution capabilities of Dask, deployed in Kubernetes proved to be a very efficient approach for handling string similarity problems of large scale. Special thanks to Gaiar Baimuratov for making the deployment happen and writing the corresponding section.
[ { "code": null, "e": 721, "s": 171, "text": "Our story — like most stories — starts with an ambitious undertaking! We are offered two large data-sets (coming from two tables in BigQuery). One consists of all the app names from the Google Play and iOS App Stores — about 14 million entries— which we shall call the “clean” app names. The other contains about 5K “dirty” app names. Dirtiness refers to missing words, misspelling of certain words, additional words referring to the OS or other info etc. Examples can be found by looking at the section “Putting everything together and running it”." }, { "code": null, "e": 891, "s": 721, "text": "Along with the data-sets we are offered a blue and a red pill. We think we are brave enough, decide to take the red pill, accept the challenge and seek the brutal truth." }, { "code": null, "e": 1025, "s": 891, "text": "The request is to match entries from the “dirty” data-set to entries in the “clean” one and then store the results as a lookup table." }, { "code": null, "e": 1337, "s": 1025, "text": "Before becoming a man and facing t̶h̶e̶ ̶r̶e̶a̶l̶ ̶w̶o̶r̶l̶d̶ production, a boy needs to develop his skills in the playground. A fancy one is Google Colaboratory, a Jupyter notebook hosted on the cloud, offering free, powerful computing resources (including GPUs/TPUs) and that’s where the first tests were run." }, { "code": null, "e": 1636, "s": 1337, "text": "A computer scientist would classify our problem as an approximate string matching problem. Traditional solutions to these problems use different string metrics to come up with a distance between two given sequences of characters. Examples are the Jaro–Winkler distance and the Levenshtein distance." }, { "code": null, "e": 2283, "s": 1636, "text": "Our first attempt was to employ fuzzy wuzzy, a Python library that implements the Levenshtein distance. (Please take the rough numbers that follow — rather than an appropriate bench-marking — with a pinch of salt. The final differences are so significant that perfect precision is of little importance.) Fuzzy wuzzy needed about 15 min to compute the distance between a single entry from the “dirty” data-set and all the entries from the “clean” data-set. Repeating the process 5K times translates to about 52 days, which is slightly more than we would like for a process that runs at least once daily. If time is money, we would be broke by now!" }, { "code": null, "e": 2777, "s": 2283, "text": "To avoid crippling loans and bankruptcy, a slightly different approach was employed: increasing performance through the power of numbers. The string data-sets are transformed into vectors based on tf–idf in order to use the cosine similarity. The core of the algorithm has been used before for similar problems here, here and here. A few modifications are introduced in this article to enable running the computations distributed on a cloud Dask client in order to further improve performance." }, { "code": null, "e": 2801, "s": 2777, "text": "Why Dask?/What is Dask?" }, { "code": null, "e": 3318, "s": 2801, "text": "Dask is a library that provides ways to scale Pandas, Scikit-Learn, and Numpy workflows natively, with minimal rewriting. Thus, ordinary Python operations can be distributed/parallelized between different nodes/CPU cores. It also can (but doesn’t have to) run on a distributed cluster. I.e., Dask is doing nothing more than providing the infrastructure to split data, such as a Pandas DataFrame, into different nodes and then perform operations using multiple cores and ensuring communication between the split data." }, { "code": null, "e": 3438, "s": 3318, "text": "Note: Below the clean and dirty name conventions are used for the baseline and the to-be-matched data-set respectively." }, { "code": null, "e": 3509, "s": 3438, "text": "Here is a list of the basic libraries that were used for this project:" }, { "code": null, "e": 3868, "s": 3509, "text": "To get data from BigQuery, we are using the BigQuery Client Library for Python. The data is loaded into a Pandas DataFrame by the client, which is immediately transformed into a Dask DataFrame. The Dask DataFrame is nothing more than a composition of Pandas DataFrames distributed over a number of partitions (npartitions), depending on the CPU architecture." }, { "code": null, "e": 3966, "s": 3868, "text": "Transforming the DataFrames from strings to vectors using tf-idf needs literally 3 lines of code:" }, { "code": null, "e": 4323, "s": 3966, "text": "The vectorizing function is initialized using the TfidfVectorizer function from Scikit-Learn and by defining the analyzer function (see info below). The clean DataFrame is used to define the feature vector (based on the analyzer) and compute the clean tf-idf matrix at the same time (fit_transform) and then the dirty tf-idf matrix is computed (transform)." }, { "code": null, "e": 4914, "s": 4323, "text": "The analyzer is the function that is used to split each app name (string) into smaller bits. Gathering all these smaller bits from all entries of the clean DataFrame defines the feature vector. If a specific app name contains this bit, then when transforming into a vector it will get a float value at the corresponding position — if not a 0. The float value depends on the number of times this bit appears within the app name and the value is modified so that the vector for this app name is normalized (vector norm equal to 1 unit). To give an example: If the analyzer is defined as below" }, { "code": null, "e": 4963, "s": 4914, "text": "and the clean DataFrame is simply the following," }, { "code": null, "e": 5002, "s": 4963, "text": "then the feature vector has this form:" }, { "code": null, "e": 5094, "s": 5002, "text": "['ACE', 'AGR', 'BOO', 'CEB', 'EBO', 'FAC', 'GRA', 'INS', 'NST', 'OOK', 'RAM', 'STA', 'TAG']" }, { "code": null, "e": 5254, "s": 5094, "text": "and the clean DataFrame is transformed to the following vector matrix (the output matrix is given in sparse matrix (CSR) format but displayed as an array here)" }, { "code": null, "e": 5534, "s": 5254, "text": "[[0.40824829 0. 0.40824829 0.40824829 0.40824829 0.40824829 0. 0. 0. 0.40824829 0. 0. 0. ] [0. 0.37796447 0. 0. 0. 0. 0.37796447 0.37796447 0.37796447 0. 0.37796447 0.37796447 0.37796447]]" }, { "code": null, "e": 5859, "s": 5534, "text": "As soon as clean and dirty data-sets are in vector mode, we can proceed with getting the cosine similarity scores matrix. Performing the dot product between the clean and dirty vectorized matrices is enough to give us the cosine since the vectors are normalized. I.e., the dot product coincides with the cosine (similarity)." }, { "code": null, "e": 5897, "s": 5859, "text": "To do so, the following code is used:" }, { "code": null, "e": 6210, "s": 5897, "text": "Here, the sparse_dot_topn package is used, which provides a fast way to perform a sparse matrix multiplication followed by top-n multiplication result selection using Cython. The cosine similarities will be given in a sparse matrix form with rows corresponding to the dirty data-set and columns to the clean one." }, { "code": null, "e": 6333, "s": 6210, "text": "Using this similarity matrix, we can extract the entries matched between clean and dirty and their similarity score using:" }, { "code": null, "e": 6477, "s": 6333, "text": "Last but not least, we need to upload the result of our matching process back to BiqQuery as a lookup table. The code to do so looks like this:" }, { "code": null, "e": 6587, "s": 6477, "text": "Would you prefer a picture rather than a thousand words of the algorithm? Here is a simplified diagram of it:" }, { "code": null, "e": 6623, "s": 6587, "text": "Section written by Gaiar Baimuratov" }, { "code": null, "e": 7104, "s": 6623, "text": "Dask is such a versatile tool that can benefit you even by running it locally using its drop-in Pandas API support. However, it shows it’s full power when it runs on a distributed system — aka cluster. In collaboration with the DevOps engineers, we got access to a managed Kubernetes (k8s) cluster deployed on Google Cloud Platform (GCP). In most cases, after getting access to the cluster, Dask can easily be deployed on k8s using the helm package manager by running the command:" }, { "code": null, "e": 7143, "s": 7104, "text": "helm install —name my-dask stable/dask" }, { "code": null, "e": 7186, "s": 7143, "text": "After a while, you’ll get 5 pods deployed:" }, { "code": null, "e": 7225, "s": 7186, "text": "the scheduler — main Dask task manager" }, { "code": null, "e": 7274, "s": 7225, "text": "3 workers — to process data and apply operations" }, { "code": null, "e": 7355, "s": 7274, "text": "the Jupyter pod —a pre-setup Jupiter Lab pod as a nice way to interact with Dask" }, { "code": null, "e": 7515, "s": 7355, "text": "To get the list of the pods, once deployed, we’ve created a simple shell script. Run it and it will show the list of IP addresses for all freshly created pods:" }, { "code": null, "e": 7608, "s": 7515, "text": "In case you don’t need it anymore or you broke something and want a fresh start you can run:" }, { "code": null, "e": 7632, "s": 7608, "text": "helm delete dask —purge" }, { "code": null, "e": 7713, "s": 7632, "text": "Does it look too easy to be true? You’re right; universal solutions rarely work." }, { "code": null, "e": 7778, "s": 7713, "text": "Here comes a bit of customization to make it work for our needs." }, { "code": null, "e": 7866, "s": 7778, "text": "After the initial test, we’ve discovered a couple of issues when using Dask helm as-is." }, { "code": null, "e": 8215, "s": 7866, "text": "It had several bugs. Luckily all fixes existed as pending pull requests (PRs) in the official repo but were not merged.Default images were missing for some of the packages we needed.One package didn’t have a binary version in pip and was failing at pip install ... part.Default pod configuration wasn’t beefy enough to process our large DataFrames." }, { "code": null, "e": 8335, "s": 8215, "text": "It had several bugs. Luckily all fixes existed as pending pull requests (PRs) in the official repo but were not merged." }, { "code": null, "e": 8399, "s": 8335, "text": "Default images were missing for some of the packages we needed." }, { "code": null, "e": 8488, "s": 8399, "text": "One package didn’t have a binary version in pip and was failing at pip install ... part." }, { "code": null, "e": 8567, "s": 8488, "text": "Default pod configuration wasn’t beefy enough to process our large DataFrames." }, { "code": null, "e": 8595, "s": 8567, "text": "Moving on to the solutions:" }, { "code": null, "e": 9120, "s": 8595, "text": "1. Bugs in helm configurationFortunately, the bugs were fixed already in the official repo via pending PRs. To apply them, we had to make a local clone of the repo and merge all the PRs with the solutions as patches. That is certainly not the ideal solution but it is a quick way to make it work.Another problem was that the Jupyter Lab version defined in the repo had some UI troubles. To overcome them, it had to be upgraded by specifying the package version. The way to do it is included in the solution of the 2nd issue." }, { "code": null, "e": 9482, "s": 9120, "text": "2. Missing packagesAs our data pipeline is based on GCP, we needed to include the SDK packages and some other libraries. Fortunately, Dask helm chart supports the usage of a YAML config file. Thus, it can be specified which pip or conda packages to be included, how much RAM to allocate to workers and much more than that.In our case, we’ve added the following:" }, { "code": null, "e": 9646, "s": 9482, "text": "Most of the packages will be installed via conda using the channels conda-forge and gaiar(see below why this channel is needed too). The rest is installed via pip." }, { "code": null, "e": 10445, "s": 9646, "text": "3. Missing binary package versionFor speeding up the sparse matrix multiplication, we are using sparse_dot_topn, as mentioned in the algorithm section, which relies on Cython. Packages like this are usually supplied in two ways: either as binary, pre-compiled packages or when library compiles some of it is parts on installation host. In our case, we were missing the binary distribution and this meant that we should add compilation tools in our already “not-so-light” image. Instead, we chose another way. I’ve already had experience in building and maintaining conda packages in my own channel. A significant advantage of conda is that it ships packages in a binary way and that’s exactly what we needed.Defining the YAML file with conda recipe based on the pip distribution is relatively easy:" }, { "code": null, "e": 10797, "s": 10445, "text": "With that recipe, you run the conda build command and upload the package to the channel you have access to. Then, the package can be installed with conda -c CHANNEL_NAME PACKAGE_NAME or in our case conda -c gaiar sparse_dot_topn. I prepared two versions of it — one for Linux and another for MacOS (as it also had some troubles with the installation)." }, { "code": null, "e": 11079, "s": 10797, "text": "4. Limited resources for podsThis part is case specific and depends on what kind of tasks Dask is running and which are the constraints. In our case, we needed more RAM and wanted to define also the upper limit that every pod can consume. This is done again via a config YAML file:" }, { "code": null, "e": 11183, "s": 11079, "text": "This translates to: the lower limit for every worker is 3G, but it can request up to 6G if it needs to." }, { "code": null, "e": 11236, "s": 11183, "text": "Here is a simple demo of Dask working on k8s on GCP:" }, { "code": null, "e": 11421, "s": 11236, "text": "Combining the algorithm and the deployment mentioned above, our code performs the matching process in about 20–30 mins; quite a significant speed up compared to the original 52 days. 😆" }, { "code": null, "e": 11484, "s": 11421, "text": "Here is a small part from the output table of one of our runs:" }, { "code": null, "e": 11619, "s": 11484, "text": "This table and the execution time needed to obtain it is an indication that the red pill might have been the wiser decision this time." }, { "code": null, "e": 11951, "s": 11619, "text": "Let’s try to give it in one sentence: Tf-idf vectorization and cosine similarity combined with efficient sparse matrix computations and parallel execution of operations using the distribution capabilities of Dask, deployed in Kubernetes proved to be a very efficient approach for handling string similarity problems of large scale." } ]
Getting an HTML H1 value to JavaScript variable?
To get the value of H1 to JavaScript variable, you can use − document.getElementById().innerHTML. Let’s say the following is our H1 heading − <h1 id="demo"> This is the demo program of JavaScript ........</h1> Now, let’s get the H1 value using the below code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <h1 id="demo"> This is the demo program of JavaScript ........</h1> <script> var data=document.getElementById('demo').innerHTML; console.log("The data is="+data); </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output −
[ { "code": null, "e": 1123, "s": 1062, "text": "To get the value of H1 to JavaScript variable, you can use −" }, { "code": null, "e": 1160, "s": 1123, "text": "document.getElementById().innerHTML." }, { "code": null, "e": 1204, "s": 1160, "text": "Let’s say the following is our H1 heading −" }, { "code": null, "e": 1272, "s": 1204, "text": "<h1 id=\"demo\"> This is the demo program of JavaScript ........</h1>" }, { "code": null, "e": 1323, "s": 1272, "text": "Now, let’s get the H1 value using the below code −" }, { "code": null, "e": 1334, "s": 1323, "text": " Live Demo" }, { "code": null, "e": 1921, "s": 1334, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\"href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<h1 id=\"demo\"> This is the demo program of JavaScript ........</h1>\n<script>\n var data=document.getElementById('demo').innerHTML;\n console.log(\"The data is=\"+data);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2083, "s": 1921, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2124, "s": 2083, "text": "This will produce the following output −" } ]
What is the difference between $ErrorActionPreference and $ErrorAction cmdlet in PowerShell ?
As we know $ErrorActionPreference and $ErrorAction both have the same functionality and both are used to handle terminating errors by converting Non-Terminating errors to Terminating errors. But when both the variables are used, we need to know which takes precedence. $ErrorActionPreference variable is used at the start of the script while the $erroraction variable is a common parameter and used with the cmdlet. In some cases, we might need the script to be terminated as soon as an error occurs but inside the script, we have some cmdlets which need to be ignored or continued if the error occurs. In that situation, we -ErrorAction is important and it takes precedence. $ErrorActionPreference = "Stop" try{ Get-Service -Name ABC Get-Process powershell Get-Process chromesds Get-Service Spooler } catch{ $_.Exception.Message } Cannot find any service with service name 'ABC'. In the above example, the script is terminated because the ABC service name doesn’t exist and because of it, the next commands can’t execute as the $ErrorActionPreference value is set to Stop. Once we add the -ErrorAction in the Get-Service command, it will take the precedence. $ErrorActionPreference = "Stop" try{ Get-Service -Name ABC -ErrorAction Continue Get-Process powershell Get-Process chromesds Get-Service Spooler } catch{ $_.Exception.Message } Line | 4 | Get-Service -Name ABC -ErrorAction Continue | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Cannot find any service with service name 'ABC'. NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 43 234.39 11.33 49.17 7668 1 powershell Cannot find a process with the name "chromesds". Verify the process name and call the cmdlet again. Once we add the -ErrorAction parameter with Continue value, execution moves to the next command as shown in the above output and stops when it can’t find process name “Chromesds” and can’t execute next command as -ErrorAction is not mentioned in that command.
[ { "code": null, "e": 1331, "s": 1062, "text": "As we know $ErrorActionPreference and $ErrorAction both have the same functionality and both are used to handle terminating errors by converting Non-Terminating errors to Terminating errors. But when both the variables are used, we need to know which takes precedence." }, { "code": null, "e": 1738, "s": 1331, "text": "$ErrorActionPreference variable is used at the start of the script while the $erroraction variable is a common parameter and used with the cmdlet. In some cases, we might need the script to be terminated as soon as an error occurs but inside the script, we have some cmdlets which need to be ignored or continued if the error occurs. In that situation, we -ErrorAction is important and it takes precedence." }, { "code": null, "e": 1909, "s": 1738, "text": "$ErrorActionPreference = \"Stop\"\ntry{\n Get-Service -Name ABC\n Get-Process powershell\n Get-Process chromesds\n Get-Service Spooler\n}\ncatch{\n $_.Exception.Message\n}" }, { "code": null, "e": 1958, "s": 1909, "text": "Cannot find any service with service name 'ABC'." }, { "code": null, "e": 2237, "s": 1958, "text": "In the above example, the script is terminated because the ABC service name doesn’t exist and because of it, the next commands can’t execute as the $ErrorActionPreference value is set to Stop. Once we add the -ErrorAction in the Get-Service command, it will take the precedence." }, { "code": null, "e": 2430, "s": 2237, "text": "$ErrorActionPreference = \"Stop\"\ntry{\n Get-Service -Name ABC -ErrorAction Continue\n Get-Process powershell\n Get-Process chromesds\n Get-Service Spooler\n}\ncatch{\n $_.Exception.Message\n}" }, { "code": null, "e": 2892, "s": 2430, "text": "Line |\n 4 | Get-Service -Name ABC -ErrorAction Continue\n | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | Cannot find any service with service name 'ABC'.\nNPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName\n------ ----- ----- ------ -- -- -----------\n43 234.39 11.33 49.17 7668 1 powershell\nCannot find a process with the name \"chromesds\". Verify the process name and call\nthe cmdlet again." }, { "code": null, "e": 3152, "s": 2892, "text": "Once we add the -ErrorAction parameter with Continue value, execution moves to the next command as shown in the above output and stops when it can’t find process name “Chromesds” and can’t execute next command as -ErrorAction is not mentioned in that command." } ]
How to get current Wi-Fi IP address in android?
This example demonstrate about How to get current Wi-Fi IP address in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show WIFI mac ip address. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); String ipAddress = Formatter.formatIpAddress(wifiInfo.getIpAddress()); textView.setText("" + ipAddress); } @Override protected void onStop() { super.onStop(); } @Override protected void onResume() { super.onResume(); } } Step 4 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" /> <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" /> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1141, "s": 1062, "text": "This example demonstrate about How to get current Wi-Fi IP address in android." }, { "code": null, "e": 1270, "s": 1141, "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": 1335, "s": 1270, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1895, "s": 1335, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1967, "s": 1895, "text": "In the above code, we have taken text view to show WIFI mac ip address." }, { "code": null, "e": 2024, "s": 1967, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3086, "s": 2024, "text": "package com.example.myapplication;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.format.Formatter;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n WifiInfo wifiInfo = wifiMgr.getConnectionInfo();\n String ipAddress = Formatter.formatIpAddress(wifiInfo.getIpAddress());\n textView.setText(\"\" + ipAddress);\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}" }, { "code": null, "e": 3141, "s": 3086, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4005, "s": 3141, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <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 <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4352, "s": 4005, "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": 4392, "s": 4352, "text": "Click here to download the project code" } ]
numpy.polyder() in Python - GeeksforGeeks
04 Dec, 2020 The numpy.polyder() method evaluates the derivative of a polynomial with specified order. Syntax :numpy.polyder(p, m)Parameters :p : [array_like or poly1D]the polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.For example : poly1d(3, 2, 6) = 3x2 + 2x + 6 m : [int, optional] Order of differentiation. Return: Derivative of polynomial. Code : Python code explaining polyder() # Python code explaining # numpy.polyder() # importing librariesimport numpy as npimport pandas as pd # Constructing polynomial p1 = np.poly1d([1, 2]) p2 = np.poly1d([4, 9, 5, 4]) print ("P1 : ", p1) print ("\n p2 : \n", p2) # Solve for x = 2 print ("\n\np1 at x = 2 : ", p1(2)) print ("p2 at x = 2 : ", p2(2)) a = np.polyder(p1, 1)b = np.polyder(p2, 1)print ("\n\nUsing polyder")print ("p1 derivative of order = 1 : \n", a) print ("p2 derivative of order = 1 : \n", b) a = np.polyder(p1, 2)b = np.polyder(p2, 2)print ("\n\nUsing polyder")print ("p1 derivative of order = 2 : ", a) print ("p2 derivative of order = 2 : ", b) Python numpy-polynomials 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25627, "s": 25537, "text": "The numpy.polyder() method evaluates the derivative of a polynomial with specified order." }, { "code": null, "e": 25911, "s": 25627, "text": "Syntax :numpy.polyder(p, m)Parameters :p : [array_like or poly1D]the polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.For example : poly1d(3, 2, 6) = 3x2 + 2x + 6" }, { "code": null, "e": 25957, "s": 25911, "text": "m : [int, optional] Order of differentiation." }, { "code": null, "e": 25991, "s": 25957, "text": "Return: Derivative of polynomial." }, { "code": null, "e": 26031, "s": 25991, "text": "Code : Python code explaining polyder()" }, { "code": "# Python code explaining # numpy.polyder() # importing librariesimport numpy as npimport pandas as pd # Constructing polynomial p1 = np.poly1d([1, 2]) p2 = np.poly1d([4, 9, 5, 4]) print (\"P1 : \", p1) print (\"\\n p2 : \\n\", p2) ", "e": 26265, "s": 26031, "text": null }, { "code": " # Solve for x = 2 print (\"\\n\\np1 at x = 2 : \", p1(2)) print (\"p2 at x = 2 : \", p2(2)) ", "e": 26355, "s": 26265, "text": null }, { "code": "a = np.polyder(p1, 1)b = np.polyder(p2, 1)print (\"\\n\\nUsing polyder\")print (\"p1 derivative of order = 1 : \\n\", a) print (\"p2 derivative of order = 1 : \\n\", b) ", "e": 26515, "s": 26355, "text": null }, { "code": "a = np.polyder(p1, 2)b = np.polyder(p2, 2)print (\"\\n\\nUsing polyder\")print (\"p1 derivative of order = 2 : \", a) print (\"p2 derivative of order = 2 : \", b)", "e": 26670, "s": 26515, "text": null }, { "code": null, "e": 26695, "s": 26670, "text": "Python numpy-polynomials" }, { "code": null, "e": 26708, "s": 26695, "text": "Python-numpy" }, { "code": null, "e": 26715, "s": 26708, "text": "Python" }, { "code": null, "e": 26813, "s": 26715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26845, "s": 26813, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26887, "s": 26845, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26929, "s": 26887, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26956, "s": 26929, "text": "Python Classes and Objects" }, { "code": null, "e": 27012, "s": 26956, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27034, "s": 27012, "text": "Defaultdict in Python" }, { "code": null, "e": 27073, "s": 27034, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27104, "s": 27073, "text": "Python | os.path.join() method" }, { "code": null, "e": 27133, "s": 27104, "text": "Create a directory in Python" } ]
Advance CSS layout with flexbox - GeeksforGeeks
21 Aug, 2019 It is also called a flexible box model. It is basically a layout model that provides an easy and clean way to arrange items within container. Flexbox is different from the block model which is vertically bias and the inline which is horizontally bias. Flexbox was created for small-scales layouts and there’s another standard called grids which is geared more towards larger scale layouts, It works similar to the way to Twitter bootstrap grid system works. Flexbox is responsive and mobile-friendly. To start with flexbox firstly create a flex container. To create a flex container set the display property to flex. Example: .main-container { display: flex; } Flex Properties: flex-direction flex-wrap flex-flow justify-content align-items align-content flex-direction: The flex-direction is used to define the direction of flexible item. The default axis is horizontal in flexbox, so the items flow into a row. Syntax: // Stacking flex items column wise flex-direction: column; // Stacking flex items from bottom to top flex-direction: column-reverse; // Stacking flex items row wise flex-direction: row; // Stacking flex items from right to left flex-direction: row-reverse; Example: <!DOCTYPE html><html> <head> <title>flexbox</title> <style> .gfg_flex { display: flex; flex-direction: row; background-color: green; text-align:center; } .gfg_flex > div { background-color: #f4f4f4; width: 100px; height:100px; margin: 10px; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = "geeks">GeeksforGeeks</div> <h2>flex-direction Property</h2> <div class="gfg_flex"> <div>Box A</div> <div>Box B</div> <div>Box C</div> <div>Box D</div> <div>Box E</div> </div> </body></html> Output: flex-wrap: The flex-wrap property is used to define the wrap of flex-items. If flex-wrap property set to wrap then browser’s window set the box. If browser window is smaller than elements then elements go down to the next line. Syntax: // Wrap flex items when necessary flex-wrap: wrap; // Flex items will not wrap flex-wrap: nowrap; Example: <!DOCTYPE html><html> <head> <title>flex-wrap property</title> <style> .gfg_flex { display: flex; flex-wrap: wrap; text-align:center; background-color: green; } .gfg_flex > div { background-color: #f4f4f4; width: 100px; height:100px; margin: 10px; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = "geeks">GeeksforGeeks</div> <h2>flex-wrap Property</h2> <div class="gfg_flex"> <div>Box A</div> <div>Box B</div> <div>Box C</div> <div>Box D</div> <div>Box E</div> <div>Box F</div> <div>Box G</div> <div>Box H</div> <div>Box I</div> </div> </body></html> Output: Note: The flex-flow is a shorthand for flex-direction and flex-wrap.Syntax: flex-flow: row wrap; justify-content: The justify-content property is used to align the flex items according to the main axis within a flexbox container. Syntax: // Aligns the flex items at the center justify-content: center; // The space is distributed around the flexbox items //and it also adds space before the first item and after the last one. justify-content: space-around; // Space between the lines justify-content: space-between; // Aligns the flex items at the beginning of the container justify-content: flex-start; // Aligns the flex items at the end of the container justify-content: flex-end; Example: <!DOCTYPE html><html> <head> <title>justify flexbox property</title> <style> .flex1 { display: flex; justify-content: center; background-color: green; } .flex2 { display: flex; justify-content: space-around; background-color: green; } .flex3 { display: flex; justify-content: space-between; background-color: green; } .flex4 { display: flex; justify-content: flex-start; background-color: green; } .flex5 { display: flex; justify-content: flex-end; background-color: green; } .flex-items { background-color: #f4f4f4; width: 100px; height:50px; margin: 10px; text-align: center; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = "geeks">GeeksforGeeks</div> <h2>The justify-content Property</h2> <b>justify-content: center </b> <div class="flex1"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>justify-content: space-around </b> <div class="flex2"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>justify-content: space-between </b> <div class="flex3"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>justify-content: flex-start </b> <div class="flex4"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>justify-content: flex-end </b> <div class="flex5"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> </body></html> Output: align-items: This property is used to align flex items vertically according to the cross axis.Syntax: // Aligns the flex items in the middle of the container align-items: center; // Flexbox items are aligned at the baseline of the cross axis align-items: baseline; // Stretches the flex items align-items: stretch; // Aligns the flex items at the top of the container align-items: flex-start; // Aligns elements at the bottom of the container align-items: flex-end; Example: <!DOCTYPE html><html> <head> <title>align-items property</title> <style> .flex1 { display: flex; height: 200px; align-items: center; background-color: green; } .flex2 { display: flex; height: 200px; align-items: baseline; background-color: green; } .flex3 { display: flex; height: 200px; align-items: stretch; background-color: green; } .flex4 { display: flex; height: 200px; align-items: flex-start; background-color: green; } .flex5 { display: flex; height: 200px; align-items: flex-end; background-color: green; } .flex-items { background-color: #f4f4f4; width: 100px; margin: 10px; text-align: center; font-size: 50px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = "geeks">GeeksforGeeks</div> <h2>The align-items Property</h2> <b>align-items: center </b> <div class="flex1"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>align-items: baseline </b> <div class="flex2"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>align-items: stretch </b> <div class="flex3"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>align-items: flex-start </b> <div class="flex4"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> <br> <b>align-items: flex-end </b> <div class="flex5"> <div class="flex-items">1</div> <div class="flex-items">2</div> <div class="flex-items">3</div> </div> </body></html> Output: align-content: This property defines how each flex line is aligned within a flexbox and it only applicable if flex-wrap: wrap is applied i.e. if there are multiple lines of flexbox items present.Syntax : // Displays the flex lines with equal space between them align-content: space-between; // Displays the flex lines at the start of the container align-content: flex-start; // Displays the flex lines at the end of the container align-content: flex-end; // Dy using space-around property space will be // Distributed equally around the flex lines align-content: space-around; // Stretches the flex lines align-content: stretch; Example: <!DOCTYPE html><html> <head> <title>align-content property</title> <style> .main-container { display: flex; height: 400px; flex-wrap: wrap; align-content: space-between; background-color: green; } .main-container div { background-color: #f4f4f4; width: 100px; margin: 10px; text-align: center; font-size: 50px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = "geeks">GeeksforGeeks</div> <h2>The align-content Property</h2> <div class="main-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nidhi_biet CSS-Advanced Picked CSS 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 create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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
[ { "code": null, "e": 29315, "s": 29287, "text": "\n21 Aug, 2019" }, { "code": null, "e": 29932, "s": 29315, "text": "It is also called a flexible box model. It is basically a layout model that provides an easy and clean way to arrange items within container. Flexbox is different from the block model which is vertically bias and the inline which is horizontally bias. Flexbox was created for small-scales layouts and there’s another standard called grids which is geared more towards larger scale layouts, It works similar to the way to Twitter bootstrap grid system works. Flexbox is responsive and mobile-friendly. To start with flexbox firstly create a flex container. To create a flex container set the display property to flex." }, { "code": null, "e": 29941, "s": 29932, "text": "Example:" }, { "code": null, "e": 29979, "s": 29941, "text": ".main-container {\n display: flex;\n}\n" }, { "code": null, "e": 29996, "s": 29979, "text": "Flex Properties:" }, { "code": null, "e": 30011, "s": 29996, "text": "flex-direction" }, { "code": null, "e": 30021, "s": 30011, "text": "flex-wrap" }, { "code": null, "e": 30031, "s": 30021, "text": "flex-flow" }, { "code": null, "e": 30047, "s": 30031, "text": "justify-content" }, { "code": null, "e": 30059, "s": 30047, "text": "align-items" }, { "code": null, "e": 30073, "s": 30059, "text": "align-content" }, { "code": null, "e": 30231, "s": 30073, "text": "flex-direction: The flex-direction is used to define the direction of flexible item. The default axis is horizontal in flexbox, so the items flow into a row." }, { "code": null, "e": 30239, "s": 30231, "text": "Syntax:" }, { "code": null, "e": 30500, "s": 30239, "text": "// Stacking flex items column wise\nflex-direction: column;\n\n// Stacking flex items from bottom to top\nflex-direction: column-reverse;\n\n// Stacking flex items row wise\nflex-direction: row;\n\n// Stacking flex items from right to left\nflex-direction: row-reverse;\n" }, { "code": null, "e": 30509, "s": 30500, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>flexbox</title> <style> .gfg_flex { display: flex; flex-direction: row; background-color: green; text-align:center; } .gfg_flex > div { background-color: #f4f4f4; width: 100px; height:100px; margin: 10px; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = \"geeks\">GeeksforGeeks</div> <h2>flex-direction Property</h2> <div class=\"gfg_flex\"> <div>Box A</div> <div>Box B</div> <div>Box C</div> <div>Box D</div> <div>Box E</div> </div> </body></html> ", "e": 31571, "s": 30509, "text": null }, { "code": null, "e": 31579, "s": 31571, "text": "Output:" }, { "code": null, "e": 31807, "s": 31579, "text": "flex-wrap: The flex-wrap property is used to define the wrap of flex-items. If flex-wrap property set to wrap then browser’s window set the box. If browser window is smaller than elements then elements go down to the next line." }, { "code": null, "e": 31815, "s": 31807, "text": "Syntax:" }, { "code": null, "e": 31915, "s": 31815, "text": "// Wrap flex items when necessary\nflex-wrap: wrap;\n\n// Flex items will not wrap\nflex-wrap: nowrap;\n" }, { "code": null, "e": 31924, "s": 31915, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>flex-wrap property</title> <style> .gfg_flex { display: flex; flex-wrap: wrap; text-align:center; background-color: green; } .gfg_flex > div { background-color: #f4f4f4; width: 100px; height:100px; margin: 10px; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = \"geeks\">GeeksforGeeks</div> <h2>flex-wrap Property</h2> <div class=\"gfg_flex\"> <div>Box A</div> <div>Box B</div> <div>Box C</div> <div>Box D</div> <div>Box E</div> <div>Box F</div> <div>Box G</div> <div>Box H</div> <div>Box I</div> </div> </body></html> ", "e": 33116, "s": 31924, "text": null }, { "code": null, "e": 33124, "s": 33116, "text": "Output:" }, { "code": null, "e": 33200, "s": 33124, "text": "Note: The flex-flow is a shorthand for flex-direction and flex-wrap.Syntax:" }, { "code": null, "e": 33222, "s": 33200, "text": "flex-flow: row wrap;\n" }, { "code": null, "e": 33355, "s": 33222, "text": "justify-content: The justify-content property is used to align the flex items according to the main axis within a flexbox container." }, { "code": null, "e": 33363, "s": 33355, "text": "Syntax:" }, { "code": null, "e": 33814, "s": 33363, "text": "// Aligns the flex items at the center\njustify-content: center;\n\n// The space is distributed around the flexbox items\n//and it also adds space before the first item and after the last one.\njustify-content: space-around;\n\n// Space between the lines\njustify-content: space-between;\n\n// Aligns the flex items at the beginning of the container\njustify-content: flex-start;\n\n// Aligns the flex items at the end of the container\njustify-content: flex-end;\n" }, { "code": null, "e": 33823, "s": 33814, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>justify flexbox property</title> <style> .flex1 { display: flex; justify-content: center; background-color: green; } .flex2 { display: flex; justify-content: space-around; background-color: green; } .flex3 { display: flex; justify-content: space-between; background-color: green; } .flex4 { display: flex; justify-content: flex-start; background-color: green; } .flex5 { display: flex; justify-content: flex-end; background-color: green; } .flex-items { background-color: #f4f4f4; width: 100px; height:50px; margin: 10px; text-align: center; font-size: 40px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = \"geeks\">GeeksforGeeks</div> <h2>The justify-content Property</h2> <b>justify-content: center </b> <div class=\"flex1\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>justify-content: space-around </b> <div class=\"flex2\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>justify-content: space-between </b> <div class=\"flex3\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>justify-content: flex-start </b> <div class=\"flex4\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>justify-content: flex-end </b> <div class=\"flex5\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> </body></html> ", "e": 36500, "s": 33823, "text": null }, { "code": null, "e": 36508, "s": 36500, "text": "Output:" }, { "code": null, "e": 36610, "s": 36508, "text": "align-items: This property is used to align flex items vertically according to the cross axis.Syntax:" }, { "code": null, "e": 36980, "s": 36610, "text": "// Aligns the flex items in the middle of the container\nalign-items: center;\n\n// Flexbox items are aligned at the baseline of the cross axis\nalign-items: baseline;\n\n// Stretches the flex items\n align-items: stretch;\n\n// Aligns the flex items at the top of the container\nalign-items: flex-start;\n\n// Aligns elements at the bottom of the container\nalign-items: flex-end;\n" }, { "code": null, "e": 36989, "s": 36980, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>align-items property</title> <style> .flex1 { display: flex; height: 200px; align-items: center; background-color: green; } .flex2 { display: flex; height: 200px; align-items: baseline; background-color: green; } .flex3 { display: flex; height: 200px; align-items: stretch; background-color: green; } .flex4 { display: flex; height: 200px; align-items: flex-start; background-color: green; } .flex5 { display: flex; height: 200px; align-items: flex-end; background-color: green; } .flex-items { background-color: #f4f4f4; width: 100px; margin: 10px; text-align: center; font-size: 50px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = \"geeks\">GeeksforGeeks</div> <h2>The align-items Property</h2> <b>align-items: center </b> <div class=\"flex1\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>align-items: baseline </b> <div class=\"flex2\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>align-items: stretch </b> <div class=\"flex3\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>align-items: flex-start </b> <div class=\"flex4\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> <br> <b>align-items: flex-end </b> <div class=\"flex5\"> <div class=\"flex-items\">1</div> <div class=\"flex-items\">2</div> <div class=\"flex-items\">3</div> </div> </body></html> ", "e": 39585, "s": 36989, "text": null }, { "code": null, "e": 39593, "s": 39585, "text": "Output:" }, { "code": null, "e": 39797, "s": 39593, "text": "align-content: This property defines how each flex line is aligned within a flexbox and it only applicable if flex-wrap: wrap is applied i.e. if there are multiple lines of flexbox items present.Syntax :" }, { "code": null, "e": 40229, "s": 39797, "text": "// Displays the flex lines with equal space between them\nalign-content: space-between;\n\n// Displays the flex lines at the start of the container\nalign-content: flex-start;\n\n// Displays the flex lines at the end of the container\n align-content: flex-end;\n\n// Dy using space-around property space will be \n// Distributed equally around the flex lines\nalign-content: space-around;\n\n// Stretches the flex lines\nalign-content: stretch;\n" }, { "code": null, "e": 40238, "s": 40229, "text": "Example:" }, { "code": " <!DOCTYPE html><html> <head> <title>align-content property</title> <style> .main-container { display: flex; height: 400px; flex-wrap: wrap; align-content: space-between; background-color: green; } .main-container div { background-color: #f4f4f4; width: 100px; margin: 10px; text-align: center; font-size: 50px; } h2 { text-align:center; } .geeks { font-size:40px; text-align:center; color:#009900; font-weight:bold; } </style> </head> <body> <div class = \"geeks\">GeeksforGeeks</div> <h2>The align-content Property</h2> <div class=\"main-container\"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> </body></html> ", "e": 41537, "s": 40238, "text": null }, { "code": null, "e": 41545, "s": 41537, "text": "Output:" }, { "code": null, "e": 41682, "s": 41545, "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": 41693, "s": 41682, "text": "nidhi_biet" }, { "code": null, "e": 41706, "s": 41693, "text": "CSS-Advanced" }, { "code": null, "e": 41713, "s": 41706, "text": "Picked" }, { "code": null, "e": 41717, "s": 41713, "text": "CSS" }, { "code": null, "e": 41722, "s": 41717, "text": "HTML" }, { "code": null, "e": 41739, "s": 41722, "text": "Web Technologies" }, { "code": null, "e": 41744, "s": 41739, "text": "HTML" }, { "code": null, "e": 41842, "s": 41744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41892, "s": 41842, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 41954, "s": 41892, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42002, "s": 41954, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 42060, "s": 42002, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 42115, "s": 42060, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 42165, "s": 42115, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 42227, "s": 42165, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42275, "s": 42227, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 42335, "s": 42275, "text": "How to set the default value for an HTML <select> element ?" } ]
Python | Pandas Timestamp.timetuple - GeeksforGeeks
17 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.timetuple() function return a time tuple for the given Timestamp object. The returned tuple contains values ranging from year, month to hours and seconds. The time tuple is compatible with time.localtime(). Syntax :Timestamp.timetuple() Parameters : None Return : time tuple Example #1: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.timetuple() function to return a time tuple. # return time tuplets.timetuple() Output : As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc. Example #2: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.timetuple() function to return a time tuple. # return time tuplets.timetuple() Output : As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc. Python Pandas-Timestamp Python-pandas 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": 25537, "s": 25509, "text": "\n17 Jan, 2019" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25975, "s": 25751, "text": "Pandas Timestamp.timetuple() function return a time tuple for the given Timestamp object. The returned tuple contains values ranging from year, month to hours and seconds. The time tuple is compatible with time.localtime()." }, { "code": null, "e": 26005, "s": 25975, "text": "Syntax :Timestamp.timetuple()" }, { "code": null, "e": 26023, "s": 26005, "text": "Parameters : None" }, { "code": null, "e": 26043, "s": 26023, "text": "Return : time tuple" }, { "code": null, "e": 26145, "s": 26043, "text": "Example #1: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 26374, "s": 26145, "text": null }, { "code": null, "e": 26383, "s": 26374, "text": "Output :" }, { "code": null, "e": 26458, "s": 26383, "text": "Now we will use the Timestamp.timetuple() function to return a time tuple." }, { "code": "# return time tuplets.timetuple()", "e": 26492, "s": 26458, "text": null }, { "code": null, "e": 26501, "s": 26492, "text": "Output :" }, { "code": null, "e": 26666, "s": 26501, "text": "As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc." }, { "code": null, "e": 26768, "s": 26666, "text": "Example #2: Use Timestamp.timetuple() function to return a time tuple for the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 26996, "s": 26768, "text": null }, { "code": null, "e": 27005, "s": 26996, "text": "Output :" }, { "code": null, "e": 27080, "s": 27005, "text": "Now we will use the Timestamp.timetuple() function to return a time tuple." }, { "code": "# return time tuplets.timetuple()", "e": 27114, "s": 27080, "text": null }, { "code": null, "e": 27123, "s": 27114, "text": "Output :" }, { "code": null, "e": 27288, "s": 27123, "text": "As we can see in the output, the Timestamp.timetuple() function has returned a tuple for the given Timestamp object which contains values like year, month, day etc." }, { "code": null, "e": 27312, "s": 27288, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 27326, "s": 27312, "text": "Python-pandas" }, { "code": null, "e": 27333, "s": 27326, "text": "Python" }, { "code": null, "e": 27431, "s": 27333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27463, "s": 27431, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27505, "s": 27463, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27547, "s": 27505, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27603, "s": 27547, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27630, "s": 27603, "text": "Python Classes and Objects" }, { "code": null, "e": 27661, "s": 27630, "text": "Python | os.path.join() method" }, { "code": null, "e": 27700, "s": 27661, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27729, "s": 27700, "text": "Create a directory in Python" }, { "code": null, "e": 27751, "s": 27729, "text": "Defaultdict in Python" } ]
Introduction to JavaScript - GeeksforGeeks
26 Oct, 2021 JavaScript is a lightweight, cross-platform, and interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of language elements like operators, control structures, and statements. Client-side: It supplies objects to control a browser and its Document Object Model (DOM). Like if client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation. Useful libraries for the client-side are AngularJS, ReactJS, VueJS and so many others. Server-side: It supplies objects relevant to running JavaScript on a server. Like if the server-side extensions allow an application to communicate with a database, and provide continuity of information from one invocation to another of the application, or perform file manipulations on a server. The useful framework which is the most famous these days is node.js. JavaScript can be added to your HTML file in two ways: Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag according to the requirement. External JS: We can write JavaScript code in other file having an extension .js and then link this file inside the <head> tag of the HTML file in which we want to add this code. Syntax: <script> // JavaScript Code </script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> Basic Example to Describe JavaScript </title></head> <body> <!-- JavaScript code can be embedded inside head section or body section --> <script> console.log("Welcome to GeeksforGeeks"); </script></body> </html> Output: The output will display on the console. Welcome to GeeksforGeeks History of JavaScript: It was created in 1995 by Brendan Eich while he was an engineer at Netscape. It was originally going to be named LiveScript but was renamed. Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser. Features of JavaScript: According to a recent survey conducted by Stack Overflow, JavaScript is the most popular language on earth. With advances in browser technology and JavaScript having moved into the server with Node.js and other frameworks, JavaScript is capable of so much more. Here are a few things that we can do with JavaScript: JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static, after JS was created dynamic Web sites were made. Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions. Can handle date and time. Performs Form Validation although the forms are created using HTML. No compiler is needed. Applications of JavaScript: Web Development: Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By using AngularJS that can be achieved so easily. Web Applications: With technology, browsers have improved to the extent that a language was required to create robust web applications. When we explore a map in Google Maps then we only need to click and drag the mouse. All detailed view is just a click away, and this is possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that provide extra power to the code. The Electron and React is helpful in this department. Server Applications: With the help of Node.js, JavaScript made its way from client to server and node.js is the most powerful on the server-side. Games: Not only in websites, but JavaScript also helps in creating games for leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in game development as well. It provides the EaseJS library which provides solutions for working with rich graphics. Smartwatches: JavaScript is being used in all possible devices and applications. It provides a library PebbleJS which is used in smartwatch applications. This framework works for applications that require the internet for its functioning. Art: Artists and designers can create whatever they want using JavaScript to draw on HTML 5 canvas, make the sound more effective also can be used p5.js library. Machine Learning: This JavaScript ml5.js library can be used in web development by using machine learning. Limitations of JavaScript: Performance: JavaScript does not provide the same level of performance as offered by many traditional languages as a complex program written in JavaScript would be comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so performance is not considered a big restriction in its use. Complexity: To master a scripting language, programmers must have a thorough knowledge of all the programming concepts, core language objects, client and server-side objects otherwise it would be difficult for them to write advanced scripts using JavaScript. Weak error handling and type checking facilities: It is weakly typed language as there is no need to specify the data type of the variable. So wrong type checking is not performed by compile. 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. itskawal2000 ghoshsuman0129 Pushpender007 javascript-basics JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31329, "s": 31301, "text": "\n26 Oct, 2021" }, { "code": null, "e": 31761, "s": 31329, "text": "JavaScript is a lightweight, cross-platform, and interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of language elements like operators, control structures, and statements. " }, { "code": null, "e": 32107, "s": 31761, "text": "Client-side: It supplies objects to control a browser and its Document Object Model (DOM). Like if client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation. Useful libraries for the client-side are AngularJS, ReactJS, VueJS and so many others." }, { "code": null, "e": 32473, "s": 32107, "text": "Server-side: It supplies objects relevant to running JavaScript on a server. Like if the server-side extensions allow an application to communicate with a database, and provide continuity of information from one invocation to another of the application, or perform file manipulations on a server. The useful framework which is the most famous these days is node.js." }, { "code": null, "e": 32528, "s": 32473, "text": "JavaScript can be added to your HTML file in two ways:" }, { "code": null, "e": 32738, "s": 32528, "text": "Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the <script> tag. The <script> tag can either be placed inside the <head> or the <body> tag according to the requirement." }, { "code": null, "e": 32916, "s": 32738, "text": "External JS: We can write JavaScript code in other file having an extension .js and then link this file inside the <head> tag of the HTML file in which we want to add this code." }, { "code": null, "e": 32924, "s": 32916, "text": "Syntax:" }, { "code": null, "e": 32966, "s": 32924, "text": "<script>\n // JavaScript Code\n</script>" }, { "code": null, "e": 32975, "s": 32966, "text": "Example:" }, { "code": null, "e": 32980, "s": 32975, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Basic Example to Describe JavaScript </title></head> <body> <!-- JavaScript code can be embedded inside head section or body section --> <script> console.log(\"Welcome to GeeksforGeeks\"); </script></body> </html>", "e": 33280, "s": 32980, "text": null }, { "code": null, "e": 33329, "s": 33280, "text": " Output: The output will display on the console." }, { "code": null, "e": 33354, "s": 33329, "text": "Welcome to GeeksforGeeks" }, { "code": null, "e": 34173, "s": 33354, "text": "History of JavaScript: It was created in 1995 by Brendan Eich while he was an engineer at Netscape. It was originally going to be named LiveScript but was renamed. Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser. Features of JavaScript: According to a recent survey conducted by Stack Overflow, JavaScript is the most popular language on earth. With advances in browser technology and JavaScript having moved into the server with Node.js and other frameworks, JavaScript is capable of so much more. Here are a few things that we can do with JavaScript: " }, { "code": null, "e": 34324, "s": 34173, "text": "JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static, after JS was created dynamic Web sites were made." }, { "code": null, "e": 34468, "s": 34324, "text": "Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions." }, { "code": null, "e": 34494, "s": 34468, "text": "Can handle date and time." }, { "code": null, "e": 34562, "s": 34494, "text": "Performs Form Validation although the forms are created using HTML." }, { "code": null, "e": 34585, "s": 34562, "text": "No compiler is needed." }, { "code": null, "e": 34615, "s": 34585, "text": "Applications of JavaScript: " }, { "code": null, "e": 34777, "s": 34615, "text": "Web Development: Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By using AngularJS that can be achieved so easily." }, { "code": null, "e": 35227, "s": 34777, "text": "Web Applications: With technology, browsers have improved to the extent that a language was required to create robust web applications. When we explore a map in Google Maps then we only need to click and drag the mouse. All detailed view is just a click away, and this is possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that provide extra power to the code. The Electron and React is helpful in this department." }, { "code": null, "e": 35373, "s": 35227, "text": "Server Applications: With the help of Node.js, JavaScript made its way from client to server and node.js is the most powerful on the server-side." }, { "code": null, "e": 35642, "s": 35373, "text": "Games: Not only in websites, but JavaScript also helps in creating games for leisure. The combination of JavaScript and HTML 5 makes JavaScript popular in game development as well. It provides the EaseJS library which provides solutions for working with rich graphics." }, { "code": null, "e": 35881, "s": 35642, "text": "Smartwatches: JavaScript is being used in all possible devices and applications. It provides a library PebbleJS which is used in smartwatch applications. This framework works for applications that require the internet for its functioning." }, { "code": null, "e": 36043, "s": 35881, "text": "Art: Artists and designers can create whatever they want using JavaScript to draw on HTML 5 canvas, make the sound more effective also can be used p5.js library." }, { "code": null, "e": 36150, "s": 36043, "text": "Machine Learning: This JavaScript ml5.js library can be used in web development by using machine learning." }, { "code": null, "e": 36178, "s": 36150, "text": "Limitations of JavaScript: " }, { "code": null, "e": 36489, "s": 36178, "text": "Performance: JavaScript does not provide the same level of performance as offered by many traditional languages as a complex program written in JavaScript would be comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so performance is not considered a big restriction in its use." }, { "code": null, "e": 36748, "s": 36489, "text": "Complexity: To master a scripting language, programmers must have a thorough knowledge of all the programming concepts, core language objects, client and server-side objects otherwise it would be difficult for them to write advanced scripts using JavaScript." }, { "code": null, "e": 36940, "s": 36748, "text": "Weak error handling and type checking facilities: It is weakly typed language as there is no need to specify the data type of the variable. So wrong type checking is not performed by compile." }, { "code": null, "e": 37161, "s": 36942, "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": 37174, "s": 37161, "text": "itskawal2000" }, { "code": null, "e": 37189, "s": 37174, "text": "ghoshsuman0129" }, { "code": null, "e": 37203, "s": 37189, "text": "Pushpender007" }, { "code": null, "e": 37221, "s": 37203, "text": "javascript-basics" }, { "code": null, "e": 37232, "s": 37221, "text": "JavaScript" }, { "code": null, "e": 37249, "s": 37232, "text": "Web Technologies" }, { "code": null, "e": 37347, "s": 37249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37387, "s": 37347, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37432, "s": 37387, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37493, "s": 37432, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37565, "s": 37493, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37634, "s": 37565, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 37674, "s": 37634, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37707, "s": 37674, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37752, "s": 37707, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37795, "s": 37752, "text": "How to fetch data from an API in ReactJS ?" } ]
Graph Plotting in R Programming - GeeksforGeeks
03 Dec, 2021 When it comes to interpreting the world and the enormous amount of data it is producing on a daily basis, Data Visualization becomes the most desirable way. Rather than screening huge Excel sheets, it is always better to visualize that data through charts and graphs, to gain meaningful insights. The R Programming Language provides some easy and quick tools that let us convert our data into visually insightful elements like graphs. One-dimensional Plotting: In one-dimensional plotting, we plot one variable at a time. For example, we may plot a variable with the number of times each of its values occurred in the entire dataset (frequency). So, it is not compared to any other variable of the dataset. These are the 4 major types of graphs that are used for One-dimensional analysis – Five Point SummaryBox PlottingHistogramsBar Plotting Five Point Summary Box Plotting Histograms Bar Plotting Two-dimensional Plotting: In two-dimensional plotting, we visualize and compare one variable with respect to the other. For example, in a dataset of Air Quality measures, we would like to compare how the AQI varies with the temperature at a particular place. So, temperature and AQI are two different variables and we wish to see how one changes with respect to the other. These are the 3 major kinds of graphs used for such kinds of analysis – Box PlottingHistogramsScatter plots Box Plotting Histograms Scatter plots For the purpose of this article, we will use the default dataset (mtcars) that is provided by RStudio. Open RStudio (or R Terminal) and start by loading the dataset. Type these commands in the console. This is a way to load the default datasets provided by R. (Any other dataset may also be downloaded and used) R library(datasets)data(mtcars) To check if the data is correctly loaded, we run the following command on console: R head(mtcars) Output: By running this command, we also get to know what columns does our dataset contains. In this case, the dataset mtcars contains 11 columns namely – mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, and carb. Note that the number of rows is larger than displayed here. head() function displays only the top 6 rows of the dataset. In one-dimensional plotting, we essentially plot one variable at a time. So, it is not compared to any other variable of the dataset. Rather, only its features of statistical inference are taken care of. To reference a particular column name in R, we use the ‘$’ sign. For example, if we want to refer to the ‘gear’ column in the mtcars dataset, we refer to it as – mtcars$gear. So, for any particular column of the dataset, we can generate a Five-Point summary using the summary() function. We simply pass the column name (referred using $ sign) as an argument to this function, as follows: R summary(mtcars) Output: This summary lists down features like Mean, Median, Minimum Value, Maximum Value, and Quadrant values of the particular column. A box plot generates a rectangle that covers the area spanned by the column of the dataset. It can be produced as follows: R boxplot(mtcars$mpg, col="green") Output: Note that the thick line in the rectangle depicts the median of the mpg column, i.e. 19.20 as seen in the Five Point Summary. The col=”green” simply colors the plot green. Histograms are the most widely used plots for analyzing datasets. Here is how we can plot a histogram that maps a variable (column name) to its frequency: R hist(mtcars$mpg, col = "green") ## Plot 1hist(mtcars$mpg, col = "green", breaks = 25) ## Plot 2hist(mtcars$mpg, col = "green", breaks = 50) ## Plot 3 The ‘breaks’ argument essentially alters the width of the histogram bars. It is seen that as we increase the value of the break, the bars grow thinner. Outputs: In bar graphs, we get a discrete value-frequency mapping for each value present in the variable (column). For example: R barplot(table(mtcars$carb), col="green") Output: We see that the column ‘carb’ contains 6 discrete values (in all its rows). The above bar graph maps these 6 values to their frequency (the number of times they occur). In two-dimensional plotting, we visualize and compare one variable with respect to the other. Suppose we wish to generate multiple boxplots, on the basis of the number of gears that each car has. So, the number of boxplots we wish to have is equal to the number of discrete values in the column ‘gear’, i.e. one plot for each value of the gear. This can be achieved in the following way – R boxplot(mpg~gear, data=mtcars, col = "green") Output: We see that there are 3 values of gears in the ‘gear’ column. So, 3 different box-plots, one for each gear have been plotted. Now suppose, we wish to create separate histograms for cars that have 4 cylinders and cars that have 8 cylinders. To do this, we subset our dataset such that the subset data contains data only for those cars which have 4 (or 8) cylinders. Then, we can easily plot our subset data using hist() function as before. This is how we can achieve this: R hist(subset(mtcars, cyl == 4)$mpg, col = "green") ## Plot 1hist(subset(mtcars, cyl == 8)$mpg, col = "green") ## Plot 2 Scatter plots are used to plot data points for two variables on the x and y-axis. They tell us patterns amongst data and are widely used for modeling ML algorithms. Here, we scatter plot the column qsec with respect to the column mpg. R with(mtcars, plot(mpg, qsec)) Output: However, the above plot does not really show us any patterns in data. This is because of the limited number of rows (samples) we had in our dataset. When we obtain data from external resources, it normally has a minimum of 1000+ rows. On plotting such an extensive dataset on a scatter plot, we pave way for really interesting observations and insights. kumar_satyam R-Graphs R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? R Programming Language - Introduction K-Means Clustering in R Programming
[ { "code": null, "e": 26117, "s": 26089, "text": "\n03 Dec, 2021" }, { "code": null, "e": 26415, "s": 26117, "text": "When it comes to interpreting the world and the enormous amount of data it is producing on a daily basis, Data Visualization becomes the most desirable way. Rather than screening huge Excel sheets, it is always better to visualize that data through charts and graphs, to gain meaningful insights. " }, { "code": null, "e": 26555, "s": 26415, "text": "The R Programming Language provides some easy and quick tools that let us convert our data into visually insightful elements like graphs. " }, { "code": null, "e": 26963, "s": 26555, "text": "One-dimensional Plotting: In one-dimensional plotting, we plot one variable at a time. For example, we may plot a variable with the number of times each of its values occurred in the entire dataset (frequency). So, it is not compared to any other variable of the dataset. These are the 4 major types of graphs that are used for One-dimensional analysis – Five Point SummaryBox PlottingHistogramsBar Plotting" }, { "code": null, "e": 26982, "s": 26963, "text": "Five Point Summary" }, { "code": null, "e": 26995, "s": 26982, "text": "Box Plotting" }, { "code": null, "e": 27006, "s": 26995, "text": "Histograms" }, { "code": null, "e": 27019, "s": 27006, "text": "Bar Plotting" }, { "code": null, "e": 27500, "s": 27019, "text": "Two-dimensional Plotting: In two-dimensional plotting, we visualize and compare one variable with respect to the other. For example, in a dataset of Air Quality measures, we would like to compare how the AQI varies with the temperature at a particular place. So, temperature and AQI are two different variables and we wish to see how one changes with respect to the other. These are the 3 major kinds of graphs used for such kinds of analysis – Box PlottingHistogramsScatter plots" }, { "code": null, "e": 27513, "s": 27500, "text": "Box Plotting" }, { "code": null, "e": 27524, "s": 27513, "text": "Histograms" }, { "code": null, "e": 27538, "s": 27524, "text": "Scatter plots" }, { "code": null, "e": 27642, "s": 27538, "text": "For the purpose of this article, we will use the default dataset (mtcars) that is provided by RStudio. " }, { "code": null, "e": 27851, "s": 27642, "text": "Open RStudio (or R Terminal) and start by loading the dataset. Type these commands in the console. This is a way to load the default datasets provided by R. (Any other dataset may also be downloaded and used)" }, { "code": null, "e": 27853, "s": 27851, "text": "R" }, { "code": "library(datasets)data(mtcars)", "e": 27883, "s": 27853, "text": null }, { "code": null, "e": 27966, "s": 27883, "text": "To check if the data is correctly loaded, we run the following command on console:" }, { "code": null, "e": 27968, "s": 27966, "text": "R" }, { "code": "head(mtcars)", "e": 27981, "s": 27968, "text": null }, { "code": null, "e": 27989, "s": 27981, "text": "Output:" }, { "code": null, "e": 28317, "s": 27989, "text": "By running this command, we also get to know what columns does our dataset contains. In this case, the dataset mtcars contains 11 columns namely – mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, and carb. Note that the number of rows is larger than displayed here. head() function displays only the top 6 rows of the dataset." }, { "code": null, "e": 28521, "s": 28317, "text": "In one-dimensional plotting, we essentially plot one variable at a time. So, it is not compared to any other variable of the dataset. Rather, only its features of statistical inference are taken care of." }, { "code": null, "e": 28909, "s": 28521, "text": "To reference a particular column name in R, we use the ‘$’ sign. For example, if we want to refer to the ‘gear’ column in the mtcars dataset, we refer to it as – mtcars$gear. So, for any particular column of the dataset, we can generate a Five-Point summary using the summary() function. We simply pass the column name (referred using $ sign) as an argument to this function, as follows:" }, { "code": null, "e": 28911, "s": 28909, "text": "R" }, { "code": "summary(mtcars)", "e": 28927, "s": 28911, "text": null }, { "code": null, "e": 28935, "s": 28927, "text": "Output:" }, { "code": null, "e": 29064, "s": 28935, "text": "This summary lists down features like Mean, Median, Minimum Value, Maximum Value, and Quadrant values of the particular column. " }, { "code": null, "e": 29187, "s": 29064, "text": "A box plot generates a rectangle that covers the area spanned by the column of the dataset. It can be produced as follows:" }, { "code": null, "e": 29189, "s": 29187, "text": "R" }, { "code": "boxplot(mtcars$mpg, col=\"green\")", "e": 29222, "s": 29189, "text": null }, { "code": null, "e": 29230, "s": 29222, "text": "Output:" }, { "code": null, "e": 29403, "s": 29230, "text": "Note that the thick line in the rectangle depicts the median of the mpg column, i.e. 19.20 as seen in the Five Point Summary. The col=”green” simply colors the plot green. " }, { "code": null, "e": 29558, "s": 29403, "text": "Histograms are the most widely used plots for analyzing datasets. Here is how we can plot a histogram that maps a variable (column name) to its frequency:" }, { "code": null, "e": 29560, "s": 29558, "text": "R" }, { "code": "hist(mtcars$mpg, col = \"green\") ## Plot 1hist(mtcars$mpg, col = \"green\", breaks = 25) ## Plot 2hist(mtcars$mpg, col = \"green\", breaks = 50) ## Plot 3", "e": 29726, "s": 29560, "text": null }, { "code": null, "e": 29878, "s": 29726, "text": "The ‘breaks’ argument essentially alters the width of the histogram bars. It is seen that as we increase the value of the break, the bars grow thinner." }, { "code": null, "e": 29887, "s": 29878, "text": "Outputs:" }, { "code": null, "e": 30006, "s": 29887, "text": "In bar graphs, we get a discrete value-frequency mapping for each value present in the variable (column). For example:" }, { "code": null, "e": 30008, "s": 30006, "text": "R" }, { "code": "barplot(table(mtcars$carb), col=\"green\")", "e": 30049, "s": 30008, "text": null }, { "code": null, "e": 30057, "s": 30049, "text": "Output:" }, { "code": null, "e": 30226, "s": 30057, "text": "We see that the column ‘carb’ contains 6 discrete values (in all its rows). The above bar graph maps these 6 values to their frequency (the number of times they occur)." }, { "code": null, "e": 30320, "s": 30226, "text": "In two-dimensional plotting, we visualize and compare one variable with respect to the other." }, { "code": null, "e": 30615, "s": 30320, "text": "Suppose we wish to generate multiple boxplots, on the basis of the number of gears that each car has. So, the number of boxplots we wish to have is equal to the number of discrete values in the column ‘gear’, i.e. one plot for each value of the gear. This can be achieved in the following way –" }, { "code": null, "e": 30617, "s": 30615, "text": "R" }, { "code": "boxplot(mpg~gear, data=mtcars, col = \"green\")", "e": 30663, "s": 30617, "text": null }, { "code": null, "e": 30671, "s": 30663, "text": "Output:" }, { "code": null, "e": 30797, "s": 30671, "text": "We see that there are 3 values of gears in the ‘gear’ column. So, 3 different box-plots, one for each gear have been plotted." }, { "code": null, "e": 31143, "s": 30797, "text": "Now suppose, we wish to create separate histograms for cars that have 4 cylinders and cars that have 8 cylinders. To do this, we subset our dataset such that the subset data contains data only for those cars which have 4 (or 8) cylinders. Then, we can easily plot our subset data using hist() function as before. This is how we can achieve this:" }, { "code": null, "e": 31145, "s": 31143, "text": "R" }, { "code": "hist(subset(mtcars, cyl == 4)$mpg, col = \"green\") ## Plot 1hist(subset(mtcars, cyl == 8)$mpg, col = \"green\") ## Plot 2", "e": 31278, "s": 31145, "text": null }, { "code": null, "e": 31513, "s": 31278, "text": "Scatter plots are used to plot data points for two variables on the x and y-axis. They tell us patterns amongst data and are widely used for modeling ML algorithms. Here, we scatter plot the column qsec with respect to the column mpg." }, { "code": null, "e": 31515, "s": 31513, "text": "R" }, { "code": "with(mtcars, plot(mpg, qsec))", "e": 31545, "s": 31515, "text": null }, { "code": null, "e": 31553, "s": 31545, "text": "Output:" }, { "code": null, "e": 31907, "s": 31553, "text": "However, the above plot does not really show us any patterns in data. This is because of the limited number of rows (samples) we had in our dataset. When we obtain data from external resources, it normally has a minimum of 1000+ rows. On plotting such an extensive dataset on a scatter plot, we pave way for really interesting observations and insights." }, { "code": null, "e": 31920, "s": 31907, "text": "kumar_satyam" }, { "code": null, "e": 31929, "s": 31920, "text": "R-Graphs" }, { "code": null, "e": 31937, "s": 31929, "text": "R-plots" }, { "code": null, "e": 31950, "s": 31937, "text": "R-Statistics" }, { "code": null, "e": 31961, "s": 31950, "text": "R Language" }, { "code": null, "e": 32059, "s": 31961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32117, "s": 32059, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 32169, "s": 32117, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 32201, "s": 32169, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 32245, "s": 32201, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 32297, "s": 32245, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32332, "s": 32297, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32370, "s": 32332, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32428, "s": 32370, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32466, "s": 32428, "text": "R Programming Language - Introduction" } ]
numpy.conj() in Python - GeeksforGeeks
04 Dec, 2020 The numpy.conj() function helps the user to conjugate any complex number. The conjugate of a complex number is obtained by changing the sign of its imaginary part. If the complex number is 2+5j then its conjugate is 2-5j. Syntax:numpy.conj(x[, out] = ufunc ‘conjugate’)Parameters :x [array_like]: Input value.out [ndarray, optional] : Output array with same dimensions as Input array, placed with result. Return :x : ndarray. The complex conjugate of x, with same dtype as y. Code #1 : # Python3 code demonstrate conj() function #importing numpyimport numpy as np in_complx1 = 2+4jout_complx1 = np.conj(in_complx1)print ("Output conjugated complex number of 2+4j : ", out_complx1) in_complx2 =5-8jout_complx2 = np.conj(in_complx2)print ("Output conjugated complex number of 5-8j: ", out_complx2) Output : Output conjugated complex number of 2+4j : (2-4j) Output conjugated complex number of 5-8j: (5+8j) Code #2 : # Python3 code demonstrate conj() function # importing numpyimport numpy as np in_array = np.eye(2) + 3j * np.eye(2)print ("Input array : ", in_array) out_array = np.conjugate(in_array)print ("Output conjugated array : ", out_array) Output : Input array : [[ 1.+3.j 0.+0.j] [ 0.+0.j 1.+3.j]] Output conjugated array : [[ 1.-3.j 0.-0.j] [ 0.-0.j 1.-3.j]] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26375, "s": 26347, "text": "\n04 Dec, 2020" }, { "code": null, "e": 26449, "s": 26375, "text": "The numpy.conj() function helps the user to conjugate any complex number." }, { "code": null, "e": 26597, "s": 26449, "text": "The conjugate of a complex number is obtained by changing the sign of its imaginary part. If the complex number is 2+5j then its conjugate is 2-5j." }, { "code": null, "e": 26780, "s": 26597, "text": "Syntax:numpy.conj(x[, out] = ufunc ‘conjugate’)Parameters :x [array_like]: Input value.out [ndarray, optional] : Output array with same dimensions as Input array, placed with result." }, { "code": null, "e": 26851, "s": 26780, "text": "Return :x : ndarray. The complex conjugate of x, with same dtype as y." }, { "code": null, "e": 26861, "s": 26851, "text": "Code #1 :" }, { "code": "# Python3 code demonstrate conj() function #importing numpyimport numpy as np in_complx1 = 2+4jout_complx1 = np.conj(in_complx1)print (\"Output conjugated complex number of 2+4j : \", out_complx1) in_complx2 =5-8jout_complx2 = np.conj(in_complx2)print (\"Output conjugated complex number of 5-8j: \", out_complx2)", "e": 27175, "s": 26861, "text": null }, { "code": null, "e": 27184, "s": 27175, "text": "Output :" }, { "code": null, "e": 27287, "s": 27184, "text": "Output conjugated complex number of 2+4j : (2-4j)\nOutput conjugated complex number of 5-8j: (5+8j)\n" }, { "code": null, "e": 27298, "s": 27287, "text": " Code #2 :" }, { "code": "# Python3 code demonstrate conj() function # importing numpyimport numpy as np in_array = np.eye(2) + 3j * np.eye(2)print (\"Input array : \", in_array) out_array = np.conjugate(in_array)print (\"Output conjugated array : \", out_array)", "e": 27534, "s": 27298, "text": null }, { "code": null, "e": 27543, "s": 27534, "text": "Output :" }, { "code": null, "e": 27664, "s": 27543, "text": "Input array : [[ 1.+3.j 0.+0.j]\n [ 0.+0.j 1.+3.j]]\nOutput conjugated array : [[ 1.-3.j 0.-0.j]\n [ 0.-0.j 1.-3.j]]\n" }, { "code": null, "e": 27699, "s": 27664, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27712, "s": 27699, "text": "Python-numpy" }, { "code": null, "e": 27719, "s": 27712, "text": "Python" }, { "code": null, "e": 27817, "s": 27719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27835, "s": 27817, "text": "Python Dictionary" }, { "code": null, "e": 27870, "s": 27835, "text": "Read a file line by line in Python" }, { "code": null, "e": 27902, "s": 27870, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27924, "s": 27902, "text": "Enumerate() in Python" }, { "code": null, "e": 27966, "s": 27924, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27996, "s": 27966, "text": "Iterate over a list in Python" }, { "code": null, "e": 28022, "s": 27996, "text": "Python String | replace()" }, { "code": null, "e": 28051, "s": 28022, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28095, "s": 28051, "text": "Reading and Writing to text files in Python" } ]
Semantic-UI | Segment - GeeksforGeeks
13 Sep, 2021 A semantic UI open-source framework provides a segment or portion on a webpage that is used to create a group of related content. It is very similar to bootstrap usage and has different elements to make your website more amazing using jQuery and CSS for interfaces. For styling of elements, it uses classes. Example: <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Segment</h2> <br> <div class="ui segment"> <center> <h3>Welcome to geeksforgeeks.</h3> <p>Learn anything you want</p> <p> Get tutorial of anything related to computer science. </p> <p>Courses on programming</p> <p>Solve programming problems.</p> <p>Help other by writing articles.</p> </center> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The example shows placeholder segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Placeholder segment</h2> <br> <div class="ui placeholder segment"> <div class="ui icon header"> <i class="file image icon"></i> Upload Photo </div> <div class="ui primary button"> Add Photo </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: This example shows raised segment that gives a top view on the page. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Raised segment</h2> <br> <div class="ui raised segment"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows stacked segment which looks multiple pages. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Stacked segment</h2> <br> <div class="ui tall stacked segment"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows piled segment like pages. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Piled segment</h2> <br> <div class="ui piled segment"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows vertical segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Vertical segment</h2> <br> <div class="ui vertical segment"> <p>Data Structure</p> </div> <div class="ui vertical segment"> <p>Web Programming</p> </div> <div class="ui vertical segment"> <p>Competative Programming</p> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows group segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Group segment</h2> <br> <div class="ui segments"> <div class="ui segment"> <p>Data Structure</p> </div> <div class="ui green segment"> <p>Web Programming</p> </div> <div class="ui blue segment"> <p>Competative Programming</p> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows nested segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Nested segment</h2> <br> <div class="ui segment"> <p>Web Programming</p> <div class="ui segments"> <div class="ui segment"> <p>Django</p> </div> <div class="ui segment"> <p>NodeJS</p> </div> </div> </div> <div class="ui segment"> <p>Data Structure</p> <div class="ui segments"> <div class="ui segment"> <p>Array</p> </div> <div class="ui segment"> <p>Linklist</p> </div> <div class="ui segment"> <p>Tree</p> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows horizontal segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Horizontal segment</h2> <br> <div class="ui horizontal segments"> <div class="ui segment"> <p>Array</p> </div> <div class="ui segment"> <p>Linklist</p> </div> <div class="ui segment"> <p>Tree</p> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows loading segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Loading segment</h2> <br> <div class="ui loading segment"> <p></p> <p></p> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows inverted segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Inverted segment</h2> <br> <div class="ui inverted segment"> <h2> Hello, welcome to geeksforgeeks. </h2> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Example: The following example shows circular segment. <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /></head> <body> <div style="margin-top: 100px" class="ui container"> <h2>Circular segment</h2> <br> <div class="ui circular segment"> <h2> Hello, welcome to geeksforgeeks. </h2> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></body> </html> Output: Akanksha_Rai sagar0719kumar Semantic-UI CSS Web Technologies 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 create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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?
[ { "code": null, "e": 40451, "s": 40423, "text": "\n13 Sep, 2021" }, { "code": null, "e": 40759, "s": 40451, "text": "A semantic UI open-source framework provides a segment or portion on a webpage that is used to create a group of related content. It is very similar to bootstrap usage and has different elements to make your website more amazing using jQuery and CSS for interfaces. For styling of elements, it uses classes." }, { "code": null, "e": 40768, "s": 40759, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Segment</h2> <br> <div class=\"ui segment\"> <center> <h3>Welcome to geeksforgeeks.</h3> <p>Learn anything you want</p> <p> Get tutorial of anything related to computer science. </p> <p>Courses on programming</p> <p>Solve programming problems.</p> <p>Help other by writing articles.</p> </center> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 41839, "s": 40768, "text": null }, { "code": null, "e": 41847, "s": 41839, "text": "Output:" }, { "code": null, "e": 41895, "s": 41847, "text": "Example: The example shows placeholder segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Placeholder segment</h2> <br> <div class=\"ui placeholder segment\"> <div class=\"ui icon header\"> <i class=\"file image icon\"></i> Upload Photo </div> <div class=\"ui primary button\"> Add Photo </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 42799, "s": 41895, "text": null }, { "code": null, "e": 42807, "s": 42799, "text": "Output:" }, { "code": null, "e": 42885, "s": 42807, "text": "Example: This example shows raised segment that gives a top view on the page." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Raised segment</h2> <br> <div class=\"ui raised segment\"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 43656, "s": 42885, "text": null }, { "code": null, "e": 43664, "s": 43656, "text": "Output:" }, { "code": null, "e": 43745, "s": 43664, "text": "Example: The following example shows stacked segment which looks multiple pages." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Stacked segment</h2> <br> <div class=\"ui tall stacked segment\"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 44525, "s": 43745, "text": null }, { "code": null, "e": 44533, "s": 44525, "text": "Output:" }, { "code": null, "e": 44596, "s": 44533, "text": "Example: The following example shows piled segment like pages." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Piled segment</h2> <br> <div class=\"ui piled segment\"> <h2> Hello, Welcome to geeksforgeeks </h2> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 45365, "s": 44596, "text": null }, { "code": null, "e": 45373, "s": 45365, "text": "Output:" }, { "code": null, "e": 45428, "s": 45373, "text": "Example: The following example shows vertical segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Vertical segment</h2> <br> <div class=\"ui vertical segment\"> <p>Data Structure</p> </div> <div class=\"ui vertical segment\"> <p>Web Programming</p> </div> <div class=\"ui vertical segment\"> <p>Competative Programming</p> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 46327, "s": 45428, "text": null }, { "code": null, "e": 46335, "s": 46327, "text": "Output:" }, { "code": null, "e": 46387, "s": 46335, "text": "Example: The following example shows group segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Group segment</h2> <br> <div class=\"ui segments\"> <div class=\"ui segment\"> <p>Data Structure</p> </div> <div class=\"ui green segment\"> <p>Web Programming</p> </div> <div class=\"ui blue segment\"> <p>Competative Programming</p> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 47349, "s": 46387, "text": null }, { "code": null, "e": 47357, "s": 47349, "text": "Output:" }, { "code": null, "e": 47410, "s": 47357, "text": "Example: The following example shows nested segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Nested segment</h2> <br> <div class=\"ui segment\"> <p>Web Programming</p> <div class=\"ui segments\"> <div class=\"ui segment\"> <p>Django</p> </div> <div class=\"ui segment\"> <p>NodeJS</p> </div> </div> </div> <div class=\"ui segment\"> <p>Data Structure</p> <div class=\"ui segments\"> <div class=\"ui segment\"> <p>Array</p> </div> <div class=\"ui segment\"> <p>Linklist</p> </div> <div class=\"ui segment\"> <p>Tree</p> </div> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 48777, "s": 47410, "text": null }, { "code": null, "e": 48785, "s": 48777, "text": "Output:" }, { "code": null, "e": 48842, "s": 48785, "text": "Example: The following example shows horizontal segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Horizontal segment</h2> <br> <div class=\"ui horizontal segments\"> <div class=\"ui segment\"> <p>Array</p> </div> <div class=\"ui segment\"> <p>Linklist</p> </div> <div class=\"ui segment\"> <p>Tree</p> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 49778, "s": 48842, "text": null }, { "code": null, "e": 49786, "s": 49778, "text": "Output:" }, { "code": null, "e": 49840, "s": 49786, "text": "Example: The following example shows loading segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Loading segment</h2> <br> <div class=\"ui loading segment\"> <p></p> <p></p> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 50555, "s": 49840, "text": null }, { "code": null, "e": 50563, "s": 50555, "text": "Output:" }, { "code": null, "e": 50618, "s": 50563, "text": "Example: The following example shows inverted segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Inverted segment</h2> <br> <div class=\"ui inverted segment\"> <h2> Hello, welcome to geeksforgeeks. </h2> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 51390, "s": 50618, "text": null }, { "code": null, "e": 51398, "s": 51390, "text": "Output:" }, { "code": null, "e": 51453, "s": 51398, "text": "Example: The following example shows circular segment." }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /></head> <body> <div style=\"margin-top: 100px\" class=\"ui container\"> <h2>Circular segment</h2> <br> <div class=\"ui circular segment\"> <h2> Hello, welcome to geeksforgeeks. </h2> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></body> </html>", "e": 52225, "s": 51453, "text": null }, { "code": null, "e": 52233, "s": 52225, "text": "Output:" }, { "code": null, "e": 52246, "s": 52233, "text": "Akanksha_Rai" }, { "code": null, "e": 52261, "s": 52246, "text": "sagar0719kumar" }, { "code": null, "e": 52273, "s": 52261, "text": "Semantic-UI" }, { "code": null, "e": 52277, "s": 52273, "text": "CSS" }, { "code": null, "e": 52294, "s": 52277, "text": "Web Technologies" }, { "code": null, "e": 52392, "s": 52294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52442, "s": 52392, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 52504, "s": 52442, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 52552, "s": 52504, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 52610, "s": 52552, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 52665, "s": 52610, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 52705, "s": 52665, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 52738, "s": 52705, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 52783, "s": 52738, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 52826, "s": 52783, "text": "How to fetch data from an API in ReactJS ?" } ]
How to calculate the Fibonacci series in JavaScript ? - GeeksforGeeks
13 Dec, 2021 Fibonacci series is a number series that contains integers in the following pattern. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, .. In terms of mathematics, the general formula for calculating the Fibonacci series is fn = fn-1 + fn-2 , where n ≥ 2 Here, f0 = 0 and f1 = 1. We need to calculate n Fibonacci numbers for any given integer n, where n≥0. Example: Input : n = 5 Output : [0, 1, 1, 2, 3] Input : n = 10 Output : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] In this article, we are focusing on two major and common ways for calculating the Fibonacci series. Using For loop and While loopUsing recursion Using For loop and While loop Using recursion Using Loop: The method of calculating Fibonacci Series using this method is better as compared to the recursive method. This method makes use of Dynamic Programming which works by storing the number generated so far and then using it for further calculations. As the number for n=1 and n=2 are fixed, i.e, 0 and 1, then the rest of the numbers in the series can be calculated by the logic, f3 = f2 + f1 f4 = f3 + f2 f5 = f4 + f3 ... fn = fn-1 + fn-2 This logic can be implemented using for as well as the while loop in JavaScript. Using for loop: As the first two values of the series are fixed, we start the loop with i = 2 and iterate until i < n, because array indexing starts at 0, so, n = 1 will technically mean i = 0 in case of arrays. HTML <script> const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); // Seed value for 1st element series[0] = 0; // Seed value for 2nd element series[1] = 1; for(let i = 2; i < n; i++) { // Apply basic Fibonacci formulae series[i] = series[i-1] + series[i-2]; } // Print the series console.log(series);</script> Output: Fibonacci series up till 10th element gets printed Using while loop: HTML <script> const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); // Seed value for 1st element series[0] = 0; // Seed value for 2nd element series[1] = 1; // Initialize the conditional variable let i = 2; while(i < n) { // Apply basic Fibonacci formulae series[i] = series[i-1] + series[i-2]; // Increment the conditional variable i++; } // Print the series console.log(series); </script> Output: Fibonacci series up till 10th element gets printed Using Recursion: The recursion method to print the whole Fibonacci series till a certain number is not recommended because, recursion algorithm itself is costly in terms of time and complexity, and along with fetching a Fibonacci series number at a certain position, we need to store them in an array, which calls the recursive function again and again for each and every element, i.e, n times! The recursion method can be applied as follows in JavaScript. HTML <script> function fibonacci(n){ if(n == 1) return 0; // Return value for n=1 if(n == 2) return 1; // Return value for n=2 // Recursive call return fibonacci(n-1) + fibonacci(n-2); } const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); for(let i = 1; i <= n; i++) { // Store i-th Fibonacci number series[i-1] = fibonacci(i); } // Print the series console.log(series);</script> Output: Fibonacci series up till 10th element gets printed JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n13 Dec, 2021" }, { "code": null, "e": 26630, "s": 26545, "text": "Fibonacci series is a number series that contains integers in the following pattern." }, { "code": null, "e": 26670, "s": 26630, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, .." }, { "code": null, "e": 26755, "s": 26670, "text": "In terms of mathematics, the general formula for calculating the Fibonacci series is" }, { "code": null, "e": 26786, "s": 26755, "text": "fn = fn-1 + fn-2 , where n ≥ 2" }, { "code": null, "e": 26811, "s": 26786, "text": "Here, f0 = 0 and f1 = 1." }, { "code": null, "e": 26888, "s": 26811, "text": "We need to calculate n Fibonacci numbers for any given integer n, where n≥0." }, { "code": null, "e": 26897, "s": 26888, "text": "Example:" }, { "code": null, "e": 27001, "s": 26897, "text": "Input : n = 5\nOutput : [0, 1, 1, 2, 3]\n\nInput : n = 10\nOutput : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" }, { "code": null, "e": 27101, "s": 27001, "text": "In this article, we are focusing on two major and common ways for calculating the Fibonacci series." }, { "code": null, "e": 27146, "s": 27101, "text": "Using For loop and While loopUsing recursion" }, { "code": null, "e": 27176, "s": 27146, "text": "Using For loop and While loop" }, { "code": null, "e": 27192, "s": 27176, "text": "Using recursion" }, { "code": null, "e": 27452, "s": 27192, "text": "Using Loop: The method of calculating Fibonacci Series using this method is better as compared to the recursive method. This method makes use of Dynamic Programming which works by storing the number generated so far and then using it for further calculations." }, { "code": null, "e": 27582, "s": 27452, "text": "As the number for n=1 and n=2 are fixed, i.e, 0 and 1, then the rest of the numbers in the series can be calculated by the logic," }, { "code": null, "e": 27642, "s": 27582, "text": "f3 = f2 + f1\nf4 = f3 + f2\nf5 = f4 + f3\n...\nfn = fn-1 + fn-2" }, { "code": null, "e": 27724, "s": 27642, "text": "This logic can be implemented using for as well as the while loop in JavaScript. " }, { "code": null, "e": 27936, "s": 27724, "text": "Using for loop: As the first two values of the series are fixed, we start the loop with i = 2 and iterate until i < n, because array indexing starts at 0, so, n = 1 will technically mean i = 0 in case of arrays." }, { "code": null, "e": 27941, "s": 27936, "text": "HTML" }, { "code": "<script> const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); // Seed value for 1st element series[0] = 0; // Seed value for 2nd element series[1] = 1; for(let i = 2; i < n; i++) { // Apply basic Fibonacci formulae series[i] = series[i-1] + series[i-2]; } // Print the series console.log(series);</script>", "e": 28413, "s": 27941, "text": null }, { "code": null, "e": 28421, "s": 28413, "text": "Output:" }, { "code": null, "e": 28472, "s": 28421, "text": "Fibonacci series up till 10th element gets printed" }, { "code": null, "e": 28490, "s": 28472, "text": "Using while loop:" }, { "code": null, "e": 28495, "s": 28490, "text": "HTML" }, { "code": "<script> const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); // Seed value for 1st element series[0] = 0; // Seed value for 2nd element series[1] = 1; // Initialize the conditional variable let i = 2; while(i < n) { // Apply basic Fibonacci formulae series[i] = series[i-1] + series[i-2]; // Increment the conditional variable i++; } // Print the series console.log(series); </script>", "e": 29087, "s": 28495, "text": null }, { "code": null, "e": 29095, "s": 29087, "text": "Output:" }, { "code": null, "e": 29146, "s": 29095, "text": "Fibonacci series up till 10th element gets printed" }, { "code": null, "e": 29541, "s": 29146, "text": "Using Recursion: The recursion method to print the whole Fibonacci series till a certain number is not recommended because, recursion algorithm itself is costly in terms of time and complexity, and along with fetching a Fibonacci series number at a certain position, we need to store them in an array, which calls the recursive function again and again for each and every element, i.e, n times!" }, { "code": null, "e": 29603, "s": 29541, "text": "The recursion method can be applied as follows in JavaScript." }, { "code": null, "e": 29608, "s": 29603, "text": "HTML" }, { "code": "<script> function fibonacci(n){ if(n == 1) return 0; // Return value for n=1 if(n == 2) return 1; // Return value for n=2 // Recursive call return fibonacci(n-1) + fibonacci(n-2); } const n = 10; // Create a new array of size 'n' var series = new Array(n); // Fills all places in array with 0 series.fill(0); for(let i = 1; i <= n; i++) { // Store i-th Fibonacci number series[i-1] = fibonacci(i); } // Print the series console.log(series);</script>", "e": 30163, "s": 29608, "text": null }, { "code": null, "e": 30171, "s": 30163, "text": "Output:" }, { "code": null, "e": 30222, "s": 30171, "text": "Fibonacci series up till 10th element gets printed" }, { "code": null, "e": 30243, "s": 30222, "text": "JavaScript-Questions" }, { "code": null, "e": 30250, "s": 30243, "text": "Picked" }, { "code": null, "e": 30261, "s": 30250, "text": "JavaScript" }, { "code": null, "e": 30278, "s": 30261, "text": "Web Technologies" }, { "code": null, "e": 30376, "s": 30278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30416, "s": 30376, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30477, "s": 30416, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30518, "s": 30477, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30540, "s": 30518, "text": "JavaScript | Promises" }, { "code": null, "e": 30594, "s": 30540, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30634, "s": 30594, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30667, "s": 30634, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30710, "s": 30667, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30760, "s": 30710, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python - Itertools.tee() - GeeksforGeeks
11 Jun, 2020 In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse(). Note: For more information, refer to Python Itertools This iterator splits the container into a number of iterators mentioned in the argument. Syntax: tee(iterator, count) Parameter: This method contains two arguments, the first argument is iterator and the second argument is a integer.Return Value: This method returns the number of iterators mentioned in the argument. Example 1: # Python code to demonstrate the working of tee() # importing "itertools" for iterator operations import itertools # initializing list li = [2, 4, 6, 7, 8, 10, 20] # storing list in iterator iti = iter(li) # using tee() to make a list of iterators # makes list of 3 iterators having same values. it = itertools.tee(iti, 3) # printing the values of iterators print ("The iterators are : ") for i in range (0, 3): print (list(it[i])) Output: The iterators are : [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20] Example 2: # Python code to demonstrate the working of tee() # importing "itertools" for iterator operations import itertools # using tee() to make a list of iterators iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2) # printing the values of iterators print (list(iterator1)) print (list(iterator1)) print (list(iterator2)) Output: [1, 2, 3, 4, 5, 6, 7] [] [1, 2, 3, 4, 5, 6, 7] Example 3: # Python code to demonstrate the working of tee() # importing "itertools" for iterator operations import itertools # using tee() to make a list of iterators for i in itertools.tee(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 4): # printing the values of iterators print (list(i)) Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] Picked Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe 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": "\n11 Jun, 2020" }, { "code": null, "e": 25764, "s": 25537, "text": "In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse()." }, { "code": null, "e": 25818, "s": 25764, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 25907, "s": 25818, "text": "This iterator splits the container into a number of iterators mentioned in the argument." }, { "code": null, "e": 25915, "s": 25907, "text": "Syntax:" }, { "code": null, "e": 25936, "s": 25915, "text": "tee(iterator, count)" }, { "code": null, "e": 26136, "s": 25936, "text": "Parameter: This method contains two arguments, the first argument is iterator and the second argument is a integer.Return Value: This method returns the number of iterators mentioned in the argument." }, { "code": null, "e": 26147, "s": 26136, "text": "Example 1:" }, { "code": "# Python code to demonstrate the working of tee() # importing \"itertools\" for iterator operations import itertools # initializing list li = [2, 4, 6, 7, 8, 10, 20] # storing list in iterator iti = iter(li) # using tee() to make a list of iterators # makes list of 3 iterators having same values. it = itertools.tee(iti, 3) # printing the values of iterators print (\"The iterators are : \") for i in range (0, 3): print (list(it[i])) ", "e": 26605, "s": 26147, "text": null }, { "code": null, "e": 26613, "s": 26605, "text": "Output:" }, { "code": null, "e": 26707, "s": 26613, "text": "The iterators are : \n[2, 4, 6, 7, 8, 10, 20]\n[2, 4, 6, 7, 8, 10, 20]\n[2, 4, 6, 7, 8, 10, 20]\n" }, { "code": null, "e": 26718, "s": 26707, "text": "Example 2:" }, { "code": "# Python code to demonstrate the working of tee() # importing \"itertools\" for iterator operations import itertools # using tee() to make a list of iterators iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2) # printing the values of iterators print (list(iterator1)) print (list(iterator1)) print (list(iterator2)) ", "e": 27062, "s": 26718, "text": null }, { "code": null, "e": 27070, "s": 27062, "text": "Output:" }, { "code": null, "e": 27118, "s": 27070, "text": "[1, 2, 3, 4, 5, 6, 7]\n[]\n[1, 2, 3, 4, 5, 6, 7]\n" }, { "code": null, "e": 27129, "s": 27118, "text": "Example 3:" }, { "code": "# Python code to demonstrate the working of tee() # importing \"itertools\" for iterator operations import itertools # using tee() to make a list of iterators for i in itertools.tee(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 4): # printing the values of iterators print (list(i))", "e": 27421, "s": 27129, "text": null }, { "code": null, "e": 27429, "s": 27421, "text": "Output:" }, { "code": null, "e": 27574, "s": 27429, "text": "['a', 'b', 'c', 'd', 'e', 'f', 'g']\n['a', 'b', 'c', 'd', 'e', 'f', 'g']\n['a', 'b', 'c', 'd', 'e', 'f', 'g']\n['a', 'b', 'c', 'd', 'e', 'f', 'g']\n" }, { "code": null, "e": 27581, "s": 27574, "text": "Picked" }, { "code": null, "e": 27598, "s": 27581, "text": "Python-itertools" }, { "code": null, "e": 27605, "s": 27598, "text": "Python" }, { "code": null, "e": 27703, "s": 27605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27735, "s": 27703, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27777, "s": 27735, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27819, "s": 27777, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27846, "s": 27819, "text": "Python Classes and Objects" }, { "code": null, "e": 27902, "s": 27846, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27941, "s": 27902, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27972, "s": 27941, "text": "Python | os.path.join() method" }, { "code": null, "e": 27994, "s": 27972, "text": "Defaultdict in Python" }, { "code": null, "e": 28023, "s": 27994, "text": "Create a directory in Python" } ]
Program to add two polynomials - GeeksforGeeks
03 Nov, 2021 Given two polynomials represented by two arrays, write a function that adds given two polynomials. Example: Input: A[] = {5, 0, 10, 6} B[] = {1, 2, 4} Output: sum[] = {6, 2, 14, 6} The first input array represents "5 + 0x^1 + 10x^2 + 6x^3" The second array represents "1 + 2x^1 + 4x^2" And Output is "6 + 2x^1 + 14x^2 + 6x^3" We strongly recommend to minimize your browser and try this yourself first. Addition is simpler than multiplication of polynomials. We initialize result as one of the two polynomials, then we traverse the other polynomial and add all terms to the result. add(A[0..m-1], B[0..n01]) 1) Create a sum array sum[] of size equal to maximum of 'm' and 'n' 2) Copy A[] to sum[]. 3) Traverse array B[] and do following for every element B[i] sum[i] = sum[i] + B[i] 4) Return sum[]. The following is implementation of above algorithm. C++ Java Python3 C# PHP Javascript // Simple C++ program to add two polynomials#include <iostream>using namespace std; // A utility function to return maximum of two integersint max(int m, int n) { return (m > n)? m: n; } // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyint *add(int A[], int B[], int m, int n){ int size = max(m, n); int *sum = new int[size]; // Initialize the product polynomial for (int i = 0; i<m; i++) sum[i] = A[i]; // Take ever term of first polynomial for (int i=0; i<n; i++) sum[i] += B[i]; return sum;} // A utility function to print a polynomialvoid printPoly(int poly[], int n){ for (int i=0; i<n; i++) { cout << poly[i]; if (i != 0) cout << "x^" << i ; if (i != n-1) cout << " + "; }} // Driver program to test above functionsint main(){ // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = sizeof(A)/sizeof(A[0]); int n = sizeof(B)/sizeof(B[0]); cout << "First polynomial is \n"; printPoly(A, m); cout << "\nSecond polynomial is \n"; printPoly(B, n); int *sum = add(A, B, m, n); int size = max(m, n); cout << "\nsum polynomial is \n"; printPoly(sum, size); return 0;} // Java program to add two polynomials class GFG { // A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; } // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively static int[] add(int A[], int B[], int m, int n) { int size = max(m, n); int sum[] = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; } // Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; } // A utility function to print a polynomial static void printPoly(int poly[], int n) { for (int i = 0; i < n; i++) { System.out.print(poly[i]); if (i != 0) { System.out.print("x^" + i); } if (i != n - 1) { System.out.print(" + "); } } } // Driver program to test above functions public static void main(String[] args) { // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = A.length; int n = B.length; System.out.println("First polynomial is"); printPoly(A, m); System.out.println("\nSecond polynomial is"); printPoly(B, n); int sum[] = add(A, B, m, n); int size = max(m, n); System.out.println("\nsum polynomial is"); printPoly(sum, size); }} # Simple Python 3 program to add two# polynomials # A utility function to return maximum# of two integers # A[] represents coefficients of first polynomial# B[] represents coefficients of second polynomial# m and n are sizes of A[] and B[] respectivelydef add(A, B, m, n): size = max(m, n); sum = [0 for i in range(size)] # Initialize the product polynomial for i in range(0, m, 1): sum[i] = A[i] # Take ever term of first polynomial for i in range(n): sum[i] += B[i] return sum # A utility function to print a polynomialdef printPoly(poly, n): for i in range(n): print(poly[i], end = "") if (i != 0): print("x^", i, end = "") if (i != n - 1): print(" + ", end = "") # Driver Codeif __name__ == '__main__': # The following array represents # polynomial 5 + 10x^2 + 6x^3 A = [5, 0, 10, 6] # The following array represents # polynomial 1 + 2x + 4x^2 B = [1, 2, 4] m = len(A) n = len(B) print("First polynomial is") printPoly(A, m) print("\n", end = "") print("Second polynomial is") printPoly(B, n) print("\n", end = "") sum = add(A, B, m, n) size = max(m, n) print("sum polynomial is") printPoly(sum, size) # This code is contributed by# Sahil_Shelangia // C# program to add two polynomialsusing System;class GFG { // A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; } // A[] represents coefficients of first polynomial // B[] represents coefficients of second polynomial // m and n are sizes of A[] and B[] respectively static int[] add(int[] A, int[] B, int m, int n) { int size = max(m, n); int[] sum = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; } // Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; } // A utility function to print a polynomial static void printPoly(int[] poly, int n) { for (int i = 0; i < n; i++) { Console.Write(poly[i]); if (i != 0) { Console.Write("x^" + i); } if (i != n - 1) { Console.Write(" + "); } } } // Driver code public static void Main() { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int[] A = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int[] B = {1, 2, 4}; int m = A.Length; int n = B.Length; Console.WriteLine("First polynomial is"); printPoly(A, m); Console.WriteLine("\nSecond polynomial is"); printPoly(B, n); int[] sum = add(A, B, m, n); int size = max(m, n); Console.WriteLine("\nsum polynomial is"); printPoly(sum, size); }} //This Code is Contributed// by Mukul Singh <?php// Simple PHP program to add two polynomials // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyfunction add($A, $B, $m, $n){ $size = max($m, $n); $sum = array_fill(0, $size, 0); // Initialize the product polynomial for ($i = 0; $i < $m; $i++) $sum[$i] = $A[$i]; // Take ever term of first polynomial for ($i = 0; $i < $n; $i++) $sum[$i] += $B[$i]; return $sum;} // A utility function to print a polynomialfunction printPoly($poly, $n){ for ($i = 0; $i < $n; $i++) { echo $poly[$i]; if ($i != 0) echo "x^" . $i; if ($i != $n - 1) echo " + "; }} // Driver Code // The following array represents// polynomial 5 + 10x^2 + 6x^3$A = array(5, 0, 10, 6); // The following array represents// polynomial 1 + 2x + 4x^2$B = array(1, 2, 4);$m = count($A);$n = count($B); echo "First polynomial is \n";printPoly($A, $m);echo "\nSecond polynomial is \n";printPoly($B, $n); $sum = add($A, $B, $m, $n);$size = max($m, $n); echo "\nsum polynomial is \n";printPoly($sum, $size); // This code is contributed by chandan_jnu?> <script> // Simple JavaScript program to add two// polynomials// A utility function to return maximum// of two integers // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively function add(A, B, m, n){ let size = Math.max(m, n); var sum = []; for (var i = 0; i < 10; i++) sum[i] = 0; // Initialize the product polynomial for(let i = 0;i<m;i++){ sum[i] = A[i]; } // Take ever term of first polynomial for (let i = 0;i<n;i++){ sum[i] += B[i]; } return sum; } // A utility function to print a polynomial function printPoly(poly, n){ let ans = ''; for(let i = 0;i<n;i++){ ans += poly[i]; if (i != 0){ ans +="x^ "; ans +=i; } if (i != n - 1){ ans += " + "; } } document.write(ans); } // Driver Code // The following array represents // polynomial 5 + 10x^2 + 6x^3 let A = [5, 0, 10, 6]; // The following array represents // polynomial 1 + 2x + 4x^2 let B = [1, 2, 4]; let m = A.length; let n = B.length; document.write("First polynomial is" + "</br>"); printPoly(A, m); document.write("</br>"); document.write("Second polynomial is" + "</br>"); printPoly(B, n); let sum = add(A, B, m, n); let size = Math.max(m, n); document.write("</br>"); document.write("sum polynomial is" + "</br>"); printPoly(sum, size); </script> Output: First polynomial is 5 + 0x^1 + 10x^2 + 6x^3 Second polynomial is 1 + 2x^1 + 4x^2 Sum polynomial is 6 + 2x^1 + 14x^2 + 6x^3 Time complexity of the above algorithm and program is O(m+n) where m and n are orders of two given polynomials. Auxiliary Space: O(max(m, n))This article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above maths-polynomial Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Sieve of Eratosthenes Operators in C / C++ Program for factorial of a number The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value
[ { "code": null, "e": 26439, "s": 26411, "text": "\n03 Nov, 2021" }, { "code": null, "e": 26549, "s": 26439, "text": "Given two polynomials represented by two arrays, write a function that adds given two polynomials. Example: " }, { "code": null, "e": 26780, "s": 26549, "text": "Input: A[] = {5, 0, 10, 6} \n B[] = {1, 2, 4} \nOutput: sum[] = {6, 2, 14, 6}\n\nThe first input array represents \"5 + 0x^1 + 10x^2 + 6x^3\"\nThe second array represents \"1 + 2x^1 + 4x^2\" \nAnd Output is \"6 + 2x^1 + 14x^2 + 6x^3\"" }, { "code": null, "e": 27036, "s": 26780, "text": "We strongly recommend to minimize your browser and try this yourself first. Addition is simpler than multiplication of polynomials. We initialize result as one of the two polynomials, then we traverse the other polynomial and add all terms to the result. " }, { "code": null, "e": 27264, "s": 27036, "text": "add(A[0..m-1], B[0..n01])\n1) Create a sum array sum[] of size equal to maximum of 'm' and 'n'\n2) Copy A[] to sum[].\n3) Traverse array B[] and do following for every element B[i]\n sum[i] = sum[i] + B[i]\n4) Return sum[]." }, { "code": null, "e": 27318, "s": 27264, "text": "The following is implementation of above algorithm. " }, { "code": null, "e": 27322, "s": 27318, "text": "C++" }, { "code": null, "e": 27327, "s": 27322, "text": "Java" }, { "code": null, "e": 27335, "s": 27327, "text": "Python3" }, { "code": null, "e": 27338, "s": 27335, "text": "C#" }, { "code": null, "e": 27342, "s": 27338, "text": "PHP" }, { "code": null, "e": 27353, "s": 27342, "text": "Javascript" }, { "code": "// Simple C++ program to add two polynomials#include <iostream>using namespace std; // A utility function to return maximum of two integersint max(int m, int n) { return (m > n)? m: n; } // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyint *add(int A[], int B[], int m, int n){ int size = max(m, n); int *sum = new int[size]; // Initialize the product polynomial for (int i = 0; i<m; i++) sum[i] = A[i]; // Take ever term of first polynomial for (int i=0; i<n; i++) sum[i] += B[i]; return sum;} // A utility function to print a polynomialvoid printPoly(int poly[], int n){ for (int i=0; i<n; i++) { cout << poly[i]; if (i != 0) cout << \"x^\" << i ; if (i != n-1) cout << \" + \"; }} // Driver program to test above functionsint main(){ // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = sizeof(A)/sizeof(A[0]); int n = sizeof(B)/sizeof(B[0]); cout << \"First polynomial is \\n\"; printPoly(A, m); cout << \"\\nSecond polynomial is \\n\"; printPoly(B, n); int *sum = add(A, B, m, n); int size = max(m, n); cout << \"\\nsum polynomial is \\n\"; printPoly(sum, size); return 0;}", "e": 28757, "s": 27353, "text": null }, { "code": "// Java program to add two polynomials class GFG { // A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; } // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively static int[] add(int A[], int B[], int m, int n) { int size = max(m, n); int sum[] = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; } // Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; } // A utility function to print a polynomial static void printPoly(int poly[], int n) { for (int i = 0; i < n; i++) { System.out.print(poly[i]); if (i != 0) { System.out.print(\"x^\" + i); } if (i != n - 1) { System.out.print(\" + \"); } } } // Driver program to test above functions public static void main(String[] args) { // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = A.length; int n = B.length; System.out.println(\"First polynomial is\"); printPoly(A, m); System.out.println(\"\\nSecond polynomial is\"); printPoly(B, n); int sum[] = add(A, B, m, n); int size = max(m, n); System.out.println(\"\\nsum polynomial is\"); printPoly(sum, size); }}", "e": 30422, "s": 28757, "text": null }, { "code": "# Simple Python 3 program to add two# polynomials # A utility function to return maximum# of two integers # A[] represents coefficients of first polynomial# B[] represents coefficients of second polynomial# m and n are sizes of A[] and B[] respectivelydef add(A, B, m, n): size = max(m, n); sum = [0 for i in range(size)] # Initialize the product polynomial for i in range(0, m, 1): sum[i] = A[i] # Take ever term of first polynomial for i in range(n): sum[i] += B[i] return sum # A utility function to print a polynomialdef printPoly(poly, n): for i in range(n): print(poly[i], end = \"\") if (i != 0): print(\"x^\", i, end = \"\") if (i != n - 1): print(\" + \", end = \"\") # Driver Codeif __name__ == '__main__': # The following array represents # polynomial 5 + 10x^2 + 6x^3 A = [5, 0, 10, 6] # The following array represents # polynomial 1 + 2x + 4x^2 B = [1, 2, 4] m = len(A) n = len(B) print(\"First polynomial is\") printPoly(A, m) print(\"\\n\", end = \"\") print(\"Second polynomial is\") printPoly(B, n) print(\"\\n\", end = \"\") sum = add(A, B, m, n) size = max(m, n) print(\"sum polynomial is\") printPoly(sum, size) # This code is contributed by# Sahil_Shelangia", "e": 31731, "s": 30422, "text": null }, { "code": "// C# program to add two polynomialsusing System;class GFG { // A utility function to return maximum of two integers static int max(int m, int n) { return (m > n) ? m : n; } // A[] represents coefficients of first polynomial // B[] represents coefficients of second polynomial // m and n are sizes of A[] and B[] respectively static int[] add(int[] A, int[] B, int m, int n) { int size = max(m, n); int[] sum = new int[size]; // Initialize the product polynomial for (int i = 0; i < m; i++) { sum[i] = A[i]; } // Take ever term of first polynomial for (int i = 0; i < n; i++) { sum[i] += B[i]; } return sum; } // A utility function to print a polynomial static void printPoly(int[] poly, int n) { for (int i = 0; i < n; i++) { Console.Write(poly[i]); if (i != 0) { Console.Write(\"x^\" + i); } if (i != n - 1) { Console.Write(\" + \"); } } } // Driver code public static void Main() { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int[] A = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int[] B = {1, 2, 4}; int m = A.Length; int n = B.Length; Console.WriteLine(\"First polynomial is\"); printPoly(A, m); Console.WriteLine(\"\\nSecond polynomial is\"); printPoly(B, n); int[] sum = add(A, B, m, n); int size = max(m, n); Console.WriteLine(\"\\nsum polynomial is\"); printPoly(sum, size); }} //This Code is Contributed// by Mukul Singh", "e": 33514, "s": 31731, "text": null }, { "code": "<?php// Simple PHP program to add two polynomials // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyfunction add($A, $B, $m, $n){ $size = max($m, $n); $sum = array_fill(0, $size, 0); // Initialize the product polynomial for ($i = 0; $i < $m; $i++) $sum[$i] = $A[$i]; // Take ever term of first polynomial for ($i = 0; $i < $n; $i++) $sum[$i] += $B[$i]; return $sum;} // A utility function to print a polynomialfunction printPoly($poly, $n){ for ($i = 0; $i < $n; $i++) { echo $poly[$i]; if ($i != 0) echo \"x^\" . $i; if ($i != $n - 1) echo \" + \"; }} // Driver Code // The following array represents// polynomial 5 + 10x^2 + 6x^3$A = array(5, 0, 10, 6); // The following array represents// polynomial 1 + 2x + 4x^2$B = array(1, 2, 4);$m = count($A);$n = count($B); echo \"First polynomial is \\n\";printPoly($A, $m);echo \"\\nSecond polynomial is \\n\";printPoly($B, $n); $sum = add($A, $B, $m, $n);$size = max($m, $n); echo \"\\nsum polynomial is \\n\";printPoly($sum, $size); // This code is contributed by chandan_jnu?>", "e": 34721, "s": 33514, "text": null }, { "code": "<script> // Simple JavaScript program to add two// polynomials// A utility function to return maximum// of two integers // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectively function add(A, B, m, n){ let size = Math.max(m, n); var sum = []; for (var i = 0; i < 10; i++) sum[i] = 0; // Initialize the product polynomial for(let i = 0;i<m;i++){ sum[i] = A[i]; } // Take ever term of first polynomial for (let i = 0;i<n;i++){ sum[i] += B[i]; } return sum; } // A utility function to print a polynomial function printPoly(poly, n){ let ans = ''; for(let i = 0;i<n;i++){ ans += poly[i]; if (i != 0){ ans +=\"x^ \"; ans +=i; } if (i != n - 1){ ans += \" + \"; } } document.write(ans); } // Driver Code // The following array represents // polynomial 5 + 10x^2 + 6x^3 let A = [5, 0, 10, 6]; // The following array represents // polynomial 1 + 2x + 4x^2 let B = [1, 2, 4]; let m = A.length; let n = B.length; document.write(\"First polynomial is\" + \"</br>\"); printPoly(A, m); document.write(\"</br>\"); document.write(\"Second polynomial is\" + \"</br>\"); printPoly(B, n); let sum = add(A, B, m, n); let size = Math.max(m, n); document.write(\"</br>\"); document.write(\"sum polynomial is\" + \"</br>\"); printPoly(sum, size); </script>", "e": 36238, "s": 34721, "text": null }, { "code": null, "e": 36247, "s": 36238, "text": "Output: " }, { "code": null, "e": 36370, "s": 36247, "text": "First polynomial is\n5 + 0x^1 + 10x^2 + 6x^3\nSecond polynomial is\n1 + 2x^1 + 4x^2\nSum polynomial is\n6 + 2x^1 + 14x^2 + 6x^3" }, { "code": null, "e": 36482, "s": 36370, "text": "Time complexity of the above algorithm and program is O(m+n) where m and n are orders of two given polynomials." }, { "code": null, "e": 36674, "s": 36482, "text": "Auxiliary Space: O(max(m, n))This article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36691, "s": 36674, "text": "maths-polynomial" }, { "code": null, "e": 36704, "s": 36691, "text": "Mathematical" }, { "code": null, "e": 36717, "s": 36704, "text": "Mathematical" }, { "code": null, "e": 36815, "s": 36717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36839, "s": 36815, "text": "Merge two sorted arrays" }, { "code": null, "e": 36882, "s": 36839, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36896, "s": 36882, "text": "Prime Numbers" }, { "code": null, "e": 36938, "s": 36896, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 37011, "s": 36938, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 37033, "s": 37011, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 37054, "s": 37033, "text": "Operators in C / C++" }, { "code": null, "e": 37088, "s": 37054, "text": "Program for factorial of a number" }, { "code": null, "e": 37131, "s": 37088, "text": "The Knight's tour problem | Backtracking-1" } ]
SimpleDateFormat applyPattern() Method in Java with Examples - GeeksforGeeks
08 Jul, 2021 The applyPattern() Method of SimpleDateFormat class is used to set a given defined pattern to the Date Format. It simply converts a particular date and time to a specific format as defined by the user for eg., dd/ MM/ yyyy HH:mm Z or MM/ dd/ yyyy HH:mm Z.Syntax: public void applyPattern(String pattern) Parameters: The method takes one parameter pattern of String type and refers to the new date and time pattern for this date format.Return Value: The method returns void type.Below programs illustrate the working of applyPattern() Method of SimpleDateFormat:Example 1: Java // Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDFormat = new SimpleDateFormat(); // Initializing the calendar Object Calendar cal = Calendar.getInstance(); // Using the below pattern String new_pat = "dd/ MM/ yyyy HH:mm Z"; // Use of applyPattern() method SDFormat.applyPattern(new_pat); // Displaying Current date and time String curr_date = SDFormat.format(cal.getTime()); System.out.println("The Current Date: " + curr_date); // Displaying the pattern System.out.println("Applied Pattern: " + SDFormat.toPattern()); }} The Current Date: 29/ 01/ 2019 07:22 +0000 Applied Pattern: dd/ MM/ yyyy HH:mm Z Example 2: Java // Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDFormat = new SimpleDateFormat(); // Initializing the calendar Object Calendar cal = Calendar.getInstance(); // Using the below pattern String new_pat = "MM/ dd/ yyyy HH:mm Z"; // Use of applyPattern() method SDFormat.applyPattern(new_pat); // Displaying Current date and time String curr_date = SDFormat.format(cal.getTime()); System.out.println("The Current Date: " + curr_date); // Displaying the pattern System.out.println("Applied Pattern: " + SDFormat.toPattern()); }} The Current Date: 01/ 29/ 2019 07:22 +0000 Applied Pattern: MM/ dd/ yyyy HH:mm Z clintra Java-Functions Java-SimpleDateFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n08 Jul, 2021" }, { "code": null, "e": 25490, "s": 25225, "text": "The applyPattern() Method of SimpleDateFormat class is used to set a given defined pattern to the Date Format. It simply converts a particular date and time to a specific format as defined by the user for eg., dd/ MM/ yyyy HH:mm Z or MM/ dd/ yyyy HH:mm Z.Syntax: " }, { "code": null, "e": 25531, "s": 25490, "text": "public void applyPattern(String pattern)" }, { "code": null, "e": 25801, "s": 25531, "text": "Parameters: The method takes one parameter pattern of String type and refers to the new date and time pattern for this date format.Return Value: The method returns void type.Below programs illustrate the working of applyPattern() Method of SimpleDateFormat:Example 1: " }, { "code": null, "e": 25806, "s": 25801, "text": "Java" }, { "code": "// Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDFormat = new SimpleDateFormat(); // Initializing the calendar Object Calendar cal = Calendar.getInstance(); // Using the below pattern String new_pat = \"dd/ MM/ yyyy HH:mm Z\"; // Use of applyPattern() method SDFormat.applyPattern(new_pat); // Displaying Current date and time String curr_date = SDFormat.format(cal.getTime()); System.out.println(\"The Current Date: \" + curr_date); // Displaying the pattern System.out.println(\"Applied Pattern: \" + SDFormat.toPattern()); }}", "e": 26683, "s": 25806, "text": null }, { "code": null, "e": 26764, "s": 26683, "text": "The Current Date: 29/ 01/ 2019 07:22 +0000\nApplied Pattern: dd/ MM/ yyyy HH:mm Z" }, { "code": null, "e": 26779, "s": 26766, "text": "Example 2: " }, { "code": null, "e": 26784, "s": 26779, "text": "Java" }, { "code": "// Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDFormat = new SimpleDateFormat(); // Initializing the calendar Object Calendar cal = Calendar.getInstance(); // Using the below pattern String new_pat = \"MM/ dd/ yyyy HH:mm Z\"; // Use of applyPattern() method SDFormat.applyPattern(new_pat); // Displaying Current date and time String curr_date = SDFormat.format(cal.getTime()); System.out.println(\"The Current Date: \" + curr_date); // Displaying the pattern System.out.println(\"Applied Pattern: \" + SDFormat.toPattern()); }}", "e": 27660, "s": 26784, "text": null }, { "code": null, "e": 27741, "s": 27660, "text": "The Current Date: 01/ 29/ 2019 07:22 +0000\nApplied Pattern: MM/ dd/ yyyy HH:mm Z" }, { "code": null, "e": 27751, "s": 27743, "text": "clintra" }, { "code": null, "e": 27766, "s": 27751, "text": "Java-Functions" }, { "code": null, "e": 27788, "s": 27766, "text": "Java-SimpleDateFormat" }, { "code": null, "e": 27806, "s": 27788, "text": "Java-text package" }, { "code": null, "e": 27811, "s": 27806, "text": "Java" }, { "code": null, "e": 27816, "s": 27811, "text": "Java" }, { "code": null, "e": 27914, "s": 27816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27929, "s": 27914, "text": "Stream In Java" }, { "code": null, "e": 27950, "s": 27929, "text": "Constructors in Java" }, { "code": null, "e": 27969, "s": 27950, "text": "Exceptions in Java" }, { "code": null, "e": 27999, "s": 27969, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28045, "s": 27999, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28062, "s": 28045, "text": "Generics in Java" }, { "code": null, "e": 28083, "s": 28062, "text": "Introduction to Java" }, { "code": null, "e": 28126, "s": 28083, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28162, "s": 28126, "text": "Internal Working of HashMap in Java" } ]
Program to print 'N' alphabet using the number pattern from 1 to n - GeeksforGeeks
15 Apr, 2021 Given an integer N, the task is to print the Alphabet N Pattern as given below: 1 1 2 2 2 3 3 3 * * * * * * * * * N N Examples: Input: N = 6 Output: 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 Input: N = 5 Output: 1 1 2 2 2 3 3 3 4 4 4 5 5 Approach: Except the first and the last row, every other row will follow the following: Print the first value as index + 1 where index is the index of the row. Then print blank spaces 2 * index times. Again print the value index + 1 as the diagonal element for the current row. Then print the rest of the 2 * (N – index – 1) blank spaces followed by the ending element which is again index + 1. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to print the desired Alphabet N Patternvoid Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values cout << Left++; // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) cout << " "; // Condition for the diagonals if (index != 0 && index != N - 1) cout << Diagonal++; else cout << " "; // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) cout << " "; // For the right values cout << Right++; cout << endl; }} // Driver Codeint main(int argc, char** argv){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);} // C implementation of the approach#include <stdio.h> // Function to print the desired Alphabet N Patternvoid Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values printf("%d", Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) printf(" "); // Condition for the diagonals if (index != 0 && index != N - 1) printf("%d", Diagonal++); else printf(" "); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) printf(" "); // For the right values printf("%d", Right++); printf("\n"); }} // Driver Codeint main(int argc, char** argv){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);} // Java implementation of the approachimport java.util.*; class solution{ // Function to print the desired Alphabet N Patternstatic void Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values System.out.print(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) System.out.print(" "); // Condition for the diagonals if (index != 0 && index != N - 1) System.out.print(Diagonal++); else System.out.print(" "); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) System.out.print(" "); // For the right values System.out.print(Right++); System.out.println(); }} // Driver Codepublic static void main(String args[]){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);} } // This code is contributed by// Surendra_Gagwar # Python 3 implementation of the approach # Function to print the desired# Alphabet N Patterndef Alphabet_N_Pattern(N): # Declaring the values of Right, Left # and Diagonal values Right = 1 Left = 1 Diagonal = 2 # Main Loop for the rows for index in range(N): # For the left Values print(Left, end = "") Left += 1 # Spaces for the diagonals for side_index in range(0, 2 * (index), 1): print(" ", end = "") # Condition for the diagonals if (index != 0 and index != N - 1): print(Diagonal, end = "") Diagonal += 1 else: print(" ", end = "") # Spaces for the Right Values for side_index in range(0, 2 * (N - index - 1), 1): print(" ", end = "") # For the right values print(Right, end = "") Right += 1 print("\n", end = "") # Driver Codeif __name__ == '__main__': # Size of the Pattern Size = 6 # Calling the function to print # the desired Pattern Alphabet_N_Pattern(Size) # This code is contributed by# Sanjit_Prasad // C# implementation of the approachusing System; class GFG{ // Function to print the desired Alphabet N Patternpublic static void Alphabet_N_Pattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values Console.Write(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) Console.Write(" "); // Condition for the diagonals if (index != 0 && index != N - 1) Console.Write(Diagonal++); else Console.Write(" "); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) Console.Write(" "); // For the right values Console.Write(Right++); Console.Write("\n"); }} // Driver Codestatic void Main(){ // Size of the Pattern int Size = 6; // Calling the function to print // the desired Pattern Alphabet_N_Pattern(Size);}} // This code is contributed by DrRoot_ <?php// PHP implementation of the approach // Function to print the desired// Alphabet N Patternfunction Alphabet_N_Pattern($N){ $index; $side_index; $size; // Declaring the values of Right, // Left and Diagonal values $Right = 1; $Left = 1; $Diagonal = 2; // Main Loop for the rows for ($index = 0; $index < $N; $index++) { // For the left Values echo $Left++; // Spaces for the diagonals for ($side_index = 0; $side_index < 2 * ($index); $side_index++) echo " "; // Condition for the diagonals if ($index != 0 && $index != $N - 1) echo $Diagonal++; else echo " "; // Spaces for the Right Values for ($side_index = 0; $side_index < 2 * ($N - $index - 1); $side_index++) echo " "; // For the right values echo $Right++; echo "\n"; }} // Driver Code // Size of the Pattern$Size = 6; // Calling the function to// print the desired PatternAlphabet_N_Pattern($Size); // This code is contributed by ajit?> <script> // JavaScript implementation of the approach // Function to print the desired // Alphabet N Pattern function Alphabet_N_Pattern(N) { var index, side_index, size; // Declaring the values of Right, // Left and Diagonal values var Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values document.write(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * index; side_index++) document.write(" "); // Condition for the diagonals if (index != 0 && index != N - 1) document.write(Diagonal++); else document.write(" "); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) document.write(" "); // For the right values document.write(Right++); document.write("<br>"); } } // Driver Code // Size of the Pattern var Size = 6; // Calling the function to print // the desired Pattern Alphabet_N_Pattern(Size); </script> 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 jit_t SURENDRA_GANGWAR DrRoot_ Sanjit_Prasad rdtank pattern-printing Mathematical School Programming Mathematical pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25721, "s": 25693, "text": "\n15 Apr, 2021" }, { "code": null, "e": 25802, "s": 25721, "text": "Given an integer N, the task is to print the Alphabet N Pattern as given below: " }, { "code": null, "e": 25900, "s": 25802, "text": "1 1\n2 2 2\n3 3 3\n* * *\n* * *\n* * *\nN N" }, { "code": null, "e": 25912, "s": 25900, "text": "Examples: " }, { "code": null, "e": 26099, "s": 25912, "text": "Input: N = 6\nOutput:\n1 1\n2 2 2\n3 3 3\n4 4 4\n5 5 5\n6 6\n\nInput: N = 5\nOutput:\n1 1\n2 2 2\n3 3 3\n4 4 4\n5 5" }, { "code": null, "e": 26191, "s": 26101, "text": "Approach: Except the first and the last row, every other row will follow the following: " }, { "code": null, "e": 26263, "s": 26191, "text": "Print the first value as index + 1 where index is the index of the row." }, { "code": null, "e": 26304, "s": 26263, "text": "Then print blank spaces 2 * index times." }, { "code": null, "e": 26381, "s": 26304, "text": "Again print the value index + 1 as the diagonal element for the current row." }, { "code": null, "e": 26498, "s": 26381, "text": "Then print the rest of the 2 * (N – index – 1) blank spaces followed by the ending element which is again index + 1." }, { "code": null, "e": 26551, "s": 26498, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26555, "s": 26551, "text": "C++" }, { "code": null, "e": 26557, "s": 26555, "text": "C" }, { "code": null, "e": 26562, "s": 26557, "text": "Java" }, { "code": null, "e": 26570, "s": 26562, "text": "Python3" }, { "code": null, "e": 26573, "s": 26570, "text": "C#" }, { "code": null, "e": 26577, "s": 26573, "text": "PHP" }, { "code": null, "e": 26588, "s": 26577, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to print the desired Alphabet N Patternvoid Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values cout << Left++; // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) cout << \" \"; // Condition for the diagonals if (index != 0 && index != N - 1) cout << Diagonal++; else cout << \" \"; // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) cout << \" \"; // For the right values cout << Right++; cout << endl; }} // Driver Codeint main(int argc, char** argv){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);}", "e": 27686, "s": 26588, "text": null }, { "code": "// C implementation of the approach#include <stdio.h> // Function to print the desired Alphabet N Patternvoid Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values printf(\"%d\", Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) printf(\" \"); // Condition for the diagonals if (index != 0 && index != N - 1) printf(\"%d\", Diagonal++); else printf(\" \"); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) printf(\" \"); // For the right values printf(\"%d\", Right++); printf(\"\\n\"); }} // Driver Codeint main(int argc, char** argv){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);}", "e": 28779, "s": 27686, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class solution{ // Function to print the desired Alphabet N Patternstatic void Alphabet_N_Pattern(int N){ int index, side_index, size; // Declaring the values of Right, Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values System.out.print(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) System.out.print(\" \"); // Condition for the diagonals if (index != 0 && index != N - 1) System.out.print(Diagonal++); else System.out.print(\" \"); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) System.out.print(\" \"); // For the right values System.out.print(Right++); System.out.println(); }} // Driver Codepublic static void main(String args[]){ // Size of the Pattern int Size = 6; // Calling the function to print the desired Pattern Alphabet_N_Pattern(Size);} } // This code is contributed by// Surendra_Gagwar", "e": 30008, "s": 28779, "text": null }, { "code": "# Python 3 implementation of the approach # Function to print the desired# Alphabet N Patterndef Alphabet_N_Pattern(N): # Declaring the values of Right, Left # and Diagonal values Right = 1 Left = 1 Diagonal = 2 # Main Loop for the rows for index in range(N): # For the left Values print(Left, end = \"\") Left += 1 # Spaces for the diagonals for side_index in range(0, 2 * (index), 1): print(\" \", end = \"\") # Condition for the diagonals if (index != 0 and index != N - 1): print(Diagonal, end = \"\") Diagonal += 1 else: print(\" \", end = \"\") # Spaces for the Right Values for side_index in range(0, 2 * (N - index - 1), 1): print(\" \", end = \"\") # For the right values print(Right, end = \"\") Right += 1 print(\"\\n\", end = \"\") # Driver Codeif __name__ == '__main__': # Size of the Pattern Size = 6 # Calling the function to print # the desired Pattern Alphabet_N_Pattern(Size) # This code is contributed by# Sanjit_Prasad", "e": 31151, "s": 30008, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print the desired Alphabet N Patternpublic static void Alphabet_N_Pattern(int N){ int index, side_index; // Declaring the values of Right, // Left and Diagonal values int Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values Console.Write(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * (index); side_index++) Console.Write(\" \"); // Condition for the diagonals if (index != 0 && index != N - 1) Console.Write(Diagonal++); else Console.Write(\" \"); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) Console.Write(\" \"); // For the right values Console.Write(Right++); Console.Write(\"\\n\"); }} // Driver Codestatic void Main(){ // Size of the Pattern int Size = 6; // Calling the function to print // the desired Pattern Alphabet_N_Pattern(Size);}} // This code is contributed by DrRoot_", "e": 32388, "s": 31151, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the desired// Alphabet N Patternfunction Alphabet_N_Pattern($N){ $index; $side_index; $size; // Declaring the values of Right, // Left and Diagonal values $Right = 1; $Left = 1; $Diagonal = 2; // Main Loop for the rows for ($index = 0; $index < $N; $index++) { // For the left Values echo $Left++; // Spaces for the diagonals for ($side_index = 0; $side_index < 2 * ($index); $side_index++) echo \" \"; // Condition for the diagonals if ($index != 0 && $index != $N - 1) echo $Diagonal++; else echo \" \"; // Spaces for the Right Values for ($side_index = 0; $side_index < 2 * ($N - $index - 1); $side_index++) echo \" \"; // For the right values echo $Right++; echo \"\\n\"; }} // Driver Code // Size of the Pattern$Size = 6; // Calling the function to// print the desired PatternAlphabet_N_Pattern($Size); // This code is contributed by ajit?>", "e": 33509, "s": 32388, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to print the desired // Alphabet N Pattern function Alphabet_N_Pattern(N) { var index, side_index, size; // Declaring the values of Right, // Left and Diagonal values var Right = 1, Left = 1, Diagonal = 2; // Main Loop for the rows for (index = 0; index < N; index++) { // For the left Values document.write(Left++); // Spaces for the diagonals for (side_index = 0; side_index < 2 * index; side_index++) document.write(\" \"); // Condition for the diagonals if (index != 0 && index != N - 1) document.write(Diagonal++); else document.write(\" \"); // Spaces for the Right Values for (side_index = 0; side_index < 2 * (N - index - 1); side_index++) document.write(\" \"); // For the right values document.write(Right++); document.write(\"<br>\"); } } // Driver Code // Size of the Pattern var Size = 6; // Calling the function to print // the desired Pattern Alphabet_N_Pattern(Size); </script>", "e": 34767, "s": 33509, "text": null }, { "code": null, "e": 34851, "s": 34767, "text": "1 1\n2 2 2\n3 3 3\n4 4 4\n5 5 5\n6 6" }, { "code": null, "e": 34859, "s": 34853, "text": "jit_t" }, { "code": null, "e": 34876, "s": 34859, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34884, "s": 34876, "text": "DrRoot_" }, { "code": null, "e": 34898, "s": 34884, "text": "Sanjit_Prasad" }, { "code": null, "e": 34905, "s": 34898, "text": "rdtank" }, { "code": null, "e": 34922, "s": 34905, "text": "pattern-printing" }, { "code": null, "e": 34935, "s": 34922, "text": "Mathematical" }, { "code": null, "e": 34954, "s": 34935, "text": "School Programming" }, { "code": null, "e": 34967, "s": 34954, "text": "Mathematical" }, { "code": null, "e": 34984, "s": 34967, "text": "pattern-printing" }, { "code": null, "e": 35082, "s": 34984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35106, "s": 35082, "text": "Merge two sorted arrays" }, { "code": null, "e": 35149, "s": 35106, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35163, "s": 35149, "text": "Prime Numbers" }, { "code": null, "e": 35205, "s": 35163, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 35278, "s": 35205, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35296, "s": 35278, "text": "Python Dictionary" }, { "code": null, "e": 35312, "s": 35296, "text": "Arrays in C/C++" }, { "code": null, "e": 35331, "s": 35312, "text": "Inheritance in C++" }, { "code": null, "e": 35356, "s": 35331, "text": "Reverse a string in Java" } ]
JavaScript Date toLocaleTimeString() Method - GeeksforGeeks
22 Oct, 2021 Below is the example of Date toLocaleTimeString() method. Example:<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 16, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script> <script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 16, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script> Output:5:35:32 5:35:32 The date.toLocaleTimeString() method is used to fetch the time from a given Date object.Syntax: DateObj.toLocaleTimeString() Parameter: This method does not accept any parameter. It is just used along with a Date Object from which we want to fetch the time. Return Values: It returns a string which is time from given Date object. Note: The DateObj is a valid Date object created using Date() constructor from which we want to fetch the time. More codes for the above method are as follows: PRogram 1: The date of the month should lie in between 1 to 31 because none of the months have the date greater than 31 that is why it returns Invalid Date because the date for the month does not exist. Hence, Year will not have existed when the date of the month is given as 36 i.e, greater than 31. <script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 36, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script> Output: Invalid Date Program 2: If nothing as parameter is given to the Date() constructor the current date is passed in Date object and hence toLocaleTimeString() will return current time. <script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script> Output: The time returned in this program is Current time 4:09:16 Supported Browsers: The browsers supported by JavaScript Date toLocaleTimeString() Method are listed below: Google Chrome 1and above Edge 12 and above Firefox 1 and above Internet Explorer 5.5 and above Opera 5 and above Safari 1 and above ysachin2314 javascript-date JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26545, "s": 26517, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26603, "s": 26545, "text": "Below is the example of Date toLocaleTimeString() method." }, { "code": null, "e": 26913, "s": 26603, "text": "Example:<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 16, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script>" }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 16, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script>", "e": 27215, "s": 26913, "text": null }, { "code": null, "e": 27231, "s": 27215, "text": "Output:5:35:32 " }, { "code": null, "e": 27240, "s": 27231, "text": "5:35:32 " }, { "code": null, "e": 27336, "s": 27240, "text": "The date.toLocaleTimeString() method is used to fetch the time from a given Date object.Syntax:" }, { "code": null, "e": 27365, "s": 27336, "text": "DateObj.toLocaleTimeString()" }, { "code": null, "e": 27498, "s": 27365, "text": "Parameter: This method does not accept any parameter. It is just used along with a Date Object from which we want to fetch the time." }, { "code": null, "e": 27571, "s": 27498, "text": "Return Values: It returns a string which is time from given Date object." }, { "code": null, "e": 27683, "s": 27571, "text": "Note: The DateObj is a valid Date object created using Date() constructor from which we want to fetch the time." }, { "code": null, "e": 27731, "s": 27683, "text": "More codes for the above method are as follows:" }, { "code": null, "e": 28032, "s": 27731, "text": "PRogram 1: The date of the month should lie in between 1 to 31 because none of the months have the date greater than 31 that is why it returns Invalid Date because the date for the month does not exist. Hence, Year will not have existed when the date of the month is given as 36 i.e, greater than 31." }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('July 36, 2018 05:35:32'); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script>", "e": 28337, "s": 28032, "text": null }, { "code": null, "e": 28345, "s": 28337, "text": "Output:" }, { "code": null, "e": 28358, "s": 28345, "text": "Invalid Date" }, { "code": null, "e": 28527, "s": 28358, "text": "Program 2: If nothing as parameter is given to the Date() constructor the current date is passed in Date object and hence toLocaleTimeString() will return current time." }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date(); // time from above date object is // being extracted using toLocaleTimeString() var B = dateobj.toLocaleTimeString(); // Printing time document.write(B); </script>", "e": 28807, "s": 28527, "text": null }, { "code": null, "e": 28865, "s": 28807, "text": "Output: The time returned in this program is Current time" }, { "code": null, "e": 28875, "s": 28865, "text": "4:09:16 \n" }, { "code": null, "e": 28983, "s": 28875, "text": "Supported Browsers: The browsers supported by JavaScript Date toLocaleTimeString() Method are listed below:" }, { "code": null, "e": 29008, "s": 28983, "text": "Google Chrome 1and above" }, { "code": null, "e": 29026, "s": 29008, "text": "Edge 12 and above" }, { "code": null, "e": 29046, "s": 29026, "text": "Firefox 1 and above" }, { "code": null, "e": 29078, "s": 29046, "text": "Internet Explorer 5.5 and above" }, { "code": null, "e": 29096, "s": 29078, "text": "Opera 5 and above" }, { "code": null, "e": 29115, "s": 29096, "text": "Safari 1 and above" }, { "code": null, "e": 29127, "s": 29115, "text": "ysachin2314" }, { "code": null, "e": 29143, "s": 29127, "text": "javascript-date" }, { "code": null, "e": 29162, "s": 29143, "text": "JavaScript-Methods" }, { "code": null, "e": 29173, "s": 29162, "text": "JavaScript" }, { "code": null, "e": 29190, "s": 29173, "text": "Web Technologies" }, { "code": null, "e": 29288, "s": 29190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29328, "s": 29288, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29389, "s": 29328, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29430, "s": 29389, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29452, "s": 29430, "text": "JavaScript | Promises" }, { "code": null, "e": 29506, "s": 29452, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29546, "s": 29506, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29579, "s": 29546, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29622, "s": 29579, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29684, "s": 29622, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
PL/SQL - EXIT Statement
The EXIT statement in PL/SQL programming language has the following two usages − When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block. If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block. The syntax for an EXIT statement in PL/SQL is as follows − EXIT; DECLARE a number(2) := 10; BEGIN -- while loop execution WHILE a < 20 LOOP dbms_output.put_line ('value of a: ' || a); a := a + 1; IF a > 15 THEN -- terminate the loop using the exit statement EXIT; END IF; END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 PL/SQL procedure successfully completed. The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the condition is true, the loop completes and control passes to the statement immediately after the END LOOP. Following are the two important aspects for the EXIT WHEN statement − Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop. Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop. A statement inside the loop must change the value of the condition. A statement inside the loop must change the value of the condition. The syntax for an EXIT WHEN statement in PL/SQL is as follows − EXIT WHEN condition; The EXIT WHEN statement replaces a conditional statement like if-then used with the EXIT statement. DECLARE a number(2) := 10; BEGIN -- while loop execution WHILE a < 20 LOOP dbms_output.put_line ('value of a: ' || a); a := a + 1; -- terminate the loop using the exit when statement EXIT WHEN a > 15; END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 PL/SQL procedure successfully completed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2146, "s": 2065, "text": "The EXIT statement in PL/SQL programming language has the following two usages −" }, { "code": null, "e": 2309, "s": 2146, "text": "When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 2472, "s": 2309, "text": "When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 2664, "s": 2472, "text": "If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block." }, { "code": null, "e": 2856, "s": 2664, "text": "If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block." }, { "code": null, "e": 2915, "s": 2856, "text": "The syntax for an EXIT statement in PL/SQL is as follows −" }, { "code": null, "e": 2922, "s": 2915, "text": "EXIT;\n" }, { "code": null, "e": 3215, "s": 2922, "text": "DECLARE \n a number(2) := 10; \nBEGIN \n -- while loop execution \n WHILE a < 20 LOOP \n dbms_output.put_line ('value of a: ' || a); \n a := a + 1; \n IF a > 15 THEN \n -- terminate the loop using the exit statement \n EXIT; \n END IF; \n END LOOP; \nEND; \n/ " }, { "code": null, "e": 3301, "s": 3215, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3441, "s": 3301, "text": "value of a: 10 \nvalue of a: 11 \nvalue of a: 12 \nvalue of a: 13 \nvalue of a: 14 \nvalue of a: 15 \n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 3635, "s": 3441, "text": "The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the condition is true, the loop completes and control passes to the statement immediately after the END LOOP." }, { "code": null, "e": 3705, "s": 3635, "text": "Following are the two important aspects for the EXIT WHEN statement −" }, { "code": null, "e": 3856, "s": 3705, "text": "Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop." }, { "code": null, "e": 4007, "s": 3856, "text": "Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop." }, { "code": null, "e": 4075, "s": 4007, "text": "A statement inside the loop must change the value of the condition." }, { "code": null, "e": 4143, "s": 4075, "text": "A statement inside the loop must change the value of the condition." }, { "code": null, "e": 4207, "s": 4143, "text": "The syntax for an EXIT WHEN statement in PL/SQL is as follows −" }, { "code": null, "e": 4229, "s": 4207, "text": "EXIT WHEN condition;\n" }, { "code": null, "e": 4329, "s": 4229, "text": "The EXIT WHEN statement replaces a conditional statement like if-then used with the EXIT statement." }, { "code": null, "e": 4595, "s": 4329, "text": "DECLARE \n a number(2) := 10; \nBEGIN \n -- while loop execution \n WHILE a < 20 LOOP \n dbms_output.put_line ('value of a: ' || a); \n a := a + 1; \n -- terminate the loop using the exit when statement \n EXIT WHEN a > 15; \n END LOOP; \nEND; \n/" }, { "code": null, "e": 4681, "s": 4595, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 4824, "s": 4681, "text": "value of a: 10 \nvalue of a: 11 \nvalue of a: 12 \nvalue of a: 13 \nvalue of a: 14 \nvalue of a: 15 \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 4831, "s": 4824, "text": " Print" }, { "code": null, "e": 4842, "s": 4831, "text": " Add Notes" } ]
PL/SQL - Cursors
In this chapter, we will discuss the cursors in PL/SQL. Oracle creates a memory area, known as the context area, for processing an SQL statement, which contains all the information needed for processing the statement; for example, the number of rows processed, etc. A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set. You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors − Implicit cursors Explicit cursors Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected. In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statement. The following table provides the description of the most used attributes − %FOUND Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE. %NOTFOUND The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE. %ISOPEN Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement. %ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement. Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example. We will be using the CUSTOMERS table we had created and used in the previous chapters. Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+ The following program will update the table and increase the salary of each customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected − DECLARE total_rows number(2); BEGIN UPDATE customers SET salary = salary + 500; IF sql%notfound THEN dbms_output.put_line('no customers selected'); ELSIF sql%found THEN total_rows := sql%rowcount; dbms_output.put_line( total_rows || ' customers selected '); END IF; END; / When the above code is executed at the SQL prompt, it produces the following result − 6 customers selected PL/SQL procedure successfully completed. If you check the records in customers table, you will find that the rows have been updated − Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2500.00 | | 2 | Khilan | 25 | Delhi | 2000.00 | | 3 | kaushik | 23 | Kota | 2500.00 | | 4 | Chaitali | 25 | Mumbai | 7000.00 | | 5 | Hardik | 27 | Bhopal | 9000.00 | | 6 | Komal | 22 | MP | 5000.00 | +----+----------+-----+-----------+----------+ Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. The syntax for creating an explicit cursor is − CURSOR cursor_name IS select_statement; Working with an explicit cursor includes the following steps − Declaring the cursor for initializing the memory Opening the cursor for allocating the memory Fetching the cursor for retrieving the data Closing the cursor to release the allocated memory Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example − CURSOR c_customers IS SELECT id, name, address FROM customers; Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open the above defined cursor as follows − OPEN c_customers; Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened cursor as follows − FETCH c_customers INTO c_id, c_name, c_addr; Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as follows − CLOSE c_customers; Following is a complete example to illustrate the concepts of explicit cursors &minua; DECLARE c_id customers.id%type; c_name customers.name%type; c_addr customers.address%type; CURSOR c_customers is SELECT id, name, address FROM customers; BEGIN OPEN c_customers; LOOP FETCH c_customers into c_id, c_name, c_addr; EXIT WHEN c_customers%notfound; dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr); END LOOP; CLOSE c_customers; END; / When the above code is executed at the SQL prompt, it produces the following result − 1 Ramesh Ahmedabad 2 Khilan Delhi 3 kaushik Kota 4 Chaitali Mumbai 5 Hardik Bhopal 6 Komal MP PL/SQL procedure successfully completed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2331, "s": 2065, "text": "In this chapter, we will discuss the cursors in PL/SQL. Oracle creates a memory area, known as the context area, for processing an SQL statement, which contains all the information needed for processing the statement; for example, the number of rows processed, etc." }, { "code": null, "e": 2560, "s": 2331, "text": "A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set." }, { "code": null, "e": 2736, "s": 2560, "text": "You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors −" }, { "code": null, "e": 2753, "s": 2736, "text": "Implicit cursors" }, { "code": null, "e": 2770, "s": 2753, "text": "Explicit cursors" }, { "code": null, "e": 2989, "s": 2770, "text": "Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it." }, { "code": null, "e": 3272, "s": 2989, "text": "Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected." }, { "code": null, "e": 3628, "s": 3272, "text": "In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statement. The following table provides the description of the most used attributes −" }, { "code": null, "e": 3635, "s": 3628, "text": "%FOUND" }, { "code": null, "e": 3799, "s": 3635, "text": "Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE." }, { "code": null, "e": 3809, "s": 3799, "text": "%NOTFOUND" }, { "code": null, "e": 3991, "s": 3809, "text": "The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE." }, { "code": null, "e": 3999, "s": 3991, "text": "%ISOPEN" }, { "code": null, "e": 4139, "s": 3999, "text": "Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement." }, { "code": null, "e": 4149, "s": 4139, "text": "%ROWCOUNT" }, { "code": null, "e": 4268, "s": 4149, "text": "Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement." }, { "code": null, "e": 4363, "s": 4268, "text": "Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example." }, { "code": null, "e": 4450, "s": 4363, "text": "We will be using the CUSTOMERS table we had created and used in the previous chapters." }, { "code": null, "e": 4958, "s": 4450, "text": "Select * from customers; \n\n+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 5128, "s": 4958, "text": "The following program will update the table and increase the salary of each customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected −" }, { "code": null, "e": 5456, "s": 5128, "text": "DECLARE \n total_rows number(2); \nBEGIN \n UPDATE customers \n SET salary = salary + 500; \n IF sql%notfound THEN \n dbms_output.put_line('no customers selected'); \n ELSIF sql%found THEN \n total_rows := sql%rowcount;\n dbms_output.put_line( total_rows || ' customers selected '); \n END IF; \nEND; \n/ " }, { "code": null, "e": 5542, "s": 5456, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 5609, "s": 5542, "text": "6 customers selected \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 5702, "s": 5609, "text": "If you check the records in customers table, you will find that the rows have been updated −" }, { "code": null, "e": 6210, "s": 5702, "text": "Select * from customers; \n\n+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2500.00 | \n| 2 | Khilan | 25 | Delhi | 2000.00 | \n| 3 | kaushik | 23 | Kota | 2500.00 | \n| 4 | Chaitali | 25 | Mumbai | 7000.00 | \n| 5 | Hardik | 27 | Bhopal | 9000.00 | \n| 6 | Komal | 22 | MP | 5000.00 | \n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 6460, "s": 6210, "text": "Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row." }, { "code": null, "e": 6508, "s": 6460, "text": "The syntax for creating an explicit cursor is −" }, { "code": null, "e": 6550, "s": 6508, "text": "CURSOR cursor_name IS select_statement; \n" }, { "code": null, "e": 6613, "s": 6550, "text": "Working with an explicit cursor includes the following steps −" }, { "code": null, "e": 6662, "s": 6613, "text": "Declaring the cursor for initializing the memory" }, { "code": null, "e": 6707, "s": 6662, "text": "Opening the cursor for allocating the memory" }, { "code": null, "e": 6751, "s": 6707, "text": "Fetching the cursor for retrieving the data" }, { "code": null, "e": 6802, "s": 6751, "text": "Closing the cursor to release the allocated memory" }, { "code": null, "e": 6905, "s": 6802, "text": "Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −" }, { "code": null, "e": 6973, "s": 6905, "text": "CURSOR c_customers IS \n SELECT id, name, address FROM customers; " }, { "code": null, "e": 7172, "s": 6973, "text": "Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open the above defined cursor as follows −" }, { "code": null, "e": 7191, "s": 7172, "text": "OPEN c_customers; " }, { "code": null, "e": 7323, "s": 7191, "text": "Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened cursor as follows −" }, { "code": null, "e": 7369, "s": 7323, "text": "FETCH c_customers INTO c_id, c_name, c_addr; " }, { "code": null, "e": 7490, "s": 7369, "text": "Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as follows −" }, { "code": null, "e": 7509, "s": 7490, "text": "CLOSE c_customers;" }, { "code": null, "e": 7596, "s": 7509, "text": "Following is a complete example to illustrate the concepts of explicit cursors &minua;" }, { "code": null, "e": 8014, "s": 7596, "text": "DECLARE \n c_id customers.id%type; \n c_name customers.name%type; \n c_addr customers.address%type; \n CURSOR c_customers is \n SELECT id, name, address FROM customers; \nBEGIN \n OPEN c_customers; \n LOOP \n FETCH c_customers into c_id, c_name, c_addr; \n EXIT WHEN c_customers%notfound; \n dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr); \n END LOOP; \n CLOSE c_customers; \nEND; \n/" }, { "code": null, "e": 8100, "s": 8014, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 8256, "s": 8100, "text": "1 Ramesh Ahmedabad \n2 Khilan Delhi \n3 kaushik Kota \n4 Chaitali Mumbai \n5 Hardik Bhopal \n6 Komal MP \n \nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 8263, "s": 8256, "text": " Print" }, { "code": null, "e": 8274, "s": 8263, "text": " Add Notes" } ]
DirectX - Pixel Shader
The Pixel Shader is called once per pixel in comparison to vertex shader which it calls as per vertex and gets its data from the preceding pipeline station respectively from the preceding Shader. It calculates the required pixel color (pixel depth or any other values are possible) and returns them to the required pipeline. The Pixel Shader is considered as the last Shader in the pipeline and therefore already gives the data to the Output Merger, which helps us to determine the final pixel color. Pixel Shaders are prominently used for rendering surfaces but in comparison to shaders, they can be used for special calculations. The two most important ways to use them include texturing and lighting, for which we will focus on the example following the pixel shader representation or structure. In principle with reference to snapshot given below, you will find there is no real difference to a Vertex Shader, only the input and output data is different. The following code demonstrates how texturing and lighting with a Pixel Shader is done − struct PixelShaderInput{ float4 position : SV_POSITION; float3 outVec : POSITION0; float3 normal : NORMAL0; float3 light : POSITION1; }; float4 main(PixelShaderInput input) : SV_TARGET{ float3 L = normalize(input.light); float3 V = normalize(input.outVec); float3 R = normalize(reflect(L, input.normal)); float4 diffuse = Ka + (lightColor * Kd * max(dot(input.normal, L), 0.0f)); diffuse = saturate(diffuse); float4 specular = Ks * pow(max(dot(R, V), 0.0f), shininess.x - 50.0f); specular = saturate(specular); float4 finalColor = diffuse + specular; return finalColor; } The buffer includes the light position in world coordinates which is created and a texture with reference to sampler is always used. The Sampler is mandatory to read the texture color on the corresponding texture coordinates. The Pixel Shader includes the input data received from the Vertex Shader which is interpolated by DirectX. This means with reference to the current pixel from the three vertices of the current triangle we can draw, distance- and mode-dependent "averages" are calculated. Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2298, "text": "The Pixel Shader is called once per pixel in comparison to vertex shader which it calls as per vertex and gets its data from the preceding pipeline station respectively from the preceding Shader. It calculates the required pixel color (pixel depth or any other values are possible) and returns them to the required pipeline." }, { "code": null, "e": 3097, "s": 2623, "text": "The Pixel Shader is considered as the last Shader in the pipeline and therefore already gives the data to the Output Merger, which helps us to determine the final pixel color. Pixel Shaders are prominently used for rendering surfaces but in comparison to shaders, they can be used for special calculations. The two most important ways to use them include texturing and lighting, for which we will focus on the example following the pixel shader representation or structure." }, { "code": null, "e": 3257, "s": 3097, "text": "In principle with reference to snapshot given below, you will find there is no real difference to a Vertex Shader, only the input and output data is different." }, { "code": null, "e": 3346, "s": 3257, "text": "The following code demonstrates how texturing and lighting with a Pixel Shader is done −" }, { "code": null, "e": 3957, "s": 3346, "text": "struct PixelShaderInput{\n float4 position : SV_POSITION;\n float3 outVec : POSITION0;\n float3 normal : NORMAL0;\n float3 light : POSITION1;\n};\nfloat4 main(PixelShaderInput input) : SV_TARGET{\n float3 L = normalize(input.light);\n float3 V = normalize(input.outVec);\n float3 R = normalize(reflect(L, input.normal));\n float4 diffuse = Ka + (lightColor * Kd * max(dot(input.normal, L), 0.0f));\n diffuse = saturate(diffuse);\n float4 specular = Ks * pow(max(dot(R, V), 0.0f), shininess.x - 50.0f);\n specular = saturate(specular);\n float4 finalColor = diffuse + specular;\n return finalColor;\n}" }, { "code": null, "e": 4454, "s": 3957, "text": "The buffer includes the light position in world coordinates which is created and a texture with reference to sampler is always used. The Sampler is mandatory to read the texture color on the corresponding texture coordinates. The Pixel Shader includes the input data received from the Vertex Shader which is interpolated by DirectX. This means with reference to the current pixel from the three vertices of the current triangle we can draw, distance- and mode-dependent \"averages\" are calculated." }, { "code": null, "e": 4461, "s": 4454, "text": " Print" }, { "code": null, "e": 4472, "s": 4461, "text": " Add Notes" } ]
Pad the values of the column with zeros in MySQL
For this, use the concept of ZEROFILL. It pads the displayed value of the field with zeros up to the display width set in the column definition Let us first create a table − mysql> create table DemoTable626 (Value int(5) zerofill); Query OK, 0 rows affected (0.71 sec) Insert some records in the table using insert command − mysql> insert into DemoTable626 values(9); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable626 values(12); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable626 values(567); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable626 values(3478); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement − mysql> select *from DemoTable626; This will produce the following output − +-------+ | Value | +-------+ | 00009 | | 00012 | | 00567 | | 03478 | +-------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1206, "s": 1062, "text": "For this, use the concept of ZEROFILL. It pads the displayed value of the field with zeros up to the display width set in the column definition" }, { "code": null, "e": 1236, "s": 1206, "text": "Let us first create a table −" }, { "code": null, "e": 1331, "s": 1236, "text": "mysql> create table DemoTable626 (Value int(5) zerofill);\nQuery OK, 0 rows affected (0.71 sec)" }, { "code": null, "e": 1387, "s": 1331, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1709, "s": 1387, "text": "mysql> insert into DemoTable626 values(9);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable626 values(12);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable626 values(567);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable626 values(3478);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1769, "s": 1709, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1803, "s": 1769, "text": "mysql> select *from DemoTable626;" }, { "code": null, "e": 1844, "s": 1803, "text": "This will produce the following output −" }, { "code": null, "e": 1949, "s": 1844, "text": "+-------+\n| Value |\n+-------+\n| 00009 |\n| 00012 |\n| 00567 |\n| 03478 |\n+-------+\n4 rows in set (0.00 sec)" } ]
Exploring confusion matrix evolution on tensorboard | by Sushrut Ashtikar | Towards Data Science
Tensorboard is the best tool for visualizing many metrics while training and validating a neural network. In most of the case, we need to look for more details like how a model is performing on validation data. Sometimes training and validation loss and accuracy are not enough, we need to figure out the performance of validation data. One of the ways is to visualize using a confusion matrix. In the field of machine learning and specifically the problem of statistical classification, a confusion matrix, also known as an error matrix, is a specific table layout that allows visualization of the performance of an algorithm, typically a supervised learning one (in unsupervised learning it is usually called a matching matrix). Each row of the matrix represents the instances in a predicted class while each column represents the instances in an actual class (or vice versa). The name stems from the fact that it makes it easy to see if the system is confusing two classes (i.e. commonly mislabeling one as another). I won’t be digging deep into coding, I will highlight only important code portions which shows how to set up and implement a custom callback in tensorboard in python. In case if you want to view complete code you can check my repository, which I have added a link at the bottom of this story. I assume you have already built and compiled a Keras sequential model. Defining a function to plot cm def plot_confusion_matrix(cm, class_names): """ Returns a matplotlib figure containing the plotted confusion matrix. Args: cm (array, shape = [n, n]): a confusion matrix of integer classes class_names (array, shape = [n]): String names of the integer classes """ figure = plt.figure(figsize=(8, 8)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title("Confusion matrix") plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_marks, class_names) # Normalize the confusion matrix. cm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2) # Use white text if squares are dark; otherwise black. threshold = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): color = "white" if cm[i, j] > threshold else "black" plt.text(j, i, cm[i, j], horizontalalignment="center", color=color) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return figure We are now ready to train the CNN and regularly log the confusion matrix during the process. Using the below code, you will create a Keras TensorBoard callback to log basic metrics. logdir = "logs/image/" + datetime.now().strftime("%Y%m%d-%H%M%S")tensorboard_callback = keras.callbacks.TensorBoard(log_dir = logdir, histogram_freq = 1)file_writer_cm = tf.summary.create_file_writer(logdir + '/cm') Unfortunately, the Matplotlib file format cannot be logged as an image, but the PNG file format can be logged. So, we will create a helper function that takes a Matplotlib figure and converts it to PNG format so it can be written. def plot_to_image(figure): """ Converts the matplotlib plot specified by 'figure' to a PNG image and returns it. The supplied figure is closed and inaccessible after this call. """ buf = io.BytesIO() # Use plt.savefig to save the plot to a PNG in memory. plt.savefig(buf, format='png') # Closing the figure prevents it from being displayed directly inside # the notebook. plt.close(figure) buf.seek(0) # Use tf.image.decode_png to convert the PNG buffer # to a TF image. Make sure you use 4 channels. image = tf.image.decode_png(buf.getvalue(), channels=4) # Use tf.expand_dims to add the batch dimension image = tf.expand_dims(image, 0) return image We will define a function that calculates the confusion matrix. def log_confusion_matrix(epoch, logs): # Use the model to predict the values from the test_images. test_pred_raw = model.predict(test_images) test_pred = np.argmax(test_pred_raw, axis=1) # Calculate the confusion matrix using sklearn.metrics cm = sklearn.metrics.confusion_matrix(test_labels, test_pred) figure = plot_confusion_matrix(cm, class_names=class_names) cm_image = plot_to_image(figure) # Log the confusion matrix as an image summary. with file_writer_cm.as_default(): tf.summary.image("Confusion Matrix", cm_image, step=epoch) We will set up tensorboard callback to log confusion matrix on epoch end cm_callback = keras.callbacks.LambdaCallback(on_epoch_end=log_confusion_matrix) We need to specify values as a list to callbacks parameter in model.fit to specify Keras to use our custom callback functions while training. # Start TensorBoard.%tensorboard --logdir logs/image# Train the classifier.model.fit(train_images, train_labels, epochs=5, verbose=0, # Suppress chatty output callbacks=[tensorboard_callback, cm_callback], validation_data=(test_images, test_labels)) The tensorboard server runs on port 6006 by default, in case you want to specify any other port you need to specify as an arg to tensorboard command.Jupyter users can simply type%load_ext tensorboard in the first cell and run before importing libraries, this will load tensorboard inside Jupyter notebook. Wanna try out yourself github.com Refer to my Github repo link. I have trained a CNN classifier on the Fashion Mnist dataset and setup a confusion matrix. The above output is from my tensorboard server. Deep Dive into TensorBoard: Tutorial With Exampleshttps://neptune.ai/blog/tensorboard-tutorial Deep Dive into TensorBoard: Tutorial With Exampleshttps://neptune.ai/blog/tensorboard-tutorial
[ { "code": null, "e": 567, "s": 172, "text": "Tensorboard is the best tool for visualizing many metrics while training and validating a neural network. In most of the case, we need to look for more details like how a model is performing on validation data. Sometimes training and validation loss and accuracy are not enough, we need to figure out the performance of validation data. One of the ways is to visualize using a confusion matrix." }, { "code": null, "e": 1192, "s": 567, "text": "In the field of machine learning and specifically the problem of statistical classification, a confusion matrix, also known as an error matrix, is a specific table layout that allows visualization of the performance of an algorithm, typically a supervised learning one (in unsupervised learning it is usually called a matching matrix). Each row of the matrix represents the instances in a predicted class while each column represents the instances in an actual class (or vice versa). The name stems from the fact that it makes it easy to see if the system is confusing two classes (i.e. commonly mislabeling one as another)." }, { "code": null, "e": 1485, "s": 1192, "text": "I won’t be digging deep into coding, I will highlight only important code portions which shows how to set up and implement a custom callback in tensorboard in python. In case if you want to view complete code you can check my repository, which I have added a link at the bottom of this story." }, { "code": null, "e": 1556, "s": 1485, "text": "I assume you have already built and compiled a Keras sequential model." }, { "code": null, "e": 1587, "s": 1556, "text": "Defining a function to plot cm" }, { "code": null, "e": 2704, "s": 1587, "text": "def plot_confusion_matrix(cm, class_names): \"\"\" Returns a matplotlib figure containing the plotted confusion matrix. Args: cm (array, shape = [n, n]): a confusion matrix of integer classes class_names (array, shape = [n]): String names of the integer classes \"\"\" figure = plt.figure(figsize=(8, 8)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title(\"Confusion matrix\") plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_marks, class_names) # Normalize the confusion matrix. cm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2) # Use white text if squares are dark; otherwise black. threshold = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): color = \"white\" if cm[i, j] > threshold else \"black\" plt.text(j, i, cm[i, j], horizontalalignment=\"center\", color=color) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return figure" }, { "code": null, "e": 2886, "s": 2704, "text": "We are now ready to train the CNN and regularly log the confusion matrix during the process. Using the below code, you will create a Keras TensorBoard callback to log basic metrics." }, { "code": null, "e": 3102, "s": 2886, "text": "logdir = \"logs/image/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")tensorboard_callback = keras.callbacks.TensorBoard(log_dir = logdir, histogram_freq = 1)file_writer_cm = tf.summary.create_file_writer(logdir + '/cm')" }, { "code": null, "e": 3333, "s": 3102, "text": "Unfortunately, the Matplotlib file format cannot be logged as an image, but the PNG file format can be logged. So, we will create a helper function that takes a Matplotlib figure and converts it to PNG format so it can be written." }, { "code": null, "e": 4059, "s": 3333, "text": "def plot_to_image(figure): \"\"\" Converts the matplotlib plot specified by 'figure' to a PNG image and returns it. The supplied figure is closed and inaccessible after this call. \"\"\" buf = io.BytesIO() # Use plt.savefig to save the plot to a PNG in memory. plt.savefig(buf, format='png') # Closing the figure prevents it from being displayed directly inside # the notebook. plt.close(figure) buf.seek(0) # Use tf.image.decode_png to convert the PNG buffer # to a TF image. Make sure you use 4 channels. image = tf.image.decode_png(buf.getvalue(), channels=4) # Use tf.expand_dims to add the batch dimension image = tf.expand_dims(image, 0) return image" }, { "code": null, "e": 4123, "s": 4059, "text": "We will define a function that calculates the confusion matrix." }, { "code": null, "e": 4715, "s": 4123, "text": "def log_confusion_matrix(epoch, logs): # Use the model to predict the values from the test_images. test_pred_raw = model.predict(test_images) test_pred = np.argmax(test_pred_raw, axis=1) # Calculate the confusion matrix using sklearn.metrics cm = sklearn.metrics.confusion_matrix(test_labels, test_pred) figure = plot_confusion_matrix(cm, class_names=class_names) cm_image = plot_to_image(figure) # Log the confusion matrix as an image summary. with file_writer_cm.as_default(): tf.summary.image(\"Confusion Matrix\", cm_image, step=epoch)" }, { "code": null, "e": 4788, "s": 4715, "text": "We will set up tensorboard callback to log confusion matrix on epoch end" }, { "code": null, "e": 4868, "s": 4788, "text": "cm_callback = keras.callbacks.LambdaCallback(on_epoch_end=log_confusion_matrix)" }, { "code": null, "e": 5010, "s": 4868, "text": "We need to specify values as a list to callbacks parameter in model.fit to specify Keras to use our custom callback functions while training." }, { "code": null, "e": 5305, "s": 5010, "text": "# Start TensorBoard.%tensorboard --logdir logs/image# Train the classifier.model.fit(train_images, train_labels, epochs=5, verbose=0, # Suppress chatty output callbacks=[tensorboard_callback, cm_callback], validation_data=(test_images, test_labels))" }, { "code": null, "e": 5611, "s": 5305, "text": "The tensorboard server runs on port 6006 by default, in case you want to specify any other port you need to specify as an arg to tensorboard command.Jupyter users can simply type%load_ext tensorboard in the first cell and run before importing libraries, this will load tensorboard inside Jupyter notebook." }, { "code": null, "e": 5634, "s": 5611, "text": "Wanna try out yourself" }, { "code": null, "e": 5645, "s": 5634, "text": "github.com" }, { "code": null, "e": 5814, "s": 5645, "text": "Refer to my Github repo link. I have trained a CNN classifier on the Fashion Mnist dataset and setup a confusion matrix. The above output is from my tensorboard server." }, { "code": null, "e": 5909, "s": 5814, "text": "Deep Dive into TensorBoard: Tutorial With Exampleshttps://neptune.ai/blog/tensorboard-tutorial" } ]
Fetch specific multiple documents in MongoDB
To fetch specific multiple documents in MongoDB, use $in. Let us create a collection with documents − > db.demo593.insertOne({id:1,"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e93177dfd2d90c177b5bcd9") } > db.demo593.insertOne({id:2,"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e931785fd2d90c177b5bcda") } > db.demo593.insertOne({id:3,"Name":"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e93178cfd2d90c177b5bcdb") } > db.demo593.insertOne({id:4,"Name":"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e931792fd2d90c177b5bcdc") } Display all documents from a collection with the help of find() method − > db.demo593.find(); This will produce the following output − { "_id" : ObjectId("5e93177dfd2d90c177b5bcd9"), "id" : 1, "Name" : "Chris" } { "_id" : ObjectId("5e931785fd2d90c177b5bcda"), "id" : 2, "Name" : "John" } { "_id" : ObjectId("5e93178cfd2d90c177b5bcdb"), "id" : 3, "Name" : "Bob" } { "_id" : ObjectId("5e931792fd2d90c177b5bcdc"), "id" : 4, "Name" : "Sam" } Following is the query to fetch specific multiple documents − > db.demo593.find({id:{$in:[1,3]}}); This will produce the following output − { "_id" : ObjectId("5e93177dfd2d90c177b5bcd9"), "id" : 1, "Name" : "Chris" } { "_id" : ObjectId("5e93178cfd2d90c177b5bcdb"), "id" : 3, "Name" : "Bob" }
[ { "code": null, "e": 1164, "s": 1062, "text": "To fetch specific multiple documents in MongoDB, use $in. Let us create a collection with documents −" }, { "code": null, "e": 1671, "s": 1164, "text": "> db.demo593.insertOne({id:1,\"Name\":\"Chris\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e93177dfd2d90c177b5bcd9\")\n}\n> db.demo593.insertOne({id:2,\"Name\":\"John\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e931785fd2d90c177b5bcda\")\n}\n> db.demo593.insertOne({id:3,\"Name\":\"Bob\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e93178cfd2d90c177b5bcdb\")\n}\n> db.demo593.insertOne({id:4,\"Name\":\"Sam\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e931792fd2d90c177b5bcdc\")\n}" }, { "code": null, "e": 1744, "s": 1671, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1765, "s": 1744, "text": "> db.demo593.find();" }, { "code": null, "e": 1806, "s": 1765, "text": "This will produce the following output −" }, { "code": null, "e": 2109, "s": 1806, "text": "{ \"_id\" : ObjectId(\"5e93177dfd2d90c177b5bcd9\"), \"id\" : 1, \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e931785fd2d90c177b5bcda\"), \"id\" : 2, \"Name\" : \"John\" }\n{ \"_id\" : ObjectId(\"5e93178cfd2d90c177b5bcdb\"), \"id\" : 3, \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e931792fd2d90c177b5bcdc\"), \"id\" : 4, \"Name\" : \"Sam\" }" }, { "code": null, "e": 2171, "s": 2109, "text": "Following is the query to fetch specific multiple documents −" }, { "code": null, "e": 2208, "s": 2171, "text": "> db.demo593.find({id:{$in:[1,3]}});" }, { "code": null, "e": 2249, "s": 2208, "text": "This will produce the following output −" }, { "code": null, "e": 2401, "s": 2249, "text": "{ \"_id\" : ObjectId(\"5e93177dfd2d90c177b5bcd9\"), \"id\" : 1, \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e93178cfd2d90c177b5bcdb\"), \"id\" : 3, \"Name\" : \"Bob\" }" } ]
Interpreting Image Classification Model with LIME | by Ruben Winastwan | Towards Data Science
The advancement rate and growth in the area of machine learning are insane. Nowadays, we can choose a variety of machine learning models to solve our problems. Let’s say we want to solve a classification task, now we don’t only have logistic regression to choose from. We also have decision tree, random forest, SVM, Gradient Boosting, Neural Networks, and so on that will do the trick. However, of all of the available machine learning models out there, we can agree that most of them are black boxes. This means that most machine learning models are doing something under the hood that is so complex that we don’t have a clue anymore why they behave the way they do. In other words, we don’t know the thought process of our model in predicting something. Understanding the behavior of our machine learning model is becoming very important. Judging the model performance based on its accuracy alone is not sufficient anymore as your model can trick you. Let’s take a look at a ball classifier below which has one main job: to classify a ball either as a football or a basketball. In the above image, our ball classifier performed really well. It predicted correctly the class of all of the six images. Next, we are happy with it and proceed to use this model for production. However, little did we know that our classifier has successfully tricked us. Why is that? Let’s take a look at the model explanation below. It turns out that our classifier was correctly predicting a ball as a football because of the human body parts, not because of the ball itself. So our classifier wasn’t trying to classify between a football and a basketball, but to classify between a human body parts and a basketball. Obviously, it’s not what we want and thus, we shouldn’t trust our model only based on its accuracy. Unfortunately, interpreting the behavior of our black-box model, like a deep neural network, is a very difficult thing to do. And this is where we need LIME. LIME stands for Local Interpretable Model-agnostic Explanations. It is a Python library based on a paper from Ribeiro et al. to help you understand the behavior of your black-box classifier model. Currently, you can use LIME for a classifier model that classify tabular data, images, or texts. The abbreviation of LIME itself should give you an intuition about the core idea behind it. LIME is: Model agnostic, which means that LIME is model-independent. In other words, LIME is able to explain any black-box classifier you can think of. Interpretable, which means that LIME provides you a solution to understand why your model behaves the way it does. Local, which means that LIME tries to find the explanation of your black-box model by approximating the local linear behavior of your model. Let’s take a look at below picture to understand more about LIME being local. Let’s say you have a feature space with non-linear boundaries as shown in the left image above. The data points residing inside the black curve will be classified as A and otherwise, will be classified as B. Now we want to predict the class of a data point denoted by red star in the above image. Instead of looking at the global behavior (left image), LIME will go into the vicinity area of the red star point such that it becomes very local that a linear classifier could explain your model’s prediction (right image). Next, let’s take a look at how LIME explain the model’s behavior step-by step. Internally, LIME tries to interpret a black box model by conducting these four steps: 1. Input data permutation As you can see in the image above, let’s say we want LIME to explain why a data point denoted by the red star is classified in one of the class instead of the other. The first step that LIME would do is to create several artificial data points that are close with the data denoted by the red star. If our input data is an image, LIME will generate several samples that are similar with our input image by turning on and off some of the super-pixels of the image. 2. Predict the class of each artificial data point Next, LIME will predict the class of each of the artificial data point that has been generated using our trained model. If your input data is an image, then the prediction of each perturbed image will be generated at this stage. 3. Calculate the weight of each artificial data point The third step is to calculate the weight of each artificial data to measure its importance. To do this, first the cosine distance metric is usually applied to calculate how far the distance of each artificial data point with respect to our original input data. Next, the distance will be mapped into a value between zero to one with a kernel function. The closer the distance, the closer the mapped value to one, and hence, the bigger the weight. The bigger the weight, the bigger the importance of a certain artificial data point. If the input data is an image, then the cosine distance between each perturbed image and the original image will be computed. The more the similarity between a perturbed image to the original image, the bigger its weight and importance. 4. Fit a linear classifier to explain the most important features The last step is fitting a linear regression model using the weighted artificial data points. After this step, we should get the fitted coefficient of each feature, just like the usual linear regression analysis. Now if we sort the coefficient, the features that have larger coefficients are the ones that play a big role in determining the prediction of our black-box machine learning model. Now that we know how LIME works, let’s use it to explain the behavior of our machine learning model. In this article, we are going to create two image classification models: one with a custom model and one with a pre-trained InceptionV3 model. Let’s load the data first. The dataset that we’re going to use is the dog-cat-panda dataset that you can freely download on Kaggle. It contains in total 3,000 images of dogs, cats, and pandas. If you’ve just downloaded it, then you need to unzip the file. Next, make sure that you have the following structure in your folders. dog-cat-panda/ dog/ img_1.jpg img_2.jpg ..... cat/ img_1.jpg img_2.jpg ......... panda/ img_1.jpg img_2.jpg ........... Now we can generate our training and test data by using image generator from TensorFlow. In the below code, we want to split the data into 80% of training data and 20% of test data. And with that we have successfully generated our data! Now it’s time for us to create our custom image classifier model. The model consists of three convolution layers before we flatten it and a fully-connected layer as the last layer of our model. Next, let’s compile and train the model. For this article, we’re going to use Adam optimizer, accuracy metrics, and of course, categorical cross-entropy loss function. Great! After this step now the model is ready to make a prediction of an input image. But before that, let’s create a pre-trained model based on InceptionV3. We can load the pre-trained model with one line of code as follows. from tensorflow.keras.applications import inception_v3 as inc_net Now let’s use the model to make a prediction of our input image and see how LIME could help us to understand the behavior of our model. Let’s say we want our custom model to make a prediction of a panda image below: The first step would be to preprocess our input image into the format that can be read by our custom model. After reading and transforming the input image, we can use our custom model to predict our input image. And our custom model correctly predicts that the animal in the image is a panda! As you can see, our model predicts that with reasonable certainty, i.e with 81% probability. But as mentioned earlier, we don’t know for sure why our model classifies the animal in the image as a panda. What makes our model think that the animal in our image is a panda instead of a dog or a cat? This is where we use LIME. Before we start, if you haven’t installed LIME yet, you can do so by typing the following pip command. pip install lime Next, we need to import all of the necessary libraries. Since our input data is an image, we’re going to use LimeImageExplainer() method from lime_image . If your input data is a tabular data, you need to use LimeTabularExplainer() method from lime_tabular instead. Now it’s time for us to start interpreting the prediction of our custom model. All we need to do is to call the explain_instance method from explainer object that we’ve created before. As you can see above, we passed several arguments there: images — The image that we want LIME to explain. classifier_fn — Your image classier prediction function. top_labels — The number of labels that you want LIME to show. If it’s 3, then it will only show the top 3 labels with highest probabilities and ignore the rest. num_samples — to determine the amount of artificial data points similar to our input that will be generated by LIME. Next, we can proceed to visualize the explanation provided by LIME. Now we know why our model classifies our image as a panda! On the left image, we can see that only the super-pixels where the panda is visible are shown. This means that our model classifies our image as a panda because of these parts of super-pixels. On the right image, the area of super-pixels colored in green are the ones that increase the probability of our image belongs to a panda class, while the super-pixels colored in red are the ones that decrease the probability. Now we want to do the same step as above, but using the pre-trained InceptionV3 model. First, let’s see the prediction of the pre-trained InceptionV3 model using the same input image. Below is the code to do so. As you can see, the pre-trained InceptionV3 model also predicts that our image is a panda. A giant panda to be precise. Now let’s interpret the behavior of our pre-trained model with the same step as our custom model before. Now we also know why our pre-trained model classifies our image as a panda instead of a dog or a cat. It turns out that both of the custom model and pre-trained InceptionV3 model are able to classify our image as a panda due to the specific features of a panda, which is something that we want. That’s it for now. Hopefully now you know the fundamental aspect of LIME and how it can be used to interpret our black-box machine learning model. You can find the complete Jupyter Notebook covered in this article here.
[ { "code": null, "e": 559, "s": 172, "text": "The advancement rate and growth in the area of machine learning are insane. Nowadays, we can choose a variety of machine learning models to solve our problems. Let’s say we want to solve a classification task, now we don’t only have logistic regression to choose from. We also have decision tree, random forest, SVM, Gradient Boosting, Neural Networks, and so on that will do the trick." }, { "code": null, "e": 929, "s": 559, "text": "However, of all of the available machine learning models out there, we can agree that most of them are black boxes. This means that most machine learning models are doing something under the hood that is so complex that we don’t have a clue anymore why they behave the way they do. In other words, we don’t know the thought process of our model in predicting something." }, { "code": null, "e": 1253, "s": 929, "text": "Understanding the behavior of our machine learning model is becoming very important. Judging the model performance based on its accuracy alone is not sufficient anymore as your model can trick you. Let’s take a look at a ball classifier below which has one main job: to classify a ball either as a football or a basketball." }, { "code": null, "e": 1588, "s": 1253, "text": "In the above image, our ball classifier performed really well. It predicted correctly the class of all of the six images. Next, we are happy with it and proceed to use this model for production. However, little did we know that our classifier has successfully tricked us. Why is that? Let’s take a look at the model explanation below." }, { "code": null, "e": 1974, "s": 1588, "text": "It turns out that our classifier was correctly predicting a ball as a football because of the human body parts, not because of the ball itself. So our classifier wasn’t trying to classify between a football and a basketball, but to classify between a human body parts and a basketball. Obviously, it’s not what we want and thus, we shouldn’t trust our model only based on its accuracy." }, { "code": null, "e": 2100, "s": 1974, "text": "Unfortunately, interpreting the behavior of our black-box model, like a deep neural network, is a very difficult thing to do." }, { "code": null, "e": 2132, "s": 2100, "text": "And this is where we need LIME." }, { "code": null, "e": 2426, "s": 2132, "text": "LIME stands for Local Interpretable Model-agnostic Explanations. It is a Python library based on a paper from Ribeiro et al. to help you understand the behavior of your black-box classifier model. Currently, you can use LIME for a classifier model that classify tabular data, images, or texts." }, { "code": null, "e": 2527, "s": 2426, "text": "The abbreviation of LIME itself should give you an intuition about the core idea behind it. LIME is:" }, { "code": null, "e": 2670, "s": 2527, "text": "Model agnostic, which means that LIME is model-independent. In other words, LIME is able to explain any black-box classifier you can think of." }, { "code": null, "e": 2785, "s": 2670, "text": "Interpretable, which means that LIME provides you a solution to understand why your model behaves the way it does." }, { "code": null, "e": 2926, "s": 2785, "text": "Local, which means that LIME tries to find the explanation of your black-box model by approximating the local linear behavior of your model." }, { "code": null, "e": 3004, "s": 2926, "text": "Let’s take a look at below picture to understand more about LIME being local." }, { "code": null, "e": 3525, "s": 3004, "text": "Let’s say you have a feature space with non-linear boundaries as shown in the left image above. The data points residing inside the black curve will be classified as A and otherwise, will be classified as B. Now we want to predict the class of a data point denoted by red star in the above image. Instead of looking at the global behavior (left image), LIME will go into the vicinity area of the red star point such that it becomes very local that a linear classifier could explain your model’s prediction (right image)." }, { "code": null, "e": 3604, "s": 3525, "text": "Next, let’s take a look at how LIME explain the model’s behavior step-by step." }, { "code": null, "e": 3690, "s": 3604, "text": "Internally, LIME tries to interpret a black box model by conducting these four steps:" }, { "code": null, "e": 3716, "s": 3690, "text": "1. Input data permutation" }, { "code": null, "e": 4014, "s": 3716, "text": "As you can see in the image above, let’s say we want LIME to explain why a data point denoted by the red star is classified in one of the class instead of the other. The first step that LIME would do is to create several artificial data points that are close with the data denoted by the red star." }, { "code": null, "e": 4179, "s": 4014, "text": "If our input data is an image, LIME will generate several samples that are similar with our input image by turning on and off some of the super-pixels of the image." }, { "code": null, "e": 4230, "s": 4179, "text": "2. Predict the class of each artificial data point" }, { "code": null, "e": 4459, "s": 4230, "text": "Next, LIME will predict the class of each of the artificial data point that has been generated using our trained model. If your input data is an image, then the prediction of each perturbed image will be generated at this stage." }, { "code": null, "e": 4513, "s": 4459, "text": "3. Calculate the weight of each artificial data point" }, { "code": null, "e": 5046, "s": 4513, "text": "The third step is to calculate the weight of each artificial data to measure its importance. To do this, first the cosine distance metric is usually applied to calculate how far the distance of each artificial data point with respect to our original input data. Next, the distance will be mapped into a value between zero to one with a kernel function. The closer the distance, the closer the mapped value to one, and hence, the bigger the weight. The bigger the weight, the bigger the importance of a certain artificial data point." }, { "code": null, "e": 5283, "s": 5046, "text": "If the input data is an image, then the cosine distance between each perturbed image and the original image will be computed. The more the similarity between a perturbed image to the original image, the bigger its weight and importance." }, { "code": null, "e": 5349, "s": 5283, "text": "4. Fit a linear classifier to explain the most important features" }, { "code": null, "e": 5742, "s": 5349, "text": "The last step is fitting a linear regression model using the weighted artificial data points. After this step, we should get the fitted coefficient of each feature, just like the usual linear regression analysis. Now if we sort the coefficient, the features that have larger coefficients are the ones that play a big role in determining the prediction of our black-box machine learning model." }, { "code": null, "e": 5986, "s": 5742, "text": "Now that we know how LIME works, let’s use it to explain the behavior of our machine learning model. In this article, we are going to create two image classification models: one with a custom model and one with a pre-trained InceptionV3 model." }, { "code": null, "e": 6013, "s": 5986, "text": "Let’s load the data first." }, { "code": null, "e": 6179, "s": 6013, "text": "The dataset that we’re going to use is the dog-cat-panda dataset that you can freely download on Kaggle. It contains in total 3,000 images of dogs, cats, and pandas." }, { "code": null, "e": 6313, "s": 6179, "text": "If you’ve just downloaded it, then you need to unzip the file. Next, make sure that you have the following structure in your folders." }, { "code": null, "e": 6491, "s": 6313, "text": "dog-cat-panda/ dog/ img_1.jpg img_2.jpg ..... cat/ img_1.jpg img_2.jpg ......... panda/ img_1.jpg img_2.jpg ..........." }, { "code": null, "e": 6673, "s": 6491, "text": "Now we can generate our training and test data by using image generator from TensorFlow. In the below code, we want to split the data into 80% of training data and 20% of test data." }, { "code": null, "e": 6728, "s": 6673, "text": "And with that we have successfully generated our data!" }, { "code": null, "e": 6922, "s": 6728, "text": "Now it’s time for us to create our custom image classifier model. The model consists of three convolution layers before we flatten it and a fully-connected layer as the last layer of our model." }, { "code": null, "e": 7090, "s": 6922, "text": "Next, let’s compile and train the model. For this article, we’re going to use Adam optimizer, accuracy metrics, and of course, categorical cross-entropy loss function." }, { "code": null, "e": 7316, "s": 7090, "text": "Great! After this step now the model is ready to make a prediction of an input image. But before that, let’s create a pre-trained model based on InceptionV3. We can load the pre-trained model with one line of code as follows." }, { "code": null, "e": 7382, "s": 7316, "text": "from tensorflow.keras.applications import inception_v3 as inc_net" }, { "code": null, "e": 7518, "s": 7382, "text": "Now let’s use the model to make a prediction of our input image and see how LIME could help us to understand the behavior of our model." }, { "code": null, "e": 7598, "s": 7518, "text": "Let’s say we want our custom model to make a prediction of a panda image below:" }, { "code": null, "e": 7810, "s": 7598, "text": "The first step would be to preprocess our input image into the format that can be read by our custom model. After reading and transforming the input image, we can use our custom model to predict our input image." }, { "code": null, "e": 7984, "s": 7810, "text": "And our custom model correctly predicts that the animal in the image is a panda! As you can see, our model predicts that with reasonable certainty, i.e with 81% probability." }, { "code": null, "e": 8215, "s": 7984, "text": "But as mentioned earlier, we don’t know for sure why our model classifies the animal in the image as a panda. What makes our model think that the animal in our image is a panda instead of a dog or a cat? This is where we use LIME." }, { "code": null, "e": 8318, "s": 8215, "text": "Before we start, if you haven’t installed LIME yet, you can do so by typing the following pip command." }, { "code": null, "e": 8335, "s": 8318, "text": "pip install lime" }, { "code": null, "e": 8601, "s": 8335, "text": "Next, we need to import all of the necessary libraries. Since our input data is an image, we’re going to use LimeImageExplainer() method from lime_image . If your input data is a tabular data, you need to use LimeTabularExplainer() method from lime_tabular instead." }, { "code": null, "e": 8786, "s": 8601, "text": "Now it’s time for us to start interpreting the prediction of our custom model. All we need to do is to call the explain_instance method from explainer object that we’ve created before." }, { "code": null, "e": 8843, "s": 8786, "text": "As you can see above, we passed several arguments there:" }, { "code": null, "e": 8892, "s": 8843, "text": "images — The image that we want LIME to explain." }, { "code": null, "e": 8949, "s": 8892, "text": "classifier_fn — Your image classier prediction function." }, { "code": null, "e": 9110, "s": 8949, "text": "top_labels — The number of labels that you want LIME to show. If it’s 3, then it will only show the top 3 labels with highest probabilities and ignore the rest." }, { "code": null, "e": 9227, "s": 9110, "text": "num_samples — to determine the amount of artificial data points similar to our input that will be generated by LIME." }, { "code": null, "e": 9295, "s": 9227, "text": "Next, we can proceed to visualize the explanation provided by LIME." }, { "code": null, "e": 9547, "s": 9295, "text": "Now we know why our model classifies our image as a panda! On the left image, we can see that only the super-pixels where the panda is visible are shown. This means that our model classifies our image as a panda because of these parts of super-pixels." }, { "code": null, "e": 9773, "s": 9547, "text": "On the right image, the area of super-pixels colored in green are the ones that increase the probability of our image belongs to a panda class, while the super-pixels colored in red are the ones that decrease the probability." }, { "code": null, "e": 9985, "s": 9773, "text": "Now we want to do the same step as above, but using the pre-trained InceptionV3 model. First, let’s see the prediction of the pre-trained InceptionV3 model using the same input image. Below is the code to do so." }, { "code": null, "e": 10210, "s": 9985, "text": "As you can see, the pre-trained InceptionV3 model also predicts that our image is a panda. A giant panda to be precise. Now let’s interpret the behavior of our pre-trained model with the same step as our custom model before." }, { "code": null, "e": 10505, "s": 10210, "text": "Now we also know why our pre-trained model classifies our image as a panda instead of a dog or a cat. It turns out that both of the custom model and pre-trained InceptionV3 model are able to classify our image as a panda due to the specific features of a panda, which is something that we want." }, { "code": null, "e": 10652, "s": 10505, "text": "That’s it for now. Hopefully now you know the fundamental aspect of LIME and how it can be used to interpret our black-box machine learning model." } ]
GATE | GATE-CS-2004 | Question 45 - GeeksforGeeks
15 Sep, 2021 Consider the grammar with the following translation rules and E as the start symbol. E → E1 # T { E.value = E1.value * T.value } | T{ E.value = T.value } T → T1 & F { T.value = T1.value + F.value } | F{ T.value = F.value } F → num { F.value = num.value } Compute E.value for the root of the parse tree for the expression: 2 # 3 & 5 # 6 & 4.(A) 200(B) 180(C) 160(D) 40Answer: (C)Explanation: See question 5 of https://www.geeksforgeeks.org/compilers-set-1/ YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0056:18 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE CS 2011 | Question 7
[ { "code": null, "e": 24560, "s": 24532, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24645, "s": 24560, "text": "Consider the grammar with the following translation rules and E as the start symbol." }, { "code": null, "e": 24835, "s": 24645, "text": "E → E1 # T { E.value = E1.value * T.value }\n | T{ E.value = T.value }\nT → T1 & F { T.value = T1.value + F.value }\n | F{ T.value = F.value }\nF → num { F.value = num.value } " }, { "code": null, "e": 25036, "s": 24835, "text": "Compute E.value for the root of the parse tree for the expression: 2 # 3 & 5 # 6 & 4.(A) 200(B) 180(C) 160(D) 40Answer: (C)Explanation: See question 5 of https://www.geeksforgeeks.org/compilers-set-1/" }, { "code": null, "e": 25949, "s": 25036, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0056:18 / 58:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LdMTs93sekg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25962, "s": 25949, "text": "GATE-CS-2004" }, { "code": null, "e": 25980, "s": 25962, "text": "GATE-GATE-CS-2004" }, { "code": null, "e": 25985, "s": 25980, "text": "GATE" }, { "code": null, "e": 26083, "s": 25985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26117, "s": 26083, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26159, "s": 26117, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26201, "s": 26159, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26235, "s": 26201, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26268, "s": 26235, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26302, "s": 26268, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26336, "s": 26302, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26370, "s": 26336, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26412, "s": 26370, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
Mastering Package Management system with Dpkg
Dpkg is a device to install, build, dispose of and manage Debian programs and is managed utterly through command line parameters, which consists of precisely one action and zero or extra options. The action parameter tells to dpkg, what to do and options to manipulate the conduct of the action is some way. This article explains about -“Mastering Package Management system with Dpkg”. To get the options of dpkg, use the following command – $ dpkg --help The sample output should be like this – Commands: -i|--install <.deb file name> ... | -R|--recursive <directory> ... --unpack <.deb file name> ... | -R|--recursive <directory> ... -A|--record-avail <.deb file name> ... | -R|--recursive <directory> ... --configure <package> ... | -a|--pending --triggers-only <package> ... | -a|--pending -r|--remove <package> ... | -a|--pending -P|--purge <package> ... | -a|--pending -V|--verify <package> ... Verify the integrity of package(s). --get-selections [<pattern> ...] Get list of selections to stdout. --set-selections Set package selections from stdin. --clear-selections Deselect every non-essential package. --update-avail [<Packages-file>] Replace available packages info. --merge-avail [<Packages-file>] Merge with info from file. --clear-avail Erase existing available info. --forget-old-unavail Forget uninstalled unavailable pkgs. -s|--status <package> ... Display package status details. -p|--print-avail <package> ... Display available version details. Assertable features: support-predepends, working-epoch, long-filenames, multi-conrep, multi-arch, versioned-provides. ......................................................................... To install package, use the following commands as shown below – $ sudo dpkg -i <File name>.deb In the below commands VLC is the package name. To remove the package, use the following command – $ sudo dpkg -r vlc To purge the package, use the following command – $ sudo dpkg -P vlc To verify the integrity package, use the following command – $ sudo dpkg -V vlc To get the status of package, use the following command – $ sudo dpkg -s vlc To display available version details of package, use the following command – $ sudo dpkg -p vlc To get the list of all packages, use the following command – $ sudo dpkg -L To search a specific package and its supported files, use the following command – $ sudo dpkg -S vlc To configure the package, use the following command – $ sudo dpkg --configure vlc To install the package from directory, use the following command – $ sudo dpkg -R -i <Directory>/<package name > To unpack the package, use the following command – $ sudo dpkg -unpack <File name>.deb To deselect every non-essential package, use the following command as shown below – $sudo dpkg --clear-selections To get the list packages concisely, use the following command as shown below – $sudo dpkg -l The sample output should be like this – ri qt-at-spi:i386 0.4.0-3 i386 at-spi accessibility plugin for Q ri qtchooser 52-gae5eeef- amd64 Wrapper to select between Qt deve ri qtcore4-l10n 4:4.8.7+dfsg all Qt 4 core module translations ri qtdeclarative5 0.6+16.04.20 amd64 transitional dummy package for On ri qtdeclarative5 5.5.1-2ubunt amd64 Qt 5 declarative development prog ri qtdeclarative5 5.5.1-2ubunt amd64 transitional dummy package Qt 5 Q ri qtdeclarative5 5.5.1-2ubunt amd64 transitional dummy package for Qt ri qtdeclarative5 1.3.1918+16. amd64 Transitional dummy package for Ub ri qtdeclarative5 1.1.0+14.04. amd64 Unity Action QML Components ri qttranslations 5.5.1-2build all translations for Qt 5 ri qtwayland5:amd 5.5.1-2build amd64 QtWayland platform plugin ri readline-commo 6.3-8ubuntu2 all GNU readline and history librarie ri remmina 1.1.2-3ubunt amd64 remote desktop client for GNOME d ri remmina-common 1.1.2-3ubunt all common files for remmina remote d ri remmina-plugin 1.1.2-3ubunt amd64 RDP plugin for remmina remote des ri remmina-plugin 1.1.2-3ubunt amd64 VNC plugin for remmina remote des ri rename 0.20-4 all Perl extension for renaming multi ........................................... To print dpkg architecture, use the following command as shown below – $sudo dpkg --print-architecture The sample output should be like this – amd64 In this articles, we have learnt about – Mastering Package Management system with Dpkg .In our next series of Linux articles, we will come up with more Linux based tricks and tips. Keep reading!!
[ { "code": null, "e": 1448, "s": 1062, "text": "Dpkg is a device to install, build, dispose of and manage Debian programs and is managed utterly through command line parameters, which consists of precisely one action and zero or extra options. The action parameter tells to dpkg, what to do and options to manipulate the conduct of the action is some way. This article explains about -“Mastering Package Management system with Dpkg”." }, { "code": null, "e": 1504, "s": 1448, "text": "To get the options of dpkg, use the following command –" }, { "code": null, "e": 1518, "s": 1504, "text": "$ dpkg --help" }, { "code": null, "e": 1558, "s": 1518, "text": "The sample output should be like this –" }, { "code": null, "e": 2862, "s": 1558, "text": "Commands:\n-i|--install <.deb file name> ... | -R|--recursive <directory> ...\n--unpack <.deb file name> ... | -R|--recursive <directory> ...\n-A|--record-avail <.deb file name> ... | -R|--recursive <directory> ...\n--configure <package> ... | -a|--pending\n--triggers-only <package> ... | -a|--pending\n-r|--remove <package> ... | -a|--pending\n-P|--purge <package> ... | -a|--pending\n-V|--verify <package> ... Verify the integrity of package(s).\n--get-selections [<pattern> ...] Get list of selections to stdout.\n--set-selections Set package selections from stdin.\n--clear-selections Deselect every non-essential package.\n--update-avail [<Packages-file>] Replace available packages info.\n--merge-avail [<Packages-file>] Merge with info from file.\n--clear-avail Erase existing available info.\n--forget-old-unavail Forget uninstalled unavailable pkgs.\n-s|--status <package> ... Display package status details.\n-p|--print-avail <package> ... Display available version details.\n\nAssertable features: support-predepends, working-epoch, long-filenames,\nmulti-conrep, multi-arch, versioned-provides.\n........................................................................." }, { "code": null, "e": 2926, "s": 2862, "text": "To install package, use the following commands as shown below –" }, { "code": null, "e": 2957, "s": 2926, "text": "$ sudo dpkg -i <File name>.deb" }, { "code": null, "e": 3004, "s": 2957, "text": "In the below commands VLC is the package name." }, { "code": null, "e": 3055, "s": 3004, "text": "To remove the package, use the following command –" }, { "code": null, "e": 3074, "s": 3055, "text": "$ sudo dpkg -r vlc" }, { "code": null, "e": 3124, "s": 3074, "text": "To purge the package, use the following command –" }, { "code": null, "e": 3143, "s": 3124, "text": "$ sudo dpkg -P vlc" }, { "code": null, "e": 3204, "s": 3143, "text": "To verify the integrity package, use the following command –" }, { "code": null, "e": 3223, "s": 3204, "text": "$ sudo dpkg -V vlc" }, { "code": null, "e": 3281, "s": 3223, "text": "To get the status of package, use the following command –" }, { "code": null, "e": 3300, "s": 3281, "text": "$ sudo dpkg -s vlc" }, { "code": null, "e": 3377, "s": 3300, "text": "To display available version details of package, use the following command –" }, { "code": null, "e": 3396, "s": 3377, "text": "$ sudo dpkg -p vlc" }, { "code": null, "e": 3457, "s": 3396, "text": "To get the list of all packages, use the following command –" }, { "code": null, "e": 3472, "s": 3457, "text": "$ sudo dpkg -L" }, { "code": null, "e": 3554, "s": 3472, "text": "To search a specific package and its supported files, use the following command –" }, { "code": null, "e": 3573, "s": 3554, "text": "$ sudo dpkg -S vlc" }, { "code": null, "e": 3627, "s": 3573, "text": "To configure the package, use the following command –" }, { "code": null, "e": 3655, "s": 3627, "text": "$ sudo dpkg --configure vlc" }, { "code": null, "e": 3722, "s": 3655, "text": "To install the package from directory, use the following command –" }, { "code": null, "e": 3768, "s": 3722, "text": "$ sudo dpkg -R -i <Directory>/<package name >" }, { "code": null, "e": 3819, "s": 3768, "text": "To unpack the package, use the following command –" }, { "code": null, "e": 3855, "s": 3819, "text": "$ sudo dpkg -unpack <File name>.deb" }, { "code": null, "e": 3939, "s": 3855, "text": "To deselect every non-essential package, use the following command as shown below –" }, { "code": null, "e": 3969, "s": 3939, "text": "$sudo dpkg --clear-selections" }, { "code": null, "e": 4048, "s": 3969, "text": "To get the list packages concisely, use the following command as shown below –" }, { "code": null, "e": 4062, "s": 4048, "text": "$sudo dpkg -l" }, { "code": null, "e": 4102, "s": 4062, "text": "The sample output should be like this –" }, { "code": null, "e": 5279, "s": 4102, "text": "ri qt-at-spi:i386 0.4.0-3 i386 at-spi accessibility plugin for Q\nri qtchooser 52-gae5eeef- amd64 Wrapper to select between Qt deve\nri qtcore4-l10n 4:4.8.7+dfsg all Qt 4 core module translations\nri qtdeclarative5 0.6+16.04.20 amd64 transitional dummy package for On\nri qtdeclarative5 5.5.1-2ubunt amd64 Qt 5 declarative development prog\nri qtdeclarative5 5.5.1-2ubunt amd64 transitional dummy package Qt 5 Q\nri qtdeclarative5 5.5.1-2ubunt amd64 transitional dummy package for Qt\nri qtdeclarative5 1.3.1918+16. amd64 Transitional dummy package for Ub\nri qtdeclarative5 1.1.0+14.04. amd64 Unity Action QML Components\nri qttranslations 5.5.1-2build all translations for Qt 5\nri qtwayland5:amd 5.5.1-2build amd64 QtWayland platform plugin\nri readline-commo 6.3-8ubuntu2 all GNU readline and history librarie\nri remmina 1.1.2-3ubunt amd64 remote desktop client for GNOME d\nri remmina-common 1.1.2-3ubunt all common files for remmina remote d\nri remmina-plugin 1.1.2-3ubunt amd64 RDP plugin for remmina remote des\nri remmina-plugin 1.1.2-3ubunt amd64 VNC plugin for remmina remote des\nri rename 0.20-4 all Perl extension for renaming multi\n..........................................." }, { "code": null, "e": 5350, "s": 5279, "text": "To print dpkg architecture, use the following command as shown below –" }, { "code": null, "e": 5382, "s": 5350, "text": "$sudo dpkg --print-architecture" }, { "code": null, "e": 5422, "s": 5382, "text": "The sample output should be like this –" }, { "code": null, "e": 5428, "s": 5422, "text": "amd64" }, { "code": null, "e": 5624, "s": 5428, "text": "In this articles, we have learnt about – Mastering Package Management system with Dpkg .In our next series of Linux articles, we will come up with more Linux based tricks and tips. Keep reading!!" } ]
Java program to Get IP address of the system
The InetAddress class This class represents an Internet Protocol (IP) address. You can get the local IP Address &amp; Hostname of the system using getLocalAddress() method of this class Live Demo import java.net.InetAddress; public class GetIpAddress { public static void main(String args[]) throws Exception{ InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local HostAddress: "+addr.getHostAddress()); String hostname = addr.getHostName(); System.out.println("Local host name: "+hostname); } } Local HostAddress: 192.168.25.1 Local host name: Tutorialspoint
[ { "code": null, "e": 1248, "s": 1062, "text": "The InetAddress class This class represents an Internet Protocol (IP) address. You can get the local IP Address &amp; Hostname of the system using getLocalAddress() method of this class" }, { "code": null, "e": 1258, "s": 1248, "text": "Live Demo" }, { "code": null, "e": 1606, "s": 1258, "text": "import java.net.InetAddress;\npublic class GetIpAddress {\n public static void main(String args[]) throws Exception{\n InetAddress addr = InetAddress.getLocalHost();\n System.out.println(\"Local HostAddress: \"+addr.getHostAddress());\n String hostname = addr.getHostName();\n System.out.println(\"Local host name: \"+hostname);\n }\n}" }, { "code": null, "e": 1670, "s": 1606, "text": "Local HostAddress: 192.168.25.1\nLocal host name: Tutorialspoint" } ]
Convert type of data object in R Programming - type.convert() Function - GeeksforGeeks
26 May, 2020 type.convert() function in R Language is used to compute the data type of a particular data object.It can convert data object to logical, integer, numeric, or factor. Syntax: type.convert(x) Parameter:x: It can be a vector matrix or an array Example 1: Apply type.convert to vector of numbers # R program to illustrate# type.convert to vector of numbers # create an example vectorx1 <- c("1", "2", "3", "4", "5", "6", "7") # Apply type.convert functionx1_convert <- type.convert(x1) # Class of converted data class(x1_convert) Output: [1] "integer" Here in the above code, we can see that before type.convert() function all the numbers are stored in it, but still its a character vector. And after the function it became “Integer”. Example 2: Type conversion of a vector with both characters and integers. # R Program to illustrate# conversion of a vector with both characters and integers # create an example vectorx1 <- c("1", "2", "3", "4", "5", "6", "7") # Create example datax2 <- c(x1, "AAA") # Class of example data class(x2) # Apply type.convert functionx2_convert <- type.convert(x2) # Class of converted data class(x2_convert) Output: [1] "character" [1] "factor" Here, in the above code there were some characters and some integers after using type.convert() function. So, the output comes to be a factor. R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr Remove rows with NA in one column of R DataFrame K-Means Clustering in R Programming How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 24788, "s": 24760, "text": "\n26 May, 2020" }, { "code": null, "e": 24955, "s": 24788, "text": "type.convert() function in R Language is used to compute the data type of a particular data object.It can convert data object to logical, integer, numeric, or factor." }, { "code": null, "e": 24979, "s": 24955, "text": "Syntax: type.convert(x)" }, { "code": null, "e": 25030, "s": 24979, "text": "Parameter:x: It can be a vector matrix or an array" }, { "code": null, "e": 25081, "s": 25030, "text": "Example 1: Apply type.convert to vector of numbers" }, { "code": "# R program to illustrate# type.convert to vector of numbers # create an example vectorx1 <- c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\") # Apply type.convert functionx1_convert <- type.convert(x1) # Class of converted data class(x1_convert) ", "e": 25388, "s": 25081, "text": null }, { "code": null, "e": 25396, "s": 25388, "text": "Output:" }, { "code": null, "e": 25411, "s": 25396, "text": "[1] \"integer\"\n" }, { "code": null, "e": 25594, "s": 25411, "text": "Here in the above code, we can see that before type.convert() function all the numbers are stored in it, but still its a character vector. And after the function it became “Integer”." }, { "code": null, "e": 25668, "s": 25594, "text": "Example 2: Type conversion of a vector with both characters and integers." }, { "code": "# R Program to illustrate# conversion of a vector with both characters and integers # create an example vectorx1 <- c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\") # Create example datax2 <- c(x1, \"AAA\") # Class of example data class(x2) # Apply type.convert functionx2_convert <- type.convert(x2) # Class of converted data class(x2_convert) ", "e": 26053, "s": 25668, "text": null }, { "code": null, "e": 26061, "s": 26053, "text": "Output:" }, { "code": null, "e": 26091, "s": 26061, "text": "[1] \"character\"\n[1] \"factor\"\n" }, { "code": null, "e": 26234, "s": 26091, "text": "Here, in the above code there were some characters and some integers after using type.convert() function. So, the output comes to be a factor." }, { "code": null, "e": 26245, "s": 26234, "text": "R Language" }, { "code": null, "e": 26343, "s": 26245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26395, "s": 26343, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26427, "s": 26395, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26479, "s": 26427, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26523, "s": 26479, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26561, "s": 26523, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26596, "s": 26561, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26645, "s": 26596, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26681, "s": 26645, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 26739, "s": 26681, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
OptionalInt getAsInt() method in Java with examples - GeeksforGeeks
30 Jul, 2019 OptionalInt help us to create an object which may or may not contain a int value. The getAsInt() method returns value If a value is present in OptionalInt object, otherwise throws NoSuchElementException. Syntax: public int getAsInt() Parameters: This method accepts nothing. Return value: This method returns the value described by this OptionalInt. Exception: This method throws NoSuchElementException if no value is present Below programs illustrate getAsInt() method: Program 1: // Java program to demonstrate// OptionalInt.getAsInt() method import java.util.OptionalInt; public class GFG { public static void main(String[] args) { // Create an OptionalInt instance OptionalInt opInt = OptionalInt.of(45); System.out.println("OptionalInt: " + opInt.toString()); // Get value in this instance // using getAsInt() System.out.println("Value in OptionalInt = " + opInt.getAsInt()); }} OptionalInt: OptionalInt[45] Value in OptionalInt = 45 Program 2: // Java program to demonstrate// OptionalInt.getAsInt() method import java.util.OptionalInt; public class GFG { public static void main(String[] args) { try { // Create an OptionalInt instance OptionalInt opInt = OptionalInt.empty(); System.out.println("OptionalInt: " + opInt.toString()); // Get value in this instance // using getAsInt() System.out.println("Value in OptionalInt = " + opInt.getAsInt()); } catch (Exception e) { System.out.println("Exception: " + e); } }} OptionalInt: OptionalInt.empty Exception: java.util.NoSuchElementException: No value present References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalInt.html#getAsInt() Akanksha_Rai Java - util package Java-Functions Java-OptionalInt Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n30 Jul, 2019" }, { "code": null, "e": 23787, "s": 23583, "text": "OptionalInt help us to create an object which may or may not contain a int value. The getAsInt() method returns value If a value is present in OptionalInt object, otherwise throws NoSuchElementException." }, { "code": null, "e": 23795, "s": 23787, "text": "Syntax:" }, { "code": null, "e": 23818, "s": 23795, "text": "public int getAsInt()\n" }, { "code": null, "e": 23859, "s": 23818, "text": "Parameters: This method accepts nothing." }, { "code": null, "e": 23934, "s": 23859, "text": "Return value: This method returns the value described by this OptionalInt." }, { "code": null, "e": 24010, "s": 23934, "text": "Exception: This method throws NoSuchElementException if no value is present" }, { "code": null, "e": 24055, "s": 24010, "text": "Below programs illustrate getAsInt() method:" }, { "code": null, "e": 24066, "s": 24055, "text": "Program 1:" }, { "code": "// Java program to demonstrate// OptionalInt.getAsInt() method import java.util.OptionalInt; public class GFG { public static void main(String[] args) { // Create an OptionalInt instance OptionalInt opInt = OptionalInt.of(45); System.out.println(\"OptionalInt: \" + opInt.toString()); // Get value in this instance // using getAsInt() System.out.println(\"Value in OptionalInt = \" + opInt.getAsInt()); }}", "e": 24581, "s": 24066, "text": null }, { "code": null, "e": 24637, "s": 24581, "text": "OptionalInt: OptionalInt[45]\nValue in OptionalInt = 45\n" }, { "code": null, "e": 24648, "s": 24637, "text": "Program 2:" }, { "code": "// Java program to demonstrate// OptionalInt.getAsInt() method import java.util.OptionalInt; public class GFG { public static void main(String[] args) { try { // Create an OptionalInt instance OptionalInt opInt = OptionalInt.empty(); System.out.println(\"OptionalInt: \" + opInt.toString()); // Get value in this instance // using getAsInt() System.out.println(\"Value in OptionalInt = \" + opInt.getAsInt()); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 25310, "s": 24648, "text": null }, { "code": null, "e": 25404, "s": 25310, "text": "OptionalInt: OptionalInt.empty\nException: java.util.NoSuchElementException: No value present\n" }, { "code": null, "e": 25497, "s": 25404, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalInt.html#getAsInt()" }, { "code": null, "e": 25510, "s": 25497, "text": "Akanksha_Rai" }, { "code": null, "e": 25530, "s": 25510, "text": "Java - util package" }, { "code": null, "e": 25545, "s": 25530, "text": "Java-Functions" }, { "code": null, "e": 25562, "s": 25545, "text": "Java-OptionalInt" }, { "code": null, "e": 25567, "s": 25562, "text": "Java" }, { "code": null, "e": 25572, "s": 25567, "text": "Java" }, { "code": null, "e": 25670, "s": 25572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25679, "s": 25670, "text": "Comments" }, { "code": null, "e": 25692, "s": 25679, "text": "Old Comments" }, { "code": null, "e": 25710, "s": 25692, "text": "Hashtable in Java" }, { "code": null, "e": 25731, "s": 25710, "text": "Constructors in Java" }, { "code": null, "e": 25777, "s": 25731, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25820, "s": 25777, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 25860, "s": 25820, "text": "Java Math random() method with Examples" }, { "code": null, "e": 25897, "s": 25860, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 25937, "s": 25897, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 25971, "s": 25937, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26005, "s": 25971, "text": "Iterating over ArrayLists in Java" } ]
Artifact Report
Now that you are comfortable with installation and running Python commands on your local system, let us move into the concepts of forensics in detail. This chapter will explain various concepts involved in dealing with artifacts in Python digital forensics. The process of digital forensics includes reporting as the third phase. This is one of the most important parts of digital forensic process. Report creation is necessary due to the following reasons − It is the document in which digital forensic examiner outlines the investigation process and its findings. It is the document in which digital forensic examiner outlines the investigation process and its findings. A good digital forensic report can be referenced by another examiner to achieve same result by given same repositories. A good digital forensic report can be referenced by another examiner to achieve same result by given same repositories. It is a technical and scientific document that contains facts found within the 1s and 0s of digital evidence. It is a technical and scientific document that contains facts found within the 1s and 0s of digital evidence. The reports are written to provide information to the reader and must start with a solid foundation. investigators can face difficulties in efficiently presenting their findings if the report is prepared without some general guidelines or standards. Some general guidelines which must be followed while creating digital forensic reports are given below − Summary − The report must contain the brief summary of information so that the reader can ascertain the report’s purpose. Summary − The report must contain the brief summary of information so that the reader can ascertain the report’s purpose. Tools used − We must mention the tools which have been used for carrying the process of digital forensics, including their purpose. Tools used − We must mention the tools which have been used for carrying the process of digital forensics, including their purpose. Repository − Suppose, we investigated someone’s computer then the summary of evidence and analysis of relevant material like email, internal search history etc., then they must be included in the report so that the case may be clearly presented. Repository − Suppose, we investigated someone’s computer then the summary of evidence and analysis of relevant material like email, internal search history etc., then they must be included in the report so that the case may be clearly presented. Recommendations for counsel − The report must have the recommendations for counsel to continue or cease investigation based on the findings in report. Recommendations for counsel − The report must have the recommendations for counsel to continue or cease investigation based on the findings in report. In the above section, we came to know about the importance of report in digital forensics along with the guidelines for creating the same. Some of the formats in Python for creating different kind of reports are discussed below − One of the most common output formats of reports is a CSV spreadsheet report. You can create a CSV to create a report of processed data using the Python code as shown below − First, import useful libraries for writing the spreadsheet − from __future__ import print_function import csv import os import sys Now, call the following method − Write_csv(TEST_DATA_LIST, ["Name", "Age", "City", "Job description"], os.getcwd()) We are using the following global variable to represent sample data types − TEST_DATA_LIST = [["Ram", 32, Bhopal, Manager], ["Raman", 42, Indore, Engg.], ["Mohan", 25, Chandigarh, HR], ["Parkash", 45, Delhi, IT]] Next, let us define the method to proceed for further operations. We open the file in the “w” mode and set the newline keyword argument to an empty string. def Write_csv(data, header, output_directory, name = None): if name is None: name = "report1.csv" print("[+] Writing {} to {}".format(name, output_directory)) with open(os.path.join(output_directory, name), "w", newline = "") as \ csvfile: writer = csv.writer(csvfile) writer.writerow(header) writer.writerow(data) If you run the above script, you will get the following details stored in report1.csv file. Another common output format of reports is Excel (.xlsx) spreadsheet report. We can create table and also plot the graph by using Excel. We can create report of processed data in Excel format using Python code as shown below− First, import XlsxWriter module for creating spreadsheet − import xlsxwriter Now, create a workbook object. For this, we need to use Workbook() constructor. workbook = xlsxwriter.Workbook('report2.xlsx') Now, create a new worksheet by using add_worksheet() module. worksheet = workbook.add_worksheet() Next, write the following data into the worksheet − report2 = (['Ram', 32, ‘Bhopal’],['Mohan',25, ‘Chandigarh’] ,['Parkash',45, ‘Delhi’]) row = 0 col = 0 You can iterate over this data and write it as follows − for item, cost in (a): worksheet.write(row, col, item) worksheet.write(row, col+1, cost) row + = 1 Now, let us close this Excel file by using close() method. workbook.close() The above script will create an Excel file named report2.xlsx having the following data − It is important for an investigator to have the detailed investigative notes to accurately recall the findings or put together all the pieces of investigation. A screenshot is very useful to keep track of the steps taken for a particular investigation. With the help of the following Python code, we can take the screenshot and save it on hard disk for future use. First, install Python module named pyscreenshot by using following command − Pip install pyscreenshot Now, import the necessary modules as shown − import pyscreenshot as ImageGrab Use the following line of code to get the screenshot − image = ImageGrab.grab() Use the following line of code to save the screenshot to the given location − image.save('d:/image123.png') Now, if you want to pop up the screenshot as a graph, you can use the following Python code − import numpy as np import matplotlib.pyplot as plt import pyscreenshot as ImageGrab imageg = ImageGrab.grab() plt.imshow(image, cmap='gray', interpolation='bilinear') plt.show() 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2211, "s": 1953, "text": "Now that you are comfortable with installation and running Python commands on your local system, let us move into the concepts of forensics in detail. This chapter will explain various concepts involved in dealing with artifacts in Python digital forensics." }, { "code": null, "e": 2412, "s": 2211, "text": "The process of digital forensics includes reporting as the third phase. This is one of the most important parts of digital forensic process. Report creation is necessary due to the following reasons −" }, { "code": null, "e": 2519, "s": 2412, "text": "It is the document in which digital forensic examiner outlines the investigation process and its findings." }, { "code": null, "e": 2626, "s": 2519, "text": "It is the document in which digital forensic examiner outlines the investigation process and its findings." }, { "code": null, "e": 2746, "s": 2626, "text": "A good digital forensic report can be referenced by another examiner to achieve same result by given same repositories." }, { "code": null, "e": 2866, "s": 2746, "text": "A good digital forensic report can be referenced by another examiner to achieve same result by given same repositories." }, { "code": null, "e": 2976, "s": 2866, "text": "It is a technical and scientific document that contains facts found within the 1s and 0s of digital evidence." }, { "code": null, "e": 3086, "s": 2976, "text": "It is a technical and scientific document that contains facts found within the 1s and 0s of digital evidence." }, { "code": null, "e": 3441, "s": 3086, "text": "The reports are written to provide information to the reader and must start with a solid foundation. investigators can face difficulties in efficiently presenting their findings if the report is prepared without some general guidelines or standards. Some general guidelines which must be followed while creating digital forensic reports are given below −" }, { "code": null, "e": 3563, "s": 3441, "text": "Summary − The report must contain the brief summary of information so that the reader can ascertain the report’s purpose." }, { "code": null, "e": 3685, "s": 3563, "text": "Summary − The report must contain the brief summary of information so that the reader can ascertain the report’s purpose." }, { "code": null, "e": 3817, "s": 3685, "text": "Tools used − We must mention the tools which have been used for carrying the process of digital forensics, including their purpose." }, { "code": null, "e": 3949, "s": 3817, "text": "Tools used − We must mention the tools which have been used for carrying the process of digital forensics, including their purpose." }, { "code": null, "e": 4195, "s": 3949, "text": "Repository − Suppose, we investigated someone’s computer then the summary of evidence and analysis of relevant material like email, internal search history etc., then they must be included in the report so that the case may be clearly presented." }, { "code": null, "e": 4441, "s": 4195, "text": "Repository − Suppose, we investigated someone’s computer then the summary of evidence and analysis of relevant material like email, internal search history etc., then they must be included in the report so that the case may be clearly presented." }, { "code": null, "e": 4592, "s": 4441, "text": "Recommendations for counsel − The report must have the recommendations for counsel to continue or cease investigation based on the findings in report." }, { "code": null, "e": 4743, "s": 4592, "text": "Recommendations for counsel − The report must have the recommendations for counsel to continue or cease investigation based on the findings in report." }, { "code": null, "e": 4973, "s": 4743, "text": "In the above section, we came to know about the importance of report in digital forensics along with the guidelines for creating the same. Some of the formats in Python for creating different kind of reports are discussed below −" }, { "code": null, "e": 5148, "s": 4973, "text": "One of the most common output formats of reports is a CSV spreadsheet report. You can create a CSV to create a report of processed data using the Python code as shown below −" }, { "code": null, "e": 5209, "s": 5148, "text": "First, import useful libraries for writing the spreadsheet −" }, { "code": null, "e": 5279, "s": 5209, "text": "from __future__ import print_function\nimport csv\nimport os\nimport sys" }, { "code": null, "e": 5312, "s": 5279, "text": "Now, call the following method −" }, { "code": null, "e": 5396, "s": 5312, "text": "Write_csv(TEST_DATA_LIST, [\"Name\", \"Age\", \"City\", \"Job description\"], os.getcwd())\n" }, { "code": null, "e": 5472, "s": 5396, "text": "We are using the following global variable to represent sample data types −" }, { "code": null, "e": 5620, "s": 5472, "text": "TEST_DATA_LIST = [[\"Ram\", 32, Bhopal, Manager], \n [\"Raman\", 42, Indore, Engg.],\n [\"Mohan\", 25, Chandigarh, HR], \n [\"Parkash\", 45, Delhi, IT]]" }, { "code": null, "e": 5776, "s": 5620, "text": "Next, let us define the method to proceed for further operations. We open the file in the “w” mode and set the newline keyword argument to an empty string." }, { "code": null, "e": 6128, "s": 5776, "text": "def Write_csv(data, header, output_directory, name = None):\n if name is None:\n name = \"report1.csv\"\n print(\"[+] Writing {} to {}\".format(name, output_directory))\n \n with open(os.path.join(output_directory, name), \"w\", newline = \"\") as \\ csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(header)\n writer.writerow(data)" }, { "code": null, "e": 6220, "s": 6128, "text": "If you run the above script, you will get the following details stored in report1.csv file." }, { "code": null, "e": 6446, "s": 6220, "text": "Another common output format of reports is Excel (.xlsx) spreadsheet report. We can create table and also plot the graph by using Excel. We can create report of processed data in Excel format using Python code as shown below−" }, { "code": null, "e": 6505, "s": 6446, "text": "First, import XlsxWriter module for creating spreadsheet −" }, { "code": null, "e": 6524, "s": 6505, "text": "import xlsxwriter\n" }, { "code": null, "e": 6604, "s": 6524, "text": "Now, create a workbook object. For this, we need to use Workbook() constructor." }, { "code": null, "e": 6652, "s": 6604, "text": "workbook = xlsxwriter.Workbook('report2.xlsx')\n" }, { "code": null, "e": 6713, "s": 6652, "text": "Now, create a new worksheet by using add_worksheet() module." }, { "code": null, "e": 6751, "s": 6713, "text": "worksheet = workbook.add_worksheet()\n" }, { "code": null, "e": 6803, "s": 6751, "text": "Next, write the following data into the worksheet −" }, { "code": null, "e": 6906, "s": 6803, "text": "report2 = (['Ram', 32, ‘Bhopal’],['Mohan',25, ‘Chandigarh’] ,['Parkash',45, ‘Delhi’])\n\nrow = 0\ncol = 0" }, { "code": null, "e": 6963, "s": 6906, "text": "You can iterate over this data and write it as follows −" }, { "code": null, "e": 7071, "s": 6963, "text": "for item, cost in (a):\n worksheet.write(row, col, item)\n worksheet.write(row, col+1, cost)\n row + = 1" }, { "code": null, "e": 7130, "s": 7071, "text": "Now, let us close this Excel file by using close() method." }, { "code": null, "e": 7148, "s": 7130, "text": "workbook.close()\n" }, { "code": null, "e": 7238, "s": 7148, "text": "The above script will create an Excel file named report2.xlsx having the following data −" }, { "code": null, "e": 7603, "s": 7238, "text": "It is important for an investigator to have the detailed investigative notes to accurately recall the findings or put together all the pieces of investigation. A screenshot is very useful to keep track of the steps taken for a particular investigation. With the help of the following Python code, we can take the screenshot and save it on hard disk for future use." }, { "code": null, "e": 7680, "s": 7603, "text": "First, install Python module named pyscreenshot by using following command −" }, { "code": null, "e": 7706, "s": 7680, "text": "Pip install pyscreenshot\n" }, { "code": null, "e": 7751, "s": 7706, "text": "Now, import the necessary modules as shown −" }, { "code": null, "e": 7785, "s": 7751, "text": "import pyscreenshot as ImageGrab\n" }, { "code": null, "e": 7840, "s": 7785, "text": "Use the following line of code to get the screenshot −" }, { "code": null, "e": 7866, "s": 7840, "text": "image = ImageGrab.grab()\n" }, { "code": null, "e": 7944, "s": 7866, "text": "Use the following line of code to save the screenshot to the given location −" }, { "code": null, "e": 7975, "s": 7944, "text": "image.save('d:/image123.png')\n" }, { "code": null, "e": 8069, "s": 7975, "text": "Now, if you want to pop up the screenshot as a graph, you can use the following Python code −" }, { "code": null, "e": 8247, "s": 8069, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pyscreenshot as ImageGrab\nimageg = ImageGrab.grab()\nplt.imshow(image, cmap='gray', interpolation='bilinear')\nplt.show()" }, { "code": null, "e": 8284, "s": 8247, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8300, "s": 8284, "text": " Malhar Lathkar" }, { "code": null, "e": 8333, "s": 8300, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 8352, "s": 8333, "text": " Arnab Chakraborty" }, { "code": null, "e": 8387, "s": 8352, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 8409, "s": 8387, "text": " In28Minutes Official" }, { "code": null, "e": 8443, "s": 8409, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 8471, "s": 8443, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8506, "s": 8471, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 8520, "s": 8506, "text": " Lets Kode It" }, { "code": null, "e": 8553, "s": 8520, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 8570, "s": 8553, "text": " Abhilash Nelson" }, { "code": null, "e": 8577, "s": 8570, "text": " Print" }, { "code": null, "e": 8588, "s": 8577, "text": " Add Notes" } ]
How to substring value in a MySQL table column?
To substring a MySQL table column, use the in-built SUBSTR() function from MySQL. The syntax is as follows − select substr(yourColumnName,AnyValue) as anyVariableName from yourTableName; To understand the function substr(), let us create a table. The query to create a table is as follows − mysql> create table SubStringDemo −> ( −> UserId varchar(200) −> ); Query OK, 0 rows affected (0.55 sec) Now insert some records in the table. The query to insert records is as follows − mysql> insert into SubStringDemo values('Bob10015'); Query OK, 1 row affected (0.29 sec) mysql> insert into SubStringDemo values('Smith0015'); Query OK, 1 row affected (0.22 sec) mysql> insert into SubStringDemo values('Carol20010'); Query OK, 1 row affected (0.14 sec) Now you can display all records from the table with the help of select statement. The query is as follows − mysql> select *from SubStringDemo; The following is the output − +------------+ | UserId | +------------+ | Bob10015 | | Smith0015 | | Carol20010 | +------------+ 3 rows in set (0.00 sec) The following is the query to substring MySQL table column − mysql> select substr(UserId,5) as ExtractSubstring from SubStringDemo; Here is the output that displays the substrings − +------------------+ | ExtractSubstring | +------------------+ | 0015 | | h0015 | | l20010 | +------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1171, "s": 1062, "text": "To substring a MySQL table column, use the in-built SUBSTR() function from MySQL. The syntax is as follows −" }, { "code": null, "e": 1249, "s": 1171, "text": "select substr(yourColumnName,AnyValue) as anyVariableName from yourTableName;" }, { "code": null, "e": 1353, "s": 1249, "text": "To understand the function substr(), let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1467, "s": 1353, "text": "mysql> create table SubStringDemo\n −> (\n −> UserId varchar(200)\n −> );\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1549, "s": 1467, "text": "Now insert some records in the table. The query to insert records is as follows −" }, { "code": null, "e": 1821, "s": 1549, "text": "mysql> insert into SubStringDemo values('Bob10015');\nQuery OK, 1 row affected (0.29 sec)\n\nmysql> insert into SubStringDemo values('Smith0015');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into SubStringDemo values('Carol20010');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1929, "s": 1821, "text": "Now you can display all records from the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 1964, "s": 1929, "text": "mysql> select *from SubStringDemo;" }, { "code": null, "e": 1994, "s": 1964, "text": "The following is the output −" }, { "code": null, "e": 2124, "s": 1994, "text": "+------------+\n| UserId |\n+------------+\n| Bob10015 |\n| Smith0015 |\n| Carol20010 |\n+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2185, "s": 2124, "text": "The following is the query to substring MySQL table column −" }, { "code": null, "e": 2256, "s": 2185, "text": "mysql> select substr(UserId,5) as ExtractSubstring from SubStringDemo;" }, { "code": null, "e": 2306, "s": 2256, "text": "Here is the output that displays the substrings −" }, { "code": null, "e": 2478, "s": 2306, "text": "+------------------+\n| ExtractSubstring |\n+------------------+\n| 0015 |\n| h0015 |\n| l20010 |\n+------------------+\n3 rows in set (0.00 sec)" } ]
Deep Learning with Keras - Importing Libraries
We first import the various libraries required by the code in our project. As typical, we use numpy for array handling and matplotlib for plotting. These libraries are imported in our project using the following import statements import numpy as np import matplotlib import matplotlib.pyplot as plot As both Tensorflow and Keras keep on revising, if you do not sync their appropriate versions in the project, at runtime you would see plenty of warning errors. As they distract your attention from learning, we shall be suppressing all the warnings in this project. This is done with the following lines of code − # silent all warnings import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' import warnings warnings.filterwarnings('ignore') from tensorflow.python.util import deprecation deprecation._PRINT_DEPRECATION_WARNINGS = False We use Keras libraries to import dataset. We will use the mnist dataset for handwritten digits. We import the required package using the following statement from keras.datasets import mnist We will be defining our deep learning neural network using Keras packages. We import the Sequential, Dense, Dropout and Activation packages for defining the network architecture. We use load_model package for saving and retrieving our model. We also use np_utils for a few utilities that we need in our project. These imports are done with the following program statements − from keras.models import Sequential, load_model from keras.layers.core import Dense, Dropout, Activation from keras.utils import np_utils When you run this code, you will see a message on the console that says that Keras uses TensorFlow at the backend. The screenshot at this stage is shown here − Now, as we have all the imports required by our project, we will proceed to define the architecture for our Deep Learning network. 87 Lectures 11 hours Abhilash Nelson 106 Lectures 13.5 hours Abhilash Nelson 28 Lectures 4 hours Abhilash Nelson 58 Lectures 8 hours Soumyadeep Dey 59 Lectures 2.5 hours Mike West 128 Lectures 5.5 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2034, "s": 1959, "text": "We first import the various libraries required by the code in our project." }, { "code": null, "e": 2189, "s": 2034, "text": "As typical, we use numpy for array handling and matplotlib for plotting. These libraries are imported in our project using the following import statements" }, { "code": null, "e": 2260, "s": 2189, "text": "import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plot\n" }, { "code": null, "e": 2573, "s": 2260, "text": "As both Tensorflow and Keras keep on revising, if you do not sync their appropriate versions in the project, at runtime you would see plenty of warning errors. As they distract your attention from learning, we shall be suppressing all the warnings in this project. This is done with the following lines of code −" }, { "code": null, "e": 2789, "s": 2573, "text": "# silent all warnings\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='3'\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom tensorflow.python.util import deprecation\ndeprecation._PRINT_DEPRECATION_WARNINGS = False" }, { "code": null, "e": 2946, "s": 2789, "text": "We use Keras libraries to import dataset. We will use the mnist dataset for handwritten digits. We import the required package using the following statement" }, { "code": null, "e": 2980, "s": 2946, "text": "from keras.datasets import mnist\n" }, { "code": null, "e": 3355, "s": 2980, "text": "We will be defining our deep learning neural network using Keras packages. We import the Sequential, Dense, Dropout and Activation packages for defining the network architecture. We use load_model package for saving and retrieving our model. We also use np_utils for a few utilities that we need in our project. These imports are done with the following program statements −" }, { "code": null, "e": 3493, "s": 3355, "text": "from keras.models import Sequential, load_model\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.utils import np_utils" }, { "code": null, "e": 3653, "s": 3493, "text": "When you run this code, you will see a message on the console that says that Keras uses TensorFlow at the backend. The screenshot at this stage is shown here −" }, { "code": null, "e": 3784, "s": 3653, "text": "Now, as we have all the imports required by our project, we will proceed to define the architecture for our Deep Learning network." }, { "code": null, "e": 3818, "s": 3784, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 3835, "s": 3818, "text": " Abhilash Nelson" }, { "code": null, "e": 3872, "s": 3835, "text": "\n 106 Lectures \n 13.5 hours \n" }, { "code": null, "e": 3889, "s": 3872, "text": " Abhilash Nelson" }, { "code": null, "e": 3922, "s": 3889, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 3939, "s": 3922, "text": " Abhilash Nelson" }, { "code": null, "e": 3972, "s": 3939, "text": "\n 58 Lectures \n 8 hours \n" }, { "code": null, "e": 3988, "s": 3972, "text": " Soumyadeep Dey" }, { "code": null, "e": 4023, "s": 3988, "text": "\n 59 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4034, "s": 4023, "text": " Mike West" }, { "code": null, "e": 4070, "s": 4034, "text": "\n 128 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4086, "s": 4070, "text": " TELCOMA Global" }, { "code": null, "e": 4093, "s": 4086, "text": " Print" }, { "code": null, "e": 4104, "s": 4093, "text": " Add Notes" } ]
Generating n random numbers between a range - JavaScript
We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument. Following is the code − const num = 10; const range = [5, 15]; const randomBetween = (a, b) => { return ((Math.random() * (b - a)) + a).toFixed(2); }; const randomBetweenRange = (num, range) => { const res = []; for(let i = 0; i < num; ){ const random = randomBetween(range[0], range[1]); if(!res.includes(random)){ res.push(random); i++; }; }; return res; }; console.log(randomBetweenRange(num, range)); This will produce the following output in console − [ '13.25', '10.31', '11.83', '5.25', '6.28', '9.99', '6.09', '7.58', '12.64', '8.92' ] This is just one of the many possible outputs. Let us run again to get a different random output − [ '5.29', '7.95', '11.61', '7.83', '10.56', '7.48', '12.96', '6.92', '8.98', '9.43' ]
[ { "code": null, "e": 1311, "s": 1062, "text": "We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument." }, { "code": null, "e": 1335, "s": 1311, "text": "Following is the code −" }, { "code": null, "e": 1767, "s": 1335, "text": "const num = 10;\nconst range = [5, 15];\nconst randomBetween = (a, b) => {\n return ((Math.random() * (b - a)) + a).toFixed(2);\n};\nconst randomBetweenRange = (num, range) => {\n const res = [];\n for(let i = 0; i < num; ){\n const random = randomBetween(range[0], range[1]);\n if(!res.includes(random)){\n res.push(random);\n i++;\n };\n };\n return res;\n};\nconsole.log(randomBetweenRange(num, range));" }, { "code": null, "e": 1819, "s": 1767, "text": "This will produce the following output in console −" }, { "code": null, "e": 1923, "s": 1819, "text": "[\n '13.25', '10.31',\n '11.83', '5.25',\n '6.28', '9.99',\n '6.09', '7.58',\n '12.64', '8.92'\n]" }, { "code": null, "e": 1970, "s": 1923, "text": "This is just one of the many possible outputs." }, { "code": null, "e": 2022, "s": 1970, "text": "Let us run again to get a different random output −" }, { "code": null, "e": 2125, "s": 2022, "text": "[\n '5.29', '7.95',\n '11.61', '7.83',\n '10.56', '7.48',\n '12.96', '6.92',\n '8.98', '9.43'\n]" } ]
Design Background color changer using HTML CSS and JavaScript - GeeksforGeeks
12 Jan, 2021 Background color changer is a project which enables to change background color of web pages with an ease. There are color boxes on a web page when user click on any one of them, then the resultant color will appear in the background of the web page. It makes web pages look attractive. File structure: index.html style.css script.js Prerequisites: Basic knowledge of HTML, CSS, and JavaScript needed. The project contains HTML, CSS and JavaScript files. The HTML file adds structure, followed by styling using CSS and JavaScript adds functionality to it. HTML File: index.html HTML layout is created using the div tag, id attribute and anchor tags for function calling. It defines the structure of the web page. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Background changer using JavaScript</title> <link rel="stylesheet" href="style.css"></head> <body> <h1>Background changer with a color box</h1> <div> <a onclick="bgchange(id)" id="color1"> #e58e26</a> <a onclick="bgchange(id)" id="color2"> #f9b4ab</a> <a onclick="bgchange(id)" id="color3"> #B1FB17</a> <a onclick="bgchange(id)" id="color4"> #78e08f</a> <a onclick="bgchange(id)" id="color5"> #fd79a8</a> </div> <script src="script.js"></script></body> </html> CSS File: style.css By using CSS properties, we will decorate the web page and make it look attractive. color, width, height and position property are given as per the requirement in the project. CSS body { background: #81ecec;} h1 { color:#6203e0;} div { width:25%; height: 50px; display: flex; justify-content: space-around; padding: 10px; background: white;} #color1 { flex: 1; background: #e58e26; color:#e58e26;} #color2 { flex: 1; background: #f9b4ab; color: #f9b4ab;} #color3 { flex: 1; background: #B1FB17; color: #B1FB17;} #color4 { flex: 1; background: #78e08f; color: #78e08f;} #color5 { flex: 1; background: #fd79a8; color: #fd79a8;} JavaScript File: script.js JavaScript code is used to give functionality to web page. Here we used arrow function with “id” parameter. Javascript const bgchange =(id) => { document.body.style.background = document.getElementById(id).innerHTML;} Output: Before picking color: Background changer with color box After picking color: Background changer with color box CSS-Misc HTML-Misc JavaScript-Misc Technical Scripter 2020 CSS HTML JavaScript Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25400, "s": 25372, "text": "\n12 Jan, 2021" }, { "code": null, "e": 25686, "s": 25400, "text": "Background color changer is a project which enables to change background color of web pages with an ease. There are color boxes on a web page when user click on any one of them, then the resultant color will appear in the background of the web page. It makes web pages look attractive." }, { "code": null, "e": 25702, "s": 25686, "text": "File structure:" }, { "code": null, "e": 25713, "s": 25702, "text": "index.html" }, { "code": null, "e": 25723, "s": 25713, "text": "style.css" }, { "code": null, "e": 25733, "s": 25723, "text": "script.js" }, { "code": null, "e": 25955, "s": 25733, "text": "Prerequisites: Basic knowledge of HTML, CSS, and JavaScript needed. The project contains HTML, CSS and JavaScript files. The HTML file adds structure, followed by styling using CSS and JavaScript adds functionality to it." }, { "code": null, "e": 26112, "s": 25955, "text": "HTML File: index.html HTML layout is created using the div tag, id attribute and anchor tags for function calling. It defines the structure of the web page." }, { "code": null, "e": 26117, "s": 26112, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Background changer using JavaScript</title> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <h1>Background changer with a color box</h1> <div> <a onclick=\"bgchange(id)\" id=\"color1\"> #e58e26</a> <a onclick=\"bgchange(id)\" id=\"color2\"> #f9b4ab</a> <a onclick=\"bgchange(id)\" id=\"color3\"> #B1FB17</a> <a onclick=\"bgchange(id)\" id=\"color4\"> #78e08f</a> <a onclick=\"bgchange(id)\" id=\"color5\"> #fd79a8</a> </div> <script src=\"script.js\"></script></body> </html>", "e": 26792, "s": 26117, "text": null }, { "code": null, "e": 26988, "s": 26792, "text": "CSS File: style.css By using CSS properties, we will decorate the web page and make it look attractive. color, width, height and position property are given as per the requirement in the project." }, { "code": null, "e": 26992, "s": 26988, "text": "CSS" }, { "code": "body { background: #81ecec;} h1 { color:#6203e0;} div { width:25%; height: 50px; display: flex; justify-content: space-around; padding: 10px; background: white;} #color1 { flex: 1; background: #e58e26; color:#e58e26;} #color2 { flex: 1; background: #f9b4ab; color: #f9b4ab;} #color3 { flex: 1; background: #B1FB17; color: #B1FB17;} #color4 { flex: 1; background: #78e08f; color: #78e08f;} #color5 { flex: 1; background: #fd79a8; color: #fd79a8;}", "e": 27514, "s": 26992, "text": null }, { "code": null, "e": 27649, "s": 27514, "text": "JavaScript File: script.js JavaScript code is used to give functionality to web page. Here we used arrow function with “id” parameter." }, { "code": null, "e": 27660, "s": 27649, "text": "Javascript" }, { "code": "const bgchange =(id) => { document.body.style.background = document.getElementById(id).innerHTML;}", "e": 27770, "s": 27660, "text": null }, { "code": null, "e": 27778, "s": 27770, "text": "Output:" }, { "code": null, "e": 27800, "s": 27778, "text": "Before picking color:" }, { "code": null, "e": 27834, "s": 27800, "text": "Background changer with color box" }, { "code": null, "e": 27855, "s": 27834, "text": "After picking color:" }, { "code": null, "e": 27890, "s": 27855, "text": "Background changer with color box " }, { "code": null, "e": 27899, "s": 27890, "text": "CSS-Misc" }, { "code": null, "e": 27909, "s": 27899, "text": "HTML-Misc" }, { "code": null, "e": 27925, "s": 27909, "text": "JavaScript-Misc" }, { "code": null, "e": 27949, "s": 27925, "text": "Technical Scripter 2020" }, { "code": null, "e": 27953, "s": 27949, "text": "CSS" }, { "code": null, "e": 27958, "s": 27953, "text": "HTML" }, { "code": null, "e": 27969, "s": 27958, "text": "JavaScript" }, { "code": null, "e": 27988, "s": 27969, "text": "Technical Scripter" }, { "code": null, "e": 28005, "s": 27988, "text": "Web Technologies" }, { "code": null, "e": 28032, "s": 28005, "text": "Web technologies Questions" }, { "code": null, "e": 28037, "s": 28032, "text": "HTML" }, { "code": null, "e": 28135, "s": 28037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28172, "s": 28135, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28201, "s": 28172, "text": "Form validation using jQuery" }, { "code": null, "e": 28240, "s": 28201, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28282, "s": 28240, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28317, "s": 28282, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28377, "s": 28317, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28438, "s": 28377, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28491, "s": 28438, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28541, "s": 28491, "text": "How to Insert Form Data into Database using PHP ?" } ]
Predicting UFC Fights With Machine Learning | by Charles Pierse | Towards Data Science
TL;DR: check out the predictor for yourself and see how it performs for an upcoming UFC fight card or check out the code on github As a fan of MMA I often find myself trying to predict the outcome of fights on an upcoming fight card. The problem is that fighting by its nature can be very unpredictable. More so than even boxing, the outcome of an MMA fight can change in a split second, but of course that’s what makes it so interesting. All the same I wondered if there was a way to apply modern machine learning techniques to historical fight data and see how a model would perform on new fights. Of course like any ML project I needed data to work with. Fortunately I had a good idea of where I might find some having often visited www.ufcstats.com the day after a fight card to get the stats breakdown for a fight. So now that I had my data source and a couple of ideas of how I could implement the model I wondered if anyone else had built a project like this and came across this post by Yuan Tian detailing his process for building a fight predictor. Yuan’s post was very detailed and insightful and my methodology for scraping the stats page was largely inspired by how he structured his scrapers. Thanks Yuan! In Yuan’s predictor he used fight data that would be available before a fight with stats that I called “static fight stats” e.g. age, reach, weight, W/L record etc. However, the UFC stats page also detailed fight specific stats for historical bouts such as strikes thrown, takedowns , submission attempts, and guard passes. As there weren’t an awful lot of data points on the UFC stats page to begin with I felt discarding these “dynamic fight stats” would be a shame. So I decided to build the predictor as a two way predictive system: The first model uses the static stats as the independent variables for fighter 1 and fighter 2 and then predicts the dependent variables, the dynamic fight stats.( A multi target regression problem). We then pass the static and dynamic fight stats to an overall winner model that predicts whether fighter 1 or fighter 2 is the winner. (A binary classification problem). The scrapers for this project are broken down into two Scrapy spiders that crawl two sections of UFC Fight Stats: Bout Scraper Fighter Scraper The Bout scrapers data object is broken down as the following Scrapy Item: class BoutScraperItem(Item): event_name = Field() event_date = Field() event_attendance = Field() fighter1 = Field() fighter2 = Field() str_stat_f1 = Field() str_stat_f2 = Field() td_stat_f1 = Field() td_stat_f2 = Field() sub_stat_f1 = Field() sub_stat_f2 = Field() pass_stat_f1 = Field() pass_stat_f2 = Field() weight_class = Field() win_method_type = Field() win_method_finish = Field() round_ = Field() time = Field() winner = Field() The Bout spider crawls the events section of UFC Fight Stats and records bout specific stats such as str_stat_f1 (striking stats for fighter 1) for each fighter, many of these will become our dependent variables for the multi target regression problem. Fighter1 and Fighter2 are the names of the fighters involved in a bout and we join the fighter scraper data on these values. The Fighter scraper data object is broken down as : class FightScraperItem(Item): fighter_name = Field() fighter_record = Field() height = Field() weight = Field() reach = Field() stance = Field() date_of_birth = Field() slpm = Field() # strikes landed per min stat td_avg = Field() # takedown average strike_acc = Field() # striking accuracy td_acc = Field() # takedown accuracy sapm = Field() # strikes absorbed per minute td_def = Field() # takedown defence strike_def = Field() # striking defence sub_avg = Field() # submission average Each item here is individually scraped from the fighter stats page which details career stats for every fighter involved in a UFC bout (although data from the earlier days of the UFC is less populated). I save both of these data objects as tables into a SQLite database and have a small script for generating a combined fight-bouts CSV file where each row is a bout with fighter1 and fighter2’s individual fighter stats appended. This CSV as well as a CSV representation of just the fighters data object will be the two files we use to build both models. If you’re interested in seeing the actual scraping logic for each spider take a look at the here. As is the case with most ML projects of this kind the real work is done in the preprocessing step and how the data is prepared for the modelling stage. This aspect of the project went through numerous iterations. I began in a Jupyter notebook but as the complexity increased and I decided that I wanted to implement it as front end application I changed the design over to classes that contain shared preprocessing methods for both the winner predictor and the stats predictor as well as task specific preprocessing methods. A lot of the preprocessing is dedicated to cleaning up values that are missing or in the wrong the format e.g. heights being represented as strings, parsing string fighter records, and getting a fighter’s age at the time of fight. One of the trickiest aspects of preprocessing was changing the ordering of fighter1 and fighter2’s stats. The reason I had to shuffle this ordering was as a result of the UFC’s bout data always being ordered such that fighter1 is the winner so I had to figure out a way to randomly select half the dataset and swap fighter1 and fighter2’s stats positions with one another so that the final dataset is neatly broken up such that 50% of fighter1 are the winner, and 50% fighter2 are winners. I’d love to tidy up this logic going forward and if anyone has any suggestions on improvements I’d love to hear ‘em. Another important feature for the processor classes is that they had to be able to handle data processing differently in production as in a production situation the dataframe isn’t neatly constructed like it is for the training step. In production fighter stats have to be predicted ad hoc and then inserted into the final dataframe for winner prediction. My solution for this was to create additional child classes for the processors that could handle production specific cases. Both models are built using Keras, with relatively straight forward architectures comprised of only a single fully connected hidden layer for each model. I took a mostly heuristic approach to finding the optimal parameters for both but I’m eager to use newer tools optimization tools like Keras Tuner to fine tune its performance. Stats Model The stats model takes a scaled numerical representation of all the stats that are available for both fighters before a fight and it’s output layer is made up of 8 fight specific stats: output_cols = [ 'pass_stat_f1', 'pass_stat_f2', 'str_stat_f1', 'str_stat_f2', 'sub_stat_f1', 'sub_stat_f2', 'td_stat_f1', 'td_stat_f2' ] As this is a regression problem the final layer in the stats model has a linear activation (the default activation). For loss I used ‘mse’ with R2 as the models' metric to evaluate performance. The R2 for this model comes out usually at about 0.63–64 on the validation set, which isn’t too bad, but it’s worth noting that R2 will always increase as an additional predictor (output) is added and some of this could be attributed to random noise that happens to align by chance. To counter this I’ll be adding adjusted R2 to penalize the model for every new output added in a new version. Winner Prediction Model Like the stats model this follows a basic single fully connected hidden layer architecture. The dependent variable is either a 0 (fighter1) or 1 (fighter2) so I add a simple sigmoid activation on the final layer to predict one of these outcomes. This model’s accuracy usually comes out at about 86% although it must be stressed that this accuracy is achieved with perfect information of the dynamic fight stats which in production are predicted values and thus not perfect information, so there is a huge contingency on the predictive power of the stats prediction model. As I wanted to serve the model and it’s predictions as a front end service I needed to build some API endpoints to access the model(s) and the list of fighters that predictions can be made for. Using Flask this was relatively straight forward. There are two main endpoints, one serves a list of fighter names for generating predictions and the other queues up the prediction pipeline and returns the result. The pipeline processes a dataframe for each fighter and then concatenates both into the correct shape and order for stats prediction. Once the stats prediction values are returned they are added as columns with their respective names and positions to the dataframe and passsed to the winner prediction model returning a result which is associated to either fighter 1 or 2. All of the API’s functionality is then called by a very simple React front end that provides the user with two searchable dropdowns and a results display that shows the predicted winner and the model’s confidence in its prediction. Setting this up in React was easy and I find React to generally be a joy to work with ( I ❤ hooks). There’s an awful lot I’d like to and will be adding to the front end such as a table showing a users’ history of predictions, and a infograph showing basic fighter stats. Hopefully this has been informative for both ML enthusiasts and/or fans of MMA in general, as I’ve mentioned there’s a lot of features I’d like to add this project in the future, and I’d love to hear your thoughts. Thanks! P.S. Maybe don’t go betting the house down on all of the model’s predicted outcomes just yet.
[ { "code": null, "e": 303, "s": 172, "text": "TL;DR: check out the predictor for yourself and see how it performs for an upcoming UFC fight card or check out the code on github" }, { "code": null, "e": 611, "s": 303, "text": "As a fan of MMA I often find myself trying to predict the outcome of fights on an upcoming fight card. The problem is that fighting by its nature can be very unpredictable. More so than even boxing, the outcome of an MMA fight can change in a split second, but of course that’s what makes it so interesting." }, { "code": null, "e": 772, "s": 611, "text": "All the same I wondered if there was a way to apply modern machine learning techniques to historical fight data and see how a model would perform on new fights." }, { "code": null, "e": 992, "s": 772, "text": "Of course like any ML project I needed data to work with. Fortunately I had a good idea of where I might find some having often visited www.ufcstats.com the day after a fight card to get the stats breakdown for a fight." }, { "code": null, "e": 1231, "s": 992, "text": "So now that I had my data source and a couple of ideas of how I could implement the model I wondered if anyone else had built a project like this and came across this post by Yuan Tian detailing his process for building a fight predictor." }, { "code": null, "e": 1392, "s": 1231, "text": "Yuan’s post was very detailed and insightful and my methodology for scraping the stats page was largely inspired by how he structured his scrapers. Thanks Yuan!" }, { "code": null, "e": 1716, "s": 1392, "text": "In Yuan’s predictor he used fight data that would be available before a fight with stats that I called “static fight stats” e.g. age, reach, weight, W/L record etc. However, the UFC stats page also detailed fight specific stats for historical bouts such as strikes thrown, takedowns , submission attempts, and guard passes." }, { "code": null, "e": 1929, "s": 1716, "text": "As there weren’t an awful lot of data points on the UFC stats page to begin with I felt discarding these “dynamic fight stats” would be a shame. So I decided to build the predictor as a two way predictive system:" }, { "code": null, "e": 2129, "s": 1929, "text": "The first model uses the static stats as the independent variables for fighter 1 and fighter 2 and then predicts the dependent variables, the dynamic fight stats.( A multi target regression problem)." }, { "code": null, "e": 2299, "s": 2129, "text": "We then pass the static and dynamic fight stats to an overall winner model that predicts whether fighter 1 or fighter 2 is the winner. (A binary classification problem)." }, { "code": null, "e": 2413, "s": 2299, "text": "The scrapers for this project are broken down into two Scrapy spiders that crawl two sections of UFC Fight Stats:" }, { "code": null, "e": 2426, "s": 2413, "text": "Bout Scraper" }, { "code": null, "e": 2442, "s": 2426, "text": "Fighter Scraper" }, { "code": null, "e": 2517, "s": 2442, "text": "The Bout scrapers data object is broken down as the following Scrapy Item:" }, { "code": null, "e": 3447, "s": 2517, "text": "class BoutScraperItem(Item): event_name = Field() event_date = Field() event_attendance = Field() fighter1 = Field() fighter2 = Field() str_stat_f1 = Field() str_stat_f2 = Field() td_stat_f1 = Field() td_stat_f2 = Field() sub_stat_f1 = Field() sub_stat_f2 = Field() pass_stat_f1 = Field() pass_stat_f2 = Field() weight_class = Field() win_method_type = Field() win_method_finish = Field() round_ = Field() time = Field() winner = Field()" }, { "code": null, "e": 3825, "s": 3447, "text": "The Bout spider crawls the events section of UFC Fight Stats and records bout specific stats such as str_stat_f1 (striking stats for fighter 1) for each fighter, many of these will become our dependent variables for the multi target regression problem. Fighter1 and Fighter2 are the names of the fighters involved in a bout and we join the fighter scraper data on these values." }, { "code": null, "e": 3877, "s": 3825, "text": "The Fighter scraper data object is broken down as :" }, { "code": null, "e": 4762, "s": 3877, "text": "class FightScraperItem(Item): fighter_name = Field() fighter_record = Field() height = Field() weight = Field() reach = Field() stance = Field() date_of_birth = Field() slpm = Field() # strikes landed per min stat td_avg = Field() # takedown average strike_acc = Field() # striking accuracy td_acc = Field() # takedown accuracy sapm = Field() # strikes absorbed per minute td_def = Field() # takedown defence strike_def = Field() # striking defence sub_avg = Field() # submission average" }, { "code": null, "e": 4965, "s": 4762, "text": "Each item here is individually scraped from the fighter stats page which details career stats for every fighter involved in a UFC bout (although data from the earlier days of the UFC is less populated)." }, { "code": null, "e": 5317, "s": 4965, "text": "I save both of these data objects as tables into a SQLite database and have a small script for generating a combined fight-bouts CSV file where each row is a bout with fighter1 and fighter2’s individual fighter stats appended. This CSV as well as a CSV representation of just the fighters data object will be the two files we use to build both models." }, { "code": null, "e": 5415, "s": 5317, "text": "If you’re interested in seeing the actual scraping logic for each spider take a look at the here." }, { "code": null, "e": 5567, "s": 5415, "text": "As is the case with most ML projects of this kind the real work is done in the preprocessing step and how the data is prepared for the modelling stage." }, { "code": null, "e": 5940, "s": 5567, "text": "This aspect of the project went through numerous iterations. I began in a Jupyter notebook but as the complexity increased and I decided that I wanted to implement it as front end application I changed the design over to classes that contain shared preprocessing methods for both the winner predictor and the stats predictor as well as task specific preprocessing methods." }, { "code": null, "e": 6171, "s": 5940, "text": "A lot of the preprocessing is dedicated to cleaning up values that are missing or in the wrong the format e.g. heights being represented as strings, parsing string fighter records, and getting a fighter’s age at the time of fight." }, { "code": null, "e": 6778, "s": 6171, "text": "One of the trickiest aspects of preprocessing was changing the ordering of fighter1 and fighter2’s stats. The reason I had to shuffle this ordering was as a result of the UFC’s bout data always being ordered such that fighter1 is the winner so I had to figure out a way to randomly select half the dataset and swap fighter1 and fighter2’s stats positions with one another so that the final dataset is neatly broken up such that 50% of fighter1 are the winner, and 50% fighter2 are winners. I’d love to tidy up this logic going forward and if anyone has any suggestions on improvements I’d love to hear ‘em." }, { "code": null, "e": 7012, "s": 6778, "text": "Another important feature for the processor classes is that they had to be able to handle data processing differently in production as in a production situation the dataframe isn’t neatly constructed like it is for the training step." }, { "code": null, "e": 7258, "s": 7012, "text": "In production fighter stats have to be predicted ad hoc and then inserted into the final dataframe for winner prediction. My solution for this was to create additional child classes for the processors that could handle production specific cases." }, { "code": null, "e": 7589, "s": 7258, "text": "Both models are built using Keras, with relatively straight forward architectures comprised of only a single fully connected hidden layer for each model. I took a mostly heuristic approach to finding the optimal parameters for both but I’m eager to use newer tools optimization tools like Keras Tuner to fine tune its performance." }, { "code": null, "e": 7601, "s": 7589, "text": "Stats Model" }, { "code": null, "e": 7786, "s": 7601, "text": "The stats model takes a scaled numerical representation of all the stats that are available for both fighters before a fight and it’s output layer is made up of 8 fight specific stats:" }, { "code": null, "e": 8009, "s": 7786, "text": "output_cols = [ 'pass_stat_f1', 'pass_stat_f2', 'str_stat_f1', 'str_stat_f2', 'sub_stat_f1', 'sub_stat_f2', 'td_stat_f1', 'td_stat_f2' ]" }, { "code": null, "e": 8203, "s": 8009, "text": "As this is a regression problem the final layer in the stats model has a linear activation (the default activation). For loss I used ‘mse’ with R2 as the models' metric to evaluate performance." }, { "code": null, "e": 8596, "s": 8203, "text": "The R2 for this model comes out usually at about 0.63–64 on the validation set, which isn’t too bad, but it’s worth noting that R2 will always increase as an additional predictor (output) is added and some of this could be attributed to random noise that happens to align by chance. To counter this I’ll be adding adjusted R2 to penalize the model for every new output added in a new version." }, { "code": null, "e": 8620, "s": 8596, "text": "Winner Prediction Model" }, { "code": null, "e": 8866, "s": 8620, "text": "Like the stats model this follows a basic single fully connected hidden layer architecture. The dependent variable is either a 0 (fighter1) or 1 (fighter2) so I add a simple sigmoid activation on the final layer to predict one of these outcomes." }, { "code": null, "e": 9192, "s": 8866, "text": "This model’s accuracy usually comes out at about 86% although it must be stressed that this accuracy is achieved with perfect information of the dynamic fight stats which in production are predicted values and thus not perfect information, so there is a huge contingency on the predictive power of the stats prediction model." }, { "code": null, "e": 9386, "s": 9192, "text": "As I wanted to serve the model and it’s predictions as a front end service I needed to build some API endpoints to access the model(s) and the list of fighters that predictions can be made for." }, { "code": null, "e": 9600, "s": 9386, "text": "Using Flask this was relatively straight forward. There are two main endpoints, one serves a list of fighter names for generating predictions and the other queues up the prediction pipeline and returns the result." }, { "code": null, "e": 9973, "s": 9600, "text": "The pipeline processes a dataframe for each fighter and then concatenates both into the correct shape and order for stats prediction. Once the stats prediction values are returned they are added as columns with their respective names and positions to the dataframe and passsed to the winner prediction model returning a result which is associated to either fighter 1 or 2." }, { "code": null, "e": 10205, "s": 9973, "text": "All of the API’s functionality is then called by a very simple React front end that provides the user with two searchable dropdowns and a results display that shows the predicted winner and the model’s confidence in its prediction." }, { "code": null, "e": 10305, "s": 10205, "text": "Setting this up in React was easy and I find React to generally be a joy to work with ( I ❤ hooks)." }, { "code": null, "e": 10476, "s": 10305, "text": "There’s an awful lot I’d like to and will be adding to the front end such as a table showing a users’ history of predictions, and a infograph showing basic fighter stats." }, { "code": null, "e": 10699, "s": 10476, "text": "Hopefully this has been informative for both ML enthusiasts and/or fans of MMA in general, as I’ve mentioned there’s a lot of features I’d like to add this project in the future, and I’d love to hear your thoughts. Thanks!" } ]
Tryit Editor v3.7
Tryit: HTML image as an object
[]
What are the differences in die() and exit() in PHP?
There is no difference between die and exit, they are the same. The PHP Manual for exit states − "This language construct is equivalent to die()." The PHP Manual for die states − "This language construct is equivalent to exit()." However, there is a small difference, i.e the amount of time it takes for the parser to return the token.
[ { "code": null, "e": 1126, "s": 1062, "text": "There is no difference between die and exit, they are the same." }, { "code": null, "e": 1159, "s": 1126, "text": "The PHP Manual for exit states −" }, { "code": null, "e": 1209, "s": 1159, "text": "\"This language construct is equivalent to die().\"" }, { "code": null, "e": 1241, "s": 1209, "text": "The PHP Manual for die states −" }, { "code": null, "e": 1292, "s": 1241, "text": "\"This language construct is equivalent to exit().\"" }, { "code": null, "e": 1398, "s": 1292, "text": "However, there is a small difference, i.e the amount of time it takes for the parser to return the token." } ]
How to remove the last digit of a number and execute the remaining digits in JavaScript?
Before the introduction of Bitwise operators, a number is first converted into a string and later on, using string methods, some part of that number is sliced and the remaining part is executed. Here type-conversion i.e a number into a string is necessary. But the introduction of Bitwise or has made the task very easy. When Bitwise or is used there is no necessity of type-conversion and there is no need of using any kind of string methods, reducing the effort and length of the code. In the following example, a string method called "string.substring()" is used to remove the last digit of a number. Live Demo <html> <body> <script> var str = '2345'; document.write((str.substring(0, str.length - 1))); </script> </body> </html> 234 But after the advent of Bitwise or, the type conversion and string methods are nowhere in the picture. Bitwise or has made the code very concise. Live Demo <html> <body> <script> document.write(2345 / 10 | 0) document.write("</br>"); document.write(2345 / 100 | 0) document.write("</br>"); document.write(2345 / 1000 | 0) </script> </body> </html> 234 23 2
[ { "code": null, "e": 1550, "s": 1062, "text": "Before the introduction of Bitwise operators, a number is first converted into a string and later on, using string methods, some part of that number is sliced and the remaining part is executed. Here type-conversion i.e a number into a string is necessary. But the introduction of Bitwise or has made the task very easy. When Bitwise or is used there is no necessity of type-conversion and there is no need of using any kind of string methods, reducing the effort and length of the code." }, { "code": null, "e": 1666, "s": 1550, "text": "In the following example, a string method called \"string.substring()\" is used to remove the last digit of a number." }, { "code": null, "e": 1676, "s": 1666, "text": "Live Demo" }, { "code": null, "e": 1801, "s": 1676, "text": "<html>\n<body>\n<script>\n var str = '2345';\n document.write((str.substring(0, str.length - 1)));\n</script>\n</body>\n</html>" }, { "code": null, "e": 1805, "s": 1801, "text": "234" }, { "code": null, "e": 1953, "s": 1805, "text": "But after the advent of Bitwise or, the type conversion and string methods are nowhere in the picture. Bitwise or has made the code very concise. " }, { "code": null, "e": 1963, "s": 1953, "text": "Live Demo" }, { "code": null, "e": 2170, "s": 1963, "text": "<html>\n<body>\n<script>\n document.write(2345 / 10 | 0)\n document.write(\"</br>\");\n document.write(2345 / 100 | 0)\n document.write(\"</br>\");\n document.write(2345 / 1000 | 0)\n</script>\n</body>\n</html>" }, { "code": null, "e": 2179, "s": 2170, "text": "234\n23\n2" } ]
Bootstrap | Carousel - GeeksforGeeks
05 Aug, 2021 In this article, we will see how to create an image slide show for your webpage to make it look more attractive. For this we will use bootstrap Carousel.It can be included into your webpage using “bootstrap.js” or “bootstrap.min.js”. Carousels are not supported properly in Internet Explorer, this is because they use CSS3 transitions and animations to achieve the slide effect.This is how we can create a image slideshow using bootstrap carousel Example: html <head> <title>Bootstrap | Carousel</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script></head> <body> <center> <h1 class="text-success">GeeksforGeeks</h1> <h4>Bootstrap | Carousel</h4> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png"> </div> <div class="item"> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190528184201/gateexam.png"> </div> <div class="item"> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190507183137/Embedded-System-Programming-Languages.png"> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div> </center></body> Output: The “Wrapper for slides” part : The slides are specified in a div with class=”carousel-inner”.The content of each image in a slideshow is defined in a div tag with class=”item”. This can be text or images.The class=”active” is added to one of the slides. Otherwise, the images of the slideshow will not be visible. The outermost div : The class=”carousel” tells us that this div tag contains a carousel.The class=”carousel-slide” adds a CSS transition and animation effect to the images,thus making them slide when showing a new item. If you do not want this effect,then do not put this class.The data-ride=”carousel” attribute tells Bootstrap to begin the slideshow immediately when the page loads. The “Indicators” part : The indicators are the little dots at the bottom of each slide which indicates how many slides there, and which slide we are currently viewing.The indicators are specified in an ordered list with class=”carousel-indicators”. The data-target attribute points to the id of the carousel which are given to their numbers appearing in the slideshow. The data-slide-to attribute makes the image slide the image it has been assigned to, when clicking on the specific dot. The “Left and right controls” part : This code adds “left” and “right” buttons that allows the us to go back and forth between the slides manually. The data-slide attribute accepts the keywords “prev” or “next”, which changes the slide position against its current position. To Add Caption to the Slide Add class=”carousel-caption” within each div class=”item” to create a caption for each slide. Example: html <head> <title>Bootstrap | Carousel</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script></head> <body> <center> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png"> <div class="carousel-caption"> <b><h1 class="text-success">GeeksforGeeks</h1> <p>Join Geeks Classes</p></b> </div> </div> <div class="item"> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190507183137/Embedded-System-Programming-Languages.png"> <div class="carousel-caption"> <b><h1 class="text-primary">GeeksforGeeks</h1> <p>Join Geeks Classes</p></b> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div> </center></body> Output: CYCLE: It cycles through the carousel from left to rightExample: html <script type="text/javascript">$(document).ready(function(){ $(".start-slide").click(function(){ $("#myCarousel").carousel('cycle'); });});</script> PAUSE: Stops the carousel from moving where ever you wantExample: html <script type="text/javascript">$(document).ready(function(){ $(".pause-slide").click(function(){ $("#myCarousel").carousel('pause'); });});</script> NUMBER: It cycles the carousel according to a particular frame(starting from 0, just like in array)Example: html <script type="text/javascript">$(document).ready(function(){ $(".slide-three").click(function(){ $("#myCarousel").carousel(3); });});</script> PREV: Cycles the carousel to its previous image,its just like we did earlier in the bootstrap partExample: html <script type="text/javascript">$(document).ready(function(){ $(".prev-slide").click(function(){ $("#myCarousel").carousel('prev'); });});</script> NEXT: Cycles the carousel to its next image,its same as we did in the bootstrap part of carouselExample: html <script type="text/javascript">$(document).ready(function(){ $(".next-slide").click(function(){ $("#myCarousel").carousel('next'); });});</script> Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28075, "s": 28047, "text": "\n05 Aug, 2021" }, { "code": null, "e": 28522, "s": 28075, "text": "In this article, we will see how to create an image slide show for your webpage to make it look more attractive. For this we will use bootstrap Carousel.It can be included into your webpage using “bootstrap.js” or “bootstrap.min.js”. Carousels are not supported properly in Internet Explorer, this is because they use CSS3 transitions and animations to achieve the slide effect.This is how we can create a image slideshow using bootstrap carousel" }, { "code": null, "e": 28532, "s": 28522, "text": "Example: " }, { "code": null, "e": 28537, "s": 28532, "text": "html" }, { "code": "<head> <title>Bootstrap | Carousel</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script></head> <body> <center> <h1 class=\"text-success\">GeeksforGeeks</h1> <h4>Bootstrap | Carousel</h4> <div id=\"myCarousel\" class=\"carousel slide\" data-ride=\"carousel\"> <!-- Indicators --> <ol class=\"carousel-indicators\"> <li data-target=\"#myCarousel\" data-slide-to=\"0\" class=\"active\"></li> <li data-target=\"#myCarousel\" data-slide-to=\"1\"></li> <li data-target=\"#myCarousel\" data-slide-to=\"2\"></li> </ol> <!-- Wrapper for slides --> <div class=\"carousel-inner\"> <div class=\"item active\"> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png\"> </div> <div class=\"item\"> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190528184201/gateexam.png\"> </div> <div class=\"item\"> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190507183137/Embedded-System-Programming-Languages.png\"> </div> </div> <!-- Left and right controls --> <a class=\"left carousel-control\" href=\"#myCarousel\" data-slide=\"prev\"> <span class=\"glyphicon glyphicon-chevron-left\"></span> <span class=\"sr-only\">Previous</span> </a> <a class=\"right carousel-control\" href=\"#myCarousel\" data-slide=\"next\"> <span class=\"glyphicon glyphicon-chevron-right\"></span> <span class=\"sr-only\">Next</span> </a> </div> </center></body>", "e": 30663, "s": 28537, "text": null }, { "code": null, "e": 30673, "s": 30663, "text": "Output: " }, { "code": null, "e": 30992, "s": 30675, "text": "The “Wrapper for slides” part : The slides are specified in a div with class=”carousel-inner”.The content of each image in a slideshow is defined in a div tag with class=”item”. This can be text or images.The class=”active” is added to one of the slides. Otherwise, the images of the slideshow will not be visible. " }, { "code": null, "e": 31379, "s": 30992, "text": "The outermost div : The class=”carousel” tells us that this div tag contains a carousel.The class=”carousel-slide” adds a CSS transition and animation effect to the images,thus making them slide when showing a new item. If you do not want this effect,then do not put this class.The data-ride=”carousel” attribute tells Bootstrap to begin the slideshow immediately when the page loads. " }, { "code": null, "e": 31870, "s": 31379, "text": "The “Indicators” part : The indicators are the little dots at the bottom of each slide which indicates how many slides there, and which slide we are currently viewing.The indicators are specified in an ordered list with class=”carousel-indicators”. The data-target attribute points to the id of the carousel which are given to their numbers appearing in the slideshow. The data-slide-to attribute makes the image slide the image it has been assigned to, when clicking on the specific dot. " }, { "code": null, "e": 32145, "s": 31870, "text": "The “Left and right controls” part : This code adds “left” and “right” buttons that allows the us to go back and forth between the slides manually. The data-slide attribute accepts the keywords “prev” or “next”, which changes the slide position against its current position." }, { "code": null, "e": 32175, "s": 32147, "text": "To Add Caption to the Slide" }, { "code": null, "e": 32280, "s": 32175, "text": "Add class=”carousel-caption” within each div class=”item” to create a caption for each slide. Example: " }, { "code": null, "e": 32285, "s": 32280, "text": "html" }, { "code": "<head> <title>Bootstrap | Carousel</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script></head> <body> <center> <div id=\"myCarousel\" class=\"carousel slide\" data-ride=\"carousel\"> <!-- Indicators --> <ol class=\"carousel-indicators\"> <li data-target=\"#myCarousel\" data-slide-to=\"0\" class=\"active\"></li> <li data-target=\"#myCarousel\" data-slide-to=\"1\"></li> </ol> <!-- Wrapper for slides --> <div class=\"carousel-inner\"> <div class=\"item active\"> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png\"> <div class=\"carousel-caption\"> <b><h1 class=\"text-success\">GeeksforGeeks</h1> <p>Join Geeks Classes</p></b> </div> </div> <div class=\"item\"> <img src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190507183137/Embedded-System-Programming-Languages.png\"> <div class=\"carousel-caption\"> <b><h1 class=\"text-primary\">GeeksforGeeks</h1> <p>Join Geeks Classes</p></b> </div> </div> </div> <!-- Left and right controls --> <a class=\"left carousel-control\" href=\"#myCarousel\" data-slide=\"prev\"> <span class=\"glyphicon glyphicon-chevron-left\"></span> <span class=\"sr-only\">Previous</span> </a> <a class=\"right carousel-control\" href=\"#myCarousel\" data-slide=\"next\"> <span class=\"glyphicon glyphicon-chevron-right\"></span> <span class=\"sr-only\">Next</span> </a> </div> </center></body>", "e": 34507, "s": 32285, "text": null }, { "code": null, "e": 34517, "s": 34507, "text": "Output: " }, { "code": null, "e": 34586, "s": 34519, "text": "CYCLE: It cycles through the carousel from left to rightExample: " }, { "code": null, "e": 34591, "s": 34586, "text": "html" }, { "code": "<script type=\"text/javascript\">$(document).ready(function(){ $(\".start-slide\").click(function(){ $(\"#myCarousel\").carousel('cycle'); });});</script>", "e": 34753, "s": 34591, "text": null }, { "code": null, "e": 34823, "s": 34755, "text": "PAUSE: Stops the carousel from moving where ever you wantExample: " }, { "code": null, "e": 34828, "s": 34823, "text": "html" }, { "code": "<script type=\"text/javascript\">$(document).ready(function(){ $(\".pause-slide\").click(function(){ $(\"#myCarousel\").carousel('pause'); });});</script>", "e": 34990, "s": 34828, "text": null }, { "code": null, "e": 35102, "s": 34992, "text": "NUMBER: It cycles the carousel according to a particular frame(starting from 0, just like in array)Example: " }, { "code": null, "e": 35107, "s": 35102, "text": "html" }, { "code": "<script type=\"text/javascript\">$(document).ready(function(){ $(\".slide-three\").click(function(){ $(\"#myCarousel\").carousel(3); });});</script>", "e": 35263, "s": 35107, "text": null }, { "code": null, "e": 35374, "s": 35265, "text": "PREV: Cycles the carousel to its previous image,its just like we did earlier in the bootstrap partExample: " }, { "code": null, "e": 35379, "s": 35374, "text": "html" }, { "code": "<script type=\"text/javascript\">$(document).ready(function(){ $(\".prev-slide\").click(function(){ $(\"#myCarousel\").carousel('prev'); });});</script>", "e": 35539, "s": 35379, "text": null }, { "code": null, "e": 35648, "s": 35541, "text": "NEXT: Cycles the carousel to its next image,its same as we did in the bootstrap part of carouselExample: " }, { "code": null, "e": 35653, "s": 35648, "text": "html" }, { "code": "<script type=\"text/javascript\">$(document).ready(function(){ $(\".next-slide\").click(function(){ $(\"#myCarousel\").carousel('next'); });});</script>", "e": 35813, "s": 35653, "text": null }, { "code": null, "e": 35832, "s": 35813, "text": "Supported Browser:" }, { "code": null, "e": 35846, "s": 35832, "text": "Google Chrome" }, { "code": null, "e": 35861, "s": 35846, "text": "Microsoft Edge" }, { "code": null, "e": 35869, "s": 35861, "text": "Firefox" }, { "code": null, "e": 35875, "s": 35869, "text": "Opera" }, { "code": null, "e": 35883, "s": 35875, "text": "Safari " }, { "code": null, "e": 35897, "s": 35885, "text": "ysachin2314" }, { "code": null, "e": 35907, "s": 35897, "text": "Bootstrap" }, { "code": null, "e": 35924, "s": 35907, "text": "Web Technologies" }, { "code": null, "e": 36022, "s": 35924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36031, "s": 36022, "text": "Comments" }, { "code": null, "e": 36044, "s": 36031, "text": "Old Comments" }, { "code": null, "e": 36094, "s": 36044, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 36123, "s": 36094, "text": "Form validation using jQuery" }, { "code": null, "e": 36179, "s": 36123, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 36220, "s": 36179, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 36261, "s": 36220, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 36317, "s": 36261, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 36350, "s": 36317, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36412, "s": 36350, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36455, "s": 36412, "text": "How to fetch data from an API in ReactJS ?" } ]
How to determine if date is weekend in JavaScript?
As we know the value 0 is for day Sunday and 6 for Saturday. First of all, you need to get day with the help of getDay(). Let’s set a date − var givenDate=new Date("2020-07-18"); Now, we will get the day − var currentDay = givenDate.getDay(); Following is the code to determine if date is weekend − var givenDate=new Date("2020-07-18"); var currentDay = givenDate.getDay(); var dateIsInWeekend = (currentDay === 6) || (currentDay === 0); if(dateIsInWeekend==true){ console.log("The given date "+givenDate+" is a Weekend"); } else { console.log("The given date " +givenDate+"is a not a Weekend"); } To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo66.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo66.js The given date Sat Jul 18 2020 05:30:00 GMT+0530 (India Standard Time) is a Weekend
[ { "code": null, "e": 1184, "s": 1062, "text": "As we know the value 0 is for day Sunday and 6 for Saturday. First of all, you need to get day with the help of getDay()." }, { "code": null, "e": 1203, "s": 1184, "text": "Let’s set a date −" }, { "code": null, "e": 1241, "s": 1203, "text": "var givenDate=new Date(\"2020-07-18\");" }, { "code": null, "e": 1268, "s": 1241, "text": "Now, we will get the day −" }, { "code": null, "e": 1305, "s": 1268, "text": "var currentDay = givenDate.getDay();" }, { "code": null, "e": 1361, "s": 1305, "text": "Following is the code to determine if date is weekend −" }, { "code": null, "e": 1666, "s": 1361, "text": "var givenDate=new Date(\"2020-07-18\");\nvar currentDay = givenDate.getDay();\nvar dateIsInWeekend = (currentDay === 6) || (currentDay === 0);\nif(dateIsInWeekend==true){\n console.log(\"The given date \"+givenDate+\" is a Weekend\");\n} else {\n console.log(\"The given date \" +givenDate+\"is a not a Weekend\");\n}" }, { "code": null, "e": 1732, "s": 1666, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1750, "s": 1732, "text": "node fileName.js." }, { "code": null, "e": 1783, "s": 1750, "text": "Here, my file name is demo66.js." }, { "code": null, "e": 1824, "s": 1783, "text": "This will produce the following output −" }, { "code": null, "e": 1957, "s": 1824, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo66.js\nThe given date Sat Jul 18 2020 05:30:00 GMT+0530 (India Standard Time) is a Weekend" } ]
How to write "Hello, World!" program in JavaScript?
JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. Let us take a simple example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write, which writes a string into our HTML document. <html> <body> <script> <!-- document.write("Hello World!") //--> </script> </body> </html>
[ { "code": null, "e": 1170, "s": 1062, "text": "JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>." }, { "code": null, "e": 1341, "s": 1170, "text": "You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags." }, { "code": null, "e": 1575, "s": 1341, "text": "Let us take a simple example to print out \"Hello World\". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a \"//-->\"." }, { "code": null, "e": 1815, "s": 1575, "text": "Here \"//\" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write, which writes a string into our HTML document." }, { "code": null, "e": 1954, "s": 1815, "text": "<html>\n <body>\n <script>\n <!--\n document.write(\"Hello World!\")\n //-->\n </script>\n </body>\n</html>" } ]
A complete NLP classification pipeline in scikit-learn | by Louis de Bruijn | Towards Data Science
What we’ll cover in this story: Reading a corpus Basic script structure including logging, argparse and ifmain. Train/test split Prior and posterior class probabilities Baseline classification Chain multiple features with FeatureUnion Show the results in a Pandas DataFrame and a confusion matrix The most important take-outs of this story are scikit-learn/sklearn's Pipeline, FeatureUnion, TfidfVectorizer and a visualisation of the confusion_matrix using the seaborn package, but also more general bites such as ifmain, argparse, logging, zip and *args will be covered. We’ll be using an dataset of Amazon reviews and the simple yet effective Naive Bayes for the classification task. trainset.txt contains a corpus of reviews taken from the Johns Hopkins Multi-Domain Sentiment Dataset and converted to the following format in a space separated .csv file. music neg 575.txt the cd came as promised and in the condition promised . i 'm very satisfied As you can see the reviews are already tokenised with a whitespace tokeniser from the nltkpackage. Each review is on one line and preceded by two tags and the identifier of the review: a tag that specifies one of the six topics: books, camera, dvd, health, music, software. a tag which indicates the sentiment expressed by the review, in terms of a positive or negative value: pos, neg. This dataset enables us to perform a binary classification of sentiment or a multi-class classification of the genre of the review and create our script in such a way that the user can specify which classification task to tackle. We’re setting up our pipeline using argparse and function flags such as use_sentiment so that we’re able to do both the binary (pos|neg) classification task and the multi-class classification task (book|camera|dvd|health|music|software) from the command-line. For those of you who are not familiar, argparse is a super-useful package that enables user-friendly command-line interfaces. If required arguments are missing, it shows an error and it shows all of the different arguments that can be used. Arguments are preceded by the argument tag --input and a whitespace: $ python3 pipeline.py --input trainset.txt --binary. We’re also adding a verbosityflag --v and using the logging capabilities of Python to output warnings, errors or info. After the arguments are parsed with args = parser.parse_args() you can then use the input from these arguments with args.input and args.verbosity in your script. Note argparse does not have a type=bool, which means that everything get’s parsed as a str. In order to add boolean flags, you can set action="store_true", which takes the False boolean as default, and if the flag --binary is included, will automatically result in aTrue boolean. We’ll be chaining all of the functions in this story in a main() function that will automatically be called by the if __name__ == '__main__' statement. When calling this file in the command line, the Python interpreter reads the source file and sets the __name__ variable as '__main__'. This way we can read the source file and execute the functions in it, but also make this file available as a module to import for other scripts, without automatically executing the statements in main(). First we’ll need to read our corpus trainset.txt. This function will make use of the --binary flag coming from our argparse function to determine whether we’re doing a binary or multi-class classification. Now that we have our reviews in documents and our classes in labels, we’re going to split them in a training-set and a test-set for our classifier. We’re going to use a split of 80% training and 20% testing, using the slice notation [:]. First we need to shuffle our data to ensure that this slice is not influencing the results: classes might be overrepresented in the train/test-set, since we don’t know how the documents in our corpus are ordered. They might for instance be ordered alphabetically, which could result in having the classes book|camera|dvd|health solely in our training set. Since we’re creating a list of tuples as such [(doc1, 'neg'), (doc2, 'pos')], we can use a neat python function, zip and * to iterate through this list and separate the tuples in a list of documents [doc1, doc2, doc3] and a list of labels ['pos', 'neg', 'pos']. Note: although this function may seem a bit verbose, I included it, because it is good to see what happens under the hood here. You can also use sklearn’s train_test_split function which does essentially the same, or use k-fold cross-validation: splitting the dataset in train and test k number of times and taking the average of each classification to ensure that the splits influence the scores as little as possible. For the classification task at hand we’ll be using Naive Bayes classifier, which makes use of Bayes theorem: computing new probability distributions over the classes incorporating the features included in the classifiers such as tf-idf or counts, which should make the new probability distribution more representative of the data. To make sense of the posterior probabilities it is useful to compare them to the prior distributions. We will thus first calculate the prior probabilities of the classes over all documents in our corpus, or the other way around: the probability that one document in our corpus has a certain class. Posterior probabilities can be computed with classifier.predict_proba. To compare the evaluation metric (accuracy) and the confusion matrix of our Naive Bayes classifier, we’re going to create a very simple baseline: using the random package, we’re going to randomly assign a label to each document out of the set of possible labels. We could also create a baseline that takes the prior probabilities of each class into account. For this classification task we’re going to add three features that are included in the classifier: Count vectoriser with POS-tags appended to each tokenTF-IDF vectoriser (which uses the very powerful term-frequency in document-frequency)An example of feature-engineering where the feature length is included in a pipeline with feature-value mappings to vectors in DictVectorizer. Count vectoriser with POS-tags appended to each token TF-IDF vectoriser (which uses the very powerful term-frequency in document-frequency) An example of feature-engineering where the feature length is included in a pipeline with feature-value mappings to vectors in DictVectorizer. Now this code is a bit complex, but it is merely an example of how multiple features can be appended in one FeatureUnion pipeline, even including pipelines as done in (.3). I’ve added a flag for each of the features in the function feature_union(), so that you’re able to turn features on and off accordingly. Now we’re also going to have to show our results. We can use sklearn’s classification_report, accuracy_score, and confusion_matrix and a bit of beauty with the seaborn package for that last one. tabular_results() creates a Pandas DataFrame with the tokenised sentences, actual labels, predicted labels and the prior/posterior probabilities. class_report() shows the accuracy scores for the classifier and has a flag show_matrix for showing the beautiful visualisation of the confusion matrix using the vis() function. We read our corpus > split the data in train/test > compute prior probabilities > create a FeatureUnion of our three features > fit the classifier to the data > make predictions > compute posterior probabilities > create a DataFrame > report results for baseline > report results for Naive Bayes. Accuracy scores for our baseline remain around 0.16/0.17 for our six-class classification and around 0.5 for our binary classification, which is logical since it’s the probability/number of classes. Naive Bayes accuracy scores are 0.685 for all three features combined and highest 0.901 when only using tf-idf vectors. This shows that feature-engineering does not always yield better results! The complete script and dataset can be found here. Remember that you can set the --binary flag for binary classification and the verbosity flag using --v to different levels (4 for debug) to see the classification_report for the classifiers. Furthermore, the feature_union() has flags to turn on/off different features and the class_report() a flag to show the confusion matrix.
[ { "code": null, "e": 204, "s": 172, "text": "What we’ll cover in this story:" }, { "code": null, "e": 221, "s": 204, "text": "Reading a corpus" }, { "code": null, "e": 284, "s": 221, "text": "Basic script structure including logging, argparse and ifmain." }, { "code": null, "e": 301, "s": 284, "text": "Train/test split" }, { "code": null, "e": 341, "s": 301, "text": "Prior and posterior class probabilities" }, { "code": null, "e": 365, "s": 341, "text": "Baseline classification" }, { "code": null, "e": 407, "s": 365, "text": "Chain multiple features with FeatureUnion" }, { "code": null, "e": 469, "s": 407, "text": "Show the results in a Pandas DataFrame and a confusion matrix" }, { "code": null, "e": 744, "s": 469, "text": "The most important take-outs of this story are scikit-learn/sklearn's Pipeline, FeatureUnion, TfidfVectorizer and a visualisation of the confusion_matrix using the seaborn package, but also more general bites such as ifmain, argparse, logging, zip and *args will be covered." }, { "code": null, "e": 1030, "s": 744, "text": "We’ll be using an dataset of Amazon reviews and the simple yet effective Naive Bayes for the classification task. trainset.txt contains a corpus of reviews taken from the Johns Hopkins Multi-Domain Sentiment Dataset and converted to the following format in a space separated .csv file." }, { "code": null, "e": 1124, "s": 1030, "text": "music neg 575.txt the cd came as promised and in the condition promised . i 'm very satisfied" }, { "code": null, "e": 1309, "s": 1124, "text": "As you can see the reviews are already tokenised with a whitespace tokeniser from the nltkpackage. Each review is on one line and preceded by two tags and the identifier of the review:" }, { "code": null, "e": 1398, "s": 1309, "text": "a tag that specifies one of the six topics: books, camera, dvd, health, music, software." }, { "code": null, "e": 1511, "s": 1398, "text": "a tag which indicates the sentiment expressed by the review, in terms of a positive or negative value: pos, neg." }, { "code": null, "e": 1741, "s": 1511, "text": "This dataset enables us to perform a binary classification of sentiment or a multi-class classification of the genre of the review and create our script in such a way that the user can specify which classification task to tackle." }, { "code": null, "e": 2001, "s": 1741, "text": "We’re setting up our pipeline using argparse and function flags such as use_sentiment so that we’re able to do both the binary (pos|neg) classification task and the multi-class classification task (book|camera|dvd|health|music|software) from the command-line." }, { "code": null, "e": 2311, "s": 2001, "text": "For those of you who are not familiar, argparse is a super-useful package that enables user-friendly command-line interfaces. If required arguments are missing, it shows an error and it shows all of the different arguments that can be used. Arguments are preceded by the argument tag --input and a whitespace:" }, { "code": null, "e": 2364, "s": 2311, "text": "$ python3 pipeline.py --input trainset.txt --binary." }, { "code": null, "e": 2645, "s": 2364, "text": "We’re also adding a verbosityflag --v and using the logging capabilities of Python to output warnings, errors or info. After the arguments are parsed with args = parser.parse_args() you can then use the input from these arguments with args.input and args.verbosity in your script." }, { "code": null, "e": 2925, "s": 2645, "text": "Note argparse does not have a type=bool, which means that everything get’s parsed as a str. In order to add boolean flags, you can set action=\"store_true\", which takes the False boolean as default, and if the flag --binary is included, will automatically result in aTrue boolean." }, { "code": null, "e": 3415, "s": 2925, "text": "We’ll be chaining all of the functions in this story in a main() function that will automatically be called by the if __name__ == '__main__' statement. When calling this file in the command line, the Python interpreter reads the source file and sets the __name__ variable as '__main__'. This way we can read the source file and execute the functions in it, but also make this file available as a module to import for other scripts, without automatically executing the statements in main()." }, { "code": null, "e": 3621, "s": 3415, "text": "First we’ll need to read our corpus trainset.txt. This function will make use of the --binary flag coming from our argparse function to determine whether we’re doing a binary or multi-class classification." }, { "code": null, "e": 4215, "s": 3621, "text": "Now that we have our reviews in documents and our classes in labels, we’re going to split them in a training-set and a test-set for our classifier. We’re going to use a split of 80% training and 20% testing, using the slice notation [:]. First we need to shuffle our data to ensure that this slice is not influencing the results: classes might be overrepresented in the train/test-set, since we don’t know how the documents in our corpus are ordered. They might for instance be ordered alphabetically, which could result in having the classes book|camera|dvd|health solely in our training set." }, { "code": null, "e": 4477, "s": 4215, "text": "Since we’re creating a list of tuples as such [(doc1, 'neg'), (doc2, 'pos')], we can use a neat python function, zip and * to iterate through this list and separate the tuples in a list of documents [doc1, doc2, doc3] and a list of labels ['pos', 'neg', 'pos']." }, { "code": null, "e": 4897, "s": 4477, "text": "Note: although this function may seem a bit verbose, I included it, because it is good to see what happens under the hood here. You can also use sklearn’s train_test_split function which does essentially the same, or use k-fold cross-validation: splitting the dataset in train and test k number of times and taking the average of each classification to ensure that the splits influence the scores as little as possible." }, { "code": null, "e": 5228, "s": 4897, "text": "For the classification task at hand we’ll be using Naive Bayes classifier, which makes use of Bayes theorem: computing new probability distributions over the classes incorporating the features included in the classifiers such as tf-idf or counts, which should make the new probability distribution more representative of the data." }, { "code": null, "e": 5597, "s": 5228, "text": "To make sense of the posterior probabilities it is useful to compare them to the prior distributions. We will thus first calculate the prior probabilities of the classes over all documents in our corpus, or the other way around: the probability that one document in our corpus has a certain class. Posterior probabilities can be computed with classifier.predict_proba." }, { "code": null, "e": 5955, "s": 5597, "text": "To compare the evaluation metric (accuracy) and the confusion matrix of our Naive Bayes classifier, we’re going to create a very simple baseline: using the random package, we’re going to randomly assign a label to each document out of the set of possible labels. We could also create a baseline that takes the prior probabilities of each class into account." }, { "code": null, "e": 6055, "s": 5955, "text": "For this classification task we’re going to add three features that are included in the classifier:" }, { "code": null, "e": 6336, "s": 6055, "text": "Count vectoriser with POS-tags appended to each tokenTF-IDF vectoriser (which uses the very powerful term-frequency in document-frequency)An example of feature-engineering where the feature length is included in a pipeline with feature-value mappings to vectors in DictVectorizer." }, { "code": null, "e": 6390, "s": 6336, "text": "Count vectoriser with POS-tags appended to each token" }, { "code": null, "e": 6476, "s": 6390, "text": "TF-IDF vectoriser (which uses the very powerful term-frequency in document-frequency)" }, { "code": null, "e": 6619, "s": 6476, "text": "An example of feature-engineering where the feature length is included in a pipeline with feature-value mappings to vectors in DictVectorizer." }, { "code": null, "e": 6792, "s": 6619, "text": "Now this code is a bit complex, but it is merely an example of how multiple features can be appended in one FeatureUnion pipeline, even including pipelines as done in (.3)." }, { "code": null, "e": 6929, "s": 6792, "text": "I’ve added a flag for each of the features in the function feature_union(), so that you’re able to turn features on and off accordingly." }, { "code": null, "e": 7124, "s": 6929, "text": "Now we’re also going to have to show our results. We can use sklearn’s classification_report, accuracy_score, and confusion_matrix and a bit of beauty with the seaborn package for that last one." }, { "code": null, "e": 7447, "s": 7124, "text": "tabular_results() creates a Pandas DataFrame with the tokenised sentences, actual labels, predicted labels and the prior/posterior probabilities. class_report() shows the accuracy scores for the classifier and has a flag show_matrix for showing the beautiful visualisation of the confusion matrix using the vis() function." }, { "code": null, "e": 7744, "s": 7447, "text": "We read our corpus > split the data in train/test > compute prior probabilities > create a FeatureUnion of our three features > fit the classifier to the data > make predictions > compute posterior probabilities > create a DataFrame > report results for baseline > report results for Naive Bayes." }, { "code": null, "e": 8137, "s": 7744, "text": "Accuracy scores for our baseline remain around 0.16/0.17 for our six-class classification and around 0.5 for our binary classification, which is logical since it’s the probability/number of classes. Naive Bayes accuracy scores are 0.685 for all three features combined and highest 0.901 when only using tf-idf vectors. This shows that feature-engineering does not always yield better results!" } ]
Cheat Sheet for NLP: A Summary of My NLP Learning Journey So Far | by Jin Pu | Towards Data Science
To be honest, I didn’t expect to learn NLP in the first place. But with its wide and intriguing applications, NLP allures me all the time to dig deeper and explore more fun with it. Unlike many machine learning algorithms, NLP is especially rich in visualization and thus is easy to understand, interpret, and apply to real-life problems. In this article, I will introduce several domains in NLP and share the ideas behind them (as well as the codes & visuals!). Here are what you should expect: Sentiment Analysis Word Cloud Named Entity Recognition Text Summarization Topic Analysis (LDA) and Similarities (LSI) Language Model (Text Generation) The tweet dataset contains 2292 Twitter users’ tweets. Though this dataset cannot represent the whole population on Twitter, our conclusions still can be of great insights. Codes are all uploaded in Github. I always find sentiment analysis interesting because it can be embedded anywhere. We, human beings, are connected with emotions and progress with opinions. More specifically, business is centered around customers. Analyzing the public sentiment towards a product or a company can help companies position themselves and make improvements. Thus, sentiment analysis can be used as a performance indicator/feedback in business. Naive Sentiment Analysis Let’s start off with the naïve method to learn about the ideas behind sentiment analysis. In naïve sentiment analysis, we encode each word to be positive or negative and then iterate over the entire text to count positive words as well as negative words. This snippet shows how to generate the word lists for positive/negative words, which later function as dictionaries where we can look words up. The full version of code is included in Github. import requestsdef sentiment_words(url): request = requests.get(url) print("retriving data >>> status code: ",request.status_code) text = request.text word_list = text[text.find("\n\n")+2:].split("\n") return word_listpos_url = 'http://ptrckprry.com/course/ssd/data/positive-words.txt'neg_url = 'http://ptrckprry.com/course/ssd/data/negative-words.txt'pos_list = sentiment_words(pos_url)[:-1]neg_list = sentiment_words(neg_url)[:-1] The graph below is the sentiment distribution of Twitter users. Overall, Twitter users are more positive than negative. Some users even have high positive scores with close to 0 negative scores. Look closer to one user: we are able to detect the changes in this user’s sentiment. Unfortunately, we do not have more accurate time information otherwise we might even find some weekly/seasonal patterns in sentimental change. NRC Emotion Lexicon Similar to the mechanism underlying naive sentiment analysis, NRC extracted 8 more emotions like joy, trust, sadness, etc. With richer information, more visuals/functionalities could be added. For example, radar plots are potential visuals for sentiment diagnosis. User 1(blue) seems to be more positive than user 2 (red) with higher scores on positive emotions (joy, trust, anticipation) and lower scores on negative emotions (sadness, anger, disgust). VADER VADER (Valence Aware Dictionary and Sentiment Reasoner) functions beyond word-level. Instead, it analyzes sentiment on the sentence-level/content-level. Moreover, it provides both polarity (positive/negative) and intensity of emotions. In Python vaderSentiment library, it returns 4 scores— positive, negative, neutral, and compound. from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzeranalyzer = SentimentIntensityAnalyzer() pos=neg=neu=compound=0sentences = nltk.sent_tokenize(text.lower())for sentence in sentences: vs = analyzer.polarity_scores(sentence) pos += vs["pos"]/len(sentences) neg += vs["neg"]/len(sentences) neu += vs["neu"]/len(sentences) compound += vs["compound"]/len(sentences) “Neutral” is significantly and negatively correlated with “positive”, which makes sense since when we are expressing emotions it’s hard to be neutral. However, most of the users are being detected as highly neutral. Is our analyzer not sensitive enough, or is it the true case in real life? Word Cloud is what many people think of when speaking of NLP. It counts the frequency of words and resizes each word based on their frequencies. The more frequent a word is, the more outstanding it is in the word cloud. The idea is simple but efficient. from wordcloud import WordCloud, STOPWORDSwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white',width=3000,height=3000).generate(text)plt.imshow(wordcloud) plt.axis('off') plt.show() Named Entity Recognition enables us to understand what or who is being talked about, and it mirrors the way human beings process sentences with language grammars. This code snippet scans a text sentence by sentence and labels each word if the word is recognized as “entity”. Having done that, we search for trees in the chunk and ask “Are you tagged with a label?” — hasattr(tree, ”label”). If the tree says yes, we will then grab the entity in tree.leaves() and also store the label tree.label(). def entity_identity(text): sentences = nltk.sent_tokenize(text) entity = [] for sentence in sentences: words = nltk.word_tokenize(sentence) tagged = nltk.pos_tag(words) chunked = nltk.ne_chunk(tagged) for tree in chunked: if hasattr(tree,"label"): entity.append([tree.label()," ".join(c[0] for c in tree.leaves())]) entity = pd.DataFrame(entity,columns=['label','entity']) return entity If combining the named entity with sentiment analysis/word cloud, things can get more interesting. Let’s first see an example in the word cloud. This function can take any type of entity and grab all the entities in that type to form a word cloud. It can be functioning as a monitor of what/who is being heavily talked about. def wordcloud_entity(entity,label="PERSON"): text = " ".join(list(entity[entity["label"]==label]["entity"])) wordcloud = WordCloud(stopwords=STOPWORDS,background_color='white',width=3000,height=3000).generate(text) fig,ax = plt.subplots(1,1,figsize=(8,8)) plt.imshow(wordcloud) plt.axis('off') plt.show() OK, now we are aware that twitter users are heavily talking about Hong Kong, America, Trump, Polina Shinkina...How about further analyzing the sentiment related to these words? Next, I search for the sentences that contain these words and utilize the VADER sentiment analyzer. def sentiment_entity(text,entity="New York"): sentences = nltk.sent_tokenize(text) analyzer = SentimentIntensityAnalyzer() pos=neg=neu=compound=count=0 for sentence in sentences: if entity.lower() in sentence.lower(): vs = analyzer.polarity_scores(sentence) pos += vs["pos"] neg += vs["neg"] neu += vs["neu"] compound += vs["compound"] count += 1 return pos/count,neg/count,neu/count,compound/count This dataset is biased in terms of the user pool it represents (e.g. college students) and the time when I extracted it, but at least it shows how we are able to incorporate sentiment analysis into named entity recognition. In the previous 3 parts, we mainly focus on word-level and sentence-level analyses. Now we are going to analyze texts in paragraphs. Normally, an article entails a beginning, a body, and an end. Some sentences in the beginning or end are key sentences summarizing the main topics of the article. Text Summarization ranks each sentence and picks sentences of top ranks. To do it naively, we can count the frequency of each word and use that as a ruler to rank sentences. Finally, we pick sentences with the highest word frequency (most representative). There is another complex way of calculating TextRank which is wrapped up in the package called gensim. Check this code out! Tweets are shorter than articles and thus may not be a good fit for summarization. I set the ratio parameter to be as small as 0.003 to squeeze the output size of tweets. import gensimgensim.summarization.summarize(text,ratio=0.003) Things are getting more and more abstract now. Topic Analysis is an unsupervised learning technique where we are trying to extract dimensions from texts. The technique I introduce here is LDA (Latent Dirichlet Allocation). LDA entails words dictionary and corpus to get ready for topic extractions. Words dictionary encodes every code in the text. Corpus is a list of lists where words in a text are stored in a list and all texts are stored separately in different lists (“bag of words”). words_list = []users = []for user,text in tweets.items(): users.append(user) words = nltk.word_tokenize(text.lower()) words = [word for word in words if word not in STOPWORDS and word.isalnum() and len(word)>=2] words_list.append(words)num_topics = 3 #self-defineddictionary = corpora.Dictionary(words_list)corpus = [dictionary.doc2bow(words) for words in words_list]lda = LdaModel(corpus, id2word=dictionary, num_topics=num_topics) Now we get 3 topics with their corresponding representative words. To show what a specific topic is like, try this code: # Topic is 0 indexed, 1 indicates the second topiclda.show_topic(1) To get the topic components of a user/document, try this code out: # corpus[2] refers to the tweets of a usersorted(lda.get_document_topics(corpus[2],minimum_probability=0,per_word_topics=False),key=lambda x:x[1],reverse=True)[output] [(0, 0.51107097), (1, 0.48721585), (2, 0.0017131236)] To compare topic similarities between different users, that is where LSI shines. LSI takes the same input as LDA — dictionary, corpus — and compares a new document with the existing corpus. lsi = models.LsiModel(corpus,id2word=dictionary, num_topics=3) words_new = nltk.word_tokenize(doc.lower())words_new = [word for word in words if word not in STOPWORDS and word.isalnum() and len(word)>=2]vec_bow = dictionary.doc2bow(words_new) vec_lsi = lsi[vec_bow]index = similarities.MatrixSimilarity(lsi[corpus])sims = index[vec_lsi] sims = sorted(enumerate(sims), key=lambda item: -item[1]) I didn’t input new tweets. Instead, I randomly chose a user. That’s why we get one similarity score of 1. Package pyLDAvis provides great visuals for LDA, through which we are able to know how topics are correlated with keywords and how to interpret topics. It takes quite a long time thus I only plot for one user. lda_display = pyLDAvis.gensim.prepare(lda, corpus, dictionary, R=15, sort_topics=False) pyLDAvis.display(lda_display) Through the steps above, we are getting to know about the sentiment, entity, keywords, topics of a text. Now let’s teach our machine how to speak like a human being. We are going to build a simple RNN model for one twitter user and mimic how this user speaks. There are 2 main obstacles in applying machine learning with series data. First, the order of series cannot be reflected in the traditional DNN model. That is where RNN comes in. RNN is a good fit for series data, just like CNN for images. Many to one RNN structure takes the first n-1 words as inputs and the nth word as outputs in a text. RNN can pass on the information from previous positions and thus can reserve the order in series. Second, series data can be of different lengths. Tweets can be as short as 3 characters but also can be as long as several sentences. Padding is especially designed for this problem. To start with, we tokenize each word since machines can not directly recognize words, and each sentence is then being encoded into a list of integers. For example, “now” is encoded as 198 in the sentence. word_index is the dictionary for deciphering. tokenizer = Tokenizer() # can set num_words to tokenizetokenizer.fit_on_texts(sentences)sequences = tokenizer.texts_to_sequences(sentences)word_index = tokenizer.word_indexindex_word = {index:word for word,index in word_index.items()} Next, to uniformize the length, each sentence is either adding 0s to make up for the blank spaces or truncating itself to fit into the box. The first n-1 terms are taken into X, while the last term of each sentence goes into Y. max_length = 15trunct_type = "post"padding_type = "pre"padded = pad_sequences(sequences,padding=padding_type,truncating=trunct_type,maxlen=max_length)vocab_size = len(word_index)+1X = padded[:,:-1]Y = padded[:,-1]Y = tf.keras.utils.to_categorical(Y,num_classes=vocab_size) When building the RNN model, we add an embedding layer. It is a way of representing words and has certain advantages over one-hot encoding representations. In one hot encoding, each word is independent/orthogonal to each other. Word embedding generates one vector for each word and enables non-orthogonal relationships. Some words can be closer and similar to each other. For example, “cat” is closer to “dog” than “westside”. Therefore, we are able to migrate our knowledge onto sentences that we haven’t seen before. Machines are able to learn “the dog is running” from the original sentence “the cat is running”. LSTM is a technique to solve vanishing gradients and strengthen the long term connection in series. model = tf.keras.Sequential([tf.keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length-1),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(512,return_sequences=True)),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256)),tf.keras.layers.Flatten(),tf.keras.layers.Dropout(0.3),tf.keras.layers.Dense(vocab_size,activation="softmax")])model.compile(loss='categorical_crossentropy',optimizer="adam",metrics=["accuracy"])model.fit(X,Y,epochs=100,verbose=1) Let’s generate text to see how our talking robot works. choice = random.randint(0,len(padded)) seed = padded[choice,1:].reshape(1,max_length-1)tweet_robot = sentences[choice]for i in range(5): predicted = model.predict_classes(seed,verbose=0) seed = np.append(seed,[int(predicted)])[1:].reshape(1,max_length-1) tweet_robot = tweet_robot + " " + str(index_word[int(predicted)]) The original sentence is a complete tweet and our talking robot helps extend the sentence by picking out the appropriate words. The result is not as satisfying as I expect. Our talking robot seems to be just throwing words out instead of producing a well-organized sentence. However, the words selected show some alignment with the topic. There is a lot more that can be done to improve the performance. Text cleaning would be my priority. Tweets are short and informal, which leads to a lot of inelegancy in word choices and sentence organizations. There is much noise in the dataset. I am just standing at the gate of the magnificent palace of NLP, knocking at the door. There’s a long way in front of me. I am writing down this article to remind me of the way I’ve come through and to encourage me to keep adventuring.
[ { "code": null, "e": 667, "s": 171, "text": "To be honest, I didn’t expect to learn NLP in the first place. But with its wide and intriguing applications, NLP allures me all the time to dig deeper and explore more fun with it. Unlike many machine learning algorithms, NLP is especially rich in visualization and thus is easy to understand, interpret, and apply to real-life problems. In this article, I will introduce several domains in NLP and share the ideas behind them (as well as the codes & visuals!). Here are what you should expect:" }, { "code": null, "e": 686, "s": 667, "text": "Sentiment Analysis" }, { "code": null, "e": 697, "s": 686, "text": "Word Cloud" }, { "code": null, "e": 722, "s": 697, "text": "Named Entity Recognition" }, { "code": null, "e": 741, "s": 722, "text": "Text Summarization" }, { "code": null, "e": 785, "s": 741, "text": "Topic Analysis (LDA) and Similarities (LSI)" }, { "code": null, "e": 818, "s": 785, "text": "Language Model (Text Generation)" }, { "code": null, "e": 1025, "s": 818, "text": "The tweet dataset contains 2292 Twitter users’ tweets. Though this dataset cannot represent the whole population on Twitter, our conclusions still can be of great insights. Codes are all uploaded in Github." }, { "code": null, "e": 1449, "s": 1025, "text": "I always find sentiment analysis interesting because it can be embedded anywhere. We, human beings, are connected with emotions and progress with opinions. More specifically, business is centered around customers. Analyzing the public sentiment towards a product or a company can help companies position themselves and make improvements. Thus, sentiment analysis can be used as a performance indicator/feedback in business." }, { "code": null, "e": 1474, "s": 1449, "text": "Naive Sentiment Analysis" }, { "code": null, "e": 1731, "s": 1474, "text": "Let’s start off with the naïve method to learn about the ideas behind sentiment analysis. In naïve sentiment analysis, we encode each word to be positive or negative and then iterate over the entire text to count positive words as well as negative words." }, { "code": null, "e": 1923, "s": 1731, "text": "This snippet shows how to generate the word lists for positive/negative words, which later function as dictionaries where we can look words up. The full version of code is included in Github." }, { "code": null, "e": 2371, "s": 1923, "text": "import requestsdef sentiment_words(url): request = requests.get(url) print(\"retriving data >>> status code: \",request.status_code) text = request.text word_list = text[text.find(\"\\n\\n\")+2:].split(\"\\n\") return word_listpos_url = 'http://ptrckprry.com/course/ssd/data/positive-words.txt'neg_url = 'http://ptrckprry.com/course/ssd/data/negative-words.txt'pos_list = sentiment_words(pos_url)[:-1]neg_list = sentiment_words(neg_url)[:-1]" }, { "code": null, "e": 2566, "s": 2371, "text": "The graph below is the sentiment distribution of Twitter users. Overall, Twitter users are more positive than negative. Some users even have high positive scores with close to 0 negative scores." }, { "code": null, "e": 2794, "s": 2566, "text": "Look closer to one user: we are able to detect the changes in this user’s sentiment. Unfortunately, we do not have more accurate time information otherwise we might even find some weekly/seasonal patterns in sentimental change." }, { "code": null, "e": 2814, "s": 2794, "text": "NRC Emotion Lexicon" }, { "code": null, "e": 3268, "s": 2814, "text": "Similar to the mechanism underlying naive sentiment analysis, NRC extracted 8 more emotions like joy, trust, sadness, etc. With richer information, more visuals/functionalities could be added. For example, radar plots are potential visuals for sentiment diagnosis. User 1(blue) seems to be more positive than user 2 (red) with higher scores on positive emotions (joy, trust, anticipation) and lower scores on negative emotions (sadness, anger, disgust)." }, { "code": null, "e": 3274, "s": 3268, "text": "VADER" }, { "code": null, "e": 3608, "s": 3274, "text": "VADER (Valence Aware Dictionary and Sentiment Reasoner) functions beyond word-level. Instead, it analyzes sentiment on the sentence-level/content-level. Moreover, it provides both polarity (positive/negative) and intensity of emotions. In Python vaderSentiment library, it returns 4 scores— positive, negative, neutral, and compound." }, { "code": null, "e": 4002, "s": 3608, "text": "from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzeranalyzer = SentimentIntensityAnalyzer() pos=neg=neu=compound=0sentences = nltk.sent_tokenize(text.lower())for sentence in sentences: vs = analyzer.polarity_scores(sentence) pos += vs[\"pos\"]/len(sentences) neg += vs[\"neg\"]/len(sentences) neu += vs[\"neu\"]/len(sentences) compound += vs[\"compound\"]/len(sentences)" }, { "code": null, "e": 4293, "s": 4002, "text": "“Neutral” is significantly and negatively correlated with “positive”, which makes sense since when we are expressing emotions it’s hard to be neutral. However, most of the users are being detected as highly neutral. Is our analyzer not sensitive enough, or is it the true case in real life?" }, { "code": null, "e": 4547, "s": 4293, "text": "Word Cloud is what many people think of when speaking of NLP. It counts the frequency of words and resizes each word based on their frequencies. The more frequent a word is, the more outstanding it is in the word cloud. The idea is simple but efficient." }, { "code": null, "e": 4762, "s": 4547, "text": "from wordcloud import WordCloud, STOPWORDSwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white',width=3000,height=3000).generate(text)plt.imshow(wordcloud) plt.axis('off') plt.show()" }, { "code": null, "e": 5260, "s": 4762, "text": "Named Entity Recognition enables us to understand what or who is being talked about, and it mirrors the way human beings process sentences with language grammars. This code snippet scans a text sentence by sentence and labels each word if the word is recognized as “entity”. Having done that, we search for trees in the chunk and ask “Are you tagged with a label?” — hasattr(tree, ”label”). If the tree says yes, we will then grab the entity in tree.leaves() and also store the label tree.label()." }, { "code": null, "e": 5716, "s": 5260, "text": "def entity_identity(text): sentences = nltk.sent_tokenize(text) entity = [] for sentence in sentences: words = nltk.word_tokenize(sentence) tagged = nltk.pos_tag(words) chunked = nltk.ne_chunk(tagged) for tree in chunked: if hasattr(tree,\"label\"): entity.append([tree.label(),\" \".join(c[0] for c in tree.leaves())]) entity = pd.DataFrame(entity,columns=['label','entity']) return entity" }, { "code": null, "e": 6042, "s": 5716, "text": "If combining the named entity with sentiment analysis/word cloud, things can get more interesting. Let’s first see an example in the word cloud. This function can take any type of entity and grab all the entities in that type to form a word cloud. It can be functioning as a monitor of what/who is being heavily talked about." }, { "code": null, "e": 6376, "s": 6042, "text": "def wordcloud_entity(entity,label=\"PERSON\"): text = \" \".join(list(entity[entity[\"label\"]==label][\"entity\"])) wordcloud = WordCloud(stopwords=STOPWORDS,background_color='white',width=3000,height=3000).generate(text) fig,ax = plt.subplots(1,1,figsize=(8,8)) plt.imshow(wordcloud) plt.axis('off') plt.show()" }, { "code": null, "e": 6653, "s": 6376, "text": "OK, now we are aware that twitter users are heavily talking about Hong Kong, America, Trump, Polina Shinkina...How about further analyzing the sentiment related to these words? Next, I search for the sentences that contain these words and utilize the VADER sentiment analyzer." }, { "code": null, "e": 7140, "s": 6653, "text": "def sentiment_entity(text,entity=\"New York\"): sentences = nltk.sent_tokenize(text) analyzer = SentimentIntensityAnalyzer() pos=neg=neu=compound=count=0 for sentence in sentences: if entity.lower() in sentence.lower(): vs = analyzer.polarity_scores(sentence) pos += vs[\"pos\"] neg += vs[\"neg\"] neu += vs[\"neu\"] compound += vs[\"compound\"] count += 1 return pos/count,neg/count,neu/count,compound/count" }, { "code": null, "e": 7364, "s": 7140, "text": "This dataset is biased in terms of the user pool it represents (e.g. college students) and the time when I extracted it, but at least it shows how we are able to incorporate sentiment analysis into named entity recognition." }, { "code": null, "e": 8211, "s": 7364, "text": "In the previous 3 parts, we mainly focus on word-level and sentence-level analyses. Now we are going to analyze texts in paragraphs. Normally, an article entails a beginning, a body, and an end. Some sentences in the beginning or end are key sentences summarizing the main topics of the article. Text Summarization ranks each sentence and picks sentences of top ranks. To do it naively, we can count the frequency of each word and use that as a ruler to rank sentences. Finally, we pick sentences with the highest word frequency (most representative). There is another complex way of calculating TextRank which is wrapped up in the package called gensim. Check this code out! Tweets are shorter than articles and thus may not be a good fit for summarization. I set the ratio parameter to be as small as 0.003 to squeeze the output size of tweets." }, { "code": null, "e": 8273, "s": 8211, "text": "import gensimgensim.summarization.summarize(text,ratio=0.003)" }, { "code": null, "e": 8763, "s": 8273, "text": "Things are getting more and more abstract now. Topic Analysis is an unsupervised learning technique where we are trying to extract dimensions from texts. The technique I introduce here is LDA (Latent Dirichlet Allocation). LDA entails words dictionary and corpus to get ready for topic extractions. Words dictionary encodes every code in the text. Corpus is a list of lists where words in a text are stored in a list and all texts are stored separately in different lists (“bag of words”)." }, { "code": null, "e": 9208, "s": 8763, "text": "words_list = []users = []for user,text in tweets.items(): users.append(user) words = nltk.word_tokenize(text.lower()) words = [word for word in words if word not in STOPWORDS and word.isalnum() and len(word)>=2] words_list.append(words)num_topics = 3 #self-defineddictionary = corpora.Dictionary(words_list)corpus = [dictionary.doc2bow(words) for words in words_list]lda = LdaModel(corpus, id2word=dictionary, num_topics=num_topics)" }, { "code": null, "e": 9329, "s": 9208, "text": "Now we get 3 topics with their corresponding representative words. To show what a specific topic is like, try this code:" }, { "code": null, "e": 9397, "s": 9329, "text": "# Topic is 0 indexed, 1 indicates the second topiclda.show_topic(1)" }, { "code": null, "e": 9464, "s": 9397, "text": "To get the topic components of a user/document, try this code out:" }, { "code": null, "e": 9686, "s": 9464, "text": "# corpus[2] refers to the tweets of a usersorted(lda.get_document_topics(corpus[2],minimum_probability=0,per_word_topics=False),key=lambda x:x[1],reverse=True)[output] [(0, 0.51107097), (1, 0.48721585), (2, 0.0017131236)]" }, { "code": null, "e": 9876, "s": 9686, "text": "To compare topic similarities between different users, that is where LSI shines. LSI takes the same input as LDA — dictionary, corpus — and compares a new document with the existing corpus." }, { "code": null, "e": 10282, "s": 9876, "text": "lsi = models.LsiModel(corpus,id2word=dictionary, num_topics=3) words_new = nltk.word_tokenize(doc.lower())words_new = [word for word in words if word not in STOPWORDS and word.isalnum() and len(word)>=2]vec_bow = dictionary.doc2bow(words_new) vec_lsi = lsi[vec_bow]index = similarities.MatrixSimilarity(lsi[corpus])sims = index[vec_lsi] sims = sorted(enumerate(sims), key=lambda item: -item[1])" }, { "code": null, "e": 10388, "s": 10282, "text": "I didn’t input new tweets. Instead, I randomly chose a user. That’s why we get one similarity score of 1." }, { "code": null, "e": 10598, "s": 10388, "text": "Package pyLDAvis provides great visuals for LDA, through which we are able to know how topics are correlated with keywords and how to interpret topics. It takes quite a long time thus I only plot for one user." }, { "code": null, "e": 10720, "s": 10598, "text": "lda_display = pyLDAvis.gensim.prepare(lda, corpus, dictionary, R=15, sort_topics=False) pyLDAvis.display(lda_display)" }, { "code": null, "e": 10980, "s": 10720, "text": "Through the steps above, we are getting to know about the sentiment, entity, keywords, topics of a text. Now let’s teach our machine how to speak like a human being. We are going to build a simple RNN model for one twitter user and mimic how this user speaks." }, { "code": null, "e": 11602, "s": 10980, "text": "There are 2 main obstacles in applying machine learning with series data. First, the order of series cannot be reflected in the traditional DNN model. That is where RNN comes in. RNN is a good fit for series data, just like CNN for images. Many to one RNN structure takes the first n-1 words as inputs and the nth word as outputs in a text. RNN can pass on the information from previous positions and thus can reserve the order in series. Second, series data can be of different lengths. Tweets can be as short as 3 characters but also can be as long as several sentences. Padding is especially designed for this problem." }, { "code": null, "e": 11853, "s": 11602, "text": "To start with, we tokenize each word since machines can not directly recognize words, and each sentence is then being encoded into a list of integers. For example, “now” is encoded as 198 in the sentence. word_index is the dictionary for deciphering." }, { "code": null, "e": 12088, "s": 11853, "text": "tokenizer = Tokenizer() # can set num_words to tokenizetokenizer.fit_on_texts(sentences)sequences = tokenizer.texts_to_sequences(sentences)word_index = tokenizer.word_indexindex_word = {index:word for word,index in word_index.items()}" }, { "code": null, "e": 12316, "s": 12088, "text": "Next, to uniformize the length, each sentence is either adding 0s to make up for the blank spaces or truncating itself to fit into the box. The first n-1 terms are taken into X, while the last term of each sentence goes into Y." }, { "code": null, "e": 12589, "s": 12316, "text": "max_length = 15trunct_type = \"post\"padding_type = \"pre\"padded = pad_sequences(sequences,padding=padding_type,truncating=trunct_type,maxlen=max_length)vocab_size = len(word_index)+1X = padded[:,:-1]Y = padded[:,-1]Y = tf.keras.utils.to_categorical(Y,num_classes=vocab_size)" }, { "code": null, "e": 13205, "s": 12589, "text": "When building the RNN model, we add an embedding layer. It is a way of representing words and has certain advantages over one-hot encoding representations. In one hot encoding, each word is independent/orthogonal to each other. Word embedding generates one vector for each word and enables non-orthogonal relationships. Some words can be closer and similar to each other. For example, “cat” is closer to “dog” than “westside”. Therefore, we are able to migrate our knowledge onto sentences that we haven’t seen before. Machines are able to learn “the dog is running” from the original sentence “the cat is running”." }, { "code": null, "e": 13305, "s": 13205, "text": "LSTM is a technique to solve vanishing gradients and strengthen the long term connection in series." }, { "code": null, "e": 13779, "s": 13305, "text": "model = tf.keras.Sequential([tf.keras.layers.Embedding(vocab_size,embedding_dim,input_length=max_length-1),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(512,return_sequences=True)),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256)),tf.keras.layers.Flatten(),tf.keras.layers.Dropout(0.3),tf.keras.layers.Dense(vocab_size,activation=\"softmax\")])model.compile(loss='categorical_crossentropy',optimizer=\"adam\",metrics=[\"accuracy\"])model.fit(X,Y,epochs=100,verbose=1)" }, { "code": null, "e": 13835, "s": 13779, "text": "Let’s generate text to see how our talking robot works." }, { "code": null, "e": 14165, "s": 13835, "text": "choice = random.randint(0,len(padded)) seed = padded[choice,1:].reshape(1,max_length-1)tweet_robot = sentences[choice]for i in range(5): predicted = model.predict_classes(seed,verbose=0) seed = np.append(seed,[int(predicted)])[1:].reshape(1,max_length-1) tweet_robot = tweet_robot + \" \" + str(index_word[int(predicted)])" }, { "code": null, "e": 14504, "s": 14165, "text": "The original sentence is a complete tweet and our talking robot helps extend the sentence by picking out the appropriate words. The result is not as satisfying as I expect. Our talking robot seems to be just throwing words out instead of producing a well-organized sentence. However, the words selected show some alignment with the topic." }, { "code": null, "e": 14751, "s": 14504, "text": "There is a lot more that can be done to improve the performance. Text cleaning would be my priority. Tweets are short and informal, which leads to a lot of inelegancy in word choices and sentence organizations. There is much noise in the dataset." } ]
PHP - Map Functions
The Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. The keys can be of any type but must be unique, and the values are replaced if added to the map by using the same key. Keys and values can be any type, including objects. Supports array syntax (square brackets). Insertion order is preserved. Performance and memory efficiency is very similar to an array. Automatically frees allocated memory when its size drops low enough. Can’t be converted to an array when objects are used as keys. Ds\Map implements Ds\Collection { /* Constants */ const int MIN_CAPACITY = 16 ; /* Methods */ public void allocate( int $capacity ) public void apply( callable $callback ) public int capacity( void ) public void clear( void ) public Ds\Map copy( void ) public Ds\Map diff( Ds\Map $map ) public Ds\Map filter([ callable $callback ] ) public Ds\Pair first( void ) public mixed get( mixed $key [, mixed $default ] ) public bool hasKey( mixed $key ) public bool hasValue( mixed $value ) public Ds\Map intersect( Ds\Map $map ) public bool isEmpty( void ) public Ds\Set keys( void ) public void ksort([ callable $comparator ] ) public Ds\Map ksorted([ callable $comparator ] ) public Ds\Pair last( void ) public Ds\Map map( callable $callback ) public Ds\Map merge( mixed $values ) public Ds\Sequence pairs( void ) public void put( mixed $key , mixed $value ) public void putAll( mixed $pairs ) public mixed reduce( callable $callback [, mixed $initial ] ) public mixed remove( mixed $key [, mixed $default ] ) public void reverse( void ) public Ds\Map reversed( void ) public Ds\Pair skip( int $position ) public Ds\Map slice int $index [, int $length ] ) public void sort([ callable $comparator ] ) public Ds\Map sorted([ callable $comparator ] ) public number sum( void ) public array toArray( void ) public Ds\Map union( Ds\Map $map ) public Ds\Sequence values( void ) public Ds\Map xor( Ds\Map $map ) } Ds\Map::MIN_CAPACITY Ds\Map::allocate() Function This Function can allocate enough memory for the required capacity. Ds\Map::apply() Function This Function can update update all values by applying a callback function to each value. Ds\Map::capacity() Function This Function can return the current capacity. Ds\Map::clear() Function This Function can remove remove all values. Ds\Map::copy() Function This Function can return the shallow copy of a map. Ds\Map::count() Function This Function can return the number of values in a map. Ds\Map::diff() Function This Function can create a new map by using keys that aren't in another map. Ds\Map::filter() Function This Function can create a new map by using a callable to determine which pairs to include. Ds\Map::first() Function This Function can return the first pair in a map. Ds\Map::get() Function This Function can return the value for a given key. Ds\Map::hasKey() Function This Function can determine whether the map contain a given key. Ds\Map::hasValue() Function This Function can determine whether the map contain a given value. Ds\Map::intersect() Function This Function can create a new map by intersecting keys with another map. Ds\Map::isEmpty() Function This Function can return return whether the map is empty. Ds\Map::jsonSerialize() Function This Function can return a representation that can be converted to JSON. Ds\Map::keys() Function This Function can return the set of map's keys. Ds\Map::ksort() Function This Function can sort the map in-place by key. Ds\Map::ksorted() Function This Function can return a copy, sorted by key. Ds\Map::last() Function This Function can return the last pair of a map. Ds\Map::map() Function This Function can return the result of applying a callback to each value. Ds\Map::merge() Function This Function can return the result of adding all given associations. Ds\Map::pairs() Function This Function can return a sequence containing all pairs of the map. Ds\Map::put() Function This Function can associate a key with a value. Ds\Map::putAll() Function This Function can associate all key-value pairs of traversable object or array. Ds\Map::reduce() Function This Function can reduce the map to a single value by using a callback function. Ds\Map::remove() Function This Function can remove and return a value by key. Ds\Map::reverse() Function This Function can can reverse the map in-place. Ds\Map::reversed() Function This Function can return a reversed copy. Ds\Map::skip() Function This Function can return the pair at a given positional index. Ds\Map::slice() Function This Function can return a subset of the map defined by starting index and length. Ds\Map::sort() Function This Function can sort the map in-place by value. Ds\Map::sorted() Function This Function can return a copy sorted by value. Ds\Map::sum() Function This Function can return the sum of all values in a map. Ds\Map::toArray() Function This Function can convert a map to an array. Ds\Map::union() Function This Function can create a new map using values from the current instance and another map. Ds\Map::values() Function This Function can return a sequence of the map's values. Ds\Map::xor() Function This Function can create a new map using the keys of either current instance or of another map, but not of both. 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2987, "s": 2757, "text": "The Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. The keys can be of any type but must be unique, and the values are replaced if added to the map by using the same key." }, { "code": null, "e": 3039, "s": 2987, "text": "Keys and values can be any type, including objects." }, { "code": null, "e": 3080, "s": 3039, "text": "Supports array syntax (square brackets)." }, { "code": null, "e": 3110, "s": 3080, "text": "Insertion order is preserved." }, { "code": null, "e": 3173, "s": 3110, "text": "Performance and memory efficiency is very similar to an array." }, { "code": null, "e": 3242, "s": 3173, "text": "Automatically frees allocated memory when its size drops low enough." }, { "code": null, "e": 3304, "s": 3242, "text": "Can’t be converted to an array when objects are used as keys." }, { "code": null, "e": 4831, "s": 3304, "text": "Ds\\Map implements Ds\\Collection {\n /* Constants */ \n \n const int MIN_CAPACITY = 16 ;\n /* Methods */\n \n public void allocate( int $capacity )\n public void apply( callable $callback )\n public int capacity( void )\n public void clear( void )\n public Ds\\Map copy( void )\n public Ds\\Map diff( Ds\\Map $map )\n public Ds\\Map filter([ callable $callback ] )\n public Ds\\Pair first( void )\n public mixed get( mixed $key [, mixed $default ] )\n public bool hasKey( mixed $key )\n public bool hasValue( mixed $value )\n public Ds\\Map intersect( Ds\\Map $map )\n public bool isEmpty( void )\n public Ds\\Set keys( void )\n public void ksort([ callable $comparator ] )\n public Ds\\Map ksorted([ callable $comparator ] )\n public Ds\\Pair last( void )\n public Ds\\Map map( callable $callback )\n public Ds\\Map merge( mixed $values )\n public Ds\\Sequence pairs( void )\n public void put( mixed $key , mixed $value )\n public void putAll( mixed $pairs )\n public mixed reduce( callable $callback [, mixed $initial ] )\n public mixed remove( mixed $key [, mixed $default ] )\n public void reverse( void )\n public Ds\\Map reversed( void )\n public Ds\\Pair skip( int $position )\n public Ds\\Map slice int $index [, int $length ] )\n public void sort([ callable $comparator ] )\n public Ds\\Map sorted([ callable $comparator ] )\n public number sum( void )\n public array toArray( void )\n public Ds\\Map union( Ds\\Map $map )\n public Ds\\Sequence values( void )\n public Ds\\Map xor( Ds\\Map $map )\n}" }, { "code": null, "e": 4852, "s": 4831, "text": "Ds\\Map::MIN_CAPACITY" }, { "code": null, "e": 4880, "s": 4852, "text": "Ds\\Map::allocate() Function" }, { "code": null, "e": 4948, "s": 4880, "text": "This Function can allocate enough memory for the required capacity." }, { "code": null, "e": 4973, "s": 4948, "text": "Ds\\Map::apply() Function" }, { "code": null, "e": 5063, "s": 4973, "text": "This Function can update update all values by applying a callback function to each value." }, { "code": null, "e": 5091, "s": 5063, "text": "Ds\\Map::capacity() Function" }, { "code": null, "e": 5138, "s": 5091, "text": "This Function can return the current capacity." }, { "code": null, "e": 5163, "s": 5138, "text": "Ds\\Map::clear() Function" }, { "code": null, "e": 5207, "s": 5163, "text": "This Function can remove remove all values." }, { "code": null, "e": 5231, "s": 5207, "text": "Ds\\Map::copy() Function" }, { "code": null, "e": 5283, "s": 5231, "text": "This Function can return the shallow copy of a map." }, { "code": null, "e": 5308, "s": 5283, "text": "Ds\\Map::count() Function" }, { "code": null, "e": 5364, "s": 5308, "text": "This Function can return the number of values in a map." }, { "code": null, "e": 5388, "s": 5364, "text": "Ds\\Map::diff() Function" }, { "code": null, "e": 5465, "s": 5388, "text": "This Function can create a new map by using keys that aren't in another map." }, { "code": null, "e": 5491, "s": 5465, "text": "Ds\\Map::filter() Function" }, { "code": null, "e": 5583, "s": 5491, "text": "This Function can create a new map by using a callable to determine which pairs to include." }, { "code": null, "e": 5608, "s": 5583, "text": "Ds\\Map::first() Function" }, { "code": null, "e": 5658, "s": 5608, "text": "This Function can return the first pair in a map." }, { "code": null, "e": 5681, "s": 5658, "text": "Ds\\Map::get() Function" }, { "code": null, "e": 5733, "s": 5681, "text": "This Function can return the value for a given key." }, { "code": null, "e": 5759, "s": 5733, "text": "Ds\\Map::hasKey() Function" }, { "code": null, "e": 5824, "s": 5759, "text": "This Function can determine whether the map contain a given key." }, { "code": null, "e": 5852, "s": 5824, "text": "Ds\\Map::hasValue() Function" }, { "code": null, "e": 5919, "s": 5852, "text": "This Function can determine whether the map contain a given value." }, { "code": null, "e": 5948, "s": 5919, "text": "Ds\\Map::intersect() Function" }, { "code": null, "e": 6022, "s": 5948, "text": "This Function can create a new map by intersecting keys with another map." }, { "code": null, "e": 6049, "s": 6022, "text": "Ds\\Map::isEmpty() Function" }, { "code": null, "e": 6107, "s": 6049, "text": "This Function can return return whether the map is empty." }, { "code": null, "e": 6140, "s": 6107, "text": "Ds\\Map::jsonSerialize() Function" }, { "code": null, "e": 6213, "s": 6140, "text": "This Function can return a representation that can be converted to JSON." }, { "code": null, "e": 6237, "s": 6213, "text": "Ds\\Map::keys() Function" }, { "code": null, "e": 6285, "s": 6237, "text": "This Function can return the set of map's keys." }, { "code": null, "e": 6310, "s": 6285, "text": "Ds\\Map::ksort() Function" }, { "code": null, "e": 6358, "s": 6310, "text": "This Function can sort the map in-place by key." }, { "code": null, "e": 6385, "s": 6358, "text": "Ds\\Map::ksorted() Function" }, { "code": null, "e": 6433, "s": 6385, "text": "This Function can return a copy, sorted by key." }, { "code": null, "e": 6457, "s": 6433, "text": "Ds\\Map::last() Function" }, { "code": null, "e": 6506, "s": 6457, "text": "This Function can return the last pair of a map." }, { "code": null, "e": 6529, "s": 6506, "text": "Ds\\Map::map() Function" }, { "code": null, "e": 6603, "s": 6529, "text": "This Function can return the result of applying a callback to each value." }, { "code": null, "e": 6628, "s": 6603, "text": "Ds\\Map::merge() Function" }, { "code": null, "e": 6698, "s": 6628, "text": "This Function can return the result of adding all given associations." }, { "code": null, "e": 6723, "s": 6698, "text": "Ds\\Map::pairs() Function" }, { "code": null, "e": 6792, "s": 6723, "text": "This Function can return a sequence containing all pairs of the map." }, { "code": null, "e": 6815, "s": 6792, "text": "Ds\\Map::put() Function" }, { "code": null, "e": 6863, "s": 6815, "text": "This Function can associate a key with a value." }, { "code": null, "e": 6889, "s": 6863, "text": "Ds\\Map::putAll() Function" }, { "code": null, "e": 6969, "s": 6889, "text": "This Function can associate all key-value pairs of traversable object or array." }, { "code": null, "e": 6995, "s": 6969, "text": "Ds\\Map::reduce() Function" }, { "code": null, "e": 7076, "s": 6995, "text": "This Function can reduce the map to a single value by using a callback function." }, { "code": null, "e": 7102, "s": 7076, "text": "Ds\\Map::remove() Function" }, { "code": null, "e": 7154, "s": 7102, "text": "This Function can remove and return a value by key." }, { "code": null, "e": 7181, "s": 7154, "text": "Ds\\Map::reverse() Function" }, { "code": null, "e": 7229, "s": 7181, "text": "This Function can can reverse the map in-place." }, { "code": null, "e": 7257, "s": 7229, "text": "Ds\\Map::reversed() Function" }, { "code": null, "e": 7299, "s": 7257, "text": "This Function can return a reversed copy." }, { "code": null, "e": 7323, "s": 7299, "text": "Ds\\Map::skip() Function" }, { "code": null, "e": 7386, "s": 7323, "text": "This Function can return the pair at a given positional index." }, { "code": null, "e": 7411, "s": 7386, "text": "Ds\\Map::slice() Function" }, { "code": null, "e": 7494, "s": 7411, "text": "This Function can return a subset of the map defined by starting index and length." }, { "code": null, "e": 7518, "s": 7494, "text": "Ds\\Map::sort() Function" }, { "code": null, "e": 7568, "s": 7518, "text": "This Function can sort the map in-place by value." }, { "code": null, "e": 7594, "s": 7568, "text": "Ds\\Map::sorted() Function" }, { "code": null, "e": 7643, "s": 7594, "text": "This Function can return a copy sorted by value." }, { "code": null, "e": 7666, "s": 7643, "text": "Ds\\Map::sum() Function" }, { "code": null, "e": 7723, "s": 7666, "text": "This Function can return the sum of all values in a map." }, { "code": null, "e": 7750, "s": 7723, "text": "Ds\\Map::toArray() Function" }, { "code": null, "e": 7795, "s": 7750, "text": "This Function can convert a map to an array." }, { "code": null, "e": 7820, "s": 7795, "text": "Ds\\Map::union() Function" }, { "code": null, "e": 7911, "s": 7820, "text": "This Function can create a new map using values from the current instance and another map." }, { "code": null, "e": 7937, "s": 7911, "text": "Ds\\Map::values() Function" }, { "code": null, "e": 7994, "s": 7937, "text": "This Function can return a sequence of the map's values." }, { "code": null, "e": 8017, "s": 7994, "text": "Ds\\Map::xor() Function" }, { "code": null, "e": 8130, "s": 8017, "text": "This Function can create a new map using the keys of either current instance or of another map, but not of both." }, { "code": null, "e": 8163, "s": 8130, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 8179, "s": 8163, "text": " Malhar Lathkar" }, { "code": null, "e": 8212, "s": 8179, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8223, "s": 8212, "text": " Syed Raza" }, { "code": null, "e": 8258, "s": 8223, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8275, "s": 8258, "text": " Frahaan Hussain" }, { "code": null, "e": 8308, "s": 8275, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8323, "s": 8308, "text": " Nivedita Jain" }, { "code": null, "e": 8358, "s": 8323, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 8370, "s": 8358, "text": " Azaz Patel" }, { "code": null, "e": 8405, "s": 8370, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8433, "s": 8405, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8440, "s": 8433, "text": " Print" }, { "code": null, "e": 8451, "s": 8440, "text": " Add Notes" } ]
Sorting a JSON object in JavaScript
Suppose we have an object like this − const obj = { key1: 56, key2: 67, key3: 23, key4: 11, key5: 88 }; We are required to write a JavaScript function that takes in this object and returns a sorted array like this − const arr = [11, 23, 56, 67, 88]; Here, we sorted the object values and placed them in an array. Therefore, let’s write the code for this function − The code for this will be − const obj = { key1: 56, key2: 67, key3: 23, key4: 11, key5: 88 }; const sortObject = obj => { const arr = Object.keys(obj).map(el => { return obj[el]; }); arr.sort((a, b) => { return a - b; }); return arr; }; console.log(sortObject(obj)); The output in the console will be − [ 11, 23, 56, 67, 88 ]
[ { "code": null, "e": 1100, "s": 1062, "text": "Suppose we have an object like this −" }, { "code": null, "e": 1181, "s": 1100, "text": "const obj = {\n key1: 56,\n key2: 67,\n key3: 23,\n key4: 11,\n key5: 88\n};" }, { "code": null, "e": 1293, "s": 1181, "text": "We are required to write a JavaScript function that takes in this object and returns a sorted array like this −" }, { "code": null, "e": 1327, "s": 1293, "text": "const arr = [11, 23, 56, 67, 88];" }, { "code": null, "e": 1390, "s": 1327, "text": "Here, we sorted the object values and placed them in an array." }, { "code": null, "e": 1442, "s": 1390, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1470, "s": 1442, "text": "The code for this will be −" }, { "code": null, "e": 1751, "s": 1470, "text": "const obj = {\n key1: 56,\n key2: 67,\n key3: 23,\n key4: 11,\n key5: 88\n};\nconst sortObject = obj => {\n const arr = Object.keys(obj).map(el => {\n return obj[el];\n });\n arr.sort((a, b) => {\n return a - b;\n });\n return arr;\n};\nconsole.log(sortObject(obj));" }, { "code": null, "e": 1787, "s": 1751, "text": "The output in the console will be −" }, { "code": null, "e": 1810, "s": 1787, "text": "[ 11, 23, 56, 67, 88 ]" } ]
How to get the current date and time in Java?
You can get the current date and time in Java in various ways. Following are some of them − The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time. Live Demo import java.util.Date; public class CreateDate { public static void main(String args[]) { Date date = new Date(); System.out.print(date); } } Thu Nov 05 20:04:57 IST 2020 The now() method of the LocaldateTime class returns the Date object representing the current time. Live Demo import java.time.LocalDate; import java.time.LocalDateTime; public class CreateDateTime { public static void main(String args[]) { LocalDateTime date = LocalDateTime.now(); System.out.println("Current Date and Time: "+date); } } Current Date and Time: 2020-11-05T21:49:11.507 The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time. Live Demo import java.util.Calendar; import java.util.Date; public class CreateDateTime { public static void main(String[] args) { Calendar obj = Calendar.getInstance(); Date date = obj.getTime(); System.out.println("Current Date and time: "+date); } } Current Date and time: Thu Nov 05 21:46:19 IST 2020 You can also get the current date ant time value using the java.time.Clock class as shown below − Live Demo import java.time.Clock; public class CreateDateTime { public static void main(String args[]) { Clock obj = Clock.systemUTC(); System.out.println("Current date time: "+obj.instant()); } } Current date time: 2020-11-05T16:33:06.155Z
[ { "code": null, "e": 1154, "s": 1062, "text": "You can get the current date and time in Java in various ways. Following are some of them −" }, { "code": null, "e": 1269, "s": 1154, "text": "The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time." }, { "code": null, "e": 1279, "s": 1269, "text": "Live Demo" }, { "code": null, "e": 1445, "s": 1279, "text": "import java.util.Date;\npublic class CreateDate {\n public static void main(String args[]) { \n Date date = new Date();\n System.out.print(date);\n }\n}" }, { "code": null, "e": 1474, "s": 1445, "text": "Thu Nov 05 20:04:57 IST 2020" }, { "code": null, "e": 1573, "s": 1474, "text": "The now() method of the LocaldateTime class returns the Date object representing the current time." }, { "code": null, "e": 1583, "s": 1573, "text": "Live Demo" }, { "code": null, "e": 1832, "s": 1583, "text": "import java.time.LocalDate;\nimport java.time.LocalDateTime;\npublic class CreateDateTime {\n public static void main(String args[]) { \n LocalDateTime date = LocalDateTime.now();\n System.out.println(\"Current Date and Time: \"+date);\n }\n}" }, { "code": null, "e": 1879, "s": 1832, "text": "Current Date and Time: 2020-11-05T21:49:11.507" }, { "code": null, "e": 2010, "s": 1879, "text": "The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time." }, { "code": null, "e": 2020, "s": 2010, "text": "Live Demo" }, { "code": null, "e": 2287, "s": 2020, "text": "import java.util.Calendar;\nimport java.util.Date;\npublic class CreateDateTime {\n public static void main(String[] args) {\n Calendar obj = Calendar.getInstance();\n Date date = obj.getTime();\n System.out.println(\"Current Date and time: \"+date);\n }\n}" }, { "code": null, "e": 2339, "s": 2287, "text": "Current Date and time: Thu Nov 05 21:46:19 IST 2020" }, { "code": null, "e": 2437, "s": 2339, "text": "You can also get the current date ant time value using the java.time.Clock class as shown below −" }, { "code": null, "e": 2447, "s": 2437, "text": "Live Demo" }, { "code": null, "e": 2652, "s": 2447, "text": "import java.time.Clock;\npublic class CreateDateTime {\n public static void main(String args[]) {\n Clock obj = Clock.systemUTC();\n System.out.println(\"Current date time: \"+obj.instant());\n }\n}" }, { "code": null, "e": 2696, "s": 2652, "text": "Current date time: 2020-11-05T16:33:06.155Z" } ]
How to Drop rows in DataFrame by conditions on column values? - GeeksforGeeks
02 Jul, 2020 In this article, we are going to see several examples of how to drop rows from the dataframe based on certain conditions applied on a column. Pandas provide data analysts a way to delete and filter data frame using dataframe.drop() method. We can use this method to drop such rows that do not satisfy the given conditions. Let’s create a Pandas dataframe. # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) df Output: Example 1 : Delete rows based on condition on a column. # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which# column Age has value 21index_names = df[ df['Age'] == 21 ].index # drop these row indexes# from dataFramedf.drop(index_names, inplace = True) df Output : Example 2 : Delete rows based on multiple conditions on a column. # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which column Age has value >= 21# and <= 23index_names = df[ (df['Age'] >= 21) & (df['Age'] <= 23)].index # drop these given row# indexes from dataFramedf.drop(index_names, inplace = True) df Output : Example 3 : Delete rows based on multiple conditions on different columns. # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which# column Age has value >= 21# and column University is BHUindex_names = df[ (df['Age'] >= 21) & (df['University'] == 'BHU')].index # drop these given row# indexes from dataFramedf.drop(index_names, inplace = True) df Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24709, "s": 24681, "text": "\n02 Jul, 2020" }, { "code": null, "e": 24851, "s": 24709, "text": "In this article, we are going to see several examples of how to drop rows from the dataframe based on certain conditions applied on a column." }, { "code": null, "e": 25032, "s": 24851, "text": "Pandas provide data analysts a way to delete and filter data frame using dataframe.drop() method. We can use this method to drop such rows that do not satisfy the given conditions." }, { "code": null, "e": 25065, "s": 25032, "text": "Let’s create a Pandas dataframe." }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) df", "e": 25594, "s": 25065, "text": null }, { "code": null, "e": 25602, "s": 25594, "text": "Output:" }, { "code": null, "e": 25658, "s": 25602, "text": "Example 1 : Delete rows based on condition on a column." }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which# column Age has value 21index_names = df[ df['Age'] == 21 ].index # drop these row indexes# from dataFramedf.drop(index_names, inplace = True) df", "e": 26339, "s": 25658, "text": null }, { "code": null, "e": 26348, "s": 26339, "text": "Output :" }, { "code": null, "e": 26414, "s": 26348, "text": "Example 2 : Delete rows based on multiple conditions on a column." }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which column Age has value >= 21# and <= 23index_names = df[ (df['Age'] >= 21) & (df['Age'] <= 23)].index # drop these given row# indexes from dataFramedf.drop(index_names, inplace = True) df", "e": 27135, "s": 26414, "text": null }, { "code": null, "e": 27144, "s": 27135, "text": "Output :" }, { "code": null, "e": 27219, "s": 27144, "text": "Example 3 : Delete rows based on multiple conditions on different columns." }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age' : [23, 21, 22, 21, 24, 25], 'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd', 'e', 'f']) # get names of indexes for which# column Age has value >= 21# and column University is BHUindex_names = df[ (df['Age'] >= 21) & (df['University'] == 'BHU')].index # drop these given row# indexes from dataFramedf.drop(index_names, inplace = True) df", "e": 27970, "s": 27219, "text": null }, { "code": null, "e": 27979, "s": 27970, "text": "Output :" }, { "code": null, "e": 28003, "s": 27979, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28017, "s": 28003, "text": "Python-pandas" }, { "code": null, "e": 28024, "s": 28017, "text": "Python" }, { "code": null, "e": 28122, "s": 28024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28131, "s": 28122, "text": "Comments" }, { "code": null, "e": 28144, "s": 28131, "text": "Old Comments" }, { "code": null, "e": 28162, "s": 28144, "text": "Python Dictionary" }, { "code": null, "e": 28197, "s": 28162, "text": "Read a file line by line in Python" }, { "code": null, "e": 28219, "s": 28197, "text": "Enumerate() in Python" }, { "code": null, "e": 28251, "s": 28219, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28281, "s": 28251, "text": "Iterate over a list in Python" }, { "code": null, "e": 28323, "s": 28281, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28366, "s": 28323, "text": "Python program to convert a list to string" }, { "code": null, "e": 28392, "s": 28366, "text": "Python String | replace()" }, { "code": null, "e": 28436, "s": 28392, "text": "Reading and Writing to text files in Python" } ]
how to convert Object array to String array in java
As list.toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter. See the example below. import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<String> data = new ArrayList<String>(); data.add("A"); data.add("B"); data.add("C"); //Object[] objects = data.toArray(); String[] strObjects = data.toArray(new String[0]); for(String obj: strObjects) { System.out.println(obj); } } } A B C
[ { "code": null, "e": 1198, "s": 1062, "text": "As list.toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter. See the example below." }, { "code": null, "e": 1614, "s": 1198, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Tester {\n public static void main(String[] args) {\n List<String> data = new ArrayList<String>();\n data.add(\"A\");\n data.add(\"B\");\n data.add(\"C\");\n //Object[] objects = data.toArray();\n String[] strObjects = data.toArray(new String[0]);\n for(String obj: strObjects) {\n System.out.println(obj);\n }\n }\n}" }, { "code": null, "e": 1620, "s": 1614, "text": "A\nB\nC" } ]
cat - Unix, Linux Command
cat - Concatenate and print the content of files. cat [Options] [File]... Cat command concatenate FILE(s), or standard input, to standard output. With no FILE, or when FILE is -, it reads standard input. Create two sample files #sample.txt This is a sample text file #sample1.txt This is a another sample text file To display content of a file. $ cat sample.txt This is a sample text file To display content of all txt files. $ cat *.txt This is a another sample text file This is a sample text file To concatenate two files. $ cat sample.txt sample1.txt > sample2.txt $ cat sample2.txt This is a sample text file This is a another sample text file To put content of a file in a variable. $ variable_content = 'cat sample.txt' 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": 10627, "s": 10577, "text": "cat - Concatenate and print the content of files." }, { "code": null, "e": 10651, "s": 10627, "text": "cat [Options] [File]..." }, { "code": null, "e": 10781, "s": 10651, "text": "Cat command concatenate FILE(s), or standard input, to standard output. With no FILE, or when FILE is -, it reads standard input." }, { "code": null, "e": 10805, "s": 10781, "text": "Create two sample files" }, { "code": null, "e": 10845, "s": 10805, "text": "#sample.txt\nThis is a sample text file\n" }, { "code": null, "e": 10894, "s": 10845, "text": "#sample1.txt\nThis is a another sample text file\n" }, { "code": null, "e": 10924, "s": 10894, "text": "To display content of a file." }, { "code": null, "e": 10969, "s": 10924, "text": "$ cat sample.txt\nThis is a sample text file\n" }, { "code": null, "e": 11006, "s": 10969, "text": "To display content of all txt files." }, { "code": null, "e": 11081, "s": 11006, "text": "$ cat *.txt\nThis is a another sample text file\nThis is a sample text file\n" }, { "code": null, "e": 11107, "s": 11081, "text": "To concatenate two files." }, { "code": null, "e": 11231, "s": 11107, "text": "$ cat sample.txt sample1.txt > sample2.txt\n$ cat sample2.txt\nThis is a sample text file\nThis is a another sample text file\n" }, { "code": null, "e": 11271, "s": 11231, "text": "To put content of a file in a variable." }, { "code": null, "e": 11310, "s": 11271, "text": "$ variable_content = 'cat sample.txt'\n" }, { "code": null, "e": 11345, "s": 11310, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11373, "s": 11345, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11407, "s": 11373, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11424, "s": 11407, "text": " Frahaan Hussain" }, { "code": null, "e": 11457, "s": 11424, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11468, "s": 11457, "text": " Pradeep D" }, { "code": null, "e": 11503, "s": 11468, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11519, "s": 11503, "text": " Musab Zayadneh" }, { "code": null, "e": 11552, "s": 11519, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11564, "s": 11552, "text": " GUHARAJANM" }, { "code": null, "e": 11596, "s": 11564, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11604, "s": 11596, "text": " Uplatz" }, { "code": null, "e": 11611, "s": 11604, "text": " Print" }, { "code": null, "e": 11622, "s": 11611, "text": " Add Notes" } ]
How to create a SplitPane in JavaFX?
A SplitPane is a UI component that contains two or more sides with a separator in between. This separator is movable; you can reduce/increase the area of a side using it. You can create a split pane by instantiating the javafx.scene.control.SplitPane class. The sides of the SplitPane can be arranged either horizontally or vertically. By default, the SpliPane created is horizontal you can change its orientation using the setOrientation() method. The following Example demonstrates the creation of a SplitPane. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.SplitPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class SplitPaneExample extends Application { public void start(Stage stage) throws FileNotFoundException { //Creating ImageView object1 Image img1 = new Image(new FileInputStream("D:\\images\\elephant.jpg")); ImageView view1 = new ImageView(img1); view1.setFitWidth(250); view1.setFitHeight(150); //Creating ImageView object2 Image img2 = new Image(new FileInputStream("D:\\images\\boy.jpg")); ImageView view2 = new ImageView(img2); view2.setFitWidth(250); view2.setFitHeight(150); //Creating a SplitPane SplitPane splitPane = new SplitPane(); //Creating stack panes holding the ImageView objects StackPane stackPane1 = new StackPane(view1); StackPane stackPane2 = new StackPane(view2); //Adding the stackpanes to the splitpane splitPane.getItems().addAll(stackPane1, stackPane2); //Setting anchor pane as the layout AnchorPane pane = new AnchorPane(); AnchorPane.setTopAnchor(splitPane, 15.0); AnchorPane.setRightAnchor(splitPane, 15.0); AnchorPane.setBottomAnchor(splitPane, 15.0); AnchorPane.setLeftAnchor(splitPane, 15.0); pane.getChildren().addAll(splitPane); pane.setStyle("-fx-background-color: BEIGE"); //Setting the stage Scene scene = new Scene(pane, 595, 300); stage.setTitle("Split Pane"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1320, "s": 1062, "text": "A SplitPane is a UI component that contains two or more sides with a separator in between. This separator is movable; you can reduce/increase the area of a side using it. You can create a split pane by instantiating the javafx.scene.control.SplitPane class." }, { "code": null, "e": 1511, "s": 1320, "text": "The sides of the SplitPane can be arranged either horizontally or vertically. By default, the SpliPane created is horizontal you can change its orientation using the setOrientation() method." }, { "code": null, "e": 1575, "s": 1511, "text": "The following Example demonstrates the creation of a SplitPane." }, { "code": null, "e": 3428, "s": 1575, "text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport javafx.application.Application;\nimport javafx.scene.Scene;\nimport javafx.scene.control.SplitPane;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.AnchorPane;\nimport javafx.scene.layout.StackPane;\nimport javafx.stage.Stage;\npublic class SplitPaneExample extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Creating ImageView object1\n Image img1 = new Image(new FileInputStream(\"D:\\\\images\\\\elephant.jpg\"));\n ImageView view1 = new ImageView(img1);\n view1.setFitWidth(250);\n view1.setFitHeight(150);\n //Creating ImageView object2\n Image img2 = new Image(new FileInputStream(\"D:\\\\images\\\\boy.jpg\"));\n ImageView view2 = new ImageView(img2);\n view2.setFitWidth(250);\n view2.setFitHeight(150);\n //Creating a SplitPane\n SplitPane splitPane = new SplitPane();\n //Creating stack panes holding the ImageView objects\n StackPane stackPane1 = new StackPane(view1);\n StackPane stackPane2 = new StackPane(view2);\n //Adding the stackpanes to the splitpane\n splitPane.getItems().addAll(stackPane1, stackPane2);\n //Setting anchor pane as the layout\n AnchorPane pane = new AnchorPane();\n AnchorPane.setTopAnchor(splitPane, 15.0);\n AnchorPane.setRightAnchor(splitPane, 15.0);\n AnchorPane.setBottomAnchor(splitPane, 15.0);\n AnchorPane.setLeftAnchor(splitPane, 15.0);\n pane.getChildren().addAll(splitPane);\n pane.setStyle(\"-fx-background-color: BEIGE\");\n //Setting the stage\n Scene scene = new Scene(pane, 595, 300);\n stage.setTitle(\"Split Pane\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
C++ Program To Remove Duplicates From A Given String - GeeksforGeeks
11 Dec, 2021 Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. METHOD 1 (Simple) C++ // CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i=0; i<n; i++) { // Check if str[i] is present before it int j; for (j=0; j<i; j++) if (str[i] == str[j]) break; // If not present, then add it to // result. if (j == i) str[index++] = str[i]; } return str;} // Driver codeint main(){ char str[]= "geeksforgeeks"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;} Output: geksfor Time Complexity : O(n * n) Auxiliary Space : O(1) Keeps order of elements the same as input. METHOD 2 (Use BST) use set which implements a self-balancing Binary Search Tree. C++ // CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '�' set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '�'; return str;} // Driver codeint main(){ char str[]= "geeksforgeeks"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;} Output: efgkors Time Complexity: O(n Log n) Auxiliary Space: O(n) Thanks to Anivesh Tiwari for suggesting this approach. It does not keep the order of elements the same as the input but prints them in sorted order. METHOD 3 (Use Sorting) Algorithm: 1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string. Example: Input string: geeksforgeeks 1) Sort the characters eeeefggkkorss 2) Remove duplicates efgkorskkorss 3) Remove extra characters efgkors Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order. Implementation: C++ // C++ program to remove duplicates, the order of// characters is not maintained in this program#include<bits/stdc++.h>using namespace std; /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '�'; return str;} /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int n = strlen(str); // Sort the character array sort(str, str+n); // Remove duplicates from sorted return removeDupsSorted(str);} /* Driver program to test removeDups */int main(){ char str[] = "geeksforgeeks"; cout << removeDups(str); return 0;} Output: efgkors Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort. Auxiliary Space: O(1) METHOD 4 (Use Hashing ) Algorithm: 1: Initialize: str = "test string" /* input string */ ip_ind = 0 /* index to keep track of location of next character in input string */ res_ind = 0 /* index to keep track of location of next character in the resultant string */ bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is already processed or not */ 2: Do following for each character *(str + ip_ind) in input string: (a) if bin_hash is not set for *(str + ip_ind) then // if program sees the character *(str + ip_ind) first time (i) Set bin_hash for *(str + ip_ind) (ii) Move *(str + ip_ind) to the resultant string. This is done in-place. (iii) res_ind++ (b) ip_ind++ /* String obtained after this step is "te stringing" */ 3: Remove extra characters at the end of the resultant string. /* String obtained after this step is "te string" */ Implementation: C++ #include <bits/stdc++.h>using namespace std; # define NO_OF_CHARS 256 # define bool int /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char str[]) { bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '�'; return str; } /* Driver code */int main() { char str[] = "geeksforgeeks"; cout << removeDups(str); return 0; } // This code is contributed by rathbhupendra Output: geksfor Time Complexity: O(n) Important Points: Method 2 doesn’t maintain the characters as original strings, but method 4 does. It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly. calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘�’. the malloc() followed by memset() could also be used. The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100 Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method C++ // C++ program to create a unique string#include <bits/stdc++.h>using namespace std; // Function to make the string uniquestring unique(string s){ string str; int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for(int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // If c is present in str, it returns // the index of c, else it returns npos auto found = str.find(c); if (found == std::string::npos) { // Adding c to str if npos is returned str += c; } } return str;} // Driver codeint main(){ // Input string with repeating chars string s = "geeksforgeeks"; cout << unique(s) << endl;} // This code is contributed by nirajgusain5 Output: geksfor Thanks debjitdbb for suggesting this approach. Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method C++ // C++ program to create a unique string using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occur and therefore it helps us check if an element exists in a string in O(1) time complexity with constant space. */ #include <bits/stdc++.h> using namespace std; char* removeDuplicates(char *s,int n){ unordered_map<char,int> exists; int index = 0; for(int i=0;i<n;i++){ if(exists[s[i]]==0) { s[index++] = s[i]; exists[s[i]]++; } } return s;} //driver codeint main(){ char s[] = "geeksforgeeks"; int n = sizeof(s)/sizeof(s[0]); cout<<removeDuplicates(s,n)<<endl; return 0;} Output: geksfor Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach. Please refer complete article on Remove duplicates from a given string for more details! frequency-counting C++ Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Dynamic _Cast in C++ Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24528, "s": 24500, "text": "\n11 Dec, 2021" }, { "code": null, "e": 24674, "s": 24528, "text": "Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string." }, { "code": null, "e": 24693, "s": 24674, "text": "METHOD 1 (Simple) " }, { "code": null, "e": 24697, "s": 24693, "text": "C++" }, { "code": "// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i=0; i<n; i++) { // Check if str[i] is present before it int j; for (j=0; j<i; j++) if (str[i] == str[j]) break; // If not present, then add it to // result. if (j == i) str[index++] = str[i]; } return str;} // Driver codeint main(){ char str[]= \"geeksforgeeks\"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;}", "e": 25427, "s": 24697, "text": null }, { "code": null, "e": 25437, "s": 25427, "text": "Output: " }, { "code": null, "e": 25445, "s": 25437, "text": "geksfor" }, { "code": null, "e": 25539, "s": 25445, "text": "Time Complexity : O(n * n) Auxiliary Space : O(1) Keeps order of elements the same as input. " }, { "code": null, "e": 25621, "s": 25539, "text": "METHOD 2 (Use BST) use set which implements a self-balancing Binary Search Tree. " }, { "code": null, "e": 25625, "s": 25621, "text": "C++" }, { "code": "// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '�' set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '�'; return str;} // Driver codeint main(){ char str[]= \"geeksforgeeks\"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;}", "e": 26169, "s": 25625, "text": null }, { "code": null, "e": 26179, "s": 26169, "text": "Output: " }, { "code": null, "e": 26189, "s": 26179, "text": " efgkors" }, { "code": null, "e": 26239, "s": 26189, "text": "Time Complexity: O(n Log n) Auxiliary Space: O(n)" }, { "code": null, "e": 26294, "s": 26239, "text": "Thanks to Anivesh Tiwari for suggesting this approach." }, { "code": null, "e": 26388, "s": 26294, "text": "It does not keep the order of elements the same as the input but prints them in sorted order." }, { "code": null, "e": 26423, "s": 26388, "text": "METHOD 3 (Use Sorting) Algorithm: " }, { "code": null, "e": 26618, "s": 26423, "text": " 1) Sort the elements.\n 2) Now in a loop, remove duplicates by comparing the \n current character with previous character.\n 3) Remove extra characters at the end of the resultant string." }, { "code": null, "e": 26629, "s": 26618, "text": "Example: " }, { "code": null, "e": 26777, "s": 26629, "text": "Input string: geeksforgeeks\n1) Sort the characters\n eeeefggkkorss\n2) Remove duplicates\n efgkorskkorss\n3) Remove extra characters\n efgkors" }, { "code": null, "e": 27089, "s": 26777, "text": "Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order." }, { "code": null, "e": 27107, "s": 27089, "text": "Implementation: " }, { "code": null, "e": 27111, "s": 27107, "text": "C++" }, { "code": "// C++ program to remove duplicates, the order of// characters is not maintained in this program#include<bits/stdc++.h>using namespace std; /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '�'; return str;} /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int n = strlen(str); // Sort the character array sort(str, str+n); // Remove duplicates from sorted return removeDupsSorted(str);} /* Driver program to test removeDups */int main(){ char str[] = \"geeksforgeeks\"; cout << removeDups(str); return 0;}", "e": 28190, "s": 27111, "text": null }, { "code": null, "e": 28200, "s": 28190, "text": "Output: " }, { "code": null, "e": 28208, "s": 28200, "text": "efgkors" }, { "code": null, "e": 28297, "s": 28208, "text": "Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort." }, { "code": null, "e": 28319, "s": 28297, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 28344, "s": 28319, "text": "METHOD 4 (Use Hashing ) " }, { "code": null, "e": 28357, "s": 28344, "text": "Algorithm: " }, { "code": null, "e": 29473, "s": 28357, "text": "1: Initialize:\n str = \"test string\" /* input string */\n ip_ind = 0 /* index to keep track of location of next\n character in input string */\n res_ind = 0 /* index to keep track of location of\n next character in the resultant string */\n bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is \n already processed or not */\n2: Do following for each character *(str + ip_ind) in input string:\n (a) if bin_hash is not set for *(str + ip_ind) then\n // if program sees the character *(str + ip_ind) first time\n (i) Set bin_hash for *(str + ip_ind)\n (ii) Move *(str + ip_ind) to the resultant string.\n This is done in-place.\n (iii) res_ind++\n (b) ip_ind++\n /* String obtained after this step is \"te stringing\" */\n3: Remove extra characters at the end of the resultant string.\n /* String obtained after this step is \"te string\" */" }, { "code": null, "e": 29491, "s": 29473, "text": "Implementation: " }, { "code": null, "e": 29495, "s": 29491, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; # define NO_OF_CHARS 256 # define bool int /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char str[]) { bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '�'; return str; } /* Driver code */int main() { char str[] = \"geeksforgeeks\"; cout << removeDups(str); return 0; } // This code is contributed by rathbhupendra", "e": 30444, "s": 29495, "text": null }, { "code": null, "e": 30454, "s": 30444, "text": "Output: " }, { "code": null, "e": 30462, "s": 30454, "text": "geksfor" }, { "code": null, "e": 30484, "s": 30462, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30504, "s": 30484, "text": "Important Points: " }, { "code": null, "e": 30585, "s": 30504, "text": "Method 2 doesn’t maintain the characters as original strings, but method 4 does." }, { "code": null, "e": 30709, "s": 30585, "text": "It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly." }, { "code": null, "e": 30890, "s": 30709, "text": "calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘�’. the malloc() followed by memset() could also be used." }, { "code": null, "e": 31146, "s": 30890, "text": "The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100" }, { "code": null, "e": 31221, "s": 31146, "text": "Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method " }, { "code": null, "e": 31225, "s": 31221, "text": "C++" }, { "code": "// C++ program to create a unique string#include <bits/stdc++.h>using namespace std; // Function to make the string uniquestring unique(string s){ string str; int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for(int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // If c is present in str, it returns // the index of c, else it returns npos auto found = str.find(c); if (found == std::string::npos) { // Adding c to str if npos is returned str += c; } } return str;} // Driver codeint main(){ // Input string with repeating chars string s = \"geeksforgeeks\"; cout << unique(s) << endl;} // This code is contributed by nirajgusain5", "e": 32103, "s": 31225, "text": null }, { "code": null, "e": 32113, "s": 32103, "text": "Output: " }, { "code": null, "e": 32121, "s": 32113, "text": "geksfor" }, { "code": null, "e": 32169, "s": 32121, "text": "Thanks debjitdbb for suggesting this approach. " }, { "code": null, "e": 32259, "s": 32169, "text": "Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method " }, { "code": null, "e": 32263, "s": 32259, "text": "C++" }, { "code": "// C++ program to create a unique string using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occur and therefore it helps us check if an element exists in a string in O(1) time complexity with constant space. */ #include <bits/stdc++.h> using namespace std; char* removeDuplicates(char *s,int n){ unordered_map<char,int> exists; int index = 0; for(int i=0;i<n;i++){ if(exists[s[i]]==0) { s[index++] = s[i]; exists[s[i]]++; } } return s;} //driver codeint main(){ char s[] = \"geeksforgeeks\"; int n = sizeof(s)/sizeof(s[0]); cout<<removeDuplicates(s,n)<<endl; return 0;}", "e": 32902, "s": 32263, "text": null }, { "code": null, "e": 32912, "s": 32902, "text": "Output: " }, { "code": null, "e": 32920, "s": 32912, "text": "geksfor" }, { "code": null, "e": 33022, "s": 32920, "text": "Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach. " }, { "code": null, "e": 33111, "s": 33022, "text": "Please refer complete article on Remove duplicates from a given string for more details!" }, { "code": null, "e": 33130, "s": 33111, "text": "frequency-counting" }, { "code": null, "e": 33143, "s": 33130, "text": "C++ Programs" }, { "code": null, "e": 33151, "s": 33143, "text": "Strings" }, { "code": null, "e": 33159, "s": 33151, "text": "Strings" }, { "code": null, "e": 33257, "s": 33159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33298, "s": 33257, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33319, "s": 33298, "text": "Const keyword in C++" }, { "code": null, "e": 33378, "s": 33319, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 33390, "s": 33378, "text": "cout in C++" }, { "code": null, "e": 33411, "s": 33390, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 33436, "s": 33411, "text": "Reverse a string in Java" }, { "code": null, "e": 33482, "s": 33436, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33516, "s": 33482, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33576, "s": 33516, "text": "Write a program to print all permutations of a given string" } ]
Sum of list with stream filter in Java
To get sum of list with stream filter in Java, the code is as follows − Live Demo import java.util.*; public class Demo { public static void main(String[] args) { List<Integer> my_list = new ArrayList<Integer>(); my_list.add(11); my_list.add(35); my_list.add(56); my_list.add(78); my_list.add(91); System.out.println(sum(my_list)); } public static int sum(List<Integer> my_list) { System.out.println("In the main function, the sum of list with filter is "); return my_list.stream().filter(i -> i > 5).mapToInt(i -> i).sum(); } } In the main function, the sum of list with filter is 271 A class named Demo contains the main function that creates an ArrayList. Elements are added into the arraylist using the ‘add()’ function. The sum of all the elements of the list can be printed on the screen using the ‘sum’ function. Another function named ‘sum’ is defined that returns the filtered output by mapping the value to an integer.
[ { "code": null, "e": 1134, "s": 1062, "text": "To get sum of list with stream filter in Java, the code is as follows −" }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 1664, "s": 1145, "text": "import java.util.*;\npublic class Demo\n{\n public static void main(String[] args)\n {\n List<Integer> my_list = new ArrayList<Integer>();\n my_list.add(11);\n my_list.add(35);\n my_list.add(56);\n my_list.add(78);\n my_list.add(91);\n System.out.println(sum(my_list));\n }\n public static int sum(List<Integer> my_list)\n {\n System.out.println(\"In the main function, the sum of list with filter is \");\n return my_list.stream().filter(i -> i > 5).mapToInt(i -> i).sum();\n }\n}" }, { "code": null, "e": 1721, "s": 1664, "text": "In the main function, the sum of list with filter is\n271" }, { "code": null, "e": 2064, "s": 1721, "text": "A class named Demo contains the main function that creates an ArrayList. Elements are added into\nthe arraylist using the ‘add()’ function. The sum of all the elements of the list can be printed on the screen using the ‘sum’ function. Another function named ‘sum’ is defined that returns the filtered output by mapping the value to an integer." } ]
Why are global and static variables initialized to their default values in C/C++?
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .bss file and at the time of loading it allocates the memory by getting the constants alloted to the variables. The following is an example of global and static variables. Live Demo #include <stdio.h> int a; static int b; int main() { int x; static int y; int z = 28; printf("The default value of global variable a : %d", a); printf("\nThe default value of global static variable b : %d", b); printf("\nThe default value of local variable x : %d", x); printf("\nThe default value of local static variable y : %d", y); printf("\nThe value of local variable z : %d", z); return 0; } The default value of global variable a : 0 The default value of global static variable b : 0 The default value of local variable x : 0 The default value of local static variable y : 0 The value of local variable z : 28 In the above program, global variables are declared outside the main() function and one of them is static variable. Three local variables are declared and variable z is initialized too. int a; static int b; .... int x; static int y; int z = 28; Their default values are printed. printf("The default value of global variable a : %d", a); printf("\nThe default value of global static variable b : %d", b); printf("\nThe default value of local variable x : %d", x); printf("\nThe default value of local static variable y : %d", y); printf("\nThe value of local variable z : %d", z);
[ { "code": null, "e": 1447, "s": 1062, "text": "Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .bss file and at the time of loading it allocates the memory by getting the constants alloted to the variables." }, { "code": null, "e": 1507, "s": 1447, "text": "The following is an example of global and static variables." }, { "code": null, "e": 1518, "s": 1507, "text": " Live Demo" }, { "code": null, "e": 1944, "s": 1518, "text": "#include <stdio.h>\nint a;\nstatic int b;\nint main() {\n int x;\n static int y;\n int z = 28;\n printf(\"The default value of global variable a : %d\", a);\n printf(\"\\nThe default value of global static variable b : %d\", b);\n printf(\"\\nThe default value of local variable x : %d\", x);\n printf(\"\\nThe default value of local static variable y : %d\", y);\n printf(\"\\nThe value of local variable z : %d\", z);\n return 0;\n}" }, { "code": null, "e": 2163, "s": 1944, "text": "The default value of global variable a : 0\nThe default value of global static variable b : 0\nThe default value of local variable x : 0\nThe default value of local static variable y : 0\nThe value of local variable z : 28" }, { "code": null, "e": 2349, "s": 2163, "text": "In the above program, global variables are declared outside the main() function and one of them is static variable. Three local variables are declared and variable z is initialized too." }, { "code": null, "e": 2408, "s": 2349, "text": "int a;\nstatic int b;\n....\nint x;\nstatic int y;\nint z = 28;" }, { "code": null, "e": 2442, "s": 2408, "text": "Their default values are printed." }, { "code": null, "e": 2743, "s": 2442, "text": "printf(\"The default value of global variable a : %d\", a);\nprintf(\"\\nThe default value of global static variable b : %d\", b);\nprintf(\"\\nThe default value of local variable x : %d\", x);\nprintf(\"\\nThe default value of local static variable y : %d\", y);\nprintf(\"\\nThe value of local variable z : %d\", z);" } ]
Python – Check if list contain particular digits
02 Feb, 2021 Given a List and some digits, the task is to write a python program to check if the list contains only certain digits. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3] Output : True Explanation : All elements are made out of 1, 4, 5 or 3 only. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5] Output : False Explanation : 3 as a digit is required in allowed digits. Method #1 : Using loop + str() + join() In this, we iterate for each element in the list and check for each element to have all the digits by joining all digits, converting to string and checking for each in all digit of elements converted to a string. Python3 # Python3 code to demonstrate working of# Test if list contain particular digits# Using loop + str() + join() # initializing liststest_list = [435, 133, 113, 451, 134] # printing original listprint("The original list is : " + str(test_list)) # initializing digitsdigs = [1, 4, 5, 3] digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list]) res = Truefor ele in all_ele: # checking for all digits in element string for el in ele: if el not in digt_str: res = False break # printing resultprint("Are all elements made from required digits? : " + str(res)) Output: The original list is : [435, 133, 113, 451, 134] Are all elements made from required digits? : True Method #2 : Using any() + list comprehension In this, we flag off if any digit not from digit string using any() and not operation. One liner alternative extended using iteration in a list comprehension. Python3 # Python3 code to demonstrate working of# Test if list contain particular digits# Using any() + list comprehension # initializing liststest_list = [435, 133, 113, 451, 134] # printing original listprint("The original list is : " + str(test_list)) # initializing digitsdigs = [1, 4, 5, 3] digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list]) # any() checks if any element is not part of digitres = not any(ele not in digt_str for ele in all_ele) # printing resultprint("Are all elements made from required digits? : " + str(res)) Output: The original list is : [435, 133, 113, 451, 134] Are all elements made from required digits? : True Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2021" }, { "code": null, "e": 147, "s": 28, "text": "Given a List and some digits, the task is to write a python program to check if the list contains only certain digits." }, { "code": null, "e": 428, "s": 147, "text": "Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3]\nOutput : True\nExplanation : All elements are made out of 1, 4, 5 or 3 only.\n\nInput : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5]\nOutput : False\nExplanation : 3 as a digit is required in allowed digits." }, { "code": null, "e": 468, "s": 428, "text": "Method #1 : Using loop + str() + join()" }, { "code": null, "e": 681, "s": 468, "text": "In this, we iterate for each element in the list and check for each element to have all the digits by joining all digits, converting to string and checking for each in all digit of elements converted to a string." }, { "code": null, "e": 689, "s": 681, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if list contain particular digits# Using loop + str() + join() # initializing liststest_list = [435, 133, 113, 451, 134] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing digitsdigs = [1, 4, 5, 3] digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list]) res = Truefor ele in all_ele: # checking for all digits in element string for el in ele: if el not in digt_str: res = False break # printing resultprint(\"Are all elements made from required digits? : \" + str(res))", "e": 1326, "s": 689, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output:" }, { "code": null, "e": 1434, "s": 1334, "text": "The original list is : [435, 133, 113, 451, 134]\nAre all elements made from required digits? : True" }, { "code": null, "e": 1479, "s": 1434, "text": "Method #2 : Using any() + list comprehension" }, { "code": null, "e": 1638, "s": 1479, "text": "In this, we flag off if any digit not from digit string using any() and not operation. One liner alternative extended using iteration in a list comprehension." }, { "code": null, "e": 1646, "s": 1638, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if list contain particular digits# Using any() + list comprehension # initializing liststest_list = [435, 133, 113, 451, 134] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing digitsdigs = [1, 4, 5, 3] digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list]) # any() checks if any element is not part of digitres = not any(ele not in digt_str for ele in all_ele) # printing resultprint(\"Are all elements made from required digits? : \" + str(res))", "e": 2225, "s": 1646, "text": null }, { "code": null, "e": 2233, "s": 2225, "text": "Output:" }, { "code": null, "e": 2333, "s": 2233, "text": "The original list is : [435, 133, 113, 451, 134]\nAre all elements made from required digits? : True" }, { "code": null, "e": 2354, "s": 2333, "text": "Python list-programs" }, { "code": null, "e": 2361, "s": 2354, "text": "Python" }, { "code": null, "e": 2377, "s": 2361, "text": "Python Programs" } ]
Data Structures and Algorithms | Set 38
21 Feb, 2019 This topic contains basic questions of Algorithm which can be helpful for GATE CS Preparation. So, it is recommended to solve each of these questions if you are preparing for GATE. Ques-1: Which one of the following correctly determines the solution of the recurrence relation given below with T(1) = 1 ? T(n)= 2T(n/4) + n1/2 (A) O(n2)(B) O(n)(C) O(n1/2 log n)(D) O(log n) Explanation:According Master Theorem, T(n)= 2T(n/4) + n1/2 Applying Masters Theorem,Here, a = 2, b = 4, K = 1/2, and p = 0 So, bK = 41/2 = 2 Thus, a = bK and (p > -1) So, the formula is, T(n)= O(nlogba log(P+1)n) Therefore, T(n) = O(nlog 42 log(0 + 1)n) = O(n1/2 log n) So, option (C) is correct. Ques-2: For merging two unsorted list of size p and q into sorted list of size (p + q). The time complexity in terms of number of comparisons is: (A) O(log p + log q)(B) O(p log p) + q log q)(C) O(p + q)(D) None Explanation:For sorting the array of size p individually it takes O(p log p) and the array of size q takes O(q log q) time, then merging will take O(m + n) time.Therefore, total number of comparisons = O(p log p) + O(q log q) + p + q = O(p log p) + O(q log q) So, option (B) is correct. Ques-3: Which of the following sorting algorithms has the highest best case time complexity using array data structure ? (A) Heap sort(B) Insertion sort(C) Bubble sort(D) Selection sort Explanation:Best case time complexity of Heap sort is O(n log n)Best case time complexity of Insertion sort is O(n)Best case time complexity of Bubble sort is O(n)Best case time complexity of selection sort is O(n2).So, option (D) is correct. Ques-4: Which of the following input gives the best case time for selection sort ? (A) 1 2 3 4 5 6 7 8 9(B) 2 3 1 5 9 7 8 6(C) 9 8 7 6 5 4 3 2 1(D) All of the above take same amount of time. Explanation:Selection sort in worst case and best case takes same time.So, option (D) is correct. Ques-5: What is the time complexity of recursive function given below: T(n)= 4T(n/2) + n2 (A) O(n2)(B) O(n)(C) O(n2 log n)(D) O(n log n) Explanation:According Master Theorem,Here, a = 4, b = 2, k = 2, p = 0 So, bk = 4 i.e., a = bk Therefore, the formula is T(n) = O(nlog ba log(P+1)n) So, T(n)= O(nlog 24 log(0 + 1)n) = O(n2 log n) So, option (C) is correct. GATE-CS-DS-&-Algo MCQ Algorithms Quiz GATE GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 209, "s": 28, "text": "This topic contains basic questions of Algorithm which can be helpful for GATE CS Preparation. So, it is recommended to solve each of these questions if you are preparing for GATE." }, { "code": null, "e": 333, "s": 209, "text": "Ques-1: Which one of the following correctly determines the solution of the recurrence relation given below with T(1) = 1 ?" }, { "code": null, "e": 355, "s": 333, "text": "T(n)= 2T(n/4) + n1/2 " }, { "code": null, "e": 402, "s": 355, "text": "(A) O(n2)(B) O(n)(C) O(n1/2 log n)(D) O(log n)" }, { "code": null, "e": 440, "s": 402, "text": "Explanation:According Master Theorem," }, { "code": null, "e": 462, "s": 440, "text": "T(n)= 2T(n/4) + n1/2 " }, { "code": null, "e": 493, "s": 462, "text": "Applying Masters Theorem,Here," }, { "code": null, "e": 574, "s": 493, "text": "a = 2, b = 4, K = 1/2, and p = 0 \n\nSo, bK = 41/2 = 2 \nThus, a = bK and (p > -1) " }, { "code": null, "e": 594, "s": 574, "text": "So, the formula is," }, { "code": null, "e": 620, "s": 594, "text": "T(n)= O(nlogba log(P+1)n)" }, { "code": null, "e": 631, "s": 620, "text": "Therefore," }, { "code": null, "e": 677, "s": 631, "text": "T(n) = O(nlog 42 log(0 + 1)n) = O(n1/2 log n)" }, { "code": null, "e": 704, "s": 677, "text": "So, option (C) is correct." }, { "code": null, "e": 850, "s": 704, "text": "Ques-2: For merging two unsorted list of size p and q into sorted list of size (p + q). The time complexity in terms of number of comparisons is:" }, { "code": null, "e": 916, "s": 850, "text": "(A) O(log p + log q)(B) O(p log p) + q log q)(C) O(p + q)(D) None" }, { "code": null, "e": 1116, "s": 916, "text": "Explanation:For sorting the array of size p individually it takes O(p log p) and the array of size q takes O(q log q) time, then merging will take O(m + n) time.Therefore, total number of comparisons" }, { "code": null, "e": 1177, "s": 1116, "text": "= O(p log p) + O(q log q) + p + q\n= O(p log p) + O(q log q) " }, { "code": null, "e": 1204, "s": 1177, "text": "So, option (B) is correct." }, { "code": null, "e": 1325, "s": 1204, "text": "Ques-3: Which of the following sorting algorithms has the highest best case time complexity using array data structure ?" }, { "code": null, "e": 1390, "s": 1325, "text": "(A) Heap sort(B) Insertion sort(C) Bubble sort(D) Selection sort" }, { "code": null, "e": 1633, "s": 1390, "text": "Explanation:Best case time complexity of Heap sort is O(n log n)Best case time complexity of Insertion sort is O(n)Best case time complexity of Bubble sort is O(n)Best case time complexity of selection sort is O(n2).So, option (D) is correct." }, { "code": null, "e": 1716, "s": 1633, "text": "Ques-4: Which of the following input gives the best case time for selection sort ?" }, { "code": null, "e": 1824, "s": 1716, "text": "(A) 1 2 3 4 5 6 7 8 9(B) 2 3 1 5 9 7 8 6(C) 9 8 7 6 5 4 3 2 1(D) All of the above take same amount of time." }, { "code": null, "e": 1922, "s": 1824, "text": "Explanation:Selection sort in worst case and best case takes same time.So, option (D) is correct." }, { "code": null, "e": 1993, "s": 1922, "text": "Ques-5: What is the time complexity of recursive function given below:" }, { "code": null, "e": 2013, "s": 1993, "text": "T(n)= 4T(n/2) + n2 " }, { "code": null, "e": 2060, "s": 2013, "text": "(A) O(n2)(B) O(n)(C) O(n2 log n)(D) O(n log n)" }, { "code": null, "e": 2103, "s": 2060, "text": "Explanation:According Master Theorem,Here," }, { "code": null, "e": 2157, "s": 2103, "text": "a = 4, b = 2, k = 2, p = 0 \n\nSo, bk = 4 i.e., a = bk " }, { "code": null, "e": 2183, "s": 2157, "text": "Therefore, the formula is" }, { "code": null, "e": 2259, "s": 2183, "text": "T(n) = O(nlog ba log(P+1)n)\n\nSo, T(n)= O(nlog 24 log(0 + 1)n) = O(n2 log n)" }, { "code": null, "e": 2286, "s": 2259, "text": "So, option (C) is correct." }, { "code": null, "e": 2304, "s": 2286, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 2308, "s": 2304, "text": "MCQ" }, { "code": null, "e": 2324, "s": 2308, "text": "Algorithms Quiz" }, { "code": null, "e": 2329, "s": 2324, "text": "GATE" }, { "code": null, "e": 2337, "s": 2329, "text": "GATE CS" } ]
GroupBy and filter data in PySpark
19 Dec, 2021 In this article, we will Group and filter the data in PySpark using Python. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show() Output: In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data. We have to use any one of the functions with groupby while using the method Syntax: dataframe.groupBy(‘column_name_group’).aggregate_operation(‘column_name’) Filter the data means removing some data based on the condition. In PySpark we can do filtering by using filter() and where() function This is used to filter the dataframe based on the condition and returns the resultant dataframe Syntax: filter(col(‘column_name’) condition ) filter with groupby(): dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”)).filter(col(‘new_column_name’) condition ) where, dataframe is the input dataframe column_name_group is the column to be grouped column_name is the column that gets aggregated with aggregate operations aggregate_function is among the functions – sum(),min(),max() ,count(),avg() new_column_name is the column to be given from old column col is the function to specify the column on filter condition is to get the data from the dataframe using relational operators Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum()# to get FEE greater than 56700dataframe.groupBy('DEPT').agg(sum( 'FEE').alias("Total Fee")).filter( col('Total Fee') >= 56700).show() Output: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum()# to get FEE greater than or equal to # 56700 and less than or equal to 100000dataframe.groupBy('DEPT').agg(sum( 'FEE').alias("Total Fee")).filter( col('Total Fee') >= 56700).filter( col('Total Fee') <= 100000).show() Output: This is used to select the dataframe based on the condition and returns the resultant dataframe Syntax: where(col(‘column_name’) condition ) where with groupby(): dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”)).where(col(‘new_column_name’) condition ) where, dataframe is the input dataframe column_name_group is the column to be grouped column_name is the column that gets aggregated with aggregate operations aggregate_function is among the functions – sum(),min(),max() ,count(),avg() new_column_name is the column to be given from old column col is the function to specify the column on where condition is to get the data from the dataframe using relational operators Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() to get# FEE greater than or equal to 56700dataframe.groupBy('DEPT').agg(sum( 'FEE').alias("Total Fee")).where( col('Total Fee') >= 56700).show() Output: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() to get# FEE greater than or equal to 56700# and less than or equal to 100000dataframe.groupBy('DEPT').agg(sum( 'FEE').alias("Total Fee")).where( col('Total Fee') >= 56700).where( col('Total Fee') <= 100000).show() Output: The window function is used for partitioning the columns in the dataframe Syntax: Window.partitionBy(‘column_name_group’) where, column_name_group is the column that contains multiple values for partition We can partition the data column that contains group values and then use the aggregate functions like min(), max, etc to get the data. In this way, we are going to filter the data from the PySpark DataFrame with where clause. Syntax: dataframe.withColumn(‘new column’, functions.max(‘column_name’).over(Window.partitionBy(‘column_name_group’))).where(functions.col(‘column_name’) == functions.col(‘new_column_name’)) where, dataframe is the input dataframe column_name_group is the column to be partitioned column_name is to get the values with grouped column new_column_name is the new filtered column Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions as f # import window modulefrom pyspark.sql import Window # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.withColumn('FEE max', f.max('FEE').over( Window.partitionBy('DEPT'))).where( f.col('FEE') == f.col('FEE max')).show() Output: We can filter the data with aggregate operations using leftsemi join, This join will return the left matching data from dataframe1 with the aggregate operation Syntax: dataframe.join(dataframe.groupBy(‘column_name_group’).agg(f.max(‘column_name’).alias(‘new_column_name’)),on=’FEE’,how=’leftsemi’) Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions as f # import window modulefrom pyspark.sql import Window # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.join(dataframe.groupBy('DEPT').agg( f.max('FEE').alias('FEE')), on='FEE', how='leftsemi').show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 104, "s": 28, "text": "In this article, we will Group and filter the data in PySpark using Python." }, { "code": null, "e": 112, "s": 104, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()", "e": 860, "s": 112, "text": null }, { "code": null, "e": 868, "s": 860, "text": "Output:" }, { "code": null, "e": 1095, "s": 868, "text": "In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data. We have to use any one of the functions with groupby while using the method" }, { "code": null, "e": 1177, "s": 1095, "text": "Syntax: dataframe.groupBy(‘column_name_group’).aggregate_operation(‘column_name’)" }, { "code": null, "e": 1312, "s": 1177, "text": "Filter the data means removing some data based on the condition. In PySpark we can do filtering by using filter() and where() function" }, { "code": null, "e": 1408, "s": 1312, "text": "This is used to filter the dataframe based on the condition and returns the resultant dataframe" }, { "code": null, "e": 1454, "s": 1408, "text": "Syntax: filter(col(‘column_name’) condition )" }, { "code": null, "e": 1477, "s": 1454, "text": "filter with groupby():" }, { "code": null, "e": 1622, "s": 1477, "text": "dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”)).filter(col(‘new_column_name’) condition )" }, { "code": null, "e": 1629, "s": 1622, "text": "where," }, { "code": null, "e": 1662, "s": 1629, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1708, "s": 1662, "text": "column_name_group is the column to be grouped" }, { "code": null, "e": 1781, "s": 1708, "text": "column_name is the column that gets aggregated with aggregate operations" }, { "code": null, "e": 1858, "s": 1781, "text": "aggregate_function is among the functions – sum(),min(),max() ,count(),avg()" }, { "code": null, "e": 1916, "s": 1858, "text": "new_column_name is the column to be given from old column" }, { "code": null, "e": 1968, "s": 1916, "text": "col is the function to specify the column on filter" }, { "code": null, "e": 2043, "s": 1968, "text": "condition is to get the data from the dataframe using relational operators" }, { "code": null, "e": 2051, "s": 2043, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum()# to get FEE greater than 56700dataframe.groupBy('DEPT').agg(sum( 'FEE').alias(\"Total Fee\")).filter( col('Total Fee') >= 56700).show()", "e": 2996, "s": 2051, "text": null }, { "code": null, "e": 3004, "s": 2996, "text": "Output:" }, { "code": null, "e": 3012, "s": 3004, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum()# to get FEE greater than or equal to # 56700 and less than or equal to 100000dataframe.groupBy('DEPT').agg(sum( 'FEE').alias(\"Total Fee\")).filter( col('Total Fee') >= 56700).filter( col('Total Fee') <= 100000).show()", "e": 4043, "s": 3012, "text": null }, { "code": null, "e": 4051, "s": 4043, "text": "Output:" }, { "code": null, "e": 4148, "s": 4051, "text": "This is used to select the dataframe based on the condition and returns the resultant dataframe" }, { "code": null, "e": 4193, "s": 4148, "text": "Syntax: where(col(‘column_name’) condition )" }, { "code": null, "e": 4215, "s": 4193, "text": "where with groupby():" }, { "code": null, "e": 4359, "s": 4215, "text": "dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”)).where(col(‘new_column_name’) condition )" }, { "code": null, "e": 4366, "s": 4359, "text": "where," }, { "code": null, "e": 4399, "s": 4366, "text": "dataframe is the input dataframe" }, { "code": null, "e": 4445, "s": 4399, "text": "column_name_group is the column to be grouped" }, { "code": null, "e": 4518, "s": 4445, "text": "column_name is the column that gets aggregated with aggregate operations" }, { "code": null, "e": 4595, "s": 4518, "text": "aggregate_function is among the functions – sum(),min(),max() ,count(),avg()" }, { "code": null, "e": 4653, "s": 4595, "text": "new_column_name is the column to be given from old column" }, { "code": null, "e": 4704, "s": 4653, "text": "col is the function to specify the column on where" }, { "code": null, "e": 4779, "s": 4704, "text": "condition is to get the data from the dataframe using relational operators" }, { "code": null, "e": 4787, "s": 4779, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() to get# FEE greater than or equal to 56700dataframe.groupBy('DEPT').agg(sum( 'FEE').alias(\"Total Fee\")).where( col('Total Fee') >= 56700).show()", "e": 5746, "s": 4787, "text": null }, { "code": null, "e": 5754, "s": 5746, "text": "Output:" }, { "code": null, "e": 5762, "s": 5754, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import colfrom pyspark.sql.functions import col, sum # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() to get# FEE greater than or equal to 56700# and less than or equal to 100000dataframe.groupBy('DEPT').agg(sum( 'FEE').alias(\"Total Fee\")).where( col('Total Fee') >= 56700).where( col('Total Fee') <= 100000).show()", "e": 6793, "s": 5762, "text": null }, { "code": null, "e": 6801, "s": 6793, "text": "Output:" }, { "code": null, "e": 6875, "s": 6801, "text": "The window function is used for partitioning the columns in the dataframe" }, { "code": null, "e": 6923, "s": 6875, "text": "Syntax: Window.partitionBy(‘column_name_group’)" }, { "code": null, "e": 7006, "s": 6923, "text": "where, column_name_group is the column that contains multiple values for partition" }, { "code": null, "e": 7232, "s": 7006, "text": "We can partition the data column that contains group values and then use the aggregate functions like min(), max, etc to get the data. In this way, we are going to filter the data from the PySpark DataFrame with where clause." }, { "code": null, "e": 7423, "s": 7232, "text": "Syntax: dataframe.withColumn(‘new column’, functions.max(‘column_name’).over(Window.partitionBy(‘column_name_group’))).where(functions.col(‘column_name’) == functions.col(‘new_column_name’))" }, { "code": null, "e": 7430, "s": 7423, "text": "where," }, { "code": null, "e": 7463, "s": 7430, "text": "dataframe is the input dataframe" }, { "code": null, "e": 7513, "s": 7463, "text": "column_name_group is the column to be partitioned" }, { "code": null, "e": 7566, "s": 7513, "text": "column_name is to get the values with grouped column" }, { "code": null, "e": 7609, "s": 7566, "text": "new_column_name is the new filtered column" }, { "code": null, "e": 7617, "s": 7609, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions as f # import window modulefrom pyspark.sql import Window # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.withColumn('FEE max', f.max('FEE').over( Window.partitionBy('DEPT'))).where( f.col('FEE') == f.col('FEE max')).show()", "e": 8593, "s": 7617, "text": null }, { "code": null, "e": 8601, "s": 8593, "text": "Output:" }, { "code": null, "e": 8761, "s": 8601, "text": "We can filter the data with aggregate operations using leftsemi join, This join will return the left matching data from dataframe1 with the aggregate operation" }, { "code": null, "e": 8899, "s": 8761, "text": "Syntax: dataframe.join(dataframe.groupBy(‘column_name_group’).agg(f.max(‘column_name’).alias(‘new_column_name’)),on=’FEE’,how=’leftsemi’)" }, { "code": null, "e": 8907, "s": 8899, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions as f # import window modulefrom pyspark.sql import Window # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.join(dataframe.groupBy('DEPT').agg( f.max('FEE').alias('FEE')), on='FEE', how='leftsemi').show()", "e": 9876, "s": 8907, "text": null }, { "code": null, "e": 9884, "s": 9876, "text": "Output:" }, { "code": null, "e": 9891, "s": 9884, "text": "Picked" }, { "code": null, "e": 9906, "s": 9891, "text": "Python-Pyspark" }, { "code": null, "e": 9913, "s": 9906, "text": "Python" } ]
Logistic Regression using Statsmodels
18 May, 2022 Prerequisite: Understanding Logistic RegressionLogistic regression is the type of regression analysis used to find the probability of a certain event occurring. It is the best suited type of regression for cases where we have a categorical dependent variable which can take only discrete values. The dataset : In this article, we will predict whether a student will be admitted to a particular college, based on their gmat, gpa scores and work experience. The dependent variable here is a Binary Logistic variable, which is expected to take strictly one of two forms i.e., admitted or not admitted. Statsmodels is a Python module that provides various functions for estimating different statistical models and performing statistical tests First, we define the set of dependent(y) and independent(X) variables. If the dependent variable is in non-numeric form, it is first converted to numeric using dummies. The file used in the example for training the model, can be downloaded here. Statsmodels provides a Logit() function for performing logistic regression. The Logit() function accepts y and X as parameters and returns the Logit object. The model is then fitted to the data. Python3 # importing librariesimport statsmodels.api as smimport pandas as pd # loading the training dataset df = pd.read_csv('logit_train1.csv', index_col = 0) # defining the dependent and independent variablesXtrain = df[['gmat', 'gpa', 'work_experience']]ytrain = df[['admitted']] # building the model and fitting the datalog_reg = sm.Logit(ytrain, Xtrain).fit() Output : Optimization terminated successfully. Current function value: 0.352707 Iterations 8 In the output, ‘Iterations‘ refer to the number of times the model iterates over the data, trying to optimize the model. By default, the maximum number of iterations performed is 35, after which the optimization fails. The summary table below gives us a descriptive summary about the regression results. Python3 # printing the summary tableprint(log_reg.summary()) Output : Logit Regression Results ============================================================================== Dep. Variable: admitted No. Observations: 30 Model: Logit Df Residuals: 27 Method: MLE Df Model: 2 Date: Wed, 15 Jul 2020 Pseudo R-squ.: 0.4912 Time: 16:09:17 Log-Likelihood: -10.581 converged: True LL-Null: -20.794 Covariance Type: nonrobust LLR p-value: 3.668e-05 =================================================================================== coef std err z P>|z| [0.025 0.975] ----------------------------------------------------------------------------------- gmat -0.0262 0.011 -2.383 0.017 -0.048 -0.005 gpa 3.9422 1.964 2.007 0.045 0.092 7.792 work_experience 1.1983 0.482 2.487 0.013 0.254 2.143 =================================================================================== Explanation of some of the terms in the summary table: coef : the coefficients of the independent variables in the regression equation. Log-Likelihood : the natural logarithm of the Maximum Likelihood Estimation(MLE) function. MLE is the optimization process of finding the set of parameters that result in the best fit. LL-Null : the value of log-likelihood of the model when no independent variable is included(only an intercept is included). Pseudo R-squ. : a substitute for the R-squared value in Least Squares linear regression. It is the ratio of the log-likelihood of the null model to that of the full model. Now we shall test our model on new test data. The test data is loaded from this csv file.The predict() function is useful for performing predictions. The predictions obtained are fractional values(between 0 and 1) which denote the probability of getting admitted. These values are hence rounded, to obtain the discrete values of 1 or 0. Python3 # loading the testing dataset df = pd.read_csv('logit_test1.csv', index_col = 0) # defining the dependent and independent variablesXtest = df[['gmat', 'gpa', 'work_experience']]ytest = df['admitted'] # performing predictions on the test datdasetyhat = log_reg.predict(Xtest)prediction = list(map(round, yhat)) # comparing original and predicted values of yprint('Actual values', list(ytest.values))print('Predictions :', prediction) Output : Optimization terminated successfully. Current function value: 0.352707 Iterations 8 Actual values [0, 0, 0, 0, 0, 1, 1, 0, 1, 1] Predictions : [0, 0, 0, 0, 0, 0, 0, 0, 1, 1] Testing the accuracy of the model : Python3 from sklearn.metrics import (confusion_matrix, accuracy_score) # confusion matrixcm = confusion_matrix(ytest, prediction) print ("Confusion Matrix : \n", cm) # accuracy score of the modelprint('Test accuracy = ', accuracy_score(ytest, prediction)) Output : Confusion Matrix : [[6 0] [2 2]] Test accuracy = 0.8 abhishek0719kadiyan akshaysingh98088 data-science Regression Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2022" }, { "code": null, "e": 325, "s": 28, "text": "Prerequisite: Understanding Logistic RegressionLogistic regression is the type of regression analysis used to find the probability of a certain event occurring. It is the best suited type of regression for cases where we have a categorical dependent variable which can take only discrete values. " }, { "code": null, "e": 629, "s": 325, "text": "The dataset : In this article, we will predict whether a student will be admitted to a particular college, based on their gmat, gpa scores and work experience. The dependent variable here is a Binary Logistic variable, which is expected to take strictly one of two forms i.e., admitted or not admitted. " }, { "code": null, "e": 771, "s": 629, "text": "Statsmodels is a Python module that provides various functions for estimating different statistical models and performing statistical tests " }, { "code": null, "e": 1017, "s": 771, "text": "First, we define the set of dependent(y) and independent(X) variables. If the dependent variable is in non-numeric form, it is first converted to numeric using dummies. The file used in the example for training the model, can be downloaded here." }, { "code": null, "e": 1212, "s": 1017, "text": "Statsmodels provides a Logit() function for performing logistic regression. The Logit() function accepts y and X as parameters and returns the Logit object. The model is then fitted to the data." }, { "code": null, "e": 1220, "s": 1212, "text": "Python3" }, { "code": "# importing librariesimport statsmodels.api as smimport pandas as pd # loading the training dataset df = pd.read_csv('logit_train1.csv', index_col = 0) # defining the dependent and independent variablesXtrain = df[['gmat', 'gpa', 'work_experience']]ytrain = df[['admitted']] # building the model and fitting the datalog_reg = sm.Logit(ytrain, Xtrain).fit()", "e": 1582, "s": 1220, "text": null }, { "code": null, "e": 1592, "s": 1582, "text": "Output : " }, { "code": null, "e": 1694, "s": 1592, "text": "Optimization terminated successfully.\n Current function value: 0.352707\n Iterations 8" }, { "code": null, "e": 1913, "s": 1694, "text": "In the output, ‘Iterations‘ refer to the number of times the model iterates over the data, trying to optimize the model. By default, the maximum number of iterations performed is 35, after which the optimization fails." }, { "code": null, "e": 2000, "s": 1913, "text": "The summary table below gives us a descriptive summary about the regression results. " }, { "code": null, "e": 2008, "s": 2000, "text": "Python3" }, { "code": "# printing the summary tableprint(log_reg.summary())", "e": 2061, "s": 2008, "text": null }, { "code": null, "e": 2071, "s": 2061, "text": "Output : " }, { "code": null, "e": 3370, "s": 2071, "text": " Logit Regression Results \n==============================================================================\nDep. Variable: admitted No. Observations: 30\nModel: Logit Df Residuals: 27\nMethod: MLE Df Model: 2\nDate: Wed, 15 Jul 2020 Pseudo R-squ.: 0.4912\nTime: 16:09:17 Log-Likelihood: -10.581\nconverged: True LL-Null: -20.794\nCovariance Type: nonrobust LLR p-value: 3.668e-05\n===================================================================================\n coef std err z P>|z| [0.025 0.975]\n-----------------------------------------------------------------------------------\ngmat -0.0262 0.011 -2.383 0.017 -0.048 -0.005\ngpa 3.9422 1.964 2.007 0.045 0.092 7.792\nwork_experience 1.1983 0.482 2.487 0.013 0.254 2.143\n===================================================================================" }, { "code": null, "e": 3425, "s": 3370, "text": "Explanation of some of the terms in the summary table:" }, { "code": null, "e": 3506, "s": 3425, "text": "coef : the coefficients of the independent variables in the regression equation." }, { "code": null, "e": 3691, "s": 3506, "text": "Log-Likelihood : the natural logarithm of the Maximum Likelihood Estimation(MLE) function. MLE is the optimization process of finding the set of parameters that result in the best fit." }, { "code": null, "e": 3815, "s": 3691, "text": "LL-Null : the value of log-likelihood of the model when no independent variable is included(only an intercept is included)." }, { "code": null, "e": 3987, "s": 3815, "text": "Pseudo R-squ. : a substitute for the R-squared value in Least Squares linear regression. It is the ratio of the log-likelihood of the null model to that of the full model." }, { "code": null, "e": 4325, "s": 3987, "text": "Now we shall test our model on new test data. The test data is loaded from this csv file.The predict() function is useful for performing predictions. The predictions obtained are fractional values(between 0 and 1) which denote the probability of getting admitted. These values are hence rounded, to obtain the discrete values of 1 or 0. " }, { "code": null, "e": 4333, "s": 4325, "text": "Python3" }, { "code": "# loading the testing dataset df = pd.read_csv('logit_test1.csv', index_col = 0) # defining the dependent and independent variablesXtest = df[['gmat', 'gpa', 'work_experience']]ytest = df['admitted'] # performing predictions on the test datdasetyhat = log_reg.predict(Xtest)prediction = list(map(round, yhat)) # comparing original and predicted values of yprint('Actual values', list(ytest.values))print('Predictions :', prediction)", "e": 4770, "s": 4333, "text": null }, { "code": null, "e": 4780, "s": 4770, "text": "Output : " }, { "code": null, "e": 4972, "s": 4780, "text": "Optimization terminated successfully.\n Current function value: 0.352707\n Iterations 8\nActual values [0, 0, 0, 0, 0, 1, 1, 0, 1, 1]\nPredictions : [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]" }, { "code": null, "e": 5009, "s": 4972, "text": "Testing the accuracy of the model : " }, { "code": null, "e": 5017, "s": 5009, "text": "Python3" }, { "code": "from sklearn.metrics import (confusion_matrix, accuracy_score) # confusion matrixcm = confusion_matrix(ytest, prediction) print (\"Confusion Matrix : \\n\", cm) # accuracy score of the modelprint('Test accuracy = ', accuracy_score(ytest, prediction))", "e": 5295, "s": 5017, "text": null }, { "code": null, "e": 5305, "s": 5295, "text": "Output : " }, { "code": null, "e": 5362, "s": 5305, "text": "Confusion Matrix : \n [[6 0]\n [2 2]]\nTest accuracy = 0.8" }, { "code": null, "e": 5384, "s": 5364, "text": "abhishek0719kadiyan" }, { "code": null, "e": 5401, "s": 5384, "text": "akshaysingh98088" }, { "code": null, "e": 5414, "s": 5401, "text": "data-science" }, { "code": null, "e": 5425, "s": 5414, "text": "Regression" }, { "code": null, "e": 5442, "s": 5425, "text": "Machine Learning" }, { "code": null, "e": 5449, "s": 5442, "text": "Python" }, { "code": null, "e": 5466, "s": 5449, "text": "Machine Learning" } ]
How to remove an HTML element using JavaScript ?
21 Jul, 2021 Given an HTML element and the task is to remove the HTML element from the document using JavaScript. Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document. Example 1: This example uses removeChild() method to remove the HTML element. <!DOCTYPE HTML> <html> <head> <title> How to remove an HTML element using JavaScript ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to remove HTML element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = "Click on button to remove the element."; function GFG_Fun() { div.parentNode.removeChild(div); down.innerHTML = "Element is removed."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example uses remove() method to remove an HTML element from the document. <!DOCTYPE HTML> <html> <head> <title> How to remove an HTML element using JavaScript ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to remove HTML element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = "Click on button to remove the element."; function GFG_Fun() { div.remove(); down.innerHTML = "Element is removed."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: 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. HTML-DOM JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 129, "s": 28, "text": "Given an HTML element and the task is to remove the HTML element from the document using JavaScript." }, { "code": null, "e": 139, "s": 129, "text": "Approach:" }, { "code": null, "e": 185, "s": 139, "text": "Select the HTML element which need to remove." }, { "code": null, "e": 280, "s": 185, "text": "Use JavaScript remove() and removeChild() method to remove the element from the HTML document." }, { "code": null, "e": 358, "s": 280, "text": "Example 1: This example uses removeChild() method to remove the HTML element." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove an HTML element using JavaScript ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to remove HTML element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = \"Click on button to remove the element.\"; function GFG_Fun() { div.parentNode.removeChild(div); down.innerHTML = \"Element is removed.\"; } </script> </body> </html> ", "e": 1803, "s": 358, "text": null }, { "code": null, "e": 1811, "s": 1803, "text": "Output:" }, { "code": null, "e": 1842, "s": 1811, "text": "Before clicking on the button:" }, { "code": null, "e": 1872, "s": 1842, "text": "After clicking on the button:" }, { "code": null, "e": 1962, "s": 1872, "text": "Example 2: This example uses remove() method to remove an HTML element from the document." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove an HTML element using JavaScript ? </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to remove HTML element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = \"Click on button to remove the element.\"; function GFG_Fun() { div.remove(); down.innerHTML = \"Element is removed.\"; } </script> </body> </html> ", "e": 3388, "s": 1962, "text": null }, { "code": null, "e": 3396, "s": 3388, "text": "Output:" }, { "code": null, "e": 3427, "s": 3396, "text": "Before clicking on the button:" }, { "code": null, "e": 3457, "s": 3427, "text": "After clicking on the button:" }, { "code": null, "e": 3676, "s": 3457, "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": 3685, "s": 3676, "text": "HTML-DOM" }, { "code": null, "e": 3696, "s": 3685, "text": "JavaScript" }, { "code": null, "e": 3713, "s": 3696, "text": "Web Technologies" }, { "code": null, "e": 3740, "s": 3713, "text": "Web technologies Questions" } ]
Depth First Search or DFS for a Graph
14 Jul, 2022 Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram: Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Prerequisites: See this post for all applications of Depth First Traversal. Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path. Algorithm: Create a recursive function that takes the index of the node and a visited array. Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node. Mark the current node as visited and print the node. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node. Implementation: Below are implementations of simple Depth First Traversal. The C++ implementation uses an adjacency list representation of graphs. STL’s list container is used to store lists of adjacent nodes. C++ Java Python3 C# Javascript // C++ program to print DFS traversal from// a given vertex in a given graph#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph {public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFS(int v){ // Mark the current node as visited and // print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Depth First Traversal" " (starting from vertex 2) \n"; g.DFS(2); return 0;} // improved by Vishnudev C // Java program to print DFS// traversal from a given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + " "); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() void DFS(int v) { // Mark all the vertices as // not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper // function to print DFS // traversal DFSUtil(v, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( "Following is Depth First Traversal " + "(starting from vertex 2)"); g.DFS(2); }}// This code is contributed by Aakash Hasija # Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print("Following is DFS from (starting from vertex 2)")g.DFS(2) # This code is contributed by Neelam Yadav // C# program to print DFS traversal// from a given graphusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to Add an edge into the graph void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current node as visited // and print it visited[v] = true; Console.Write(v + " "); // Recur for all the vertices // adjacent to this vertex List<int> vList = adj[v]; foreach(var n in vList) { if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited // (set as false by default in c#) bool[] visited = new bool[V]; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); } // Driver Code public static void Main(String[] args) { Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.WriteLine( "Following is Depth First Traversal " + "(starting from vertex 2)"); g.DFS(2); Console.ReadKey(); }} // This code is contributed by techno2mahi <script> // Javascript program to print DFS// traversal from a given// graph // This class represents a// directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { // Add w to v's list. this.adj[v].push(w); } // A function used by DFS DFSUtil(v, visited) { // Mark the current node as visited and print it visited[v] = true; document.write(v + " "); // Recur for all the vertices adjacent to this // vertex for(let i of this.adj[v].values()) { let n = i if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() DFS(v) { // Mark all the vertices as // not visited(set as // false by default in java) let visited = new Array(this.V); for(let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper // function to print DFS // traversal this.DFSUtil(v, visited); }} // Driver Codeg = new Graph(4); g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.addEdge(3, 3); document.write("Following is Depth First Traversal " + "(starting from vertex 2)<br>"); g.DFS(2); // This code is contributed by avanitrachhadiya2155 </script> Output: Following is Depth First Traversal (starting from vertex 2) 2 0 1 3 Complexity Analysis: Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph. Space Complexity: O(V), since an extra visited array of size V is required. Handling A Disconnected Graph: Solution: This will happen by handling a corner case. The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex, as in a Disconnected graph. To do a complete DFS traversal of such graphs, run DFS from all unvisited nodes after a DFS. The recursive function remains the same. Algorithm: Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node. Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node. Create a recursive function that takes the index of the node and a visited array. Mark the current node as visited and print the node. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node. Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node. Implementation: C++ Java Python3 C# Javascript // C++ program to print DFS// traversal for a given// graph#include <bits/stdc++.h>using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFSUtil(int v){ // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i);} // The function to do DFS traversal. It uses recursive// DFSUtil()void Graph::DFS(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first);} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << "Following is Depth First Traversal \n"; g.DFS(); return 0;}// improved by Vishnudev C // Java program to print DFS// traversal from a given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + " "); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( "Following is Depth First Traversal"); g.DFS(); }}// This code is contributed by Aakash Hasija '''Python program to print DFS traversal for complete graph'''from collections import defaultdict # this class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited.add(v) print(v,end=" ") # recur for all the vertices adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses recursive DFSUtil def DFS(self): # create a set to store all visited vertices visited = set() # call the recursive helper function to print DFS traversal starting from all # vertices one by one for vertex in self.graph: if vertex not in visited: self.DFSUtil(vertex, visited)# Driver code# create a graph given in the above diagram print("Following is Depth First Traversal \n")g = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)g.DFS() # Improved by Dheeraj Kumar // C# program to print DFS// traversal from a given// graphusing System;using System.Collections.Generic; // This class represents a// directed graph using adjacency// list representationpublic class Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current // node as visited and print it visited[v] = true; Console.Write(v + " "); // Recur for all the // vertices adjacent to this // vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) bool[] visited = new bool[V]; // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver code public static void Main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine( "Following is Depth First Traversal"); g.DFS(); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to print DFS // traversal from a given // graph // This class represents a // directed graph using adjacency // list representation class Graph { // Constructor constructor(v) { this.V = v; this.adj = new Array(v).fill([]); } // Function to Add an edge into the graph AddEdge(v, w) { this.adj[v].push(w); // Add w to v's list. } // A function used by DFS DFSUtil(v, visited) { // Mark the current // node as visited and print it visited[v] = true; document.write(v + " "); // Recur for all the // vertices adjacent to this // vertex for (const n of this.adj[v]) { if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() DFS() { // Mark all the vertices as not visited(set as var visited = new Array(this.V).fill(false); // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (var i = 0; i < this.V; ++i) if (visited[i] == false) this.DFSUtil(i, visited); } } // Driver Code var g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); document.write("Following is Depth First Traversal<br>"); g.DFS(); // This code is contributed by rdtank. </script> Output: Following is Depth First Traversal 0 1 2 3 9 Complexity Analysis: Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph. Space Complexity: O(V), since an extra visited array of size V is required. https://youtu.be/Y40bRyPQQr0 Applications of DFS. Breadth-First Traversal for a Graph Recent Articles on DFS Would you please write comments if you find anything incorrect or share more information about the topic discussed above? speak2rk09 techno2mahi princiraj1992 eshankvaish andrew1234 draco_malf0y nikhil104 akashgoac itisvishnudev koushalsagar66 rdtank avanitrachhadiya2155 dheerajkumar33 tanvimoharir byromjomaa amartyaghoshgfg surinderdawra388 DFS graph-basics Graph DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jul, 2022" }, { "code": null, "e": 313, "s": 52, "text": "Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. " }, { "code": null, "e": 323, "s": 313, "text": "Example: " }, { "code": null, "e": 454, "s": 323, "text": "Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram: " }, { "code": null, "e": 585, "s": 454, "text": "Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram: " }, { "code": null, "e": 594, "s": 585, "text": "Chapters" }, { "code": null, "e": 621, "s": 594, "text": "descriptions off, selected" }, { "code": null, "e": 671, "s": 621, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 694, "s": 671, "text": "captions off, selected" }, { "code": null, "e": 702, "s": 694, "text": "English" }, { "code": null, "e": 726, "s": 702, "text": "This is a modal window." }, { "code": null, "e": 795, "s": 726, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 817, "s": 795, "text": "End of dialog window." }, { "code": null, "e": 893, "s": 817, "text": "Prerequisites: See this post for all applications of Depth First Traversal." }, { "code": null, "e": 1473, "s": 893, "text": "Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path." }, { "code": null, "e": 1566, "s": 1473, "text": "Algorithm: Create a recursive function that takes the index of the node and a visited array." }, { "code": null, "e": 1732, "s": 1566, "text": "Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node." }, { "code": null, "e": 1785, "s": 1732, "text": "Mark the current node as visited and print the node." }, { "code": null, "e": 1899, "s": 1785, "text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node." }, { "code": null, "e": 2109, "s": 1899, "text": "Implementation: Below are implementations of simple Depth First Traversal. The C++ implementation uses an adjacency list representation of graphs. STL’s list container is used to store lists of adjacent nodes." }, { "code": null, "e": 2113, "s": 2109, "text": "C++" }, { "code": null, "e": 2118, "s": 2113, "text": "Java" }, { "code": null, "e": 2126, "s": 2118, "text": "Python3" }, { "code": null, "e": 2129, "s": 2126, "text": "C#" }, { "code": null, "e": 2140, "s": 2129, "text": "Javascript" }, { "code": "// C++ program to print DFS traversal from// a given vertex in a given graph#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph {public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v);}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFS(int v){ // Mark the current node as visited and // print it visited[v] = true; cout << v << \" \"; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i);} // Driver codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << \"Following is Depth First Traversal\" \" (starting from vertex 2) \\n\"; g.DFS(2); return 0;} // improved by Vishnudev C", "e": 3320, "s": 2140, "text": null }, { "code": "// Java program to print DFS// traversal from a given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + \" \"); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() void DFS(int v) { // Mark all the vertices as // not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper // function to print DFS // traversal DFSUtil(v, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( \"Following is Depth First Traversal \" + \"(starting from vertex 2)\"); g.DFS(2); }}// This code is contributed by Aakash Hasija", "e": 5228, "s": 3320, "text": null }, { "code": "# Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print(\"Following is DFS from (starting from vertex 2)\")g.DFS(2) # This code is contributed by Neelam Yadav", "e": 6553, "s": 5228, "text": null }, { "code": "// C# program to print DFS traversal// from a given graphusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to Add an edge into the graph void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current node as visited // and print it visited[v] = true; Console.Write(v + \" \"); // Recur for all the vertices // adjacent to this vertex List<int> vList = adj[v]; foreach(var n in vList) { if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited // (set as false by default in c#) bool[] visited = new bool[V]; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); } // Driver Code public static void Main(String[] args) { Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); Console.WriteLine( \"Following is Depth First Traversal \" + \"(starting from vertex 2)\"); g.DFS(2); Console.ReadKey(); }} // This code is contributed by techno2mahi", "e": 8381, "s": 6553, "text": null }, { "code": "<script> // Javascript program to print DFS// traversal from a given// graph // This class represents a// directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { // Add w to v's list. this.adj[v].push(w); } // A function used by DFS DFSUtil(v, visited) { // Mark the current node as visited and print it visited[v] = true; document.write(v + \" \"); // Recur for all the vertices adjacent to this // vertex for(let i of this.adj[v].values()) { let n = i if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do DFS traversal. // It uses recursive // DFSUtil() DFS(v) { // Mark all the vertices as // not visited(set as // false by default in java) let visited = new Array(this.V); for(let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper // function to print DFS // traversal this.DFSUtil(v, visited); }} // Driver Codeg = new Graph(4); g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 2);g.addEdge(2, 0);g.addEdge(2, 3);g.addEdge(3, 3); document.write(\"Following is Depth First Traversal \" + \"(starting from vertex 2)<br>\"); g.DFS(2); // This code is contributed by avanitrachhadiya2155 </script>", "e": 10025, "s": 8381, "text": null }, { "code": null, "e": 10034, "s": 10025, "text": "Output: " }, { "code": null, "e": 10102, "s": 10034, "text": "Following is Depth First Traversal (starting from vertex 2)\n2 0 1 3" }, { "code": null, "e": 10124, "s": 10102, "text": "Complexity Analysis: " }, { "code": null, "e": 10228, "s": 10124, "text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph." }, { "code": null, "e": 10304, "s": 10228, "text": "Space Complexity: O(V), since an extra visited array of size V is required." }, { "code": null, "e": 10336, "s": 10304, "text": " Handling A Disconnected Graph:" }, { "code": null, "e": 10692, "s": 10336, "text": "Solution: This will happen by handling a corner case. The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex, as in a Disconnected graph. To do a complete DFS traversal of such graphs, run DFS from all unvisited nodes after a DFS. The recursive function remains the same." }, { "code": null, "e": 11100, "s": 10692, "text": "Algorithm: Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node." }, { "code": null, "e": 11497, "s": 11100, "text": "Create a recursive function that takes the index of the node and a visited array.Mark the current node as visited and print the node.Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node." }, { "code": null, "e": 11579, "s": 11497, "text": "Create a recursive function that takes the index of the node and a visited array." }, { "code": null, "e": 11632, "s": 11579, "text": "Mark the current node as visited and print the node." }, { "code": null, "e": 11746, "s": 11632, "text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node." }, { "code": null, "e": 11897, "s": 11746, "text": "Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, call the recursive function with the current node." }, { "code": null, "e": 11914, "s": 11897, "text": "Implementation: " }, { "code": null, "e": 11918, "s": 11914, "text": "C++" }, { "code": null, "e": 11923, "s": 11918, "text": "Java" }, { "code": null, "e": 11931, "s": 11923, "text": "Python3" }, { "code": null, "e": 11934, "s": 11931, "text": "C#" }, { "code": null, "e": 11945, "s": 11934, "text": "Javascript" }, { "code": "// C++ program to print DFS// traversal for a given// graph#include <bits/stdc++.h>using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} void Graph::DFSUtil(int v){ // Mark the current node as visited and print it visited[v] = true; cout << v << \" \"; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i);} // The function to do DFS traversal. It uses recursive// DFSUtil()void Graph::DFS(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first);} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << \"Following is Depth First Traversal \\n\"; g.DFS(); return 0;}// improved by Vishnudev C", "e": 13305, "s": 11945, "text": null }, { "code": "// Java program to print DFS// traversal from a given// graphimport java.io.*;import java.util.*; // This class represents a// directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v + \" \"); // Recur for all the vertices adjacent to this // vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver Code public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println( \"Following is Depth First Traversal\"); g.DFS(); }}// This code is contributed by Aakash Hasija", "e": 15257, "s": 13305, "text": null }, { "code": "'''Python program to print DFS traversal for complete graph'''from collections import defaultdict # this class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited.add(v) print(v,end=\" \") # recur for all the vertices adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses recursive DFSUtil def DFS(self): # create a set to store all visited vertices visited = set() # call the recursive helper function to print DFS traversal starting from all # vertices one by one for vertex in self.graph: if vertex not in visited: self.DFSUtil(vertex, visited)# Driver code# create a graph given in the above diagram print(\"Following is Depth First Traversal \\n\")g = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)g.DFS() # Improved by Dheeraj Kumar", "e": 16648, "s": 15257, "text": null }, { "code": "// C# program to print DFS// traversal from a given// graphusing System;using System.Collections.Generic; // This class represents a// directed graph using adjacency// list representationpublic class Graph { private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int>[] adj; // Constructor Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool[] visited) { // Mark the current // node as visited and print it visited[v] = true; Console.Write(v + \" \"); // Recur for all the // vertices adjacent to this // vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) bool[] visited = new bool[V]; // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) if (visited[i] == false) DFSUtil(i, visited); } // Driver code public static void Main(String[] args) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine( \"Following is Depth First Traversal\"); g.DFS(); }} // This code is contributed by PrinciRaj1992", "e": 18560, "s": 16648, "text": null }, { "code": "<script> // JavaScript program to print DFS // traversal from a given // graph // This class represents a // directed graph using adjacency // list representation class Graph { // Constructor constructor(v) { this.V = v; this.adj = new Array(v).fill([]); } // Function to Add an edge into the graph AddEdge(v, w) { this.adj[v].push(w); // Add w to v's list. } // A function used by DFS DFSUtil(v, visited) { // Mark the current // node as visited and print it visited[v] = true; document.write(v + \" \"); // Recur for all the // vertices adjacent to this // vertex for (const n of this.adj[v]) { if (!visited[n]) this.DFSUtil(n, visited); } } // The function to do // DFS traversal. It uses recursive // DFSUtil() DFS() { // Mark all the vertices as not visited(set as var visited = new Array(this.V).fill(false); // Call the recursive helper // function to print DFS // traversal starting from // all vertices one by one for (var i = 0; i < this.V; ++i) if (visited[i] == false) this.DFSUtil(i, visited); } } // Driver Code var g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); document.write(\"Following is Depth First Traversal<br>\"); g.DFS(); // This code is contributed by rdtank. </script>", "e": 20280, "s": 18560, "text": null }, { "code": null, "e": 20289, "s": 20280, "text": "Output: " }, { "code": null, "e": 20334, "s": 20289, "text": "Following is Depth First Traversal\n0 1 2 3 9" }, { "code": null, "e": 20356, "s": 20334, "text": "Complexity Analysis: " }, { "code": null, "e": 20460, "s": 20356, "text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph." }, { "code": null, "e": 20536, "s": 20460, "text": "Space Complexity: O(V), since an extra visited array of size V is required." }, { "code": null, "e": 20566, "s": 20536, "text": "https://youtu.be/Y40bRyPQQr0 " }, { "code": null, "e": 20587, "s": 20566, "text": "Applications of DFS." }, { "code": null, "e": 20623, "s": 20587, "text": "Breadth-First Traversal for a Graph" }, { "code": null, "e": 20646, "s": 20623, "text": "Recent Articles on DFS" }, { "code": null, "e": 20768, "s": 20646, "text": "Would you please write comments if you find anything incorrect or share more information about the topic discussed above?" }, { "code": null, "e": 20779, "s": 20768, "text": "speak2rk09" }, { "code": null, "e": 20791, "s": 20779, "text": "techno2mahi" }, { "code": null, "e": 20805, "s": 20791, "text": "princiraj1992" }, { "code": null, "e": 20817, "s": 20805, "text": "eshankvaish" }, { "code": null, "e": 20828, "s": 20817, "text": "andrew1234" }, { "code": null, "e": 20841, "s": 20828, "text": "draco_malf0y" }, { "code": null, "e": 20851, "s": 20841, "text": "nikhil104" }, { "code": null, "e": 20861, "s": 20851, "text": "akashgoac" }, { "code": null, "e": 20875, "s": 20861, "text": "itisvishnudev" }, { "code": null, "e": 20890, "s": 20875, "text": "koushalsagar66" }, { "code": null, "e": 20897, "s": 20890, "text": "rdtank" }, { "code": null, "e": 20918, "s": 20897, "text": "avanitrachhadiya2155" }, { "code": null, "e": 20933, "s": 20918, "text": "dheerajkumar33" }, { "code": null, "e": 20946, "s": 20933, "text": "tanvimoharir" }, { "code": null, "e": 20957, "s": 20946, "text": "byromjomaa" }, { "code": null, "e": 20973, "s": 20957, "text": "amartyaghoshgfg" }, { "code": null, "e": 20990, "s": 20973, "text": "surinderdawra388" }, { "code": null, "e": 20994, "s": 20990, "text": "DFS" }, { "code": null, "e": 21007, "s": 20994, "text": "graph-basics" }, { "code": null, "e": 21013, "s": 21007, "text": "Graph" }, { "code": null, "e": 21017, "s": 21013, "text": "DFS" }, { "code": null, "e": 21023, "s": 21017, "text": "Graph" } ]
itertools.combinations() module in Python to print all possible combinations
23 Nov, 2020 Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2 Output : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module. It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. itertools.combinations(iterable, r) :It return r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD]. itertools.combinations_with_replacement(iterable, r) :It return r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD]. # Function which returns subset or r length from nfrom itertools import combinations def rSubset(arr, r): # return list of all subsets of length r # to deal with duplicate subsets use # set(list(combinations(arr, r))) return list(combinations(arr, r)) # Driver Functionif __name__ == "__main__": arr = [1, 2, 3, 4] r = 2 print (rSubset(arr, r)) Output: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python-Library Combinatorial Python Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Nov, 2020" }, { "code": null, "e": 147, "s": 52, "text": "Given an array of size n, generate and print all possible combinations of r elements in array." }, { "code": null, "e": 157, "s": 147, "text": "Examples:" }, { "code": null, "e": 266, "s": 157, "text": "Input : arr[] = [1, 2, 3, 4], \n r = 2\nOutput : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n" }, { "code": null, "e": 479, "s": 266, "text": "This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module." }, { "code": null, "e": 697, "s": 479, "text": "It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order." }, { "code": null, "e": 870, "s": 697, "text": "itertools.combinations(iterable, r) :It return r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD]." }, { "code": null, "e": 1090, "s": 870, "text": "itertools.combinations_with_replacement(iterable, r) :It return r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD]." }, { "code": "# Function which returns subset or r length from nfrom itertools import combinations def rSubset(arr, r): # return list of all subsets of length r # to deal with duplicate subsets use # set(list(combinations(arr, r))) return list(combinations(arr, r)) # Driver Functionif __name__ == \"__main__\": arr = [1, 2, 3, 4] r = 2 print (rSubset(arr, r))", "e": 1461, "s": 1090, "text": null }, { "code": null, "e": 1469, "s": 1461, "text": "Output:" }, { "code": null, "e": 1519, "s": 1469, "text": "[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n" }, { "code": null, "e": 1830, "s": 1519, "text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1955, "s": 1830, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1970, "s": 1955, "text": "Python-Library" }, { "code": null, "e": 1984, "s": 1970, "text": "Combinatorial" }, { "code": null, "e": 1991, "s": 1984, "text": "Python" }, { "code": null, "e": 2005, "s": 1991, "text": "Combinatorial" } ]
Iterative Method To Print Left View of a Binary Tree
06 Aug, 2021 Given a Binary Tree, print it’s left view. Left view of a Binary Tree is a set of nodes visible when tree is seen from the left side . Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 1 2 4 Input : 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output : 1 2 4 6 7 We have already discussed this problem using the Recursion method, here iterative approach is used to solve the above problem.The idea is to do level order traversal of the Tree using a queue and print the first node at each level. While doing level order traversal, after traversing all node at each level, push a NULL delimiter to mark the end of the current level. So, do the level order traversal of the tree. Print the first node at each level in the tree and push the children of all nodes at each level in the queue until a NULL delimiter is encountered. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to print the// left view of Binary Tree #include <bits/stdc++.h> using namespace std; // A Binary Tree Nodestruct node { int data; struct node *left, *right;}; // A utility function to create a new// Binary Tree nodestruct node* newNode(int item){ struct node* temp = new node; temp->data = item; temp->left = NULL; temp->right = NULL; return temp;} // Utility function to print the left view of// the binary treevoid leftViewUtil(struct node* root, queue<node*>& q){ if (root == NULL) return; // Push root q.push(root); // Delimiter q.push(NULL); while (!q.empty()) { node* temp = q.front(); if (temp) { // Prints first node // of each level cout << temp->data << " "; // Push children of all nodes at // current level while (q.front() != NULL) { // If left child is present // push into queue if (temp->left) q.push(temp->left); // If right child is present // push into queue if (temp->right) q.push(temp->right); // Pop the current node q.pop(); temp = q.front(); } // Push delimiter // for the next level q.push(NULL); } // Pop the delimiter of // the previous level q.pop(); }} // Function to print the leftView// of Binary Treevoid leftView(struct node* root){ // Queue to store all // the nodes of the tree queue<node*> q; leftViewUtil(root, q);} // Driver Codeint main(){ struct node* root = newNode(10); root->left = newNode(12); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); root->right->left->right = newNode(6); root->right->left->right->left = newNode(18); root->right->left->right->right = newNode(7); leftView(root); return 0;} // Java program to print the// left view of Binary Treeimport java.util.*; class GFG{ // A Binary Tree Nodestatic class node{ int data; node left, right;}; // A utility function to create a new// Binary Tree nodestatic node newNode(int item){ node temp = new node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static Queue<node> q; // Utility function to print the left view of// the binary treestatic void leftViewUtil( node root ){ if (root == null) return; // add root q.add(root); // Delimiter q.add(null); while (q.size() > 0) { node temp = q.peek(); if (temp != null) { // Prints first node // of each level System.out.print(temp.data + " "); // add children of all nodes at // current level while (q.peek() != null) { // If left child is present // add into queue if (temp.left != null) q.add(temp.left); // If right child is present // add into queue if (temp.right != null) q.add(temp.right); // remove the current node q.remove(); temp = q.peek(); } // add delimiter // for the next level q.add(null); } // remove the delimiter of // the previous level q.remove(); }} // Function to print the leftView// of Binary Treestatic void leftView( node root){ // Queue to store all // the nodes of the tree q = new LinkedList<node>(); leftViewUtil(root);} // Driver Codepublic static void main(String args[]){ node root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root);}} // This code is contributed by Arnab Kundu # Python3 program to print the# left view of Binary Tree # Binary Tree Node""" utility that allocates a newNodewith the given key """class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd=0 # Utility function to print the left# view of the binary treedef leftViewUtil(root, q) : if (root == None) : return # append root q.append(root) # Delimiter q.append(None) while (len(q)): temp = q[0] if (temp): # Prints first node of each level print(temp.data, end = " ") # append children of all nodes # at current level while (q[0] != None) : temp = q[0] # If left child is present # append into queue if (temp.left) : q.append(temp.left) # If right child is present # append into queue if (temp.right) : q.append(temp.right) # Pop the current node q.pop(0) # append delimiter # for the next level q.append(None) # Pop the delimiter of # the previous level q.pop(0) # Function to print the leftView# of Binary Treedef leftView(root): # Queue to store all # the nodes of the tree q = [] leftViewUtil(root, q) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(3) root.left.right = newNode(4) root.right.left = newNode(5) root.right.left.right = newNode(6) root.right.left.right.left = newNode(18) root.right.left.right.right = newNode(7) leftView(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to print the// left view of Binary Treeusing System;using System.Collections.Generic; class GFG{ // A Binary Tree Nodepublic class node{ public int data; public node left, right;}; // A utility function to create a new// Binary Tree nodestatic node newNode(int item){ node temp = new node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static Queue<node> q = new Queue<node>(); // Utility function to print the left view of// the binary treestatic void leftViewUtil( node root ){ if (root == null) return; // add root q.Enqueue(root); // Delimiter q.Enqueue(null); while (q.Count > 0) { node temp = q.Peek(); if (temp != null) { // Prints first node // of each level Console.Write(temp.data + " "); // add children of all nodes at // current level while (q.Peek() != null) { // If left child is present // add into queue if (temp.left != null) q.Enqueue(temp.left); // If right child is present // add into queue if (temp.right != null) q.Enqueue(temp.right); // remove the current node q.Dequeue(); temp = q.Peek(); } // add delimiter // for the next level q.Enqueue(null); } // remove the delimiter of // the previous level q.Dequeue(); }} // Function to print the leftView// of Binary Treestatic void leftView( node root){ // Queue to store all // the nodes of the tree q = new Queue<node>(); leftViewUtil(root);} // Driver Codepublic static void Main(String []args){ node root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to print the left view of Binary Tree // Binary Tree Node class node { constructor(item) { this.left = null; this.right = null; this.data = item; } } // A utility function to create a new // Binary Tree node function newNode(item) { let temp = new node(item); return temp; } let q = []; // Utility function to print the left view of // the binary tree function leftViewUtil(root) { if (root == null) return; // add root q.push(root); // Delimiter q.push(null); while (q.length > 0) { let temp = q[0]; if (temp != null) { // Prints first node // of each level document.write(temp.data + " "); // add children of all nodes at // current level while (q[0] != null) { // If left child is present // add into queue if (temp.left != null) q.push(temp.left); // If right child is present // add into queue if (temp.right != null) q.push(temp.right); // remove the current node q.shift(); temp = q[0]; } // add delimiter // for the next level q.push(null); } // remove the delimiter of // the previous level q.shift(); } } // Function to print the leftView // of Binary Tree function leftView(root) { // Queue to store all // the nodes of the tree q = []; leftViewUtil(root); } let root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root); </script> Output: 10 12 4 6 18 Time Complexity: O(N) where N is the number of vertices in the binary tree.Auxiliary Space: O(N). SHUBHAMSINGH10 andrew1234 29AjayKumar Akanksha_Rai mukesh07 pankajsharmagfg Binary Tree tree-level-order Data Structures Queue Tree Data Structures Queue Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Aug, 2021" }, { "code": null, "e": 190, "s": 54, "text": "Given a Binary Tree, print it’s left view. Left view of a Binary Tree is a set of nodes visible when tree is seen from the left side . " }, { "code": null, "e": 202, "s": 190, "text": "Examples: " }, { "code": null, "e": 520, "s": 202, "text": "Input : 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nOutput : 1 2 4\n\nInput : 1\n / \\\n 2 3\n \\ /\n 4 5\n \\\n 6\n / \\\n 7 8\nOutput : 1 2 4 6 7" }, { "code": null, "e": 1133, "s": 522, "text": "We have already discussed this problem using the Recursion method, here iterative approach is used to solve the above problem.The idea is to do level order traversal of the Tree using a queue and print the first node at each level. While doing level order traversal, after traversing all node at each level, push a NULL delimiter to mark the end of the current level. So, do the level order traversal of the tree. Print the first node at each level in the tree and push the children of all nodes at each level in the queue until a NULL delimiter is encountered. Below is the implementation of above approach: " }, { "code": null, "e": 1137, "s": 1133, "text": "C++" }, { "code": null, "e": 1142, "s": 1137, "text": "Java" }, { "code": null, "e": 1150, "s": 1142, "text": "Python3" }, { "code": null, "e": 1153, "s": 1150, "text": "C#" }, { "code": null, "e": 1164, "s": 1153, "text": "Javascript" }, { "code": "// C++ program to print the// left view of Binary Tree #include <bits/stdc++.h> using namespace std; // A Binary Tree Nodestruct node { int data; struct node *left, *right;}; // A utility function to create a new// Binary Tree nodestruct node* newNode(int item){ struct node* temp = new node; temp->data = item; temp->left = NULL; temp->right = NULL; return temp;} // Utility function to print the left view of// the binary treevoid leftViewUtil(struct node* root, queue<node*>& q){ if (root == NULL) return; // Push root q.push(root); // Delimiter q.push(NULL); while (!q.empty()) { node* temp = q.front(); if (temp) { // Prints first node // of each level cout << temp->data << \" \"; // Push children of all nodes at // current level while (q.front() != NULL) { // If left child is present // push into queue if (temp->left) q.push(temp->left); // If right child is present // push into queue if (temp->right) q.push(temp->right); // Pop the current node q.pop(); temp = q.front(); } // Push delimiter // for the next level q.push(NULL); } // Pop the delimiter of // the previous level q.pop(); }} // Function to print the leftView// of Binary Treevoid leftView(struct node* root){ // Queue to store all // the nodes of the tree queue<node*> q; leftViewUtil(root, q);} // Driver Codeint main(){ struct node* root = newNode(10); root->left = newNode(12); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); root->right->left->right = newNode(6); root->right->left->right->left = newNode(18); root->right->left->right->right = newNode(7); leftView(root); return 0;}", "e": 3198, "s": 1164, "text": null }, { "code": "// Java program to print the// left view of Binary Treeimport java.util.*; class GFG{ // A Binary Tree Nodestatic class node{ int data; node left, right;}; // A utility function to create a new// Binary Tree nodestatic node newNode(int item){ node temp = new node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static Queue<node> q; // Utility function to print the left view of// the binary treestatic void leftViewUtil( node root ){ if (root == null) return; // add root q.add(root); // Delimiter q.add(null); while (q.size() > 0) { node temp = q.peek(); if (temp != null) { // Prints first node // of each level System.out.print(temp.data + \" \"); // add children of all nodes at // current level while (q.peek() != null) { // If left child is present // add into queue if (temp.left != null) q.add(temp.left); // If right child is present // add into queue if (temp.right != null) q.add(temp.right); // remove the current node q.remove(); temp = q.peek(); } // add delimiter // for the next level q.add(null); } // remove the delimiter of // the previous level q.remove(); }} // Function to print the leftView// of Binary Treestatic void leftView( node root){ // Queue to store all // the nodes of the tree q = new LinkedList<node>(); leftViewUtil(root);} // Driver Codepublic static void main(String args[]){ node root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root);}} // This code is contributed by Arnab Kundu", "e": 5299, "s": 3198, "text": null }, { "code": "# Python3 program to print the# left view of Binary Tree # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\"class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd=0 # Utility function to print the left# view of the binary treedef leftViewUtil(root, q) : if (root == None) : return # append root q.append(root) # Delimiter q.append(None) while (len(q)): temp = q[0] if (temp): # Prints first node of each level print(temp.data, end = \" \") # append children of all nodes # at current level while (q[0] != None) : temp = q[0] # If left child is present # append into queue if (temp.left) : q.append(temp.left) # If right child is present # append into queue if (temp.right) : q.append(temp.right) # Pop the current node q.pop(0) # append delimiter # for the next level q.append(None) # Pop the delimiter of # the previous level q.pop(0) # Function to print the leftView# of Binary Treedef leftView(root): # Queue to store all # the nodes of the tree q = [] leftViewUtil(root, q) # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(3) root.left.right = newNode(4) root.right.left = newNode(5) root.right.left.right = newNode(6) root.right.left.right.left = newNode(18) root.right.left.right.right = newNode(7) leftView(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 7184, "s": 5299, "text": null }, { "code": "// C# program to print the// left view of Binary Treeusing System;using System.Collections.Generic; class GFG{ // A Binary Tree Nodepublic class node{ public int data; public node left, right;}; // A utility function to create a new// Binary Tree nodestatic node newNode(int item){ node temp = new node(); temp.data = item; temp.left = null; temp.right = null; return temp;}static Queue<node> q = new Queue<node>(); // Utility function to print the left view of// the binary treestatic void leftViewUtil( node root ){ if (root == null) return; // add root q.Enqueue(root); // Delimiter q.Enqueue(null); while (q.Count > 0) { node temp = q.Peek(); if (temp != null) { // Prints first node // of each level Console.Write(temp.data + \" \"); // add children of all nodes at // current level while (q.Peek() != null) { // If left child is present // add into queue if (temp.left != null) q.Enqueue(temp.left); // If right child is present // add into queue if (temp.right != null) q.Enqueue(temp.right); // remove the current node q.Dequeue(); temp = q.Peek(); } // add delimiter // for the next level q.Enqueue(null); } // remove the delimiter of // the previous level q.Dequeue(); }} // Function to print the leftView// of Binary Treestatic void leftView( node root){ // Queue to store all // the nodes of the tree q = new Queue<node>(); leftViewUtil(root);} // Driver Codepublic static void Main(String []args){ node root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root);}} // This code is contributed by 29AjayKumar", "e": 9361, "s": 7184, "text": null }, { "code": "<script> // JavaScript program to print the left view of Binary Tree // Binary Tree Node class node { constructor(item) { this.left = null; this.right = null; this.data = item; } } // A utility function to create a new // Binary Tree node function newNode(item) { let temp = new node(item); return temp; } let q = []; // Utility function to print the left view of // the binary tree function leftViewUtil(root) { if (root == null) return; // add root q.push(root); // Delimiter q.push(null); while (q.length > 0) { let temp = q[0]; if (temp != null) { // Prints first node // of each level document.write(temp.data + \" \"); // add children of all nodes at // current level while (q[0] != null) { // If left child is present // add into queue if (temp.left != null) q.push(temp.left); // If right child is present // add into queue if (temp.right != null) q.push(temp.right); // remove the current node q.shift(); temp = q[0]; } // add delimiter // for the next level q.push(null); } // remove the delimiter of // the previous level q.shift(); } } // Function to print the leftView // of Binary Tree function leftView(root) { // Queue to store all // the nodes of the tree q = []; leftViewUtil(root); } let root = newNode(10); root.left = newNode(12); root.right = newNode(3); root.left.right = newNode(4); root.right.left = newNode(5); root.right.left.right = newNode(6); root.right.left.right.left = newNode(18); root.right.left.right.right = newNode(7); leftView(root); </script>", "e": 11578, "s": 9361, "text": null }, { "code": null, "e": 11588, "s": 11578, "text": "Output: " }, { "code": null, "e": 11601, "s": 11588, "text": "10 12 4 6 18" }, { "code": null, "e": 11702, "s": 11601, "text": "Time Complexity: O(N) where N is the number of vertices in the binary tree.Auxiliary Space: O(N). " }, { "code": null, "e": 11717, "s": 11702, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 11728, "s": 11717, "text": "andrew1234" }, { "code": null, "e": 11740, "s": 11728, "text": "29AjayKumar" }, { "code": null, "e": 11753, "s": 11740, "text": "Akanksha_Rai" }, { "code": null, "e": 11762, "s": 11753, "text": "mukesh07" }, { "code": null, "e": 11778, "s": 11762, "text": "pankajsharmagfg" }, { "code": null, "e": 11790, "s": 11778, "text": "Binary Tree" }, { "code": null, "e": 11807, "s": 11790, "text": "tree-level-order" }, { "code": null, "e": 11823, "s": 11807, "text": "Data Structures" }, { "code": null, "e": 11829, "s": 11823, "text": "Queue" }, { "code": null, "e": 11834, "s": 11829, "text": "Tree" }, { "code": null, "e": 11850, "s": 11834, "text": "Data Structures" }, { "code": null, "e": 11856, "s": 11850, "text": "Queue" }, { "code": null, "e": 11861, "s": 11856, "text": "Tree" } ]
Subarray with XOR less than k
23 May, 2022 Given an array of n numbers and a number k. You have to write a program to find the number of subarrays with xor less than k.Examples: Input: arr[] = {8, 9, 10, 11, 12}, k=3Output: 4Explaination: Sub-arrays [1:3], [2:3], [2:5], [4:5] have xor values 2, 1, 0, 1 respectively. Input: arr[] = {12, 4, 6, 8, 21}, k=8Output: 4 Naive Approach: The naive algorithm is to simply calculate the xor value of each and every subarray and compare it with the given number k to find the answer. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to count number of// subarrays with XOR less than k#include <iostream>using namespace std; // function to count number of// subarrays with XOR less than kint xorLessK(int arr[], int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver program to test above functionint main(){ int n, k = 3; int arr[] = { 8, 9, 10, 11, 12 }; n = sizeof(arr) / sizeof(arr[0]); cout << xorLessK(arr, n, k); return 0;} // Java program to count number of// subarrays with XOR less than k import java.io.*; class GFG { // function to count number of// subarrays with XOR less than kstatic int xorLessK(int arr[], int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver program to test above function public static void main (String[] args) { int k = 3; int arr[] = new int[] { 8, 9, 10, 11, 12 }; int n = arr.length; System.out.println(xorLessK(arr, n, k)); }} # Python 3 program to count number of# subarrays with XOR less than k # function to count number of# subarrays with XOR less than kdef xorLessK(arr, n, k): count = 0 # check all subarrays for i in range(n): tempXor = 0 for j in range(i, n): tempXor ^= arr[j] if (tempXor < k): count += 1 return count # Driver Codeif __name__ == '__main__': k = 3 arr = [8, 9, 10, 11, 12] n = len(arr) print(xorLessK(arr, n, k)) # This code is contributed by# Sahil_shelangia // C# program to count number of// subarrays with XOR less than kusing System; class GFG { // function to count number of// subarrays with XOR less than kstatic int xorLessK(int []arr, int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver Codestatic public void Main (){ int k = 3; int []arr = new int[] {8, 9, 10, 11, 12 }; int n = arr.Length; Console.WriteLine(xorLessK(arr, n, k)); }} <?php// PHP program to count number of// subarrays with XOR less than k // function to count number of// subarrays with XOR less than kfunction xorLessK($arr, $n, $k){ $count = 0; // check all subarrays for ($i = 0; $i < $n; $i++) { $tempXor = 0; for ($j = $i; $j < $n; $j++) { $tempXor ^= $arr[$j]; if ($tempXor < $k) $count++; } } return $count;} // Driver Code $n; $k = 3; $arr = array(8, 9, 10, 11, 12); $n = count($arr); echo xorLessK($arr, $n, $k); // This code is contributed by anuj_67.?> <script> // Javascript program to count number of // subarrays with XOR less than k // function to count number of // subarrays with XOR less than k function xorLessK(arr, n, k) { let count = 0; // check all subarrays for (let i = 0; i < n; i++) { let tempXor = 0; for (let j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count; } let k = 3; let arr = [8, 9, 10, 11, 12]; let n = arr.length; document.write(xorLessK(arr, n, k)); </script> 3 Time Complexity: . Efficient Approach: An efficient approach will be to calculate all of the prefix xor values i.e. a[1:i] for all i. It can be verified that the xor of a subarray a[l:r] can be written as (a[1:l-1] xor a[1:r]), where a[i, j] is the xor of all the elements with index such that, i <= index <= j. Explanation: We will store a number as a binary number in trie. The left child will show that the next bit is 0 and the right child will show the next bit is 1. For example, the given picture below shows numbers 1001 and 1010 in trie. If xor[i, j] represents the xor of all elements in the subarray a[i, j], then at an index i what we have is, a trie which has xor[1:1], xor[1:2].....xor[1:i-1] already inserted. Now we somehow count how many of these (numbers in trie) are such that its xor with xor[1:i] is smaller than k. This will cover all the subarrays ending at the index i and having xor i.e. xor[j, i] <=k;Now the problem remains, how to count the numbers with xor smaller than k. So, for example, take the current bit of the ith index element is p, a current bit of number k be q and the current node in trie be node. Take the case when p=1, k=1. Then if we go to the right child the current xor would be 0 (as the right child means 1 and p=1, 1(xor)1=0).As k=1, all the numbers that are to the right child of this node would give xor value smaller than k. So, we would count the numbers that are right to this node. If we go to the left child, the current xor would be 1 (as the left child means 0 and p=1, 0(xor)1=1). So, if we go to the left child we can still find number with xor smaller than k, therefore we move on to the left child.So, to count the numbers that are below a given node, we modify the trie and each node will also store the number of leafs in that subtree and this would be modified after each insertion.Other three cases for different values of p and k can be solved in the same way to the count the number of numbers with xor less than k. Below is the C++ implementation of the above idea: CPP #include <iostream>using namespace std;class trienode {public: int left_count, right_count; trienode* left; trienode* right; trienode() { left_count = 0; right_count = 0; // Left denotes 0 left = NULL; // Right denotes 1 right = NULL; }};void insert(trienode* root, int element){ for (int i = 31; i >= 0; i--) { int x = (element >> i) & 1; // If the current bit is 1 if (x) { root->right_count++; if (root->right == NULL) root->right = new trienode(); root = root->right; } else { root->left_count++; if (root->left == NULL) root->left = new trienode(); root = root->left; } }}int query(trienode* root, int element, int k){ if (root == NULL) return 0; int res = 0; for (int i = 31; i >= 0; i--) { bool current_bit_of_k = (k >> i) & 1; bool current_bit_of_element = (element >> i) & 1; // If the current bit of k is 1 if (current_bit_of_k) { // If current bit of element is 1 if (current_bit_of_element) { res += root->right_count; if (root->left == NULL) return res; root = root->left; } // If current bit of element is 0 else { res += root->left_count; if (root->right == NULL) return res; root = root->right; } } // If the current bit of k is zero else { // If current bit of element is 1 if (current_bit_of_element) { if (root->right == NULL) return res; root = root->right; } // If current bit of element is 0 else { if (root->left == NULL) return res; root = root->left; } } } return res;} // Driver codeint main(){ int n = 5, k = 3; int arr[] = { 8, 9, 10, 11, 12 }; // Below three variables are used for storing // current XOR int temp, temp1, temp2 = 0; trienode* root = new trienode(); insert(root, 0); long long total = 0; for (int i = 0; i < n; i++) { temp = arr[i]; temp1 = temp2 ^ temp; total += query(root, temp1, k); insert(root, temp1); temp2 = temp1; } cout << total << endl; return 0;} 3 Time complexity: O(n*log(max)), where max is the maximum element in the array.Related Articles: pair minimum xor value maximum subarray xor This article is contributed by Amritya Vagmi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. vt_m jit_t sahilshelangia rameshtravel07 kuldeepy10459 Bitwise-XOR Trie Arrays Arrays Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Find Second largest element in an array Introduction to Data Structures Subset Sum Problem | DP-25
[ { "code": null, "e": 54, "s": 26, "text": "\n23 May, 2022" }, { "code": null, "e": 190, "s": 54, "text": "Given an array of n numbers and a number k. You have to write a program to find the number of subarrays with xor less than k.Examples: " }, { "code": null, "e": 332, "s": 190, "text": "Input: arr[] = {8, 9, 10, 11, 12}, k=3Output: 4Explaination: Sub-arrays [1:3], [2:3], [2:5], [4:5] have xor values 2, 1, 0, 1 respectively." }, { "code": null, "e": 380, "s": 332, "text": "Input: arr[] = {12, 4, 6, 8, 21}, k=8Output: 4" }, { "code": null, "e": 591, "s": 380, "text": "Naive Approach: The naive algorithm is to simply calculate the xor value of each and every subarray and compare it with the given number k to find the answer. Below is the implementation of the above approach: " }, { "code": null, "e": 595, "s": 591, "text": "C++" }, { "code": null, "e": 600, "s": 595, "text": "Java" }, { "code": null, "e": 608, "s": 600, "text": "Python3" }, { "code": null, "e": 611, "s": 608, "text": "C#" }, { "code": null, "e": 615, "s": 611, "text": "PHP" }, { "code": null, "e": 626, "s": 615, "text": "Javascript" }, { "code": "// C++ program to count number of// subarrays with XOR less than k#include <iostream>using namespace std; // function to count number of// subarrays with XOR less than kint xorLessK(int arr[], int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver program to test above functionint main(){ int n, k = 3; int arr[] = { 8, 9, 10, 11, 12 }; n = sizeof(arr) / sizeof(arr[0]); cout << xorLessK(arr, n, k); return 0;}", "e": 1280, "s": 626, "text": null }, { "code": "// Java program to count number of// subarrays with XOR less than k import java.io.*; class GFG { // function to count number of// subarrays with XOR less than kstatic int xorLessK(int arr[], int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver program to test above function public static void main (String[] args) { int k = 3; int arr[] = new int[] { 8, 9, 10, 11, 12 }; int n = arr.length; System.out.println(xorLessK(arr, n, k)); }}", "e": 1985, "s": 1280, "text": null }, { "code": "# Python 3 program to count number of# subarrays with XOR less than k # function to count number of# subarrays with XOR less than kdef xorLessK(arr, n, k): count = 0 # check all subarrays for i in range(n): tempXor = 0 for j in range(i, n): tempXor ^= arr[j] if (tempXor < k): count += 1 return count # Driver Codeif __name__ == '__main__': k = 3 arr = [8, 9, 10, 11, 12] n = len(arr) print(xorLessK(arr, n, k)) # This code is contributed by# Sahil_shelangia", "e": 2527, "s": 1985, "text": null }, { "code": "// C# program to count number of// subarrays with XOR less than kusing System; class GFG { // function to count number of// subarrays with XOR less than kstatic int xorLessK(int []arr, int n, int k){ int count = 0; // check all subarrays for (int i = 0; i < n; i++) { int tempXor = 0; for (int j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count;} // Driver Codestatic public void Main (){ int k = 3; int []arr = new int[] {8, 9, 10, 11, 12 }; int n = arr.Length; Console.WriteLine(xorLessK(arr, n, k)); }}", "e": 3226, "s": 2527, "text": null }, { "code": "<?php// PHP program to count number of// subarrays with XOR less than k // function to count number of// subarrays with XOR less than kfunction xorLessK($arr, $n, $k){ $count = 0; // check all subarrays for ($i = 0; $i < $n; $i++) { $tempXor = 0; for ($j = $i; $j < $n; $j++) { $tempXor ^= $arr[$j]; if ($tempXor < $k) $count++; } } return $count;} // Driver Code $n; $k = 3; $arr = array(8, 9, 10, 11, 12); $n = count($arr); echo xorLessK($arr, $n, $k); // This code is contributed by anuj_67.?>", "e": 3826, "s": 3226, "text": null }, { "code": "<script> // Javascript program to count number of // subarrays with XOR less than k // function to count number of // subarrays with XOR less than k function xorLessK(arr, n, k) { let count = 0; // check all subarrays for (let i = 0; i < n; i++) { let tempXor = 0; for (let j = i; j < n; j++) { tempXor ^= arr[j]; if (tempXor < k) count++; } } return count; } let k = 3; let arr = [8, 9, 10, 11, 12]; let n = arr.length; document.write(xorLessK(arr, n, k)); </script>", "e": 4463, "s": 3826, "text": null }, { "code": null, "e": 4465, "s": 4463, "text": "3" }, { "code": null, "e": 5014, "s": 4465, "text": "Time Complexity: . Efficient Approach: An efficient approach will be to calculate all of the prefix xor values i.e. a[1:i] for all i. It can be verified that the xor of a subarray a[l:r] can be written as (a[1:l-1] xor a[1:r]), where a[i, j] is the xor of all the elements with index such that, i <= index <= j. Explanation: We will store a number as a binary number in trie. The left child will show that the next bit is 0 and the right child will show the next bit is 1. For example, the given picture below shows numbers 1001 and 1010 in trie. " }, { "code": null, "e": 6453, "s": 5014, "text": "If xor[i, j] represents the xor of all elements in the subarray a[i, j], then at an index i what we have is, a trie which has xor[1:1], xor[1:2].....xor[1:i-1] already inserted. Now we somehow count how many of these (numbers in trie) are such that its xor with xor[1:i] is smaller than k. This will cover all the subarrays ending at the index i and having xor i.e. xor[j, i] <=k;Now the problem remains, how to count the numbers with xor smaller than k. So, for example, take the current bit of the ith index element is p, a current bit of number k be q and the current node in trie be node. Take the case when p=1, k=1. Then if we go to the right child the current xor would be 0 (as the right child means 1 and p=1, 1(xor)1=0).As k=1, all the numbers that are to the right child of this node would give xor value smaller than k. So, we would count the numbers that are right to this node. If we go to the left child, the current xor would be 1 (as the left child means 0 and p=1, 0(xor)1=1). So, if we go to the left child we can still find number with xor smaller than k, therefore we move on to the left child.So, to count the numbers that are below a given node, we modify the trie and each node will also store the number of leafs in that subtree and this would be modified after each insertion.Other three cases for different values of p and k can be solved in the same way to the count the number of numbers with xor less than k." }, { "code": null, "e": 6505, "s": 6453, "text": "Below is the C++ implementation of the above idea: " }, { "code": null, "e": 6509, "s": 6505, "text": "CPP" }, { "code": "#include <iostream>using namespace std;class trienode {public: int left_count, right_count; trienode* left; trienode* right; trienode() { left_count = 0; right_count = 0; // Left denotes 0 left = NULL; // Right denotes 1 right = NULL; }};void insert(trienode* root, int element){ for (int i = 31; i >= 0; i--) { int x = (element >> i) & 1; // If the current bit is 1 if (x) { root->right_count++; if (root->right == NULL) root->right = new trienode(); root = root->right; } else { root->left_count++; if (root->left == NULL) root->left = new trienode(); root = root->left; } }}int query(trienode* root, int element, int k){ if (root == NULL) return 0; int res = 0; for (int i = 31; i >= 0; i--) { bool current_bit_of_k = (k >> i) & 1; bool current_bit_of_element = (element >> i) & 1; // If the current bit of k is 1 if (current_bit_of_k) { // If current bit of element is 1 if (current_bit_of_element) { res += root->right_count; if (root->left == NULL) return res; root = root->left; } // If current bit of element is 0 else { res += root->left_count; if (root->right == NULL) return res; root = root->right; } } // If the current bit of k is zero else { // If current bit of element is 1 if (current_bit_of_element) { if (root->right == NULL) return res; root = root->right; } // If current bit of element is 0 else { if (root->left == NULL) return res; root = root->left; } } } return res;} // Driver codeint main(){ int n = 5, k = 3; int arr[] = { 8, 9, 10, 11, 12 }; // Below three variables are used for storing // current XOR int temp, temp1, temp2 = 0; trienode* root = new trienode(); insert(root, 0); long long total = 0; for (int i = 0; i < n; i++) { temp = arr[i]; temp1 = temp2 ^ temp; total += query(root, temp1, k); insert(root, temp1); temp2 = temp1; } cout << total << endl; return 0;}", "e": 9035, "s": 6509, "text": null }, { "code": null, "e": 9038, "s": 9035, "text": "3\n" }, { "code": null, "e": 9135, "s": 9038, "text": "Time complexity: O(n*log(max)), where max is the maximum element in the array.Related Articles: " }, { "code": null, "e": 9158, "s": 9135, "text": "pair minimum xor value" }, { "code": null, "e": 9179, "s": 9158, "text": "maximum subarray xor" }, { "code": null, "e": 9609, "s": 9179, "text": "This article is contributed by Amritya Vagmi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 9614, "s": 9609, "text": "vt_m" }, { "code": null, "e": 9620, "s": 9614, "text": "jit_t" }, { "code": null, "e": 9635, "s": 9620, "text": "sahilshelangia" }, { "code": null, "e": 9650, "s": 9635, "text": "rameshtravel07" }, { "code": null, "e": 9664, "s": 9650, "text": "kuldeepy10459" }, { "code": null, "e": 9676, "s": 9664, "text": "Bitwise-XOR" }, { "code": null, "e": 9681, "s": 9676, "text": "Trie" }, { "code": null, "e": 9688, "s": 9681, "text": "Arrays" }, { "code": null, "e": 9695, "s": 9688, "text": "Arrays" }, { "code": null, "e": 9700, "s": 9695, "text": "Trie" }, { "code": null, "e": 9798, "s": 9700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9866, "s": 9798, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9910, "s": 9866, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9942, "s": 9910, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9990, "s": 9942, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 10004, "s": 9990, "text": "Linear Search" }, { "code": null, "e": 10027, "s": 10004, "text": "Introduction to Arrays" }, { "code": null, "e": 10083, "s": 10027, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 10123, "s": 10083, "text": "Find Second largest element in an array" }, { "code": null, "e": 10155, "s": 10123, "text": "Introduction to Data Structures" } ]
Read integers from console in Java
To read integers from console, use Scanner class. Scanner myInput = new Scanner( System.in ); Allow a use to add an integer using the nextInt() method. System.out.print( "Enter first integer: " ); int a = myInput.nextInt(); In the same way, take another input in a new variable. System.out.print( "Enter second integer: " ); Int b = myInput.nextInt(); Let us see the complete example. import java.util.Scanner; public class Demo { public static void main( String args[] ) { Scanner myInput = new Scanner( System.in ); int a; int b; int sum; System.out.print( "Enter first integer: " ); a = myInput.nextInt(); System.out.print( "Enter second integer: " ); b = myInput.nextInt(); sum = a + b; System.out.printf( "Sum = %d\n", sum ); } } We added the following two integer values from the console. 5 10 After adding the values and running the program, the following output can be seen. Enter first integer: 5 Enter second integer: 10 Sum = 15
[ { "code": null, "e": 1112, "s": 1062, "text": "To read integers from console, use Scanner class." }, { "code": null, "e": 1156, "s": 1112, "text": "Scanner myInput = new Scanner( System.in );" }, { "code": null, "e": 1214, "s": 1156, "text": "Allow a use to add an integer using the nextInt() method." }, { "code": null, "e": 1286, "s": 1214, "text": "System.out.print( \"Enter first integer: \" );\nint a = myInput.nextInt();" }, { "code": null, "e": 1341, "s": 1286, "text": "In the same way, take another input in a new variable." }, { "code": null, "e": 1414, "s": 1341, "text": "System.out.print( \"Enter second integer: \" );\nInt b = myInput.nextInt();" }, { "code": null, "e": 1447, "s": 1414, "text": "Let us see the complete example." }, { "code": null, "e": 1863, "s": 1447, "text": "import java.util.Scanner;\npublic class Demo {\n public static void main( String args[] ) {\n Scanner myInput = new Scanner( System.in );\n int a;\n int b;\n int sum;\n System.out.print( \"Enter first integer: \" );\n a = myInput.nextInt();\n System.out.print( \"Enter second integer: \" );\n b = myInput.nextInt();\n sum = a + b;\n System.out.printf( \"Sum = %d\\n\", sum );\n }\n}" }, { "code": null, "e": 1923, "s": 1863, "text": "We added the following two integer values from the console." }, { "code": null, "e": 1928, "s": 1923, "text": "5\n10" }, { "code": null, "e": 2011, "s": 1928, "text": "After adding the values and running the program, the following output can be seen." }, { "code": null, "e": 2068, "s": 2011, "text": "Enter first integer: 5\nEnter second integer: 10\nSum = 15" } ]
Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda | by J Li | Towards Data Science
Serverless computing is a cloud-computing execution model in which the cloud provider runs the server, and dynamically manages the allocation of machine resources. Pricing is based on the actual amount of resources consumed by an application, rather than on pre-purchased units of capacity. — Wikipedia (this post is also available in my blog) This is the second post of my full stack development tutorial series. Previous post — Full Stack Development Tutorial: Visualize Trading Data on Angular SPA Serverless computing shines in a way that it executes when it needs to. The price is totally based on the usage. There is no need for developers to maintain a server, patch security vulnerability, upgrade software etc. Amazon’s AWS Lambda is an event-driven serverless computing platform. It has great runtime support including Node.js, Python, Java, Go, Ruby and C#. As an event-driven platform, Lambda is ideal for a scenario like handling change of events such as “file is being uploaded to S3”, “Database is updated”, “Sensor data is received in IoT” etc. In this tutorial, we will leverage serverless framework to create a serverless REST API for our stock app in this tutorial. Serverless framework is an open-source framework that help develop and deploy serverless functions on multiple cloud environments including AWS Lambda. Design our endpoint Following the REST practice, lets define our endpoint /price?ticker=<ticker_name>. And response will look like the following to feed the chart in UI. [ { "name": "Ticker", "series": [ { "name": "2018-11-05", "value": 1 }, { "name": "2018-11-07", "value": 1.0784432590958841 } ] }] AWS First you need an AWS account. Sign up if you don’t have an AWS account yet. Then create an IAM user. At the end you will get the credentials of IAM user. You will need it to set up the serverless cli, so that you can deploy and run your serverless service on AWS. serverless config credentials --provider aws --key <ACCESS KEY ID> --secret <SECRET KEY> Serverless installation Follow instructions to install docker for deployment. Create the serverless.yml file for the service. It needs plugin wsgi as web server to run the REST service. The built in flask development server isn’t performant enough for production. Note that the slim flag in pythonRequirements help to limit the size of the source code. There is size limit of source code for Lambda. The slim flag helps reduce the size. For that reason, it’s also critical to exclude all unnecessary files like the files in venv. The zip flag help zipping the source code before uploading to S3 for deployment. The rest of config is self-explanatory. The deployment process is as follow in summary. Serverless framework builds and package the file as zip file. It then uses the IAM credentials to upload source code to S3 bucket (this bucket is created automatically by the serverless cli). Then it leverages CloudFormation to deploy the service the Lambda. All happens in once single command. Implementation The actual implementation is straightforward. When a request of historical data comes, it grabs data (csv file) from S3 and read it into a panda dataframe (S3 is an AWS storage service). Then we will iterate the dataframe to construct a response we defined above. As we define the Lambda entry point app.app in the serverless.yml. We will write our service in app.py. Before running our application, download historical stock data from Yahoo finance and put it in a directory call data. Then run start the application locally. (venv) ➜ stock-backend python app.py* Serving Flask app "app" (lazy loading)* Environment: productionWARNING: This is a development server. Do not use it in a production deployment.Use a production WSGI server instead.* Debug mode: on* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 248-351-201 From now, you can verify if your REST endpoint works. Say if you have a SPY.csv file in data directory. Open browser and enter http://127.0.0.1:5000/price?ticker=SPY in the URL bar. The result of JSON response will be displayed in your browser. [ { "name": "SPY", "series": [ { "name": "2014-10-20", "value": 190.300003 }, { "name": "2014-10-21", "value": 194.070007 }, { "name": "2014-10-22", "value": 192.690002 }, { "name": "2014-10-23", "value": 194.929993 }...] Or you can use curl command to do the same test curl http://127.0.0.1:5000/price?ticker=SPY The above implementation relies on local storage to keep store the historical stock data. We can leverage AWS S3 to host the data. Go to the AWS Console and choose S3. Create a S3 bucket and give it a name. Make sure the name is globally unique. Now, we can upload our csv file to the bucket. Next, for Lambda to be able to access to this S3 bucket, we need to assign a S3 read only policy to the role of Lambda. Yes, this can be done via the serverless.yml config file without interacting with the AWS console. The updated provider in serverless.yml will look like follow provider: name: aws runtime: python3.7 stage: prod region: us-west-2 iamRoleStatements: - Effect: 'Allow' Action: - 's3:ListBucket' Resource: { 'Fn::Join': ['', ['arn:aws:s3:::<YOUR_S3_BUCKET_NAME>']] } - Effect: 'Allow' Action: - 's3:getObject' Resource: Fn::Join: - '' - - 'arn:aws:s3:::<YOUR_S3_BUCKET_NAME>' - '/*' In the app.py, make sure we load data from S3 instead of reading from local disk. # path = '{}/data/{}.csv'.format(os.path.dirname(os.path.realpath(__file__)), ticker)# df = pd.read_csv(path, index_col='Date', parse_dates=True, usecols=['Date', 'Close'],# na_values=['nan'])df = pd.read_csv('s3://<YOUR_S3_BUCKET_NAME>/{}.csv'.format(ticker), index_col='Date', parse_dates=True, usecols=['Date', 'Close'], na_values=['nan']) Now it comes to the exciting part. Let’s deploy our service to Lambda. (venv) ➜ stock-backend sls deployServerless: Adding Python requirements helper.......Service Informationservice: stock-backendstage: prodregion: us-west-2stack: stock-backend-prodresources: 11api keys:Noneendpoints:ANY - https://9rn0mg6p6b.execute-api.us-west-2.amazonaws.com/prodANY - https://9rn0mg6p6b.execute-api.us-west-2.amazonaws.com/prod/{proxy+}functions:app: stock-backend-prod-applayers:NoneServerless: Run the "serverless" command to setup monitoring, troubleshooting and testing. At the end, you will get the endpoint of your new API. This is the URL from API gateway. You can test it on your browser. Note that your URL will be different. Let’s use browser or curl to test. The following is the result. Now we have our backend service running on AWS Lambda. Deployment is easy. If you’re interested in what AWS created, you can login your AWS console and find out. It creates S3 bucket and Cloudformation resources for deployment. A Lambda function is created with new IAM role for Lambda Execution. Also the role has user-defined role to access to the stock data S3 bucket. I will connect the UI from previous post with the backend running on lambda, then deploy the UI to AWS. Stay tuned! Recommnded reads: Learn the A to Z of Amazon Web Services (AWS) AWS Lambda in Action: Event-driven serverless applications 1st Edition Amazon Web Services in Action 2nd Edition Previous posts: My posts about Finance and Tech My posts about FAANG interview From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA Full Stack Development Tutorial: Visualize Trading Data on Angular SPA Reinforcement Learning: Introduction to Q Learning
[ { "code": null, "e": 475, "s": 172, "text": "Serverless computing is a cloud-computing execution model in which the cloud provider runs the server, and dynamically manages the allocation of machine resources. Pricing is based on the actual amount of resources consumed by an application, rather than on pre-purchased units of capacity. — Wikipedia" }, { "code": null, "e": 516, "s": 475, "text": "(this post is also available in my blog)" }, { "code": null, "e": 673, "s": 516, "text": "This is the second post of my full stack development tutorial series. Previous post — Full Stack Development Tutorial: Visualize Trading Data on Angular SPA" }, { "code": null, "e": 892, "s": 673, "text": "Serverless computing shines in a way that it executes when it needs to. The price is totally based on the usage. There is no need for developers to maintain a server, patch security vulnerability, upgrade software etc." }, { "code": null, "e": 1233, "s": 892, "text": "Amazon’s AWS Lambda is an event-driven serverless computing platform. It has great runtime support including Node.js, Python, Java, Go, Ruby and C#. As an event-driven platform, Lambda is ideal for a scenario like handling change of events such as “file is being uploaded to S3”, “Database is updated”, “Sensor data is received in IoT” etc." }, { "code": null, "e": 1509, "s": 1233, "text": "In this tutorial, we will leverage serverless framework to create a serverless REST API for our stock app in this tutorial. Serverless framework is an open-source framework that help develop and deploy serverless functions on multiple cloud environments including AWS Lambda." }, { "code": null, "e": 1529, "s": 1509, "text": "Design our endpoint" }, { "code": null, "e": 1679, "s": 1529, "text": "Following the REST practice, lets define our endpoint /price?ticker=<ticker_name>. And response will look like the following to feed the chart in UI." }, { "code": null, "e": 1869, "s": 1679, "text": "[ { \"name\": \"Ticker\", \"series\": [ { \"name\": \"2018-11-05\", \"value\": 1 }, { \"name\": \"2018-11-07\", \"value\": 1.0784432590958841 } ] }]" }, { "code": null, "e": 1873, "s": 1869, "text": "AWS" }, { "code": null, "e": 2138, "s": 1873, "text": "First you need an AWS account. Sign up if you don’t have an AWS account yet. Then create an IAM user. At the end you will get the credentials of IAM user. You will need it to set up the serverless cli, so that you can deploy and run your serverless service on AWS." }, { "code": null, "e": 2227, "s": 2138, "text": "serverless config credentials --provider aws --key <ACCESS KEY ID> --secret <SECRET KEY>" }, { "code": null, "e": 2251, "s": 2227, "text": "Serverless installation" }, { "code": null, "e": 2305, "s": 2251, "text": "Follow instructions to install docker for deployment." }, { "code": null, "e": 2878, "s": 2305, "text": "Create the serverless.yml file for the service. It needs plugin wsgi as web server to run the REST service. The built in flask development server isn’t performant enough for production. Note that the slim flag in pythonRequirements help to limit the size of the source code. There is size limit of source code for Lambda. The slim flag helps reduce the size. For that reason, it’s also critical to exclude all unnecessary files like the files in venv. The zip flag help zipping the source code before uploading to S3 for deployment. The rest of config is self-explanatory." }, { "code": null, "e": 3221, "s": 2878, "text": "The deployment process is as follow in summary. Serverless framework builds and package the file as zip file. It then uses the IAM credentials to upload source code to S3 bucket (this bucket is created automatically by the serverless cli). Then it leverages CloudFormation to deploy the service the Lambda. All happens in once single command." }, { "code": null, "e": 3236, "s": 3221, "text": "Implementation" }, { "code": null, "e": 3604, "s": 3236, "text": "The actual implementation is straightforward. When a request of historical data comes, it grabs data (csv file) from S3 and read it into a panda dataframe (S3 is an AWS storage service). Then we will iterate the dataframe to construct a response we defined above. As we define the Lambda entry point app.app in the serverless.yml. We will write our service in app.py." }, { "code": null, "e": 3723, "s": 3604, "text": "Before running our application, download historical stock data from Yahoo finance and put it in a directory call data." }, { "code": null, "e": 3763, "s": 3723, "text": "Then run start the application locally." }, { "code": null, "e": 4127, "s": 3763, "text": "(venv) ➜ stock-backend python app.py* Serving Flask app \"app\" (lazy loading)* Environment: productionWARNING: This is a development server. Do not use it in a production deployment.Use a production WSGI server instead.* Debug mode: on* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 248-351-201" }, { "code": null, "e": 4372, "s": 4127, "text": "From now, you can verify if your REST endpoint works. Say if you have a SPY.csv file in data directory. Open browser and enter http://127.0.0.1:5000/price?ticker=SPY in the URL bar. The result of JSON response will be displayed in your browser." }, { "code": null, "e": 4705, "s": 4372, "text": "[ { \"name\": \"SPY\", \"series\": [ { \"name\": \"2014-10-20\", \"value\": 190.300003 }, { \"name\": \"2014-10-21\", \"value\": 194.070007 }, { \"name\": \"2014-10-22\", \"value\": 192.690002 }, { \"name\": \"2014-10-23\", \"value\": 194.929993 }...]" }, { "code": null, "e": 4753, "s": 4705, "text": "Or you can use curl command to do the same test" }, { "code": null, "e": 4797, "s": 4753, "text": "curl http://127.0.0.1:5000/price?ticker=SPY" }, { "code": null, "e": 5043, "s": 4797, "text": "The above implementation relies on local storage to keep store the historical stock data. We can leverage AWS S3 to host the data. Go to the AWS Console and choose S3. Create a S3 bucket and give it a name. Make sure the name is globally unique." }, { "code": null, "e": 5090, "s": 5043, "text": "Now, we can upload our csv file to the bucket." }, { "code": null, "e": 5370, "s": 5090, "text": "Next, for Lambda to be able to access to this S3 bucket, we need to assign a S3 read only policy to the role of Lambda. Yes, this can be done via the serverless.yml config file without interacting with the AWS console. The updated provider in serverless.yml will look like follow" }, { "code": null, "e": 5770, "s": 5370, "text": "provider: name: aws runtime: python3.7 stage: prod region: us-west-2 iamRoleStatements: - Effect: 'Allow' Action: - 's3:ListBucket' Resource: { 'Fn::Join': ['', ['arn:aws:s3:::<YOUR_S3_BUCKET_NAME>']] } - Effect: 'Allow' Action: - 's3:getObject' Resource: Fn::Join: - '' - - 'arn:aws:s3:::<YOUR_S3_BUCKET_NAME>' - '/*'" }, { "code": null, "e": 5852, "s": 5770, "text": "In the app.py, make sure we load data from S3 instead of reading from local disk." }, { "code": null, "e": 6236, "s": 5852, "text": "# path = '{}/data/{}.csv'.format(os.path.dirname(os.path.realpath(__file__)), ticker)# df = pd.read_csv(path, index_col='Date', parse_dates=True, usecols=['Date', 'Close'],# na_values=['nan'])df = pd.read_csv('s3://<YOUR_S3_BUCKET_NAME>/{}.csv'.format(ticker), index_col='Date', parse_dates=True, usecols=['Date', 'Close'], na_values=['nan'])" }, { "code": null, "e": 6307, "s": 6236, "text": "Now it comes to the exciting part. Let’s deploy our service to Lambda." }, { "code": null, "e": 6801, "s": 6307, "text": "(venv) ➜ stock-backend sls deployServerless: Adding Python requirements helper.......Service Informationservice: stock-backendstage: prodregion: us-west-2stack: stock-backend-prodresources: 11api keys:Noneendpoints:ANY - https://9rn0mg6p6b.execute-api.us-west-2.amazonaws.com/prodANY - https://9rn0mg6p6b.execute-api.us-west-2.amazonaws.com/prod/{proxy+}functions:app: stock-backend-prod-applayers:NoneServerless: Run the \"serverless\" command to setup monitoring, troubleshooting and testing." }, { "code": null, "e": 7100, "s": 6801, "text": "At the end, you will get the endpoint of your new API. This is the URL from API gateway. You can test it on your browser. Note that your URL will be different. Let’s use browser or curl to test. The following is the result. Now we have our backend service running on AWS Lambda. Deployment is easy." }, { "code": null, "e": 7397, "s": 7100, "text": "If you’re interested in what AWS created, you can login your AWS console and find out. It creates S3 bucket and Cloudformation resources for deployment. A Lambda function is created with new IAM role for Lambda Execution. Also the role has user-defined role to access to the stock data S3 bucket." }, { "code": null, "e": 7513, "s": 7397, "text": "I will connect the UI from previous post with the backend running on lambda, then deploy the UI to AWS. Stay tuned!" }, { "code": null, "e": 7531, "s": 7513, "text": "Recommnded reads:" }, { "code": null, "e": 7577, "s": 7531, "text": "Learn the A to Z of Amazon Web Services (AWS)" }, { "code": null, "e": 7648, "s": 7577, "text": "AWS Lambda in Action: Event-driven serverless applications 1st Edition" }, { "code": null, "e": 7690, "s": 7648, "text": "Amazon Web Services in Action 2nd Edition" }, { "code": null, "e": 7706, "s": 7690, "text": "Previous posts:" }, { "code": null, "e": 7738, "s": 7706, "text": "My posts about Finance and Tech" }, { "code": null, "e": 7769, "s": 7738, "text": "My posts about FAANG interview" }, { "code": null, "e": 7858, "s": 7769, "text": "From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning" }, { "code": null, "e": 7948, "s": 7858, "text": "Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA" }, { "code": null, "e": 8019, "s": 7948, "text": "Full Stack Development Tutorial: Visualize Trading Data on Angular SPA" } ]
Try-Catch-Finally in C#
C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. C# exception handling is performed using the following keywords − try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. The following is an example showing how to handle exceptions in C# − using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } Above, we have set the values in a try, and then caught exceptions in the catch. Finally is also set to show the result − try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); }
[ { "code": null, "e": 1198, "s": 1062, "text": "C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero." }, { "code": null, "e": 1264, "s": 1198, "text": "C# exception handling is performed using the following keywords −" }, { "code": null, "e": 1399, "s": 1264, "text": "try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks." }, { "code": null, "e": 1534, "s": 1399, "text": "try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks." }, { "code": null, "e": 1721, "s": 1534, "text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception." }, { "code": null, "e": 1908, "s": 1721, "text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception." }, { "code": null, "e": 2118, "s": 1908, "text": "finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not." }, { "code": null, "e": 2328, "s": 2118, "text": "finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not." }, { "code": null, "e": 2397, "s": 2328, "text": "The following is an example showing how to handle exceptions in C# −" }, { "code": null, "e": 2991, "s": 2397, "text": "using System;\n\nnamespace ErrorHandlingApplication {\n class DivNumbers {\n int result;\n\n DivNumbers() {\n result = 0;\n }\n\n public void division(int num1, int num2) {\n try {\n result = num1 / num2;\n } catch (DivideByZeroException e) {\n Console.WriteLine(\"Exception caught: {0}\", e);\n } finally {\n Console.WriteLine(\"Result: {0}\", result);\n }\n }\n\n static void Main(string[] args) {\n DivNumbers d = new DivNumbers();\n d.division(25, 0);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3113, "s": 2991, "text": "Above, we have set the values in a try, and then caught exceptions in the catch. Finally is also set to show the result −" }, { "code": null, "e": 3289, "s": 3113, "text": "try {\n result = num1 / num2;\n} catch (DivideByZeroException e) {\n Console.WriteLine(\"Exception caught: {0}\", e);\n} finally {\n Console.WriteLine(\"Result: {0}\", result);\n}" } ]
Count frequencies of all elements in array in Python using collections module
As python allows duplicate elements in a list we can have one element present multiple Times. The frequency of elements in a list indicates how many times an element occurs in a list. In this article we use the Counter function of the collections module to find out the frequency of each item in a list. Syntax: Counter(list) Where list is an iterable in python The below code uses the Counter() to keep track of frequency and items() to iterate over each item in the result of counter function for printing in a formatted manner. from collections import Counter list = ['Mon', 'Tue', 'Wed', 'Mon','Mon','Tue'] # Finding count of each element list_freq= (Counter(list)) #Printing result of counter print(list_freq) # Printing it using loop for key, value in list_freq.items(): print(key, " has count ", value) Running the above code gives us the following result − Counter({'Mon': 3, 'Tue': 2, 'Wed': 1}) Mon has count 3 Tue has count 2 Wed has count 1
[ { "code": null, "e": 1366, "s": 1062, "text": "As python allows duplicate elements in a list we can have one element present multiple Times. The frequency of elements in a list indicates how many times an element occurs in a list. In this article we use the Counter function of the collections module to find out the frequency of each item in a list." }, { "code": null, "e": 1424, "s": 1366, "text": "Syntax: Counter(list)\nWhere list is an iterable in python" }, { "code": null, "e": 1593, "s": 1424, "text": "The below code uses the Counter() to keep track of frequency and items() to iterate over each item in the result of counter function for printing in a formatted manner." }, { "code": null, "e": 1878, "s": 1593, "text": "from collections import Counter\nlist = ['Mon', 'Tue', 'Wed', 'Mon','Mon','Tue']\n\n# Finding count of each element\nlist_freq= (Counter(list))\n\n#Printing result of counter\nprint(list_freq)\n\n# Printing it using loop\nfor key, value in list_freq.items():\n print(key, \" has count \", value)" }, { "code": null, "e": 1933, "s": 1878, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2021, "s": 1933, "text": "Counter({'Mon': 3, 'Tue': 2, 'Wed': 1})\nMon has count 3\nTue has count 2\nWed has count 1" } ]
Important instructions used in dockerfile
We all know the importance of dockerfile in creating an efficient and flexible Docker Image. A dockerfile contains a set of instructions that are executed step by step when you use the docker build command to build the docker image. It contains certain instructions and commands that decides the structure of your image, the amount of time taken to build the image, contains instructions related to docker build context, contains information related to the packages and libraries to be installed in the container and many more. Hence, it becomes very important to create an efficient, reusable, clean dockerfile as it contains the blueprint of the image that you will build. In this article, I have created a curated list of all the important commands and instructions that are extensively used in a dockerfile. In a separate article, I have also enlisted best practices to create a dockerfile. https://www.tutorialspoint.com/best-practices-for-writing-a-dockerfile Without any further ado, let’s discuss some of the most important dockerfile commands that you should thoroughly be aware of in order to efficiently create a dockerfile. You must have noticed that almost all the dockerfile starts with the FROM command. The FROM command is of the form − FROM <image name>:<tag name> A FROM command allows you to create a base image such as an operating system, a programming language, etc. All the instructions executed after this command take place on this base image. It contains an image name and an optional tag name. If you already have the base image pulled previously in your local machine, it doesn’t pull a new one. There are several pre published docker base images available in the docker registry. You can also push your own customized base image inside the docker registry. Examples of FROM instruction along with different base images are − FROM ubuntu FROM centos FROM python:3 A RUN instruction is used to run specified commands. You can use several RUN instructions to run different commands. But it is an efficient approach to combine all the RUN instructions into a single one. Each RUN command creates a new cache layer or an intermediate image layer and hence chaining all of them into a single line, becomes efficient. However, chaining multiple RUN instructions could lead to cache bursts as well. Some example of RUN commands are − RUN apt−get −y install vim RUN apt−get −y update You can chain multiple RUN instructions in the following way − RUN apt−get −y update \ && apt−get −y install firefox \ && apt−get −y install vim If you want to run a docker container by specifying a default command that gets executed for all the containers of that image by default, you can use a CMD command. In case you specify a command during the docker run command, it overrides the default one. Specifying more than one CMD instructions, will allow only the last one to get executed. Example of a CMD command − CMD echo "Welcome to TutorialsPoint" If you specify the above line in the dockerfile and run the container using the following command without specifying any arguments, the output will be “Welcome to TutorialsPoint” sudo docker run −it <image_name> Output − “Welcome to TutorialsPoint” In case you try to specify any other arguments such as /bin/bash, etc, the default CMD command will be overridden. The difference between ENTRYPOINT and CMD is that, if you try to specify default arguments in the docker run command, it will not ignore the ENTRYPOINT arguments. The exec form of an ENTRYPOINT command is − ENTRYPOINT [“<executable-command>”, “<parameter 1>”, “<parameter 2>”, ....] If you have used the exec form of the ENTRYPOINT instruction, you can also set additional parameters with the help of CMD command. For example − ENTRYPOINT ["/bin/echo", "Welcome to TutorialsPoint"] CMD ["Hello World!"] Running docker run command without any argument would output − Welcome to TutorialsPoint Hello World! If you specify any other CLI arguments, “Hello World!” will get overridden. You can specify your working directory inside the container using the WORKDIR instruction. Any other instruction after that in the dockerfile, will be executed on that particular working directory only. WORKDIR /usr/src/app Sets the working directory to /usr/src/app inside the container. This instruction allows you to copy a directory from your local machine to the docker container. For example, FROM ubuntu WORKDIR /usr/src/app COPY ∽/Desktop/myapp . This would copy all the files inside the directory ∽/Desktop/myapp in your local machine to your current working directory inside the docker container. Similar to COPY instruction, you can use ADD to copy files and folders from your local machine to docker containers. However, ADD also allows you to copy files from a URL as well as a tar file. For example, ADD ∽/Desktop/myapp/practice.tar.gz /usr/src/app Would copy all the contents inside the tar file to /usr/src/app inside the container. ADD <URL such as a github url> <Destination path inside the container> This command would copy all the files inside the github url to the destination. The EXPOSE instruction inside the dockerfile informs that the container is listening to the specified port in the network. The default protocol is TCP. Example EXPOSE 8080 Will map the 8080 port to the container. You can use the −p flag with the docker run command to make the container listen to another container or the host machine. You can use a LABEL instruction to add description or meta data for a docker image. Its a key−value pair. Example − LABEL description="This is a sample image" To conclude, these were some of the basic as well as important instructions that are most commonly used in a dockerfile and using them in the right way would surely make you docker image to build efficiently, reduce its size, make it flexible and reusable.
[ { "code": null, "e": 1737, "s": 1062, "text": "We all know the importance of dockerfile in creating an efficient and flexible Docker Image. A dockerfile contains a set of instructions that are executed step by step when you use the docker build command to build the docker image. It contains certain instructions and commands that decides the structure of your image, the amount of time taken to build the image, contains instructions related to docker build context, contains information related to the packages and libraries to be installed in the container and many more. Hence, it becomes very important to create an efficient, reusable, clean dockerfile as it contains the blueprint of the image that you will build." }, { "code": null, "e": 1957, "s": 1737, "text": "In this article, I have created a curated list of all the important commands and instructions that are extensively used in a dockerfile. In a separate article, I have also enlisted best practices to create a dockerfile." }, { "code": null, "e": 2029, "s": 1957, "text": "https://www.tutorialspoint.com/best-practices-for-writing-a-dockerfile " }, { "code": null, "e": 2199, "s": 2029, "text": "Without any further ado, let’s discuss some of the most important dockerfile commands that you should thoroughly be aware of in order to efficiently create a dockerfile." }, { "code": null, "e": 2316, "s": 2199, "text": "You must have noticed that almost all the dockerfile starts with the FROM command. The FROM command is of the form −" }, { "code": null, "e": 2345, "s": 2316, "text": "FROM <image name>:<tag name>" }, { "code": null, "e": 2849, "s": 2345, "text": "A FROM command allows you to create a base image such as an operating system, a programming language, etc. All the instructions executed after this command take place on this base image. It contains an image name and an optional tag name. If you already have the base image pulled previously in your local machine, it doesn’t pull a new one. There are several pre published docker base images available in the docker registry. You can also push your own customized base image inside the docker registry." }, { "code": null, "e": 2917, "s": 2849, "text": "Examples of FROM instruction along with different base images are −" }, { "code": null, "e": 2955, "s": 2917, "text": "FROM ubuntu\nFROM centos\nFROM python:3" }, { "code": null, "e": 3159, "s": 2955, "text": "A RUN instruction is used to run specified commands. You can use several RUN instructions to run different commands. But it is an efficient approach to combine all the RUN instructions into a single one." }, { "code": null, "e": 3383, "s": 3159, "text": "Each RUN command creates a new cache layer or an intermediate image layer and hence chaining all of them into a single line, becomes efficient. However, chaining multiple RUN instructions could lead to cache bursts as well." }, { "code": null, "e": 3418, "s": 3383, "text": "Some example of RUN commands are −" }, { "code": null, "e": 3467, "s": 3418, "text": "RUN apt−get −y install vim\nRUN apt−get −y update" }, { "code": null, "e": 3530, "s": 3467, "text": "You can chain multiple RUN instructions in the following way −" }, { "code": null, "e": 3612, "s": 3530, "text": "RUN apt−get −y update \\\n&& apt−get −y install firefox \\\n&& apt−get −y install vim" }, { "code": null, "e": 3957, "s": 3612, "text": "If you want to run a docker container by specifying a default command that gets executed for all the containers of that image by default, you can use a CMD command. In case you specify a command during the docker run command, it overrides the default one. Specifying more than one CMD instructions, will allow only the last one to get executed." }, { "code": null, "e": 3984, "s": 3957, "text": "Example of a CMD command −" }, { "code": null, "e": 4021, "s": 3984, "text": "CMD echo \"Welcome to TutorialsPoint\"" }, { "code": null, "e": 4200, "s": 4021, "text": "If you specify the above line in the dockerfile and run the container using the following command without specifying any arguments, the output will be “Welcome to TutorialsPoint”" }, { "code": null, "e": 4233, "s": 4200, "text": "sudo docker run −it <image_name>" }, { "code": null, "e": 4270, "s": 4233, "text": "Output − “Welcome to TutorialsPoint”" }, { "code": null, "e": 4385, "s": 4270, "text": "In case you try to specify any other arguments such as /bin/bash, etc, the default CMD command will be overridden." }, { "code": null, "e": 4592, "s": 4385, "text": "The difference between ENTRYPOINT and CMD is that, if you try to specify default arguments in the docker run command, it will not ignore the ENTRYPOINT arguments. The exec form of an ENTRYPOINT command is −" }, { "code": null, "e": 4668, "s": 4592, "text": "ENTRYPOINT [“<executable-command>”, “<parameter 1>”, “<parameter 2>”, ....]" }, { "code": null, "e": 4813, "s": 4668, "text": "If you have used the exec form of the ENTRYPOINT instruction, you can also set additional parameters with the help of CMD command. For example −" }, { "code": null, "e": 4888, "s": 4813, "text": "ENTRYPOINT [\"/bin/echo\", \"Welcome to TutorialsPoint\"]\nCMD [\"Hello World!\"]" }, { "code": null, "e": 4951, "s": 4888, "text": "Running docker run command without any argument would output −" }, { "code": null, "e": 4990, "s": 4951, "text": "Welcome to TutorialsPoint Hello World!" }, { "code": null, "e": 5066, "s": 4990, "text": "If you specify any other CLI arguments, “Hello World!” will get overridden." }, { "code": null, "e": 5269, "s": 5066, "text": "You can specify your working directory inside the container using the WORKDIR instruction. Any other instruction after that in the dockerfile, will be executed on that particular working directory only." }, { "code": null, "e": 5290, "s": 5269, "text": "WORKDIR /usr/src/app" }, { "code": null, "e": 5355, "s": 5290, "text": "Sets the working directory to /usr/src/app inside the container." }, { "code": null, "e": 5452, "s": 5355, "text": "This instruction allows you to copy a directory from your local machine to the docker container." }, { "code": null, "e": 5465, "s": 5452, "text": "For example," }, { "code": null, "e": 5521, "s": 5465, "text": "FROM ubuntu\nWORKDIR /usr/src/app\nCOPY ∽/Desktop/myapp ." }, { "code": null, "e": 5673, "s": 5521, "text": "This would copy all the files inside the directory ∽/Desktop/myapp in your local machine to your current working directory inside the docker container." }, { "code": null, "e": 5867, "s": 5673, "text": "Similar to COPY instruction, you can use ADD to copy files and folders from your local machine to docker containers. However, ADD also allows you to copy files from a URL as well as a tar file." }, { "code": null, "e": 5880, "s": 5867, "text": "For example," }, { "code": null, "e": 5929, "s": 5880, "text": "ADD ∽/Desktop/myapp/practice.tar.gz /usr/src/app" }, { "code": null, "e": 6015, "s": 5929, "text": "Would copy all the contents inside the tar file to /usr/src/app inside the container." }, { "code": null, "e": 6086, "s": 6015, "text": "ADD <URL such as a github url> <Destination path inside the container>" }, { "code": null, "e": 6166, "s": 6086, "text": "This command would copy all the files inside the github url to the destination." }, { "code": null, "e": 6318, "s": 6166, "text": "The EXPOSE instruction inside the dockerfile informs that the container is listening to the specified port in the network. The default protocol is TCP." }, { "code": null, "e": 6326, "s": 6318, "text": "Example" }, { "code": null, "e": 6339, "s": 6326, "text": "EXPOSE 8080\n" }, { "code": null, "e": 6380, "s": 6339, "text": "Will map the 8080 port to the container." }, { "code": null, "e": 6503, "s": 6380, "text": "You can use the −p flag with the docker run command to make the container listen to another container or the host machine." }, { "code": null, "e": 6609, "s": 6503, "text": "You can use a LABEL instruction to add description or meta data for a docker image. Its a key−value pair." }, { "code": null, "e": 6619, "s": 6609, "text": "Example −" }, { "code": null, "e": 6662, "s": 6619, "text": "LABEL description=\"This is a sample image\"" }, { "code": null, "e": 6919, "s": 6662, "text": "To conclude, these were some of the basic as well as important instructions that are most commonly used in a dockerfile and using them in the right way would surely make you docker image to build efficiently, reduce its size, make it flexible and reusable." } ]
How to install modules without npm in node.js ? - GeeksforGeeks
05 Oct, 2021 We can install modules required for a particular project in node.js without npm, the recommended node package manager using yarn. Yarn is a wonderful package manager. Like npm, if you have a project folder with package.json containing all the required dependencies mentioned for the project, you can use yarn to install all the dependencies. 1. How to install yarn? To install yarn, visit the official installation page of yarn (https://classic.yarnpkg.com/en/docs/install). The page will automatically detect the operating system you are using. Additional installation instructions are also mentioned in the installation page. Once you have followed the steps on the installation manager and the installation process is complete, type the following command in the ternimal/ command prompt. yarn --version This should show the particular version you are using in you computer. For example: 1.22.5 . Now that we have installed yarn, lets see how we use yarn in our projects. 2. How to use yarn to install projects? To use yarn, go to the folder where the modules are needed to be installed. If it is not initialized with yarn, run the yarn init command. It will ask some questions regarding the project to create the package.json file. The package.json file is the most important file as it contains the necessary modules that are required by your project. Anyone with the package.json file, can run some commands( we will discuss this later) to install all the dependencies required by your project. You will get a similar question when you run yarn init command: question name (testdir): my-awesome-package question version (1.0.0): question description: The best package you will ever find. question entry point (index.js): question git repository: https://github.com/yarnpkg/example-yarn-package question author: Yarn Contributor question license (MIT): question private: success Saved package.json Done in 87.70s. After this is done, a package, json file is created. If you open the package.json file, it should look something like this: { "name": "my-awesome-package", "version": "1.0.0", "description": "The best package you will ever find.", "main": "index.js", "repository": { "url": "https://github.com/yarnpkg/example-yarn-package", "type": "git" }, "author": "Yarn Contributor", "license": "MIT" } Alternatively, if you have a project that contains a package.json file from the beginning, you can use yarn or yarn install command to install all the mentioned dependencies from the package.json file. Note: If you do not want to answer all the questions when performing yarn init command (although not recommended), you can use yarn init -y command to initialise it with the default values. You can change the details by editing the package.json file with suitable text editor. 3. Installing packages in the project folder Now we shall see how we can install packages using yarn. Suppose we want to install the package named express. We would enter the following command to install express: // Command to install express to the current project folder yarn add express // Command to install express globally in your machine yarn global add expres // This is the most generalized way, Just replace // the <package-name> with the name of the package yarn add <package-name> Note: The global keyword is used to inform yarn that we want to install express globally. Reference: There are a lot more commands that you can execute with yarn. A list of commands is mentioned in the following link: https://classic.yarnpkg.com/en/docs/cli If you are migrating from npm to yarn, you can use this cheatsheet to know the similar commands for yarn. mridulmanochagfg how-to-install Node.js-Misc How To Installation Guide Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Align Text in HTML? Java Tutorial How to filter object array based on attributes? How to Install and Run Apache Kafka on Windows? How to Install FFmpeg on Windows? How to Install FFmpeg on Windows? How to Install and Run Apache Kafka on Windows? How to Install Pygame on Windows ? How to Install Anaconda on Windows? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 25068, "s": 25040, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25410, "s": 25068, "text": "We can install modules required for a particular project in node.js without npm, the recommended node package manager using yarn. Yarn is a wonderful package manager. Like npm, if you have a project folder with package.json containing all the required dependencies mentioned for the project, you can use yarn to install all the dependencies." }, { "code": null, "e": 25438, "s": 25412, "text": "1. How to install yarn? " }, { "code": null, "e": 25863, "s": 25438, "text": "To install yarn, visit the official installation page of yarn (https://classic.yarnpkg.com/en/docs/install). The page will automatically detect the operating system you are using. Additional installation instructions are also mentioned in the installation page. Once you have followed the steps on the installation manager and the installation process is complete, type the following command in the ternimal/ command prompt." }, { "code": null, "e": 25881, "s": 25865, "text": "yarn --version " }, { "code": null, "e": 26051, "s": 25883, "text": "This should show the particular version you are using in you computer. For example: 1.22.5 . Now that we have installed yarn, lets see how we use yarn in our projects." }, { "code": null, "e": 26093, "s": 26051, "text": "2. How to use yarn to install projects? " }, { "code": null, "e": 26643, "s": 26093, "text": "To use yarn, go to the folder where the modules are needed to be installed. If it is not initialized with yarn, run the yarn init command. It will ask some questions regarding the project to create the package.json file. The package.json file is the most important file as it contains the necessary modules that are required by your project. Anyone with the package.json file, can run some commands( we will discuss this later) to install all the dependencies required by your project. You will get a similar question when you run yarn init command:" }, { "code": null, "e": 27009, "s": 26645, "text": "question name (testdir): my-awesome-package\nquestion version (1.0.0):\nquestion description: \n The best package you will ever find.\nquestion entry point (index.js):\nquestion git repository: \n https://github.com/yarnpkg/example-yarn-package\nquestion author: Yarn Contributor\nquestion license (MIT):\nquestion private:\nsuccess Saved package.json\nDone in 87.70s." }, { "code": null, "e": 27135, "s": 27011, "text": "After this is done, a package, json file is created. If you open the package.json file, it should look something like this:" }, { "code": null, "e": 27466, "s": 27137, "text": "{\n \"name\": \"my-awesome-package\",\n \"version\": \"1.0.0\",\n \"description\": \"The best package you will ever find.\",\n \"main\": \"index.js\",\n \"repository\": {\n \"url\": \"https://github.com/yarnpkg/example-yarn-package\",\n \"type\": \"git\"\n },\n \"author\": \"Yarn Contributor\",\n \"license\": \"MIT\"\n}" }, { "code": null, "e": 27671, "s": 27468, "text": "Alternatively, if you have a project that contains a package.json file from the beginning, you can use yarn or yarn install command to install all the mentioned dependencies from the package.json file." }, { "code": null, "e": 27951, "s": 27673, "text": "Note: If you do not want to answer all the questions when performing yarn init command (although not recommended), you can use yarn init -y command to initialise it with the default values. You can change the details by editing the package.json file with suitable text editor. " }, { "code": null, "e": 27998, "s": 27951, "text": "3. Installing packages in the project folder " }, { "code": null, "e": 28167, "s": 27998, "text": "Now we shall see how we can install packages using yarn. Suppose we want to install the package named express. We would enter the following command to install express: " }, { "code": null, "e": 28457, "s": 28169, "text": "// Command to install express to the current project folder\nyarn add express \n\n// Command to install express globally in your machine\nyarn global add expres \n\n// This is the most generalized way, Just replace \n// the <package-name> with the name of the package\nyarn add <package-name> " }, { "code": null, "e": 28550, "s": 28459, "text": "Note: The global keyword is used to inform yarn that we want to install express globally. " }, { "code": null, "e": 28719, "s": 28550, "text": "Reference: There are a lot more commands that you can execute with yarn. A list of commands is mentioned in the following link: https://classic.yarnpkg.com/en/docs/cli " }, { "code": null, "e": 28826, "s": 28719, "text": "If you are migrating from npm to yarn, you can use this cheatsheet to know the similar commands for yarn. " }, { "code": null, "e": 28845, "s": 28828, "text": "mridulmanochagfg" }, { "code": null, "e": 28860, "s": 28845, "text": "how-to-install" }, { "code": null, "e": 28873, "s": 28860, "text": "Node.js-Misc" }, { "code": null, "e": 28880, "s": 28873, "text": "How To" }, { "code": null, "e": 28899, "s": 28880, "text": "Installation Guide" }, { "code": null, "e": 28907, "s": 28899, "text": "Node.js" }, { "code": null, "e": 28924, "s": 28907, "text": "Web Technologies" }, { "code": null, "e": 29022, "s": 28924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29031, "s": 29022, "text": "Comments" }, { "code": null, "e": 29044, "s": 29031, "text": "Old Comments" }, { "code": null, "e": 29071, "s": 29044, "text": "How to Align Text in HTML?" }, { "code": null, "e": 29085, "s": 29071, "text": "Java Tutorial" }, { "code": null, "e": 29133, "s": 29085, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29181, "s": 29133, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 29215, "s": 29181, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29249, "s": 29215, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29297, "s": 29249, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 29332, "s": 29297, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 29368, "s": 29332, "text": "How to Install Anaconda on Windows?" } ]
ArrayDeque iterator() Method in Java - GeeksforGeeks
10 Dec, 2018 The Java.util.ArrayDeque.iterator() method is used to return an iterator of the elements of the ArrayDeque. Syntax: Iterator iterate_value = Array_Deque.iterator(); Parameters: The method does not take any parameter. Return Value: The method iterates over the elements of the deque and returns the values(iterator). Below programs illustrate the Java.util.ArrayDeque.iterator() method:Program 1: // Java code to illustrate iterator()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Queue de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Creating an iterator Iterator value = de_que.iterator(); // Displaying the values after iterating through the Deque System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }} ArrayDeque: [Welcome, To, Geeks, 4, Geeks] The iterator values are: Welcome To Geeks 4 Geeks Program 2: // Java code to illustrate iterator()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Queue de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Creating an iterator Iterator value = de_que.iterator(); // Displaying the values after iterating through the Deque System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }} ArrayDeque: [10, 15, 30, 20, 5] The iterator values are: 10 15 30 20 5 Java - util package Java-ArrayDeque Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java
[ { "code": null, "e": 24042, "s": 24014, "text": "\n10 Dec, 2018" }, { "code": null, "e": 24150, "s": 24042, "text": "The Java.util.ArrayDeque.iterator() method is used to return an iterator of the elements of the ArrayDeque." }, { "code": null, "e": 24158, "s": 24150, "text": "Syntax:" }, { "code": null, "e": 24207, "s": 24158, "text": "Iterator iterate_value = Array_Deque.iterator();" }, { "code": null, "e": 24259, "s": 24207, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 24358, "s": 24259, "text": "Return Value: The method iterates over the elements of the deque and returns the values(iterator)." }, { "code": null, "e": 24438, "s": 24358, "text": "Below programs illustrate the Java.util.ArrayDeque.iterator() method:Program 1:" }, { "code": "// Java code to illustrate iterator()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Queue de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Creating an iterator Iterator value = de_que.iterator(); // Displaying the values after iterating through the Deque System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}", "e": 25246, "s": 24438, "text": null }, { "code": null, "e": 25341, "s": 25246, "text": "ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nThe iterator values are: \nWelcome\nTo\nGeeks\n4\nGeeks\n" }, { "code": null, "e": 25352, "s": 25341, "text": "Program 2:" }, { "code": "// Java code to illustrate iterator()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Queue de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Creating an iterator Iterator value = de_que.iterator(); // Displaying the values after iterating through the Deque System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}", "e": 26141, "s": 25352, "text": null }, { "code": null, "e": 26214, "s": 26141, "text": "ArrayDeque: [10, 15, 30, 20, 5]\nThe iterator values are: \n10\n15\n30\n20\n5\n" }, { "code": null, "e": 26234, "s": 26214, "text": "Java - util package" }, { "code": null, "e": 26250, "s": 26234, "text": "Java-ArrayDeque" }, { "code": null, "e": 26267, "s": 26250, "text": "Java-Collections" }, { "code": null, "e": 26282, "s": 26267, "text": "Java-Functions" }, { "code": null, "e": 26287, "s": 26282, "text": "Java" }, { "code": null, "e": 26292, "s": 26287, "text": "Java" }, { "code": null, "e": 26309, "s": 26292, "text": "Java-Collections" }, { "code": null, "e": 26407, "s": 26309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26422, "s": 26407, "text": "Arrays in Java" }, { "code": null, "e": 26466, "s": 26422, "text": "Split() String method in Java with examples" }, { "code": null, "e": 26488, "s": 26466, "text": "For-each loop in Java" }, { "code": null, "e": 26524, "s": 26488, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 26549, "s": 26524, "text": "Reverse a string in Java" }, { "code": null, "e": 26581, "s": 26549, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26632, "s": 26581, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26662, "s": 26632, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26681, "s": 26662, "text": "Interfaces in Java" } ]
C# | How to play user modified Beep sound through Console - GeeksforGeeks
29 Jan, 2019 Given a normal Console in C#, the task is to play a user modified Beep sound through the Console. User modified beep sound refers to the Beep sound played at a specific frequency for a specific duration of time. Approach: This can be achieved with the help of Beep(Int32, Int32) method of Console Class in System package of C#. The Beep(int, int) method of Console Class is used to play a Beep sound through the Console speaker at the specified frequency for a specified duration. These frequency and duration are specified as parameters to this method. By default, the beep plays at a frequency of 800 hertz for a duration of 200 milliseconds. Syntax: public static void Beep (int frequency, int duration); Parameters: This method accepts two parameters frequency and duration which are the frequency at which the Beep sound has to be played and the duration for which it is to be played, respectively. Exceptions: This method throws following exceptions: ArgumentOutOfRangeException if the frequency is less than 37 or more than 32767 hertz if the duration is less than or equal to zero. HostProtectionException if this method was executed on a server, such as SQL Server, that does not permit access to a user interface. Below programs show the use of Console.Beep(Int32, Int32) method: Program 1: // C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Set the Frequency int frequency = 800; // Set the Duration int duration = 200; // Play beep sound once Console.Beep(frequency, duration); }}} Program 2: // C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { int n = 5; // Set the Frequency int frequency = 1000; // Set the Duration int duration = 400; // Play beep sound n times for (int i = 1; i < n; i++) Console.Beep(frequency, duration); }}} Note: Please run the programs on offline Visual Studio to experience the output. CSharp-Console-Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Method Overriding Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# Introduction to .NET Framework C# | Class and Object
[ { "code": null, "e": 25108, "s": 25080, "text": "\n29 Jan, 2019" }, { "code": null, "e": 25320, "s": 25108, "text": "Given a normal Console in C#, the task is to play a user modified Beep sound through the Console. User modified beep sound refers to the Beep sound played at a specific frequency for a specific duration of time." }, { "code": null, "e": 25436, "s": 25320, "text": "Approach: This can be achieved with the help of Beep(Int32, Int32) method of Console Class in System package of C#." }, { "code": null, "e": 25753, "s": 25436, "text": "The Beep(int, int) method of Console Class is used to play a Beep sound through the Console speaker at the specified frequency for a specified duration. These frequency and duration are specified as parameters to this method. By default, the beep plays at a frequency of 800 hertz for a duration of 200 milliseconds." }, { "code": null, "e": 25816, "s": 25753, "text": "Syntax: public static void Beep (int frequency, int duration);" }, { "code": null, "e": 26012, "s": 25816, "text": "Parameters: This method accepts two parameters frequency and duration which are the frequency at which the Beep sound has to be played and the duration for which it is to be played, respectively." }, { "code": null, "e": 26065, "s": 26012, "text": "Exceptions: This method throws following exceptions:" }, { "code": null, "e": 26198, "s": 26065, "text": "ArgumentOutOfRangeException if the frequency is less than 37 or more than 32767 hertz if the duration is less than or equal to zero." }, { "code": null, "e": 26332, "s": 26198, "text": "HostProtectionException if this method was executed on a server, such as SQL Server, that does not permit access to a user interface." }, { "code": null, "e": 26398, "s": 26332, "text": "Below programs show the use of Console.Beep(Int32, Int32) method:" }, { "code": null, "e": 26409, "s": 26398, "text": "Program 1:" }, { "code": "// C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Set the Frequency int frequency = 800; // Set the Duration int duration = 200; // Play beep sound once Console.Beep(frequency, duration); }}}", "e": 26890, "s": 26409, "text": null }, { "code": null, "e": 26901, "s": 26890, "text": "Program 2:" }, { "code": "// C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { int n = 5; // Set the Frequency int frequency = 1000; // Set the Duration int duration = 400; // Play beep sound n times for (int i = 1; i < n; i++) Console.Beep(frequency, duration); }}}", "e": 27463, "s": 26901, "text": null }, { "code": null, "e": 27544, "s": 27463, "text": "Note: Please run the programs on offline Visual Studio to experience the output." }, { "code": null, "e": 27565, "s": 27544, "text": "CSharp-Console-Class" }, { "code": null, "e": 27579, "s": 27565, "text": "CSharp-method" }, { "code": null, "e": 27582, "s": 27579, "text": "C#" }, { "code": null, "e": 27680, "s": 27582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27708, "s": 27680, "text": "C# Dictionary with examples" }, { "code": null, "e": 27731, "s": 27708, "text": "C# | Method Overriding" }, { "code": null, "e": 27749, "s": 27731, "text": "Destructors in C#" }, { "code": null, "e": 27795, "s": 27749, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27810, "s": 27795, "text": "C# | Delegates" }, { "code": null, "e": 27828, "s": 27810, "text": "C# | Constructors" }, { "code": null, "e": 27868, "s": 27828, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27891, "s": 27868, "text": "Extension Method in C#" }, { "code": null, "e": 27922, "s": 27891, "text": "Introduction to .NET Framework" } ]
Python - Stacking a multi-level column in a Pandas DataFrame
To stack a multi-level column, use the stack() method. At first, import the required library − import pandas as pd Create a multi-level column − items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')]) Now, create a DataFrame and set multi-level columns we set above − dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items) Stack the multi-level column − dataframe.stack() Following is the complete code − import pandas as pd # multi-level columns items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'), ('Maths', 'Applied Mathematics')]) # creating a DataFrame dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items) # DataFrame print"DataFrame...\n",dataFrame # stack multi-level columns print"\nStacking...\n",dataFrame.stack() This will produce the following output − DataFrame... Maths Mental Maths Discrete Mathematics Applied Mathematics John 67 86 78 Tom 56 92 97 Henry 92 95 91 Stacking... Maths John Applied Mathematics 78 Discrete Mathematics 86 Mental Maths 67 Tom Applied Mathematics 97 Discrete Mathematics 92 Mental Maths 56 Henry Applied Mathematics 91 Discrete Mathematics 95 Mental Maths 92
[ { "code": null, "e": 1157, "s": 1062, "text": "To stack a multi-level column, use the stack() method. At first, import the required library −" }, { "code": null, "e": 1177, "s": 1157, "text": "import pandas as pd" }, { "code": null, "e": 1207, "s": 1177, "text": "Create a multi-level column −" }, { "code": null, "e": 1339, "s": 1207, "text": "items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')])\n\n" }, { "code": null, "e": 1406, "s": 1339, "text": "Now, create a DataFrame and set multi-level columns we set above −" }, { "code": null, "e": 1520, "s": 1406, "text": "dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)" }, { "code": null, "e": 1551, "s": 1520, "text": "Stack the multi-level column −" }, { "code": null, "e": 1569, "s": 1551, "text": "dataframe.stack()" }, { "code": null, "e": 1602, "s": 1569, "text": "Following is the complete code −" }, { "code": null, "e": 2029, "s": 1602, "text": "import pandas as pd\n\n# multi-level columns\nitems = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),\n('Maths', 'Applied Mathematics')])\n\n# creating a DataFrame\ndataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)\n\n# DataFrame\nprint\"DataFrame...\\n\",dataFrame\n\n# stack multi-level columns\nprint\"\\nStacking...\\n\",dataFrame.stack()" }, { "code": null, "e": 2070, "s": 2029, "text": "This will produce the following output −" }, { "code": null, "e": 2701, "s": 2070, "text": "DataFrame...\n Maths\n Mental Maths Discrete Mathematics Applied Mathematics\nJohn 67 86 78\nTom 56 92 97\nHenry 92 95 91\n\nStacking...\n Maths\nJohn Applied Mathematics 78\n Discrete Mathematics 86\n Mental Maths 67\nTom Applied Mathematics 97\n Discrete Mathematics 92\n Mental Maths 56\nHenry Applied Mathematics 91\n Discrete Mathematics 95\n Mental Maths 92" } ]
Tryit Editor v3.7
Tryit: link to stylesheet
[]
Demonstrate nested loops with return statements in JavaScript?
Here’s an example with two loops, outer and inner − let demoForLoop = ()=>{ for(var outer=1;outer<100;outer++){ for(var inner=1;inner<=5;inner++){ if(outer==3){ return 'THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP'; } } } return 'OUT OF THE LOOP'; } console.log(demoForLoop()); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo105.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo105.js THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP
[ { "code": null, "e": 1114, "s": 1062, "text": "Here’s an example with two loops, outer and inner −" }, { "code": null, "e": 1392, "s": 1114, "text": "let demoForLoop = ()=>{\n for(var outer=1;outer<100;outer++){\n for(var inner=1;inner<=5;inner++){\n if(outer==3){\n return 'THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP';\n }\n }\n }\n return 'OUT OF THE LOOP';\n}\nconsole.log(demoForLoop());" }, { "code": null, "e": 1458, "s": 1392, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1476, "s": 1458, "text": "node fileName.js." }, { "code": null, "e": 1510, "s": 1476, "text": "Here, my file name is demo105.js." }, { "code": null, "e": 1551, "s": 1510, "text": "This will produce the following output −" }, { "code": null, "e": 1647, "s": 1551, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo105.js\nTHE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP" } ]
Boundary Testing
Boundary value analysis is a type of black box or specification based testing technique in which tests are performed using the boundary values. An exam has a pass boundary at 50 percent, merit at 75 percent and distinction at 85 percent. The Valid Boundary values for this scenario will be as follows: 49, 50 - for pass 74, 75 - for merit 84, 85 - for distinction Boundary values are validated against both the valid boundaries and invalid boundaries. The Invalid Boundary Cases for the above example can be given as follows: 0 - for lower limit boundary value 101 - for upper limit boundary value 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 5889, "s": 5745, "text": "Boundary value analysis is a type of black box or specification based testing technique in which tests are performed using the boundary values." }, { "code": null, "e": 6047, "s": 5889, "text": "An exam has a pass boundary at 50 percent, merit at 75 percent and distinction at 85 percent. The Valid Boundary values for this scenario will be as follows:" }, { "code": null, "e": 6109, "s": 6047, "text": "49, 50 - for pass\n74, 75 - for merit\n84, 85 - for distinction" }, { "code": null, "e": 6197, "s": 6109, "text": "Boundary values are validated against both the valid boundaries and invalid boundaries." }, { "code": null, "e": 6271, "s": 6197, "text": "The Invalid Boundary Cases for the above example can be given as follows:" }, { "code": null, "e": 6343, "s": 6271, "text": "0 - for lower limit boundary value\n101 - for upper limit boundary value" }, { "code": null, "e": 6378, "s": 6343, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6397, "s": 6378, "text": " Arnab Chakraborty" }, { "code": null, "e": 6430, "s": 6397, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6443, "s": 6430, "text": " Zach Miller" }, { "code": null, "e": 6478, "s": 6443, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6491, "s": 6478, "text": " Zach Miller" }, { "code": null, "e": 6524, "s": 6491, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 6535, "s": 6524, "text": " John Shea" }, { "code": null, "e": 6569, "s": 6535, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 6580, "s": 6569, "text": " Daniel IT" }, { "code": null, "e": 6613, "s": 6580, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 6630, "s": 6613, "text": " GlobalETraining" }, { "code": null, "e": 6637, "s": 6630, "text": " Print" }, { "code": null, "e": 6648, "s": 6637, "text": " Add Notes" } ]
Advantage Actor Critic Tutorial: minA2C | by Mike Wang | Towards Data Science
In the field of Reinforcement Learning, the Advantage Actor Critic (A2C) algorithm combines two types of Reinforcement Learning algorithms (Policy Based and Value Based) together. Policy Based agents directly learn a policy (a probability distribution of actions) mapping input states to output actions. Value Based algorithms learn to select actions based on the predicted value of the input state or action. In our previous Deep Q-Learning Tutorial: minDQN, we learned to implement our own Deep Q-Network to solve the simple Cartpole environment. In this tutorial, we’ll be sharing a minimal Advantage Actor Critic (minA2C) implementation in order to help new users learn how to code their own Advantage Actor-Critic implementations. You can also watch the Youtube version of this tutorial here. The Advantage Actor-Critic Algorithm OverviewThe CartPole OpenAI Gym EnvironmentThe Advantage FunctionActor NetworkCritic NetworkImplementation DetailsAdvantage Actor Critic Coding ImplementationResources The Advantage Actor-Critic Algorithm Overview The CartPole OpenAI Gym Environment The Advantage Function Actor Network Critic Network Implementation Details Advantage Actor Critic Coding Implementation Resources The actor critic algorithm consists of two networks (the actor and the critic) working together to solve a particular problem. At a high level, the Advantage Function calculates the agent’s TD Error or Prediction Error. The actor network chooses an action at each time step and the critic network evaluates the quality or the Q-value of a given input state. As the critic network learns which states are better or worse, the actor uses this information to teach the agent to seek out good states and avoid bad states. In this tutorial, we’ll be solving the CartPole Environment using the Advantage Actor Critic method. At each timestep, the agent accepts 4 input states (Cart Position, Cart Velocity, Pole Angle, and Pole Velocity at the Tip) and chooses to move either left or right. Our goal is to balance the pole for as long as possible. What’s the advantage function? Considering that “Advantage” is in the Advantage Actor Critic algorithm’s name, it must be pretty important. In order to understand what the Advantage Function is, we first need to understand how to calculate the TD Error, or the Temporal Difference Error. In Temporal Difference Learning, agents learn by making predictions about future rewards and adjusting their actions based on prediction error. One of the reasons Temporal Difference Learning is quite interesting is that prediction error also seems to be one of the ways that the brain learns new things. In order to calculate the Advantage Function (TD Error), we need to first calculate the TD Target. In the equation above, the TD Target is the predicted value of all future rewards from the current state S. The function V(s’) represents the Critic Network calculating the value of the next state S’. In the Advantage Actor Critic algorithm, the Advantage is equal to the TD Error shown above. The Advantage can also be interpreted as the Prediction Error of our agent. Note that the advantage function may not always be the same as the TD Error function. For example, in many Policy Gradient algorithms, the advantage is commonly calculated to be the sum of future discounted rewards shown in Figure 4. The Advantage function tells us if a state is better or worse than expected. If an action is better than expected (the advantage is greater than 0), we want to encourage the actor to take more of that action. If an action is worse than expected (the advantage is less than 0), we want to encourage the actor to take the opposite of that action. If an action performs exactly as expected (the advantage equals 0), the actor doesn’t learn anything from that action. The actor network maps each state to a corresponding action. Just like with the Critic Network, we can update the Actor Network weights after every time step. The actor network outputs a probability distribution corresponding to each action. We sample actions from this probability distribution according to each action’s probability. If the action to go left has a value of .8 and the action to go right has a value of .2, we will only choose the left action 80% of the time and the right action 20% of the time. Because the output is a probability distribution, note that the agent will not always choose the action with the highest probability. def create_actor(state_shape, action_shape): learning_rate = 0.001 init = tf.keras.initializers.HeUniform() model = keras.Sequential() model.add(keras.layers.Dense(24, input_shape=state_shape, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(12, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(action_shape, activation='softmax', kernel_initializer=init)) model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(lr=learning_rate), metrics=['accuracy']) return model In our implementation, the Actor Network is a simple network consisting of 3 densely connected layers with the LeakyReLU activation function. The network uses the Softmax activation function and the Categorical Cross Entropy loss function because the network outputs a probability distribution of actions. Once we’ve constructed and initialized our actor network, we need to update its weights. In the above example, the agent has decided choosing to go left was the wrong decision. In this case, the agent wants to reduce the probability of choosing left from 80% to 79%. Likewise, the agent needs to increase the probability of choosing right from 20% to 21%. After updating these probabilities, we can update our network weights by fitting the network to the new probabilities. How does the algorithm decide which actions to encourage and which to discourage? The A2C algorithm makes this decision by calculating the advantage. The advantage decides how to scale the action that the agent just took. Importantly the advantage can also be negative which discourages the selected action. Likewise, a positive advantage would encourage and reinforce that action. The critic network maps each state to its corresponding Q-value. The Q-value represents the value of a state where Q represents the Quality of the state. Unlike the Actor Network which outputs a probability distribution of actions, the Critic Network outputs the TD Target of the input state as a floating point number. In the figure above, the critic network evaluates the input state to have a Q-value of 15. def create_critic(state_shape, output_shape): learning_rate = 0.001 init = tf.keras.initializers.HeUniform() model = keras.Sequential() model.add(keras.layers.Dense(24, input_shape=state_shape, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(12, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(output_shape, activation='linear', kernel_initializer=init)) model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer=tf.keras.optimizers.Adam(lr=learning_rate), metrics=['accuracy']) return model Like the Actor Network, our Critic Network also consists of 3 densely connected layers with the LeakyReLU activation function. Because the output of the Critic Network is the TD Target, the network is optimized using the Mean Squared Error loss function. Now that we know how to calculate the TD Target and the TD Error, how do we update the Critic Network weights? Note that as the TD Error approaches 0, the Critic Network gets better and better at predicting the outcome from the current state. In this case, we want to drive the TD Error as close to 0 as possible. In order to update the critic network weights, we use the Mean Squared Error of the TD Error function. In order to update the network, we fit our network weights so that they target the new TD Target value of 10. Note that the Advantage Actor Critic algorithm is different than the vanilla Policy Gradient (REINFORCE) algorithm. Instead of waiting for the end of an episode to finish as in the REINFORCE algorithm, we can update the critic network after every time step. As the agent explores its environment, the critic network is attempting to drive the advantage function to 0. At the beginning of the learning process, the critic will likely make large errors causing the calculated TD error to be quite incorrect. Because the algorithm starts out with the critic having no knowledge of the environment, the actor similarly can’t learn much from the critic. As the critic starts to make more and more accurate predictions, the calculated TD error (Advantage) becomes more accurate. The actor is able to learn from the increasingly accurate TD error to decide if a move was good or bad. For the CartPole problem, the reward of 1 at each time step stops coming when the game ends. The game ending is unexpected to the critic and commonly results in a larger negative value. The unexpected ending of rewards causes the actor to figuratively think, “that move was worse than expected, let’s try something else next time”. By repeating this learning process over many game episodes, the critic and actor together learn to balance the pole for longer periods of time. Finally, we can put the Advantage Function, the Actor, and the Critic together to solve the CartPole Environment. You can find our advantage actor critic implementation here which learns to balance the CartPole over a period of 300 episodes. Advantage Actor Critic (A2C) implementation Deep Reinforcement Learning: Pong from Pixels Policy Gradient Reinforcement Learning with Keras Actor Critic (A3C) Tutorial Everything You Need To Master Actor Critic Methods | Tensorflow 2 Tutorial Soft Actor-Critic Demystified
[ { "code": null, "e": 970, "s": 172, "text": "In the field of Reinforcement Learning, the Advantage Actor Critic (A2C) algorithm combines two types of Reinforcement Learning algorithms (Policy Based and Value Based) together. Policy Based agents directly learn a policy (a probability distribution of actions) mapping input states to output actions. Value Based algorithms learn to select actions based on the predicted value of the input state or action. In our previous Deep Q-Learning Tutorial: minDQN, we learned to implement our own Deep Q-Network to solve the simple Cartpole environment. In this tutorial, we’ll be sharing a minimal Advantage Actor Critic (minA2C) implementation in order to help new users learn how to code their own Advantage Actor-Critic implementations. You can also watch the Youtube version of this tutorial here." }, { "code": null, "e": 1175, "s": 970, "text": "The Advantage Actor-Critic Algorithm OverviewThe CartPole OpenAI Gym EnvironmentThe Advantage FunctionActor NetworkCritic NetworkImplementation DetailsAdvantage Actor Critic Coding ImplementationResources" }, { "code": null, "e": 1221, "s": 1175, "text": "The Advantage Actor-Critic Algorithm Overview" }, { "code": null, "e": 1257, "s": 1221, "text": "The CartPole OpenAI Gym Environment" }, { "code": null, "e": 1280, "s": 1257, "text": "The Advantage Function" }, { "code": null, "e": 1294, "s": 1280, "text": "Actor Network" }, { "code": null, "e": 1309, "s": 1294, "text": "Critic Network" }, { "code": null, "e": 1332, "s": 1309, "text": "Implementation Details" }, { "code": null, "e": 1377, "s": 1332, "text": "Advantage Actor Critic Coding Implementation" }, { "code": null, "e": 1387, "s": 1377, "text": "Resources" }, { "code": null, "e": 1905, "s": 1387, "text": "The actor critic algorithm consists of two networks (the actor and the critic) working together to solve a particular problem. At a high level, the Advantage Function calculates the agent’s TD Error or Prediction Error. The actor network chooses an action at each time step and the critic network evaluates the quality or the Q-value of a given input state. As the critic network learns which states are better or worse, the actor uses this information to teach the agent to seek out good states and avoid bad states." }, { "code": null, "e": 2229, "s": 1905, "text": "In this tutorial, we’ll be solving the CartPole Environment using the Advantage Actor Critic method. At each timestep, the agent accepts 4 input states (Cart Position, Cart Velocity, Pole Angle, and Pole Velocity at the Tip) and chooses to move either left or right. Our goal is to balance the pole for as long as possible." }, { "code": null, "e": 2517, "s": 2229, "text": "What’s the advantage function? Considering that “Advantage” is in the Advantage Actor Critic algorithm’s name, it must be pretty important. In order to understand what the Advantage Function is, we first need to understand how to calculate the TD Error, or the Temporal Difference Error." }, { "code": null, "e": 2822, "s": 2517, "text": "In Temporal Difference Learning, agents learn by making predictions about future rewards and adjusting their actions based on prediction error. One of the reasons Temporal Difference Learning is quite interesting is that prediction error also seems to be one of the ways that the brain learns new things." }, { "code": null, "e": 3122, "s": 2822, "text": "In order to calculate the Advantage Function (TD Error), we need to first calculate the TD Target. In the equation above, the TD Target is the predicted value of all future rewards from the current state S. The function V(s’) represents the Critic Network calculating the value of the next state S’." }, { "code": null, "e": 3291, "s": 3122, "text": "In the Advantage Actor Critic algorithm, the Advantage is equal to the TD Error shown above. The Advantage can also be interpreted as the Prediction Error of our agent." }, { "code": null, "e": 3525, "s": 3291, "text": "Note that the advantage function may not always be the same as the TD Error function. For example, in many Policy Gradient algorithms, the advantage is commonly calculated to be the sum of future discounted rewards shown in Figure 4." }, { "code": null, "e": 3989, "s": 3525, "text": "The Advantage function tells us if a state is better or worse than expected. If an action is better than expected (the advantage is greater than 0), we want to encourage the actor to take more of that action. If an action is worse than expected (the advantage is less than 0), we want to encourage the actor to take the opposite of that action. If an action performs exactly as expected (the advantage equals 0), the actor doesn’t learn anything from that action." }, { "code": null, "e": 4148, "s": 3989, "text": "The actor network maps each state to a corresponding action. Just like with the Critic Network, we can update the Actor Network weights after every time step." }, { "code": null, "e": 4637, "s": 4148, "text": "The actor network outputs a probability distribution corresponding to each action. We sample actions from this probability distribution according to each action’s probability. If the action to go left has a value of .8 and the action to go right has a value of .2, we will only choose the left action 80% of the time and the right action 20% of the time. Because the output is a probability distribution, note that the agent will not always choose the action with the highest probability." }, { "code": null, "e": 5246, "s": 4637, "text": "def create_actor(state_shape, action_shape): learning_rate = 0.001 init = tf.keras.initializers.HeUniform() model = keras.Sequential() model.add(keras.layers.Dense(24, input_shape=state_shape, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(12, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(action_shape, activation='softmax', kernel_initializer=init)) model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(lr=learning_rate), metrics=['accuracy']) return model" }, { "code": null, "e": 5552, "s": 5246, "text": "In our implementation, the Actor Network is a simple network consisting of 3 densely connected layers with the LeakyReLU activation function. The network uses the Softmax activation function and the Categorical Cross Entropy loss function because the network outputs a probability distribution of actions." }, { "code": null, "e": 6027, "s": 5552, "text": "Once we’ve constructed and initialized our actor network, we need to update its weights. In the above example, the agent has decided choosing to go left was the wrong decision. In this case, the agent wants to reduce the probability of choosing left from 80% to 79%. Likewise, the agent needs to increase the probability of choosing right from 20% to 21%. After updating these probabilities, we can update our network weights by fitting the network to the new probabilities." }, { "code": null, "e": 6409, "s": 6027, "text": "How does the algorithm decide which actions to encourage and which to discourage? The A2C algorithm makes this decision by calculating the advantage. The advantage decides how to scale the action that the agent just took. Importantly the advantage can also be negative which discourages the selected action. Likewise, a positive advantage would encourage and reinforce that action." }, { "code": null, "e": 6563, "s": 6409, "text": "The critic network maps each state to its corresponding Q-value. The Q-value represents the value of a state where Q represents the Quality of the state." }, { "code": null, "e": 6820, "s": 6563, "text": "Unlike the Actor Network which outputs a probability distribution of actions, the Critic Network outputs the TD Target of the input state as a floating point number. In the figure above, the critic network evaluates the input state to have a Q-value of 15." }, { "code": null, "e": 7437, "s": 6820, "text": "def create_critic(state_shape, output_shape): learning_rate = 0.001 init = tf.keras.initializers.HeUniform() model = keras.Sequential() model.add(keras.layers.Dense(24, input_shape=state_shape, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(12, activation=tf.keras.layers.LeakyReLU(), kernel_initializer=init)) model.add(keras.layers.Dense(output_shape, activation='linear', kernel_initializer=init)) model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer=tf.keras.optimizers.Adam(lr=learning_rate), metrics=['accuracy']) return model" }, { "code": null, "e": 7692, "s": 7437, "text": "Like the Actor Network, our Critic Network also consists of 3 densely connected layers with the LeakyReLU activation function. Because the output of the Critic Network is the TD Target, the network is optimized using the Mean Squared Error loss function." }, { "code": null, "e": 8109, "s": 7692, "text": "Now that we know how to calculate the TD Target and the TD Error, how do we update the Critic Network weights? Note that as the TD Error approaches 0, the Critic Network gets better and better at predicting the outcome from the current state. In this case, we want to drive the TD Error as close to 0 as possible. In order to update the critic network weights, we use the Mean Squared Error of the TD Error function." }, { "code": null, "e": 8477, "s": 8109, "text": "In order to update the network, we fit our network weights so that they target the new TD Target value of 10. Note that the Advantage Actor Critic algorithm is different than the vanilla Policy Gradient (REINFORCE) algorithm. Instead of waiting for the end of an episode to finish as in the REINFORCE algorithm, we can update the critic network after every time step." }, { "code": null, "e": 9096, "s": 8477, "text": "As the agent explores its environment, the critic network is attempting to drive the advantage function to 0. At the beginning of the learning process, the critic will likely make large errors causing the calculated TD error to be quite incorrect. Because the algorithm starts out with the critic having no knowledge of the environment, the actor similarly can’t learn much from the critic. As the critic starts to make more and more accurate predictions, the calculated TD error (Advantage) becomes more accurate. The actor is able to learn from the increasingly accurate TD error to decide if a move was good or bad." }, { "code": null, "e": 9572, "s": 9096, "text": "For the CartPole problem, the reward of 1 at each time step stops coming when the game ends. The game ending is unexpected to the critic and commonly results in a larger negative value. The unexpected ending of rewards causes the actor to figuratively think, “that move was worse than expected, let’s try something else next time”. By repeating this learning process over many game episodes, the critic and actor together learn to balance the pole for longer periods of time." }, { "code": null, "e": 9814, "s": 9572, "text": "Finally, we can put the Advantage Function, the Actor, and the Critic together to solve the CartPole Environment. You can find our advantage actor critic implementation here which learns to balance the CartPole over a period of 300 episodes." }, { "code": null, "e": 9858, "s": 9814, "text": "Advantage Actor Critic (A2C) implementation" }, { "code": null, "e": 9904, "s": 9858, "text": "Deep Reinforcement Learning: Pong from Pixels" }, { "code": null, "e": 9954, "s": 9904, "text": "Policy Gradient Reinforcement Learning with Keras" }, { "code": null, "e": 9982, "s": 9954, "text": "Actor Critic (A3C) Tutorial" }, { "code": null, "e": 10057, "s": 9982, "text": "Everything You Need To Master Actor Critic Methods | Tensorflow 2 Tutorial" } ]
Entity Framework - Lazy Loading
Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. Lazy loading is pretty much the default. Lazy loading is pretty much the default. If you leave the default configuration, and don’t explicitly tell Entity Framework in your query that you want something other than lazy loading, then lazy loading is what you will get. If you leave the default configuration, and don’t explicitly tell Entity Framework in your query that you want something other than lazy loading, then lazy loading is what you will get. For example, when using the Student entity class, the related Enrollments will be loaded the first time the Enrollments navigation property is accessed. For example, when using the Student entity class, the related Enrollments will be loaded the first time the Enrollments navigation property is accessed. Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual. Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual. Following is a Student class which contains navigation property of Enrollments. public partial class Student { public Student() { this.Enrollments = new HashSet<Enrollment>(); } public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public System.DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } Let’s take a look into a simple example in which student list is loaded from the database first and then it will load the enrollments of a particular student whenever you need it. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { //Loading students only IList<Student> students = context.Students.ToList<Student>(); foreach (var student in students) { string name = student.FirstMidName + " " + student.LastName; Console.WriteLine("ID: {0}, Name: {1}", student.ID, name); foreach (var enrollment in student.Enrollments) { Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", enrollment.EnrollmentID, enrollment.CourseID); } } Console.ReadKey(); } } } When the above code is compiled and executed, you will receive the following output. ID: 1, Name: Ali Alexander Enrollment ID: 1, Course ID: 1050 Enrollment ID: 2, Course ID: 4022 Enrollment ID: 3, Course ID: 4041 ID: 2, Name: Meredith Alonso Enrollment ID: 4, Course ID: 1045 Enrollment ID: 5, Course ID: 3141 Enrollment ID: 6, Course ID: 2021 ID: 3, Name: Arturo Anand Enrollment ID: 7, Course ID: 1050 ID: 4, Name: Gytis Barzdukas Enrollment ID: 8, Course ID: 1050 Enrollment ID: 9, Course ID: 4022 ID: 5, Name: Yan Li Enrollment ID: 10, Course ID: 4041 ID: 6, Name: Peggy Justice Enrollment ID: 11, Course ID: 1045 ID: 7, Name: Laura Norman Enrollment ID: 12, Course ID: 3141 Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled. It’s a good practice to turn lazy loading off before you serialize an entity. Lazy loading of the Enrollments collection can be turned off by making the Enrollments property non-virtual as shown in the following example. public partial class Student { public Student() { this.Enrollments = new HashSet<Enrollment>(); } public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public System.DateTime EnrollmentDate { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property to false as shown in the following example. public partial class UniContextEntities : DbContext { public UniContextEntities(): base("name = UniContextEntities") { this.Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } } After turning off lazy loading, now when you run the above example again you will see that the Enrollments are not loaded and only student data is retrieved. ID: 1, Name: Ali Alexander ID: 2, Name: Meredith Alons ID: 3, Name: Arturo Anand ID: 4, Name: Gytis Barzduka ID: 5, Name: Yan Li ID: 6, Name: Peggy Justice ID: 7, Name: Laura Norman ID: 8, Name: Nino Olivetto We recommend you to execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3319, "s": 3032, "text": "Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it." }, { "code": null, "e": 3483, "s": 3319, "text": "When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook." }, { "code": null, "e": 3647, "s": 3483, "text": "When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook." }, { "code": null, "e": 3688, "s": 3647, "text": "Lazy loading is pretty much the default." }, { "code": null, "e": 3729, "s": 3688, "text": "Lazy loading is pretty much the default." }, { "code": null, "e": 3915, "s": 3729, "text": "If you leave the default configuration, and don’t explicitly tell Entity Framework in your query that you want something other than lazy loading, then lazy loading is what you will get." }, { "code": null, "e": 4101, "s": 3915, "text": "If you leave the default configuration, and don’t explicitly tell Entity Framework in your query that you want something other than lazy loading, then lazy loading is what you will get." }, { "code": null, "e": 4254, "s": 4101, "text": "For example, when using the Student entity class, the related Enrollments will be loaded the first time the Enrollments navigation property is accessed." }, { "code": null, "e": 4407, "s": 4254, "text": "For example, when using the Student entity class, the related Enrollments will be loaded the first time the Enrollments navigation property is accessed." }, { "code": null, "e": 4541, "s": 4407, "text": "Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual." }, { "code": null, "e": 4675, "s": 4541, "text": "Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual." }, { "code": null, "e": 4755, "s": 4675, "text": "Following is a Student class which contains navigation property of Enrollments." }, { "code": null, "e": 5110, "s": 4755, "text": "public partial class Student {\n\n public Student() {\n this.Enrollments = new HashSet<Enrollment>();\n }\n\t\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public System.DateTime EnrollmentDate { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}" }, { "code": null, "e": 5290, "s": 5110, "text": "Let’s take a look into a simple example in which student list is loaded from the database first and then it will load the enrollments of a particular student whenever you need it." }, { "code": null, "e": 5967, "s": 5290, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n //Loading students only\n IList<Student> students = context.Students.ToList<Student>();\n\n foreach (var student in students) {\n\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", student.ID, name);\n\t\n foreach (var enrollment in student.Enrollments) {\n Console.WriteLine(\"Enrollment ID: {0}, Course ID: {1}\", \n enrollment.EnrollmentID, enrollment.CourseID);\n }\n }\n\n Console.ReadKey();\n }\n }\n}\t" }, { "code": null, "e": 6052, "s": 5967, "text": "When the above code is compiled and executed, you will receive the following output." }, { "code": null, "e": 6732, "s": 6052, "text": "ID: 1, Name: Ali Alexander\n Enrollment ID: 1, Course ID: 1050\n Enrollment ID: 2, Course ID: 4022\n Enrollment ID: 3, Course ID: 4041\nID: 2, Name: Meredith Alonso\n Enrollment ID: 4, Course ID: 1045\n Enrollment ID: 5, Course ID: 3141\n Enrollment ID: 6, Course ID: 2021\nID: 3, Name: Arturo Anand\n Enrollment ID: 7, Course ID: 1050\nID: 4, Name: Gytis Barzdukas\n Enrollment ID: 8, Course ID: 1050\n Enrollment ID: 9, Course ID: 4022\nID: 5, Name: Yan Li\n Enrollment ID: 10, Course ID: 4041\nID: 6, Name: Peggy Justice\n Enrollment ID: 11, Course ID: 1045\nID: 7, Name: Laura Norman\n Enrollment ID: 12, Course ID: 3141\n" }, { "code": null, "e": 6970, "s": 6732, "text": "Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled. It’s a good practice to turn lazy loading off before you serialize an entity." }, { "code": null, "e": 7113, "s": 6970, "text": "Lazy loading of the Enrollments collection can be turned off by making the Enrollments property non-virtual as shown in the following example." }, { "code": null, "e": 7467, "s": 7113, "text": "public partial class Student { \n\n public Student() { \n this.Enrollments = new HashSet<Enrollment>(); \n }\n\t\n public int ID { get; set; } \n public string LastName { get; set; } \n public string FirstMidName { get; set; } \n public System.DateTime EnrollmentDate { get; set; }\n\t\n public ICollection<Enrollment> Enrollments { get; set; } \n}" }, { "code": null, "e": 7622, "s": 7467, "text": "Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property to false as shown in the following example." }, { "code": null, "e": 7941, "s": 7622, "text": "public partial class UniContextEntities : DbContext { \n\n public UniContextEntities(): base(\"name = UniContextEntities\") {\n this.Configuration.LazyLoadingEnabled = false;\n }\n\t\n protected override void OnModelCreating(DbModelBuilder modelBuilder) { \n throw new UnintentionalCodeFirstException(); \n } \n}" }, { "code": null, "e": 8099, "s": 7941, "text": "After turning off lazy loading, now when you run the above example again you will see that the Enrollments are not loaded and only student data is retrieved." }, { "code": null, "e": 8309, "s": 8099, "text": "ID: 1, Name: Ali Alexander\nID: 2, Name: Meredith Alons\nID: 3, Name: Arturo Anand\nID: 4, Name: Gytis Barzduka\nID: 5, Name: Yan Li\nID: 6, Name: Peggy Justice\nID: 7, Name: Laura Norman\nID: 8, Name: Nino Olivetto\n" }, { "code": null, "e": 8406, "s": 8309, "text": "We recommend you to execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 8439, "s": 8406, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8457, "s": 8439, "text": " Trevoir Williams" }, { "code": null, "e": 8492, "s": 8457, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8505, "s": 8492, "text": " Nilay Mehta" }, { "code": null, "e": 8540, "s": 8505, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8556, "s": 8540, "text": " TELCOMA Global" }, { "code": null, "e": 8591, "s": 8556, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8609, "s": 8591, "text": " Mustafa Radaideh" }, { "code": null, "e": 8616, "s": 8609, "text": " Print" }, { "code": null, "e": 8627, "s": 8616, "text": " Add Notes" } ]
Convert a String into a square matrix grid of characters - GeeksforGeeks
07 Oct, 2021 Given a string of length L. The task is to convert the string into a grid.Examples: Input : str = "haveaniceday" Output : have anic eday Explanation: k is the separator. If k is 4 then the output will be "have anic eday" Input :str = "geeksforgeeks" Output : geek sfor geek s Note: & l = length of the string Approach: Without using an inbuilt functionMake a 2d character array of (rows * column) size.Assign the value K which is a column value.Print the 2d character array. Without using an inbuilt function Make a 2d character array of (rows * column) size. Assign the value K which is a column value. Print the 2d character array. Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // Function to string into grid formvoid gridStr(string str){ int l = str.length(); int k = 0, row, column; row = floor(sqrt(l)); column = ceil(sqrt(l)); if (row * column < l) row = column; char s[row][column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { s[i][j] = str[k]; k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i][j] == '\0') break; cout << s[i][j]; } cout << endl; }} // Driver codeint main(){ string str = "GEEKSFORGEEKS"; gridStr(str); return 0;} // Java implementation of the// above approachclass GFG{ // Function to string into grid form static void gridStr(String str) { int l = str.length(); int k = 0, row, column; row = (int) Math.floor(Math.sqrt(l)); column = (int) Math.ceil(Math.sqrt(l)); if (row * column < l) { row = column; } char s[][] = new char[row][column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if(k < str.length()) s[i][j] = str.charAt(k); k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i][j] == 0) { break; } System.out.print(s[i][j]); } System.out.println(""); } } // Driver code public static void main(String[] args) { String str = "GEEKSFORGEEKS"; gridStr(str); }} //This code is contributed by Rajput-Ji # Python3 implementation of the# above approach # Function to string into grid formdef function(str, k): for i in range(len(str)): if i %k == 0: sub = str[i:i+k] lst = [] for j in sub: lst.append(j) print(' '.join(lst)) function("GEEKSFORGEEKS", 5) /* This code contributed by nsew1999gokulcvan */ // C# implementation of the// above approachusing System; class GFG{ // Function to string into grid form static void gridStr(String str) { int l = str.Length; int k = 0, row, column; row = (int) Math.Floor(Math.Sqrt(l)); column = (int) Math.Ceiling(Math.Sqrt(l)); if (row * column < l) { row = column; } char [,]s = new char[row,column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if(k < str.Length) s[i,j] = str[k]; k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i, j] == 0) { break; } Console.Write(s[i, j]); } Console.WriteLine(""); } } // Driver code public static void Main() { String str = "GEEKSFORGEEKS"; gridStr(str); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP implementation of the// above approach // Function to string into grid formfunction gridStr($str){ $l = strlen($str); $k = 0; $row = floor(sqrt($l)); $column = ceil(sqrt($l)); if ($row * $column < $l) $row = $column; $s = array_fill(0, $row, array_fill(0, $column, "")); // convert the string into grid for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { if(!empty($str[$k])) $s[$i][$j] = $str[$k]; $k++; } } // Printing the grid for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { if ($s[$i][$j] == '\0') break; echo $s[$i][$j]; } echo "\n"; }} // Driver code$str = "GEEKSFORGEEKS";gridStr($str); // This code is contributed by mits?> <script> // Javascript implementation of the above approach // Function to string into grid form function gridStr(str) { let l = str.length; let k = 0, row, column; row = Math.floor(Math.sqrt(l)); column = Math.ceil(Math.sqrt(l)); if (row * column < l) { row = column; } let s = new Array(row); for (let i = 0; i < row; i++) { s[i] = new Array(column); for (let j = 0; j < column; j++) { s[i][j] = 0; } } // convert the string into grid for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if(k < str.length) s[i][j] = str[k]; k++; } } // Printing the grid for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if (s[i][j] == 0) { break; } document.write(s[i][j]); } document.write("</br>"); } } let str = "GEEKSFORGEEKS"; gridStr(str); // This code is contributed by decode2207.</script> GEEK SFOR GEEK S ankthon Rajput-Ji princiraj1992 Mithun Kumar hemantsonirbz nsew1999gokulcvan decode2207 sumitgumber28 school-programming Matrix Strings Strings Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flood fill Algorithm - how to implement fill() in paint? Breadth First Traversal ( BFS ) on a 2D array Program to find the Sum of each Row and each Column of a Matrix Python program to add two Matrices Mathematics | L U Decomposition of a System of Linear Equations Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24921, "s": 24893, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25007, "s": 24921, "text": "Given a string of length L. The task is to convert the string into a grid.Examples: " }, { "code": null, "e": 25273, "s": 25007, "text": "Input : str = \"haveaniceday\"\nOutput : have\n anic\n eday \n\nExplanation: k is the separator. If k is 4 then the output will be \"have\n anic\n eday\"\n\nInput :str = \"geeksforgeeks\"\nOutput : geek\n sfor\n geek\n s" }, { "code": null, "e": 25308, "s": 25273, "text": "Note: & l = length of the string " }, { "code": null, "e": 25320, "s": 25308, "text": "Approach: " }, { "code": null, "e": 25476, "s": 25320, "text": "Without using an inbuilt functionMake a 2d character array of (rows * column) size.Assign the value K which is a column value.Print the 2d character array." }, { "code": null, "e": 25510, "s": 25476, "text": "Without using an inbuilt function" }, { "code": null, "e": 25561, "s": 25510, "text": "Make a 2d character array of (rows * column) size." }, { "code": null, "e": 25605, "s": 25561, "text": "Assign the value K which is a column value." }, { "code": null, "e": 25635, "s": 25605, "text": "Print the 2d character array." }, { "code": null, "e": 25688, "s": 25635, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25692, "s": 25688, "text": "C++" }, { "code": null, "e": 25697, "s": 25692, "text": "Java" }, { "code": null, "e": 25705, "s": 25697, "text": "Python3" }, { "code": null, "e": 25708, "s": 25705, "text": "C#" }, { "code": null, "e": 25712, "s": 25708, "text": "PHP" }, { "code": null, "e": 25723, "s": 25712, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to string into grid formvoid gridStr(string str){ int l = str.length(); int k = 0, row, column; row = floor(sqrt(l)); column = ceil(sqrt(l)); if (row * column < l) row = column; char s[row][column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { s[i][j] = str[k]; k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i][j] == '\\0') break; cout << s[i][j]; } cout << endl; }} // Driver codeint main(){ string str = \"GEEKSFORGEEKS\"; gridStr(str); return 0;}", "e": 26492, "s": 25723, "text": null }, { "code": "// Java implementation of the// above approachclass GFG{ // Function to string into grid form static void gridStr(String str) { int l = str.length(); int k = 0, row, column; row = (int) Math.floor(Math.sqrt(l)); column = (int) Math.ceil(Math.sqrt(l)); if (row * column < l) { row = column; } char s[][] = new char[row][column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if(k < str.length()) s[i][j] = str.charAt(k); k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i][j] == 0) { break; } System.out.print(s[i][j]); } System.out.println(\"\"); } } // Driver code public static void main(String[] args) { String str = \"GEEKSFORGEEKS\"; gridStr(str); }} //This code is contributed by Rajput-Ji", "e": 27671, "s": 26492, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to string into grid formdef function(str, k): for i in range(len(str)): if i %k == 0: sub = str[i:i+k] lst = [] for j in sub: lst.append(j) print(' '.join(lst)) function(\"GEEKSFORGEEKS\", 5) /* This code contributed by nsew1999gokulcvan */", "e": 28041, "s": 27671, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG{ // Function to string into grid form static void gridStr(String str) { int l = str.Length; int k = 0, row, column; row = (int) Math.Floor(Math.Sqrt(l)); column = (int) Math.Ceiling(Math.Sqrt(l)); if (row * column < l) { row = column; } char [,]s = new char[row,column]; // convert the string into grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if(k < str.Length) s[i,j] = str[k]; k++; } } // Printing the grid for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (s[i, j] == 0) { break; } Console.Write(s[i, j]); } Console.WriteLine(\"\"); } } // Driver code public static void Main() { String str = \"GEEKSFORGEEKS\"; gridStr(str); }} /* This code contributed by PrinciRaj1992 */", "e": 29209, "s": 28041, "text": null }, { "code": "<?php// PHP implementation of the// above approach // Function to string into grid formfunction gridStr($str){ $l = strlen($str); $k = 0; $row = floor(sqrt($l)); $column = ceil(sqrt($l)); if ($row * $column < $l) $row = $column; $s = array_fill(0, $row, array_fill(0, $column, \"\")); // convert the string into grid for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { if(!empty($str[$k])) $s[$i][$j] = $str[$k]; $k++; } } // Printing the grid for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { if ($s[$i][$j] == '\\0') break; echo $s[$i][$j]; } echo \"\\n\"; }} // Driver code$str = \"GEEKSFORGEEKS\";gridStr($str); // This code is contributed by mits?>", "e": 30066, "s": 29209, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to string into grid form function gridStr(str) { let l = str.length; let k = 0, row, column; row = Math.floor(Math.sqrt(l)); column = Math.ceil(Math.sqrt(l)); if (row * column < l) { row = column; } let s = new Array(row); for (let i = 0; i < row; i++) { s[i] = new Array(column); for (let j = 0; j < column; j++) { s[i][j] = 0; } } // convert the string into grid for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if(k < str.length) s[i][j] = str[k]; k++; } } // Printing the grid for (let i = 0; i < row; i++) { for (let j = 0; j < column; j++) { if (s[i][j] == 0) { break; } document.write(s[i][j]); } document.write(\"</br>\"); } } let str = \"GEEKSFORGEEKS\"; gridStr(str); // This code is contributed by decode2207.</script>", "e": 31343, "s": 30066, "text": null }, { "code": null, "e": 31360, "s": 31343, "text": "GEEK\nSFOR\nGEEK\nS" }, { "code": null, "e": 31370, "s": 31362, "text": "ankthon" }, { "code": null, "e": 31380, "s": 31370, "text": "Rajput-Ji" }, { "code": null, "e": 31394, "s": 31380, "text": "princiraj1992" }, { "code": null, "e": 31407, "s": 31394, "text": "Mithun Kumar" }, { "code": null, "e": 31421, "s": 31407, "text": "hemantsonirbz" }, { "code": null, "e": 31439, "s": 31421, "text": "nsew1999gokulcvan" }, { "code": null, "e": 31450, "s": 31439, "text": "decode2207" }, { "code": null, "e": 31464, "s": 31450, "text": "sumitgumber28" }, { "code": null, "e": 31483, "s": 31464, "text": "school-programming" }, { "code": null, "e": 31490, "s": 31483, "text": "Matrix" }, { "code": null, "e": 31498, "s": 31490, "text": "Strings" }, { "code": null, "e": 31506, "s": 31498, "text": "Strings" }, { "code": null, "e": 31513, "s": 31506, "text": "Matrix" }, { "code": null, "e": 31611, "s": 31513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31668, "s": 31611, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 31714, "s": 31668, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 31778, "s": 31714, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 31813, "s": 31778, "text": "Python program to add two Matrices" }, { "code": null, "e": 31877, "s": 31813, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 31923, "s": 31877, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31948, "s": 31923, "text": "Reverse a string in Java" }, { "code": null, "e": 31982, "s": 31948, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32042, "s": 31982, "text": "Write a program to print all permutations of a given string" } ]
Exploratory Data Analysis in R of Global Data from GapMinder | by Hamza Bendemra, Ph.D. | Towards Data Science
In this post, I perform an Exploratory Data Analysis (EDA) on two data sets from GapMinder. This post includes the R code used (also found in this GitHub repo). In summary: Method: Exploratory Data Analysis (EDA), Correlation, Linear Regression Program/Platform: R/RStudio Sources: World Health Organization, World Bank In this data analysis, I use data available on GapMinder’s data webpage. Specifically, I focused on: GDP/capita (US$, inflation-adjusted) from the World Bank (WB) and Prevalence of HIV among adults aged 15–49 (%) from the World Health Organisation (WHO). The question I am asking in this analysis: Is there a correlation between GDP per Capita and prevalence of HIV in the 15–49 age bracket? And if yes, how strong is that correlation? My expectation is that there is a negative correlation between GDP per capita and HIV Prevalence; meaning that poorer countries have higher prevalence of HIV. Let’s do some initial data wrangling in R on the CSV files downloaded from GapMinder to prep our data for analysis. The data from GapMinder was in the form of CSV files that needed to be reorganised according to key-value pairs in the original CSV tables. I used the function gather() from the amazing ‘tidyr’ library. Let’s have a look at the structure of the resulting data frame structure and determine what time frame this data set covers: ## 'data.frame': 14300 obs. of 3 variables: ## $ Income per person (fixed 2000 US$): Factor w/ 275 levels "Abkhazia","Afghanistan",..: 1 2 3 5 6 7 8 9 10 12 ... ## $ Year : int 1960 1960 1960 1960 1960 1960 1960 1960 1960 1960 ... ## $ GDP : num NA NA NA NA 1280 ... ## [1] 1960 2011 The resulting dataframe features 14,300 observations of 3 variables (Country, Year, GDP). The column ‘Country’ lists 275 countries. GDP per Capita is provided for the 275 countries from 1960–2011. Let’s perform similar data tidying on the HIV prevalence data. Again, I’ll be using the function gather() from the ‘tidyr’ library. Again, let’s have a look at the structure of the resulting data frame structure: ## 'data.frame': 9075 obs. of 3 variables: ## $ Estimated HIV Prevalence% - (Ages 15-49): Factor w/ 275 levels "Abkhazia","Afghanistan",..: 1 2 3 5 6 7 8 9 10 12 ... ## $ Year : int 1979 1979 1979 1979 1979 1979 1979 1979 1979 1979 ... ## $ HIV_prev : num NA NA NA NA NA ... The resulting dataframe features 9075 observations of 3 variables (Country, Year, Estimated HIV Prevalence). The column ‘Country’ lists 275 countries. GDP per Capita is provided for the 275 countries from 1979–2011. Let’s combine the two dataframes to allow us to compare GDP per capita and HIV prevalence. I’m using the merge() function. Let’s then have a look at the structure of the resulting dataframe. ## 'data.frame': 9075 obs. of 4 variables: ## $ Country : Factor w/ 275 levels "Abkhazia","Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ... ## $ Year : int 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 ... ## $ GDP : num NA NA NA NA NA NA NA NA NA NA ... ## $ HIV_prev: num NA NA NA NA NA NA NA NA NA NA ... We now have a data frame for our subsequent data exploration. This dataframe is organised into four columns: (i) country, (ii) year, (iii) GDP/Capita for that country in that year, and (iv) HIV Prevalence for that country in that year. Datasets often feature missing data. I suspect it would be the case with this dataset also even if it was sourced from an official organisation. Let’s have a look at the percentage of missing GDP data in the combined dataframe. ## [1] 35.30579 About 35.3% of the GDP per Capita column in the combined dataframe have missing data. This is quite substantial and is most likely due the fact that consistent measurements of GDP are costly and have only started in the last few decades (N.B. the World Bank itself was founded in 1945 after WWII). Rather than replacing the missing data with an average or an estimate, missing data will be dismissed (i.e. not plotted) in the subsequent analysis. Let’s have a look at the percentage of missing data on the HIV Prevalence front. ## [1] 63.62534 We have an even higher rate at 63.6% for HIV Prevalence missing data in the combined dataframe. This is of course due to the fact that the initial dataframe from the World Health Organisation included measurement for a timeframe starting 1979, whereas our combined dataframe timeframe starts in 1960. The lag in consistent measurements of HIV associated metrics have only really been performed on a large scale from the early-1980s when HIV/Aids became a recognised major health crisis. Let’s get an initial sense of the type of distribution we may getting from both data sets. For the GDP per capita: ## Min. - 1st Qu. - Median - Mean - 3rd Qu. - Max. - NA's ## 54.51 - 590.26 - 2038.88 - 7315.07 - 9239.73 - 108111.21 - 3204 Regarding the HIV prevalence: ## Min. - 1st Qu. - Median - Mean - 3rd Qu. - Max. - NA's ## 0.010 - 0.100 - 0.300 - 1.743 - 1.200 - 26.500 - 5774 This quick glance clearly shows that some countries in our dataframe are considerable pulling the distribution’s mean up (compared to the median). This is particularly the case with the HIV Prevalence data. In this section, I generate various plots (using ggplot) to get an overview of the distribution and attempt to identify trends and patterns. First, we look at the overall data set and generate a scatter plot of GDP per Capita for the 275 countries listed in our dataset from 1960 to 2011. We also overlay the mean and the upper-lower limits (5%; 95%) of GDPs on our plot. This will give us a better understanding of where the bulk of our distribution lies. The plot shows an overall increasing trend in Global GDP between 1960 and 2011. The bulk of the data falls at a maximum GDP per Capita of USD 30,000 (xUSD 2,000). Let’s look at the data set on HIV Prevalence by generating a scatter plot of HIV Prevalence for the 275 countries listed in our dataset from 1960 to 2011. Similarly to GPD Per Capita, we also overlay the mean and the upper-lower limits (5%; 95%) of HIV prevalence on our plot. We’ll focus on data from 1985 to 2011. According to our data, the rate of HIV prevalence has increased between 1985 and 2011 with a stagnation in the mean from the early 2000s and slight decline since 2005. This would correspond to advances in preventative measures to reduce the incidence and likelihood of contracting HIV. Now, let’s focus on the combined dataframe we created to earlier to investigate the correlation between the two variables of interest. To have a first look at correlation, let’s plot HIV Prevalance v. GDP per Capita. The scatter plot clearly indicates that the lower GDP per Capita data points (i.e. countries) have a much higher HIV prevalence compared countries with higher GDP per Capita. Let’s take a closer by creating a plot with a square root scale applied to the x-axis to further emphasise countries with lower GDP per capita. We’ll also use the R function geom_smooth() to perform a simple linear regression to better visualise the relationship between the two variables. The scatter plot above further indicates that countries which shower GDP per capita have on average higher HIV prevalence. Let’s calculate the correlation factor between both variables using Pearson’s method. ## ## Pearson's product-moment correlation ## ## data: gdp.HIV$HIV_prev and gdp.HIV$GDP ## t = -10.938, df = 3183, p-value < 2.2e-16 ## alternative hypothesis: true correlation is not equal to 0 ## 95 percent confidence interval: ## -0.2235800 -0.1566303 ## sample estimates: ## cor ## -0.1903264 The resulting correlation factor is -0.19 which is a negative but weak correlation. This matches with the linear regression plotted above. This negative but weak correlation negative correlation matches other published results which found that an individual’s wealth (rather that the GDP per Capita of the country in which that individual resides) is a stronger indicator of HIV prevalence within an individual’s particular community. In this project, we collected data from public sources (GapMinder, WHO, WB). We performed data wrangling and an initial exploratory data analysis. Then, we derived a correlation factor and applied linear regression to assess the linear relationship between two variables of interest (GDP per capita, HIV prevalence).
[ { "code": null, "e": 344, "s": 171, "text": "In this post, I perform an Exploratory Data Analysis (EDA) on two data sets from GapMinder. This post includes the R code used (also found in this GitHub repo). In summary:" }, { "code": null, "e": 416, "s": 344, "text": "Method: Exploratory Data Analysis (EDA), Correlation, Linear Regression" }, { "code": null, "e": 444, "s": 416, "text": "Program/Platform: R/RStudio" }, { "code": null, "e": 491, "s": 444, "text": "Sources: World Health Organization, World Bank" }, { "code": null, "e": 592, "s": 491, "text": "In this data analysis, I use data available on GapMinder’s data webpage. Specifically, I focused on:" }, { "code": null, "e": 658, "s": 592, "text": "GDP/capita (US$, inflation-adjusted) from the World Bank (WB) and" }, { "code": null, "e": 746, "s": 658, "text": "Prevalence of HIV among adults aged 15–49 (%) from the World Health Organisation (WHO)." }, { "code": null, "e": 789, "s": 746, "text": "The question I am asking in this analysis:" }, { "code": null, "e": 927, "s": 789, "text": "Is there a correlation between GDP per Capita and prevalence of HIV in the 15–49 age bracket? And if yes, how strong is that correlation?" }, { "code": null, "e": 1086, "s": 927, "text": "My expectation is that there is a negative correlation between GDP per capita and HIV Prevalence; meaning that poorer countries have higher prevalence of HIV." }, { "code": null, "e": 1202, "s": 1086, "text": "Let’s do some initial data wrangling in R on the CSV files downloaded from GapMinder to prep our data for analysis." }, { "code": null, "e": 1405, "s": 1202, "text": "The data from GapMinder was in the form of CSV files that needed to be reorganised according to key-value pairs in the original CSV tables. I used the function gather() from the amazing ‘tidyr’ library." }, { "code": null, "e": 1530, "s": 1405, "text": "Let’s have a look at the structure of the resulting data frame structure and determine what time frame this data set covers:" }, { "code": null, "e": 1797, "s": 1530, "text": "## 'data.frame': 14300 obs. of 3 variables: ## $ Income per person (fixed 2000 US$): Factor w/ 275 levels \"Abkhazia\",\"Afghanistan\",..: 1 2 3 5 6 7 8 9 10 12 ... ## $ Year : int 1960 1960 1960 1960 1960 1960 1960 1960 1960 1960 ... ## $ GDP : num NA NA NA NA 1280 ..." }, { "code": null, "e": 1814, "s": 1797, "text": "## [1] 1960 2011" }, { "code": null, "e": 2011, "s": 1814, "text": "The resulting dataframe features 14,300 observations of 3 variables (Country, Year, GDP). The column ‘Country’ lists 275 countries. GDP per Capita is provided for the 275 countries from 1960–2011." }, { "code": null, "e": 2143, "s": 2011, "text": "Let’s perform similar data tidying on the HIV prevalence data. Again, I’ll be using the function gather() from the ‘tidyr’ library." }, { "code": null, "e": 2224, "s": 2143, "text": "Again, let’s have a look at the structure of the resulting data frame structure:" }, { "code": null, "e": 2499, "s": 2224, "text": "## 'data.frame': 9075 obs. of 3 variables: ## $ Estimated HIV Prevalence% - (Ages 15-49): Factor w/ 275 levels \"Abkhazia\",\"Afghanistan\",..: 1 2 3 5 6 7 8 9 10 12 ... ## $ Year : int 1979 1979 1979 1979 1979 1979 1979 1979 1979 1979 ... ## $ HIV_prev : num NA NA NA NA NA ..." }, { "code": null, "e": 2715, "s": 2499, "text": "The resulting dataframe features 9075 observations of 3 variables (Country, Year, Estimated HIV Prevalence). The column ‘Country’ lists 275 countries. GDP per Capita is provided for the 275 countries from 1979–2011." }, { "code": null, "e": 2906, "s": 2715, "text": "Let’s combine the two dataframes to allow us to compare GDP per capita and HIV prevalence. I’m using the merge() function. Let’s then have a look at the structure of the resulting dataframe." }, { "code": null, "e": 3210, "s": 2906, "text": "## 'data.frame': 9075 obs. of 4 variables: ## $ Country : Factor w/ 275 levels \"Abkhazia\",\"Afghanistan\",..: 1 1 1 1 1 1 1 1 1 1 ... ## $ Year : int 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 ... ## $ GDP : num NA NA NA NA NA NA NA NA NA NA ... ## $ HIV_prev: num NA NA NA NA NA NA NA NA NA NA ..." }, { "code": null, "e": 3446, "s": 3210, "text": "We now have a data frame for our subsequent data exploration. This dataframe is organised into four columns: (i) country, (ii) year, (iii) GDP/Capita for that country in that year, and (iv) HIV Prevalence for that country in that year." }, { "code": null, "e": 3674, "s": 3446, "text": "Datasets often feature missing data. I suspect it would be the case with this dataset also even if it was sourced from an official organisation. Let’s have a look at the percentage of missing GDP data in the combined dataframe." }, { "code": null, "e": 3690, "s": 3674, "text": "## [1] 35.30579" }, { "code": null, "e": 3988, "s": 3690, "text": "About 35.3% of the GDP per Capita column in the combined dataframe have missing data. This is quite substantial and is most likely due the fact that consistent measurements of GDP are costly and have only started in the last few decades (N.B. the World Bank itself was founded in 1945 after WWII)." }, { "code": null, "e": 4137, "s": 3988, "text": "Rather than replacing the missing data with an average or an estimate, missing data will be dismissed (i.e. not plotted) in the subsequent analysis." }, { "code": null, "e": 4218, "s": 4137, "text": "Let’s have a look at the percentage of missing data on the HIV Prevalence front." }, { "code": null, "e": 4234, "s": 4218, "text": "## [1] 63.62534" }, { "code": null, "e": 4535, "s": 4234, "text": "We have an even higher rate at 63.6% for HIV Prevalence missing data in the combined dataframe. This is of course due to the fact that the initial dataframe from the World Health Organisation included measurement for a timeframe starting 1979, whereas our combined dataframe timeframe starts in 1960." }, { "code": null, "e": 4721, "s": 4535, "text": "The lag in consistent measurements of HIV associated metrics have only really been performed on a large scale from the early-1980s when HIV/Aids became a recognised major health crisis." }, { "code": null, "e": 4836, "s": 4721, "text": "Let’s get an initial sense of the type of distribution we may getting from both data sets. For the GDP per capita:" }, { "code": null, "e": 4961, "s": 4836, "text": "## Min. - 1st Qu. - Median - Mean - 3rd Qu. - Max. - NA's ## 54.51 - 590.26 - 2038.88 - 7315.07 - 9239.73 - 108111.21 - 3204" }, { "code": null, "e": 4991, "s": 4961, "text": "Regarding the HIV prevalence:" }, { "code": null, "e": 5106, "s": 4991, "text": "## Min. - 1st Qu. - Median - Mean - 3rd Qu. - Max. - NA's ## 0.010 - 0.100 - 0.300 - 1.743 - 1.200 - 26.500 - 5774" }, { "code": null, "e": 5313, "s": 5106, "text": "This quick glance clearly shows that some countries in our dataframe are considerable pulling the distribution’s mean up (compared to the median). This is particularly the case with the HIV Prevalence data." }, { "code": null, "e": 5454, "s": 5313, "text": "In this section, I generate various plots (using ggplot) to get an overview of the distribution and attempt to identify trends and patterns." }, { "code": null, "e": 5602, "s": 5454, "text": "First, we look at the overall data set and generate a scatter plot of GDP per Capita for the 275 countries listed in our dataset from 1960 to 2011." }, { "code": null, "e": 5770, "s": 5602, "text": "We also overlay the mean and the upper-lower limits (5%; 95%) of GDPs on our plot. This will give us a better understanding of where the bulk of our distribution lies." }, { "code": null, "e": 5933, "s": 5770, "text": "The plot shows an overall increasing trend in Global GDP between 1960 and 2011. The bulk of the data falls at a maximum GDP per Capita of USD 30,000 (xUSD 2,000)." }, { "code": null, "e": 6088, "s": 5933, "text": "Let’s look at the data set on HIV Prevalence by generating a scatter plot of HIV Prevalence for the 275 countries listed in our dataset from 1960 to 2011." }, { "code": null, "e": 6249, "s": 6088, "text": "Similarly to GPD Per Capita, we also overlay the mean and the upper-lower limits (5%; 95%) of HIV prevalence on our plot. We’ll focus on data from 1985 to 2011." }, { "code": null, "e": 6535, "s": 6249, "text": "According to our data, the rate of HIV prevalence has increased between 1985 and 2011 with a stagnation in the mean from the early 2000s and slight decline since 2005. This would correspond to advances in preventative measures to reduce the incidence and likelihood of contracting HIV." }, { "code": null, "e": 6752, "s": 6535, "text": "Now, let’s focus on the combined dataframe we created to earlier to investigate the correlation between the two variables of interest. To have a first look at correlation, let’s plot HIV Prevalance v. GDP per Capita." }, { "code": null, "e": 6927, "s": 6752, "text": "The scatter plot clearly indicates that the lower GDP per Capita data points (i.e. countries) have a much higher HIV prevalence compared countries with higher GDP per Capita." }, { "code": null, "e": 7217, "s": 6927, "text": "Let’s take a closer by creating a plot with a square root scale applied to the x-axis to further emphasise countries with lower GDP per capita. We’ll also use the R function geom_smooth() to perform a simple linear regression to better visualise the relationship between the two variables." }, { "code": null, "e": 7340, "s": 7217, "text": "The scatter plot above further indicates that countries which shower GDP per capita have on average higher HIV prevalence." }, { "code": null, "e": 7426, "s": 7340, "text": "Let’s calculate the correlation factor between both variables using Pearson’s method." }, { "code": null, "e": 7723, "s": 7426, "text": "## ## Pearson's product-moment correlation ## ## data: gdp.HIV$HIV_prev and gdp.HIV$GDP ## t = -10.938, df = 3183, p-value < 2.2e-16 ## alternative hypothesis: true correlation is not equal to 0 ## 95 percent confidence interval: ## -0.2235800 -0.1566303 ## sample estimates: ## cor ## -0.1903264" }, { "code": null, "e": 7862, "s": 7723, "text": "The resulting correlation factor is -0.19 which is a negative but weak correlation. This matches with the linear regression plotted above." }, { "code": null, "e": 8158, "s": 7862, "text": "This negative but weak correlation negative correlation matches other published results which found that an individual’s wealth (rather that the GDP per Capita of the country in which that individual resides) is a stronger indicator of HIV prevalence within an individual’s particular community." } ]
Container and Empty Tags in HTML - GeeksforGeeks
06 Jun, 2021 HTML uses predefined tags that tell the browser how to display the content. Tags are nothing but some instructions that are enclosed in angle braces(i.e., <>). Tags are used in many places of the webpage but many users are often confused about some tags whether it is a container or an empty tag. They get this confusion because they don’t know for what tag there should be an ending tag along with the opening tag or not. There are two types of tags in HTML: Empty Container Now, let us see the definitions and examples of the most commonly used HTML container and empty tags. Container tags are generally divided into three parts, i.e., opening tag, content(which will display on the browser), and closing tag. In the content part, they can also contain some other tags. These opening and closing tags are used in pairs which are start tag and end tag, which is often called ON and OFF tags. If you forget to close the container tag, the browser applies the effect of the opening tag until the end of the page. So be careful while working with container tags. The majority of tags present in HTML are container tags. Syntax: <tag_name> ...</tag_name> Some commonly used container tags are: 1. Essential Tags: Following tags are used to create the structure of the webpage: <html>....</html>: This marks the beginning and ending of the webpage also it tells that the document is an HTML document. This contains all other tags in between these tags which are considered for making a webpage. <head>...</head>: This tag is used to define the head part of the document which contains the information related to the webpage. <title>...</title>: This tag stores the description of the web page, whatever given in these tags appears on the tab name while opened by the browser. It is described in the head tag. <body>....</body>: This tag is used to display all the information or data, i.e, text, images, hyperlinks videos, etc., on the webpage to the user. 2. Headings: Following tags are used for headings: <h1>....</h1> to <h6>...</h6>: It is used for including headings of different sizes ranging from 1 to 6. 3. Text formatters: Following tags are used for text formatting: <p>....</p>: When paragraphs are needed to be included, this tag is used <b>....</b>: Makes the contained text to bold. <i>...</i>: Makes the contained text to italic. 4. HyperLinks: Following tag is used to define a hyperlink in the webpage: <a href=”link.com”>...</a>: When we link some other webpages we add the hyper links to other webpages using this <a ...>...</a>tag. 5. Button tag: Following tag is used to create a click button: <button>...</button>: This is used in many ways but mainly used to manipulate dom by adding events and many more. 6. Division tag: Following tag is used to create a division: <div>....</div>: This defines a section in a document. The webpage can be divided to different sections using the <div>....</div> tag. 7. Iframe tag: Following tag is used for inline framing: <iframe src=”link.com> </iframe>: When some other document is to be embedded like some video or image into HTML we use this tag. 8. Navigation tag: Following tag is used to set a navigation link: <nav>...</nav>: Defines a navigation bar that contains a set of menu or a menu of hyperlinks. 9. Script tag: Following tag is used to add JavaScript code to the webpage: <script>...</script> : This contains the javascript code that adds interactivity to the webpage. 10. Lists: Following tags are used to write data in the form of ordered and unordered lists: <ol>...</ol>: This tag is used to create ordered lists. <ul>...</ul>: This tag is used to create unordered lists. <li>...</li>: This tag is used to add list items. The tags that do not contain any closing tags are known as empty tags. Empty tags contain only the opening tag but they perform some action in the webpage. Syntax: <tag_name> Some commonly used empty tags are: <br>: Inerts a line break in a webpage wherever needed.<hr>: Inserts a horizontal line wherever needed in the webpage.<img>: This tag is used to display the images on the webpage which were given in the src attribute of the tag.<input>: This is mainly used with forms to take the input from the user and we can also define the type of the input.<link>: When we store our CSS in an external file this can be used to link external files and documents to the webpage and it is mainly used to link CSS files.<meta>: Contains all metadata of the webpage. Metadata is the data about data and is described in the head tag.<source>: When an external media source is needed to be included in the webpage. source tag is used to insert any media source like audio, video etc... in our webpage. <br>: Inerts a line break in a webpage wherever needed. <hr>: Inserts a horizontal line wherever needed in the webpage. <img>: This tag is used to display the images on the webpage which were given in the src attribute of the tag. <input>: This is mainly used with forms to take the input from the user and we can also define the type of the input. <link>: When we store our CSS in an external file this can be used to link external files and documents to the webpage and it is mainly used to link CSS files. <meta>: Contains all metadata of the webpage. Metadata is the data about data and is described in the head tag. <source>: When an external media source is needed to be included in the webpage. source tag is used to insert any media source like audio, video etc... in our webpage. Example: This example demonstrates the use of container and empty tags: HTML <!DOCTYPE html><html lang="en"><head> <!--Meta data--> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--The description written on title tag get appeared as browser tab name--> <title>Geeks For Geeks </title> </head><!-- Whatever content in body tag appears on the webpage--><body> <!--Headings--> <h1> Geeks For Geeks </h1> <h2> Geeks For Geeks </h2> <h3> Geeks For Geeks </h3> <h4>Geeks For Geeks </h4> <h5> Geeks For Geeks</h5> <h6> Geeks For Geeks </h6> <p> This is a paragraph.</p> <!--For horizontal line --> <hr> <!--For paragraphs --> <p> Geeks for geeks is a computer science portal for geeks. </p> <hr> <p> This is a <br> line break </p> <h4> Link </h4> <a href="https://www.geeksforgeeks.org/"> Geeks For Geeks</a> <!--For ordered lists--> <ol> <li> Item1</li> <li> Item2 </li> <li> Item3 </li> <li> Item4</li> </ol> </body></html> Output: HTML-Tags Picked class 6 HTML School Learning School Programming HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Computers What are Different Output Devices? What is Computer Networking? Software and its Types What is Internet? Definition, Uses, Working, Advantages and Disadvantages 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
[ { "code": null, "e": 33113, "s": 33085, "text": "\n06 Jun, 2021" }, { "code": null, "e": 33573, "s": 33113, "text": "HTML uses predefined tags that tell the browser how to display the content. Tags are nothing but some instructions that are enclosed in angle braces(i.e., <>). Tags are used in many places of the webpage but many users are often confused about some tags whether it is a container or an empty tag. They get this confusion because they don’t know for what tag there should be an ending tag along with the opening tag or not. There are two types of tags in HTML:" }, { "code": null, "e": 33579, "s": 33573, "text": "Empty" }, { "code": null, "e": 33589, "s": 33579, "text": "Container" }, { "code": null, "e": 33691, "s": 33589, "text": "Now, let us see the definitions and examples of the most commonly used HTML container and empty tags." }, { "code": null, "e": 34233, "s": 33691, "text": "Container tags are generally divided into three parts, i.e., opening tag, content(which will display on the browser), and closing tag. In the content part, they can also contain some other tags. These opening and closing tags are used in pairs which are start tag and end tag, which is often called ON and OFF tags. If you forget to close the container tag, the browser applies the effect of the opening tag until the end of the page. So be careful while working with container tags. The majority of tags present in HTML are container tags. " }, { "code": null, "e": 34241, "s": 34233, "text": "Syntax:" }, { "code": null, "e": 34268, "s": 34241, "text": "<tag_name> ...</tag_name> " }, { "code": null, "e": 34307, "s": 34268, "text": "Some commonly used container tags are:" }, { "code": null, "e": 34390, "s": 34307, "text": "1. Essential Tags: Following tags are used to create the structure of the webpage:" }, { "code": null, "e": 34607, "s": 34390, "text": "<html>....</html>: This marks the beginning and ending of the webpage also it tells that the document is an HTML document. This contains all other tags in between these tags which are considered for making a webpage." }, { "code": null, "e": 34737, "s": 34607, "text": "<head>...</head>: This tag is used to define the head part of the document which contains the information related to the webpage." }, { "code": null, "e": 34921, "s": 34737, "text": "<title>...</title>: This tag stores the description of the web page, whatever given in these tags appears on the tab name while opened by the browser. It is described in the head tag." }, { "code": null, "e": 35069, "s": 34921, "text": "<body>....</body>: This tag is used to display all the information or data, i.e, text, images, hyperlinks videos, etc., on the webpage to the user." }, { "code": null, "e": 35120, "s": 35069, "text": "2. Headings: Following tags are used for headings:" }, { "code": null, "e": 35225, "s": 35120, "text": "<h1>....</h1> to <h6>...</h6>: It is used for including headings of different sizes ranging from 1 to 6." }, { "code": null, "e": 35290, "s": 35225, "text": "3. Text formatters: Following tags are used for text formatting:" }, { "code": null, "e": 35363, "s": 35290, "text": "<p>....</p>: When paragraphs are needed to be included, this tag is used" }, { "code": null, "e": 35410, "s": 35363, "text": "<b>....</b>: Makes the contained text to bold." }, { "code": null, "e": 35458, "s": 35410, "text": "<i>...</i>: Makes the contained text to italic." }, { "code": null, "e": 35533, "s": 35458, "text": "4. HyperLinks: Following tag is used to define a hyperlink in the webpage:" }, { "code": null, "e": 35665, "s": 35533, "text": "<a href=”link.com”>...</a>: When we link some other webpages we add the hyper links to other webpages using this <a ...>...</a>tag." }, { "code": null, "e": 35729, "s": 35665, "text": "5. Button tag: Following tag is used to create a click button:" }, { "code": null, "e": 35843, "s": 35729, "text": "<button>...</button>: This is used in many ways but mainly used to manipulate dom by adding events and many more." }, { "code": null, "e": 35904, "s": 35843, "text": "6. Division tag: Following tag is used to create a division:" }, { "code": null, "e": 36039, "s": 35904, "text": "<div>....</div>: This defines a section in a document. The webpage can be divided to different sections using the <div>....</div> tag." }, { "code": null, "e": 36096, "s": 36039, "text": "7. Iframe tag: Following tag is used for inline framing:" }, { "code": null, "e": 36225, "s": 36096, "text": "<iframe src=”link.com> </iframe>: When some other document is to be embedded like some video or image into HTML we use this tag." }, { "code": null, "e": 36292, "s": 36225, "text": "8. Navigation tag: Following tag is used to set a navigation link:" }, { "code": null, "e": 36386, "s": 36292, "text": "<nav>...</nav>: Defines a navigation bar that contains a set of menu or a menu of hyperlinks." }, { "code": null, "e": 36463, "s": 36386, "text": "9. Script tag: Following tag is used to add JavaScript code to the webpage:" }, { "code": null, "e": 36560, "s": 36463, "text": "<script>...</script> : This contains the javascript code that adds interactivity to the webpage." }, { "code": null, "e": 36653, "s": 36560, "text": "10. Lists: Following tags are used to write data in the form of ordered and unordered lists:" }, { "code": null, "e": 36709, "s": 36653, "text": "<ol>...</ol>: This tag is used to create ordered lists." }, { "code": null, "e": 36767, "s": 36709, "text": "<ul>...</ul>: This tag is used to create unordered lists." }, { "code": null, "e": 36817, "s": 36767, "text": "<li>...</li>: This tag is used to add list items." }, { "code": null, "e": 36973, "s": 36817, "text": "The tags that do not contain any closing tags are known as empty tags. Empty tags contain only the opening tag but they perform some action in the webpage." }, { "code": null, "e": 36981, "s": 36973, "text": "Syntax:" }, { "code": null, "e": 36992, "s": 36981, "text": "<tag_name>" }, { "code": null, "e": 37027, "s": 36992, "text": "Some commonly used empty tags are:" }, { "code": null, "e": 37810, "s": 37027, "text": "<br>: Inerts a line break in a webpage wherever needed.<hr>: Inserts a horizontal line wherever needed in the webpage.<img>: This tag is used to display the images on the webpage which were given in the src attribute of the tag.<input>: This is mainly used with forms to take the input from the user and we can also define the type of the input.<link>: When we store our CSS in an external file this can be used to link external files and documents to the webpage and it is mainly used to link CSS files.<meta>: Contains all metadata of the webpage. Metadata is the data about data and is described in the head tag.<source>: When an external media source is needed to be included in the webpage. source tag is used to insert any media source like audio, video etc... in our webpage." }, { "code": null, "e": 37866, "s": 37810, "text": "<br>: Inerts a line break in a webpage wherever needed." }, { "code": null, "e": 37930, "s": 37866, "text": "<hr>: Inserts a horizontal line wherever needed in the webpage." }, { "code": null, "e": 38041, "s": 37930, "text": "<img>: This tag is used to display the images on the webpage which were given in the src attribute of the tag." }, { "code": null, "e": 38159, "s": 38041, "text": "<input>: This is mainly used with forms to take the input from the user and we can also define the type of the input." }, { "code": null, "e": 38319, "s": 38159, "text": "<link>: When we store our CSS in an external file this can be used to link external files and documents to the webpage and it is mainly used to link CSS files." }, { "code": null, "e": 38431, "s": 38319, "text": "<meta>: Contains all metadata of the webpage. Metadata is the data about data and is described in the head tag." }, { "code": null, "e": 38599, "s": 38431, "text": "<source>: When an external media source is needed to be included in the webpage. source tag is used to insert any media source like audio, video etc... in our webpage." }, { "code": null, "e": 38608, "s": 38599, "text": "Example:" }, { "code": null, "e": 38671, "s": 38608, "text": "This example demonstrates the use of container and empty tags:" }, { "code": null, "e": 38676, "s": 38671, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <!--Meta data--> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!--The description written on title tag get appeared as browser tab name--> <title>Geeks For Geeks </title> </head><!-- Whatever content in body tag appears on the webpage--><body> <!--Headings--> <h1> Geeks For Geeks </h1> <h2> Geeks For Geeks </h2> <h3> Geeks For Geeks </h3> <h4>Geeks For Geeks </h4> <h5> Geeks For Geeks</h5> <h6> Geeks For Geeks </h6> <p> This is a paragraph.</p> <!--For horizontal line --> <hr> <!--For paragraphs --> <p> Geeks for geeks is a computer science portal for geeks. </p> <hr> <p> This is a <br> line break </p> <h4> Link </h4> <a href=\"https://www.geeksforgeeks.org/\"> Geeks For Geeks</a> <!--For ordered lists--> <ol> <li> Item1</li> <li> Item2 </li> <li> Item3 </li> <li> Item4</li> </ol> </body></html>", "e": 39751, "s": 38676, "text": null }, { "code": null, "e": 39760, "s": 39751, "text": "Output: " }, { "code": null, "e": 39770, "s": 39760, "text": "HTML-Tags" }, { "code": null, "e": 39777, "s": 39770, "text": "Picked" }, { "code": null, "e": 39785, "s": 39777, "text": "class 6" }, { "code": null, "e": 39790, "s": 39785, "text": "HTML" }, { "code": null, "e": 39806, "s": 39790, "text": "School Learning" }, { "code": null, "e": 39825, "s": 39806, "text": "School Programming" }, { "code": null, "e": 39830, "s": 39825, "text": "HTML" }, { "code": null, "e": 39928, "s": 39830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39947, "s": 39928, "text": "Types of Computers" }, { "code": null, "e": 39982, "s": 39947, "text": "What are Different Output Devices?" }, { "code": null, "e": 40011, "s": 39982, "text": "What is Computer Networking?" }, { "code": null, "e": 40034, "s": 40011, "text": "Software and its Types" }, { "code": null, "e": 40108, "s": 40034, "text": "What is Internet? Definition, Uses, Working, Advantages and Disadvantages" }, { "code": null, "e": 40158, "s": 40108, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 40220, "s": 40158, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40268, "s": 40220, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40328, "s": 40268, "text": "How to set the default value for an HTML <select> element ?" } ]
The Simplest Way to Scrape Tabular Data with Python | by Joe T. Santhanavanich | Towards Data Science
Many of you might have already read several articles about data scraping from the websites. Most of them suggested using Node.js with Cheerio library or Python with Beautiful Soup. Although it is very effective when you master the techniques, it takes your time and effort until you finish all the coding for finding an element you need, requesting data, cleaning data to create a dataframe before you can do the actual data analysis. (And, of course, some additional time to fix all the bugs and errors 🐛) This short article will show you a tutorial on how to the easiest way to scrape the tabular data from any website with the three lines of Python Script! Our hero for this is the (red) PANDAS! Yes, the popular Pandas all you guys know is cute and capable of automatically extract the tabular data from the HTML file as well. For example, you want to get the tabular data from the Worldometer website. As this dataset is dynamic, changing over time, the Data scraping is make-sense that we get the most updated result every time when running the script! To scrape this dataset, get your machine ready with Python and Pandas. We gonna use the Pandas read_html() to extract all tables of any webpage. However, we cannot just use it to read URL directly because you might face an error 403: Forbidden. To avoid the error, we gonna request it with request module first to get the HTML body before use Pandas to read it. Overall, the script looks like this: The dfs is a list result containing multiple dataframes from the table's class of the requested HTML body. Let’s explore the dataframe we get from the above script by print out the first dfs. print(dfs[0]) With three lines of Python codes, you get the updated dataframe of COVID-19 data to play with, Simple and Easy! Have fun with your data analysis/ visualization!! I hope you enjoy this short article. Feel free to leave me a message if you have questions, comments, or suggestions. About me & Check out all my blog contents: Link Be Safe and Healthy! 💪 Thank you for Reading. 📚
[ { "code": null, "e": 679, "s": 172, "text": "Many of you might have already read several articles about data scraping from the websites. Most of them suggested using Node.js with Cheerio library or Python with Beautiful Soup. Although it is very effective when you master the techniques, it takes your time and effort until you finish all the coding for finding an element you need, requesting data, cleaning data to create a dataframe before you can do the actual data analysis. (And, of course, some additional time to fix all the bugs and errors 🐛)" }, { "code": null, "e": 832, "s": 679, "text": "This short article will show you a tutorial on how to the easiest way to scrape the tabular data from any website with the three lines of Python Script!" }, { "code": null, "e": 1003, "s": 832, "text": "Our hero for this is the (red) PANDAS! Yes, the popular Pandas all you guys know is cute and capable of automatically extract the tabular data from the HTML file as well." }, { "code": null, "e": 1231, "s": 1003, "text": "For example, you want to get the tabular data from the Worldometer website. As this dataset is dynamic, changing over time, the Data scraping is make-sense that we get the most updated result every time when running the script!" }, { "code": null, "e": 1630, "s": 1231, "text": "To scrape this dataset, get your machine ready with Python and Pandas. We gonna use the Pandas read_html() to extract all tables of any webpage. However, we cannot just use it to read URL directly because you might face an error 403: Forbidden. To avoid the error, we gonna request it with request module first to get the HTML body before use Pandas to read it. Overall, the script looks like this:" }, { "code": null, "e": 1822, "s": 1630, "text": "The dfs is a list result containing multiple dataframes from the table's class of the requested HTML body. Let’s explore the dataframe we get from the above script by print out the first dfs." }, { "code": null, "e": 1836, "s": 1822, "text": "print(dfs[0])" }, { "code": null, "e": 1948, "s": 1836, "text": "With three lines of Python codes, you get the updated dataframe of COVID-19 data to play with, Simple and Easy!" }, { "code": null, "e": 2116, "s": 1948, "text": "Have fun with your data analysis/ visualization!! I hope you enjoy this short article. Feel free to leave me a message if you have questions, comments, or suggestions." }, { "code": null, "e": 2164, "s": 2116, "text": "About me & Check out all my blog contents: Link" }, { "code": null, "e": 2187, "s": 2164, "text": "Be Safe and Healthy! 💪" } ]
Number of subarrays having sum exactly equal to k - GeeksforGeeks
23 Mar, 2022 Given an unsorted array of integers, find the number of subarrays having sum exactly equal to a given number k. Examples: Input : arr[] = {10, 2, -2, -20, 10}, k = -10 Output : 3 Subarrays: arr[0...3], arr[1...4], arr[3..4] have sum exactly equal to -10. Input : arr[] = {9, 4, 20, 3, 10, 5}, k = 33 Output : 2 Subarrays : arr[0...2], arr[2...4] have sum exactly equal to 33. Naive Solution – A simple solution is to traverse all the subarrays and calculate their sum. If the sum is equal to the required sum then increment the count of subarrays. Print final count of subarray. Following is the naive implementation – C++ Java Python3 C# Javascript // C++ program for// the above approach#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = {10, 2, -2, -20, 10}; int k = -10; int n = sizeof(arr) / sizeof(arr[0]); int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; } } cout << (res) << endl;} // This code is contributed by Chitranayal // Java program for// the above approachimport java.util.*;class Solution { public static void main(String[] args) { int arr[] = { 10, 2, -2, -20, 10 }; int k = -10; int n = arr.length; int res = 0; // calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // calculate required sum sum += arr[j]; // check if sum is equal to // required sum if (sum == k) res++; } } System.out.println(res); }} # Python3 program for# the above approacharr = [ 10, 2, -2, -20, 10 ]n = len(arr)k = -10res = 0 # Calculate all subarraysfor i in range(n): summ = 0 for j in range(i, n): # Calculate required sum summ += arr[j] # Check if sum is equal to # required sum if summ == k: res += 1 print(res) # This code is contributed by kavan155gondalia // C# program for// the above approachusing System;using System.Collections.Generic;class GFG { static void Main() { int[] arr = {10, 2, -2, -20, 10}; int k = -10; int n = arr.Length; int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; } } Console.WriteLine(res); }} // This code is contributed by divyesh072019 <script> // Javascript program for// the above approachlet arr = [ 10, 2, -2, -20, 10 ];let k = -10;let n = arr.length;let res = 0; // Calculate all subarraysfor(let i = 0; i < n; i++){ let sum = 0; for(let j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; }}document.write(res); // This code is contributed by suresh07 </script> 3 Efficient Solution – An efficient solution is while traversing the array, store sum so far in currsum. Also, maintain the count of different values of currsum in a map. If the value of currsum is equal to the desired sum at any instance increment count of subarrays by one. The value of currsum exceeds the desired sum by currsum – sum. If this value is removed from currsum then the desired sum can be obtained. From the map find the number of subarrays previously found having sum equal to currsum-sum. Excluding all those subarrays from the current subarray, gives new subarrays having the desired sum. So increase count by the number of such subarrays. Note that when currsum is equal to the desired sum then also check the number of subarrays previously having a sum equal to 0. Excluding those subarrays from the current subarray gives new subarrays having the desired sum. Increase count by the number of subarrays having sum 0 in that case. Java Java Python3 C# Javascript // C++ program to find number of subarrays// with sum exactly equal to k.#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays// with sum exactly equal to k.int findSubarraySum(int arr[], int n, int sum){ // STL map to store number of subarrays // starting from index zero having // particular value of sum. unordered_map<int, int> prevSum; int res = 0; // Sum of elements so far. int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.find(currsum - sum) != prevSum.end()) res += (prevSum[currsum - sum]); // Add currsum value to count of // different values of sum. prevSum[currsum]++; } return res;} int main(){ int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = sizeof(arr) / sizeof(arr[0]); cout << findSubarraySum(arr, n, sum); return 0;} // Java program to find number of subarrays// with sum exactly equal to k.import java.util.HashMap;import java.util.Map; public class GfG { // Function to find number of subarrays // with sum exactly equal to k. static int findSubarraySum(int arr[], int n, int sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. HashMap<Integer, Integer> prevSum = new HashMap<>(); prevSum.put(0,1); int res = 0; // Sum of elements so far. int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; //calculate the sum that have to be removed //so that we can get the desired sum int removeSum=currSum-sum; //get count of occurrences of that sum that //have to removed and add it to res value if (prevSum.containsKey(removeSum)) res += prevSum.get(removeSum); // Add currsum value to count of // different values of sum. map.put(currSum,map.getOrDefault(currSum,0)+1); } return res; } public static void main(String[] args) { int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = arr.length; System.out.println(findSubarraySum(arr, n, sum)); }} // This code is contributed by Rituraj Jain # Python3 program to find the number of# subarrays with sum exactly equal to k.from collections import defaultdict # Function to find number of subarrays # with sum exactly equal to k.def findSubarraySum(arr, n, Sum): # Dictionary to store number of subarrays # starting from index zero having # particular value of sum. prevSum = defaultdict(lambda : 0) res = 0 # Sum of elements so far. currsum = 0 for i in range(0, n): # Add current element to sum so far. currsum += arr[i] # If currsum is equal to desired sum, # then a new subarray is found. So # increase count of subarrays. if currsum == Sum: res += 1 # currsum exceeds given sum by currsum - sum. # Find number of subarrays having # this sum and exclude those subarrays # from currsum by increasing count by # same amount. if (currsum - Sum) in prevSum: res += prevSum[currsum - Sum] # Add currsum value to count of # different values of sum. prevSum[currsum] += 1 return res if __name__ == "__main__": arr = [10, 2, -2, -20, 10] Sum = -10 n = len(arr) print(findSubarraySum(arr, n, Sum)) # This code is contributed by Rituraj Jain // C# program to find number of subarrays// with sum exactly equal to k.using System;using System.Collections.Generic; class GFG { // Function to find number of subarrays // with sum exactly equal to k. public static int findSubarraySum(int[] arr, int n, int sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. Dictionary<int, int> prevSum = new Dictionary<int, int>(); int res = 0; // Sum of elements so far int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.ContainsKey(currsum - sum)) res += prevSum[currsum - sum]; // Add currsum value to count of // different values of sum. if (!prevSum.ContainsKey(currsum)) prevSum.Add(currsum, 1); else { int count = prevSum[currsum]; prevSum[currsum] = count + 1; } } return res; } // Driver Code public static void Main() { int[] arr = { 10, 2, -2, -20, 10 }; int sum = -10; int n = arr.Length; Console.Write(findSubarraySum(arr, n, sum)); }} // This code is contributed by// sanjeev2552 <script>// Javascript program to find number of subarrays// with sum exactly equal to k. // Function to find number of subarrays // with sum exactly equal to k. function findSubarraySum(arr,n,sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. let prevSum = new Map(); let res = 0; // Sum of elements so far. let currsum = 0; for (let i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.has(currsum - sum)) res += prevSum.get(currsum - sum); // Add currsum value to count of // different values of sum. let count = prevSum.get(currsum); if (count == null) prevSum.set(currsum, 1); else prevSum.set(currsum, count + 1); } return res; } let arr = [10, 2, -2, -20, 10]; let sum = -10; let n = arr.length; document.write(findSubarraySum(arr, n, sum)); // This code is contributed by avanitrachhadiya2155.</script> 3 Time Complexity: O(n) Auxiliary Space: O(n) rituraj_jain sanjeev2552 rishabhdubey2 tufan_gupta2000 ukasp kavania2002 divyesh072019 navodayanabhishek suresh07 avanitrachhadiya2155 sankeerthmeda sagartomar9927 cpp-unordered_map subarray subarray-sum Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 24867, "s": 24839, "text": "\n23 Mar, 2022" }, { "code": null, "e": 24979, "s": 24867, "text": "Given an unsorted array of integers, find the number of subarrays having sum exactly equal to a given number k." }, { "code": null, "e": 24990, "s": 24979, "text": "Examples: " }, { "code": null, "e": 25266, "s": 24990, "text": "Input : arr[] = {10, 2, -2, -20, 10}, \n k = -10\nOutput : 3\nSubarrays: arr[0...3], arr[1...4], arr[3..4]\nhave sum exactly equal to -10.\n\nInput : arr[] = {9, 4, 20, 3, 10, 5},\n k = 33\nOutput : 2\nSubarrays : arr[0...2], arr[2...4] have sum\nexactly equal to 33." }, { "code": null, "e": 25510, "s": 25266, "text": "Naive Solution – A simple solution is to traverse all the subarrays and calculate their sum. If the sum is equal to the required sum then increment the count of subarrays. Print final count of subarray. Following is the naive implementation – " }, { "code": null, "e": 25514, "s": 25510, "text": "C++" }, { "code": null, "e": 25519, "s": 25514, "text": "Java" }, { "code": null, "e": 25527, "s": 25519, "text": "Python3" }, { "code": null, "e": 25530, "s": 25527, "text": "C#" }, { "code": null, "e": 25541, "s": 25530, "text": "Javascript" }, { "code": "// C++ program for// the above approach#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = {10, 2, -2, -20, 10}; int k = -10; int n = sizeof(arr) / sizeof(arr[0]); int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; } } cout << (res) << endl;} // This code is contributed by Chitranayal", "e": 26066, "s": 25541, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class Solution { public static void main(String[] args) { int arr[] = { 10, 2, -2, -20, 10 }; int k = -10; int n = arr.length; int res = 0; // calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // calculate required sum sum += arr[j]; // check if sum is equal to // required sum if (sum == k) res++; } } System.out.println(res); }}", "e": 26756, "s": 26066, "text": null }, { "code": "# Python3 program for# the above approacharr = [ 10, 2, -2, -20, 10 ]n = len(arr)k = -10res = 0 # Calculate all subarraysfor i in range(n): summ = 0 for j in range(i, n): # Calculate required sum summ += arr[j] # Check if sum is equal to # required sum if summ == k: res += 1 print(res) # This code is contributed by kavan155gondalia", "e": 27163, "s": 26756, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG { static void Main() { int[] arr = {10, 2, -2, -20, 10}; int k = -10; int n = arr.Length; int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; } } Console.WriteLine(res); }} // This code is contributed by divyesh072019", "e": 27801, "s": 27163, "text": null }, { "code": "<script> // Javascript program for// the above approachlet arr = [ 10, 2, -2, -20, 10 ];let k = -10;let n = arr.length;let res = 0; // Calculate all subarraysfor(let i = 0; i < n; i++){ let sum = 0; for(let j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to // required sum if (sum == k) res++; }}document.write(res); // This code is contributed by suresh07 </script>", "e": 28290, "s": 27801, "text": null }, { "code": null, "e": 28292, "s": 28290, "text": "3" }, { "code": null, "e": 29243, "s": 28294, "text": "Efficient Solution – An efficient solution is while traversing the array, store sum so far in currsum. Also, maintain the count of different values of currsum in a map. If the value of currsum is equal to the desired sum at any instance increment count of subarrays by one. The value of currsum exceeds the desired sum by currsum – sum. If this value is removed from currsum then the desired sum can be obtained. From the map find the number of subarrays previously found having sum equal to currsum-sum. Excluding all those subarrays from the current subarray, gives new subarrays having the desired sum. So increase count by the number of such subarrays. Note that when currsum is equal to the desired sum then also check the number of subarrays previously having a sum equal to 0. Excluding those subarrays from the current subarray gives new subarrays having the desired sum. Increase count by the number of subarrays having sum 0 in that case." }, { "code": null, "e": 29248, "s": 29243, "text": "Java" }, { "code": null, "e": 29253, "s": 29248, "text": "Java" }, { "code": null, "e": 29261, "s": 29253, "text": "Python3" }, { "code": null, "e": 29264, "s": 29261, "text": "C#" }, { "code": null, "e": 29275, "s": 29264, "text": "Javascript" }, { "code": "// C++ program to find number of subarrays// with sum exactly equal to k.#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays// with sum exactly equal to k.int findSubarraySum(int arr[], int n, int sum){ // STL map to store number of subarrays // starting from index zero having // particular value of sum. unordered_map<int, int> prevSum; int res = 0; // Sum of elements so far. int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.find(currsum - sum) != prevSum.end()) res += (prevSum[currsum - sum]); // Add currsum value to count of // different values of sum. prevSum[currsum]++; } return res;} int main(){ int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = sizeof(arr) / sizeof(arr[0]); cout << findSubarraySum(arr, n, sum); return 0;}", "e": 30612, "s": 29275, "text": null }, { "code": "// Java program to find number of subarrays// with sum exactly equal to k.import java.util.HashMap;import java.util.Map; public class GfG { // Function to find number of subarrays // with sum exactly equal to k. static int findSubarraySum(int arr[], int n, int sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. HashMap<Integer, Integer> prevSum = new HashMap<>(); prevSum.put(0,1); int res = 0; // Sum of elements so far. int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; //calculate the sum that have to be removed //so that we can get the desired sum int removeSum=currSum-sum; //get count of occurrences of that sum that //have to removed and add it to res value if (prevSum.containsKey(removeSum)) res += prevSum.get(removeSum); // Add currsum value to count of // different values of sum. map.put(currSum,map.getOrDefault(currSum,0)+1); } return res; } public static void main(String[] args) { int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = arr.length; System.out.println(findSubarraySum(arr, n, sum)); }} // This code is contributed by Rituraj Jain", "e": 32074, "s": 30612, "text": null }, { "code": "# Python3 program to find the number of# subarrays with sum exactly equal to k.from collections import defaultdict # Function to find number of subarrays # with sum exactly equal to k.def findSubarraySum(arr, n, Sum): # Dictionary to store number of subarrays # starting from index zero having # particular value of sum. prevSum = defaultdict(lambda : 0) res = 0 # Sum of elements so far. currsum = 0 for i in range(0, n): # Add current element to sum so far. currsum += arr[i] # If currsum is equal to desired sum, # then a new subarray is found. So # increase count of subarrays. if currsum == Sum: res += 1 # currsum exceeds given sum by currsum - sum. # Find number of subarrays having # this sum and exclude those subarrays # from currsum by increasing count by # same amount. if (currsum - Sum) in prevSum: res += prevSum[currsum - Sum] # Add currsum value to count of # different values of sum. prevSum[currsum] += 1 return res if __name__ == \"__main__\": arr = [10, 2, -2, -20, 10] Sum = -10 n = len(arr) print(findSubarraySum(arr, n, Sum)) # This code is contributed by Rituraj Jain", "e": 33394, "s": 32074, "text": null }, { "code": "// C# program to find number of subarrays// with sum exactly equal to k.using System;using System.Collections.Generic; class GFG { // Function to find number of subarrays // with sum exactly equal to k. public static int findSubarraySum(int[] arr, int n, int sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. Dictionary<int, int> prevSum = new Dictionary<int, int>(); int res = 0; // Sum of elements so far int currsum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.ContainsKey(currsum - sum)) res += prevSum[currsum - sum]; // Add currsum value to count of // different values of sum. if (!prevSum.ContainsKey(currsum)) prevSum.Add(currsum, 1); else { int count = prevSum[currsum]; prevSum[currsum] = count + 1; } } return res; } // Driver Code public static void Main() { int[] arr = { 10, 2, -2, -20, 10 }; int sum = -10; int n = arr.Length; Console.Write(findSubarraySum(arr, n, sum)); }} // This code is contributed by// sanjeev2552", "e": 35193, "s": 33394, "text": null }, { "code": "<script>// Javascript program to find number of subarrays// with sum exactly equal to k. // Function to find number of subarrays // with sum exactly equal to k. function findSubarraySum(arr,n,sum) { // HashMap to store number of subarrays // starting from index zero having // particular value of sum. let prevSum = new Map(); let res = 0; // Sum of elements so far. let currsum = 0; for (let i = 0; i < n; i++) { // Add current element to sum so far. currsum += arr[i]; // If currsum is equal to desired sum, // then a new subarray is found. So // increase count of subarrays. if (currsum == sum) res++; // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.has(currsum - sum)) res += prevSum.get(currsum - sum); // Add currsum value to count of // different values of sum. let count = prevSum.get(currsum); if (count == null) prevSum.set(currsum, 1); else prevSum.set(currsum, count + 1); } return res; } let arr = [10, 2, -2, -20, 10]; let sum = -10; let n = arr.length; document.write(findSubarraySum(arr, n, sum)); // This code is contributed by avanitrachhadiya2155.</script>", "e": 36795, "s": 35193, "text": null }, { "code": null, "e": 36797, "s": 36795, "text": "3" }, { "code": null, "e": 36843, "s": 36799, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 36856, "s": 36843, "text": "rituraj_jain" }, { "code": null, "e": 36868, "s": 36856, "text": "sanjeev2552" }, { "code": null, "e": 36882, "s": 36868, "text": "rishabhdubey2" }, { "code": null, "e": 36898, "s": 36882, "text": "tufan_gupta2000" }, { "code": null, "e": 36904, "s": 36898, "text": "ukasp" }, { "code": null, "e": 36916, "s": 36904, "text": "kavania2002" }, { "code": null, "e": 36930, "s": 36916, "text": "divyesh072019" }, { "code": null, "e": 36948, "s": 36930, "text": "navodayanabhishek" }, { "code": null, "e": 36957, "s": 36948, "text": "suresh07" }, { "code": null, "e": 36978, "s": 36957, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36992, "s": 36978, "text": "sankeerthmeda" }, { "code": null, "e": 37007, "s": 36992, "text": "sagartomar9927" }, { "code": null, "e": 37025, "s": 37007, "text": "cpp-unordered_map" }, { "code": null, "e": 37034, "s": 37025, "text": "subarray" }, { "code": null, "e": 37047, "s": 37034, "text": "subarray-sum" }, { "code": null, "e": 37054, "s": 37047, "text": "Arrays" }, { "code": null, "e": 37059, "s": 37054, "text": "Hash" }, { "code": null, "e": 37066, "s": 37059, "text": "Arrays" }, { "code": null, "e": 37071, "s": 37066, "text": "Hash" }, { "code": null, "e": 37169, "s": 37071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37178, "s": 37169, "text": "Comments" }, { "code": null, "e": 37191, "s": 37178, "text": "Old Comments" }, { "code": null, "e": 37214, "s": 37191, "text": "Introduction to Arrays" }, { "code": null, "e": 37246, "s": 37214, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37267, "s": 37246, "text": "Linked List vs Array" }, { "code": null, "e": 37312, "s": 37267, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 37397, "s": 37312, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37482, "s": 37397, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37518, "s": 37482, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 37549, "s": 37518, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 37576, "s": 37549, "text": "Count pairs with given sum" } ]
23 Efficient Ways of Subsetting a Pandas DataFrame | by Rukshan Pramoditha | Towards Data Science
In part 1 and part 2, we’ve learned how to inspect, describe and summarize a Pandas DataFrame. Today, we’ll learn how to extract a subset of a Pandas DataFrame. This is very useful because we often want to perform operations on subsets of our data. There are many different ways of subsetting a Pandas DataFrame. You may need to select specific columns with all rows. Sometimes, you want to select specific rows with all columns or select rows and columns that meet a specific criterion, etc. All different ways of subsetting can be divided into 4 categories: Selection, Slicing, Indexing and Filtering. As you continue reading this post, you’ll learn the differences between these categories. Before discussing any of the methods of subsetting a data frame, it is worth distinguishing between a Pandas Series object and a Pandas DataFrame object. The Series and the DataFrame are two main data structures in Pandas. Simply, a Series is similar to a single column of data while a DataFrame is similar to a sheet with rows and columns. Look at the following diagram: As you can see, a Series is one dimensional and a DataFrame is two dimensional. If we combine two or more Series objects together, we can get a DataFrame object. Let’s look at the actual view of a Series object. import numpy as npimport pandas as pddata = np.array([85, 90, 70, 80])series = pd.Series(data=data, name="marks")print(series) A Series consists of two components: One-dimensional data values and Index. The index provides meaningful labels for each data value. The users can use this index to select the values. By default, the index begins with 0. Let’s look at the actual view of a DataFrame object. import numpy as npimport pandas as pddata = np.array([[25, 85], [25, 90], [26, 70], [24, 80]])dataframe = pd.DataFrame(data=data, columns=["age", "marks"])print(dataframe) A DataFrame consists of three components: Two-dimensional data values, Row index and Column index. These indices provide meaningful labels for rows and columns. The users can use these indices to select rows and columns. By default, the indices begin with 0. Now, we discuss different ways of subsetting a Pandas DataFrame. For explaining purposes, I’ll use the “wine dataset”. Here is a part of it. When we grab the entire column(s), it refers to as Selection. The selected column(s) contain all the rows. We can select a single column of a Pandas DataFrame using its column name. If the DataFrame is referred to as df, the general syntax is: df['column_name']# Ordf.column_name # Only for single column selection The output is a Pandas Series which is a single column! # Load some dataimport pandas as pdfrom sklearn.datasets import load_winewine = load_wine()df = pd.DataFrame(data=wine.data, columns=wine.feature_names)# Select the 'alcohol column'print(df['alcohol'])print(type(df['alcohol'])) We can select multiple columns of a Pandas DataFrame using its column names. We can define columns names inside a list: ['column_1', 'column_2', ...] Then, we can include this list into df[]. The general syntax is: df[['column_1', 'column_2', ...]] This time, the output is a Pandas DataFrame! df[['alcohol', 'ash', 'hue']] The same result in Method 1 can be obtained using the .loc attribute which selects Pandas data by label (column name). df.loc[:, 'alcohol'] The same result in Method 2 can be obtained using the .loc attribute which selects Pandas data by labels (column names). df.loc[:, ['alcohol', 'ash', 'hue']] The general syntax of the .loc attribute is: df.loc['row_label', 'column_label'] If there are multiple labels, they should be specified inside lists: df.loc[['row_1', 'row_2'], ['column_1', 'column_2']] If we want to select all the rows or columns, it can be done with : symbol. The most important thing about the .loc attribute is that it selects Pandas data by label. The same result in Method 1 can be obtained using the .iloc attribute which selects Pandas data by position (column index). df.iloc[:, 0] The alcohol variable is in position 0 (first variable). The same result in Method 2 can be obtained using the .iloc attribute which selects Pandas data by positions (column indices). df.iloc[:, [0, 2, 10]] The general syntax of the .iloc attribute is: df.iloc['row_index', 'column_index'] If there are multiple labels, they should be specified inside lists: df.iloc[['row_index_1', 'row_index_2'], ['column_index_1', 'column_index_2']] If we want to select all the rows or columns, it can be done with : notation. The most important thing about the .iloc attribute is that it selects Pandas data by position using numeric indices. We can select the first 5 columns of df as follows: df.iloc[:, [0, 1, 2, 3, 4]] We can also use the following easy method to obtain the same result. df.iloc[:, 0:5] To use this, columns should be positioned consecutively. The 0:5 range includes 0 (first column), excludes 5 (sixth column) and selects every column between the range. Selecting the last column is often useful in many cases. There are two methods: First, we can count the number of columns in the data frame using the .shape attribute. df.shape# Output: (178, 13) The last column is the 13th one that can be accessed through index 12. By using .iloc, df.iloc[:, 12] The second method is much easy. Here, we do not need to know the number of columns in the data frame. df.iloc[:, -1] The -1 represents the last column. When we want to extract certain rows from the DataFrame, it refers to as Slicing. The extracted rows are called slices and contain all the columns. The easiest way to extract a single row is to use the row index inside the .iloc attribute. The general syntax is: df.iloc[row_index] The output is a Pandas Series which contains the row values. df.iloc[0] The appearance is a bit confusing as the output is a Pandas Series. If you want this as a row itself, simply use the index values inside a list as follows: df.iloc[[0]] This is a Pandas DataFrame which contains 1 row and all the columns! We can extract multiple rows of a Pandas DataFrame using its row indices. We include row indices inside a list: [row_index_1, row_index_2, ...] Then we include this list inside df.iloc[]. df.iloc[[row_index_1, row_index_2, ...]] The output is a Pandas DataFrame. df.iloc[[0, 25, 100]] The negative indices count rows from the bottom. df.iloc[[-1, -2, -3, -4, -5]] When we combine column selection and row slicing, it is referred to as Indexing. Here, we can use .loc and .iloc attributes of a Pandas DataFrame. If we specify a single row and a single column, the intersection is a single value! df.iloc[0, 0] Keep in mind that we cannot use column or row names inside .iloc[]. Only the index numbers can be used. Here we can use row or column names inside .loc[]. Also keep in mind that, in our data, the row labels are the same as the row indices. The following code gives the same result as in Method 12. df.loc[0, 'alcohol'] The general syntax is: df.iloc[[row_index_1, row_index_2, ...], [column_index_1, column_index_2, ...]] The output is a Pandas DataFrame. df.iloc[[0, 5, 100], [0, 3, 7]] The general syntax is: df.loc[[row_name, row_name_2, ...], [column_name_1, column_name_2, ...]] The output is a Pandas DataFrame. df.loc[[0, 5, 100], ['alcohol', 'ash', 'hue']] Here we can use row or column names inside .loc[]. Also keep in mind that, in our data, the row names are the same as the row indices. This can be easily done with the : notation. For this, rows and columns should be positioned consecutively. df.iloc[0:6, 0:5] Another example is: df.loc[0:6, ['alcohol', 'ash']] When we select rows and columns based on specific criteria or conditions, it is referred to as Filtering. We can also combine the above-discussed methods with this. Let’s subset our data when alcohol > 14.3. Here, we select all the columns when alcohol > 14.3. df['alcohol'] > 14.3 This is a Pandas Series of boolean data type. We can use this Series to get the required subset of the data. df[df['alcohol'] > 14.3] Let’s subset our data when alcohol > 14.3. This time, we select only 3 columns when alcohol > 14.3. For this, we can combine the above filtering technique with .loc[]. df.loc[df['alcohol'] > 14.3, ['alcohol', 'ash', 'hue']] Let’s subset our data when alcohol > 14.3 AND alcohol < 14.6. Here, we use two conditions and combine them with the AND operator. Each condition should be surrounded in parentheses. df[(df['alcohol'] > 14.3) & (df['alcohol'] < 14.6)] A similar type of filtering discussed in Method 19 can be achieved using the between() method. df[df['alcohol'].between(14.3, 14.6)] Here, the output is a bit different because the between() method includes the values of the lower bound (14.3) and upper bound (14.6) by default. However, we can pass inclusive=False if we don’t want the inclusive selection. df[df['alcohol'].between(14.3, 14.6, inclusive=False)] This subset is exactly the same as the subset obtained in Method 19. Here, the two conditions are made using two different columns: alcohol and hue. df[(df['alcohol'] > 14.3) & (df['hue'] > 1.0)] When we use the AND operator, the filtering happens considering both conditions to be true. If we want at least one condition to be true, we can use the OR operator. df[(df['alcohol'] > 14.5) | (df['hue'] > 1.4)] Let’s subset our data based on the minimum and maximum values of the alcohol variable. First, we get the indices of the minimum and maximum: df['alcohol'].idxmin() # Min value indexdf['alcohol'].idxmax() # Max value index Then we use .iloc[]. df.iloc[[df['alcohol'].idxmin(), df['alcohol'].idxmax()]] These are not the only ways of subsetting a Pandas DataFrame. There are many more. We can combine multiple methods for complex subsetting. This post helps you to be familiar with subsetting syntax. And also, you’re now familiar with the terms Selection, Slicing, Indexing and Filtering. Also, keep in mind that .iloc needs integer values (i for integer) while .loc needs label values. This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee. Sign-up link: https://rukshanpramoditha.medium.com/membership Thank you so much for your continuous support! See you in the next story. Happy learning to everyone! Special credit goes to Hans-Peter Gauster on Unsplash, who provides me with a nice cover image for this post.
[ { "code": null, "e": 664, "s": 171, "text": "In part 1 and part 2, we’ve learned how to inspect, describe and summarize a Pandas DataFrame. Today, we’ll learn how to extract a subset of a Pandas DataFrame. This is very useful because we often want to perform operations on subsets of our data. There are many different ways of subsetting a Pandas DataFrame. You may need to select specific columns with all rows. Sometimes, you want to select specific rows with all columns or select rows and columns that meet a specific criterion, etc." }, { "code": null, "e": 775, "s": 664, "text": "All different ways of subsetting can be divided into 4 categories: Selection, Slicing, Indexing and Filtering." }, { "code": null, "e": 865, "s": 775, "text": "As you continue reading this post, you’ll learn the differences between these categories." }, { "code": null, "e": 1019, "s": 865, "text": "Before discussing any of the methods of subsetting a data frame, it is worth distinguishing between a Pandas Series object and a Pandas DataFrame object." }, { "code": null, "e": 1237, "s": 1019, "text": "The Series and the DataFrame are two main data structures in Pandas. Simply, a Series is similar to a single column of data while a DataFrame is similar to a sheet with rows and columns. Look at the following diagram:" }, { "code": null, "e": 1449, "s": 1237, "text": "As you can see, a Series is one dimensional and a DataFrame is two dimensional. If we combine two or more Series objects together, we can get a DataFrame object. Let’s look at the actual view of a Series object." }, { "code": null, "e": 1595, "s": 1449, "text": "import numpy as npimport pandas as pddata = np.array([85, 90, 70, 80])series = pd.Series(data=data, name=\"marks\")print(series)" }, { "code": null, "e": 1817, "s": 1595, "text": "A Series consists of two components: One-dimensional data values and Index. The index provides meaningful labels for each data value. The users can use this index to select the values. By default, the index begins with 0." }, { "code": null, "e": 1870, "s": 1817, "text": "Let’s look at the actual view of a DataFrame object." }, { "code": null, "e": 2115, "s": 1870, "text": "import numpy as npimport pandas as pddata = np.array([[25, 85], [25, 90], [26, 70], [24, 80]])dataframe = pd.DataFrame(data=data, columns=[\"age\", \"marks\"])print(dataframe)" }, { "code": null, "e": 2374, "s": 2115, "text": "A DataFrame consists of three components: Two-dimensional data values, Row index and Column index. These indices provide meaningful labels for rows and columns. The users can use these indices to select rows and columns. By default, the indices begin with 0." }, { "code": null, "e": 2515, "s": 2374, "text": "Now, we discuss different ways of subsetting a Pandas DataFrame. For explaining purposes, I’ll use the “wine dataset”. Here is a part of it." }, { "code": null, "e": 2622, "s": 2515, "text": "When we grab the entire column(s), it refers to as Selection. The selected column(s) contain all the rows." }, { "code": null, "e": 2759, "s": 2622, "text": "We can select a single column of a Pandas DataFrame using its column name. If the DataFrame is referred to as df, the general syntax is:" }, { "code": null, "e": 2830, "s": 2759, "text": "df['column_name']# Ordf.column_name # Only for single column selection" }, { "code": null, "e": 2886, "s": 2830, "text": "The output is a Pandas Series which is a single column!" }, { "code": null, "e": 3131, "s": 2886, "text": "# Load some dataimport pandas as pdfrom sklearn.datasets import load_winewine = load_wine()df = pd.DataFrame(data=wine.data, columns=wine.feature_names)# Select the 'alcohol column'print(df['alcohol'])print(type(df['alcohol']))" }, { "code": null, "e": 3251, "s": 3131, "text": "We can select multiple columns of a Pandas DataFrame using its column names. We can define columns names inside a list:" }, { "code": null, "e": 3281, "s": 3251, "text": "['column_1', 'column_2', ...]" }, { "code": null, "e": 3346, "s": 3281, "text": "Then, we can include this list into df[]. The general syntax is:" }, { "code": null, "e": 3380, "s": 3346, "text": "df[['column_1', 'column_2', ...]]" }, { "code": null, "e": 3425, "s": 3380, "text": "This time, the output is a Pandas DataFrame!" }, { "code": null, "e": 3455, "s": 3425, "text": "df[['alcohol', 'ash', 'hue']]" }, { "code": null, "e": 3574, "s": 3455, "text": "The same result in Method 1 can be obtained using the .loc attribute which selects Pandas data by label (column name)." }, { "code": null, "e": 3595, "s": 3574, "text": "df.loc[:, 'alcohol']" }, { "code": null, "e": 3716, "s": 3595, "text": "The same result in Method 2 can be obtained using the .loc attribute which selects Pandas data by labels (column names)." }, { "code": null, "e": 3753, "s": 3716, "text": "df.loc[:, ['alcohol', 'ash', 'hue']]" }, { "code": null, "e": 3798, "s": 3753, "text": "The general syntax of the .loc attribute is:" }, { "code": null, "e": 3834, "s": 3798, "text": "df.loc['row_label', 'column_label']" }, { "code": null, "e": 3903, "s": 3834, "text": "If there are multiple labels, they should be specified inside lists:" }, { "code": null, "e": 3963, "s": 3903, "text": "df.loc[['row_1', 'row_2'], ['column_1', 'column_2']]" }, { "code": null, "e": 4130, "s": 3963, "text": "If we want to select all the rows or columns, it can be done with : symbol. The most important thing about the .loc attribute is that it selects Pandas data by label." }, { "code": null, "e": 4254, "s": 4130, "text": "The same result in Method 1 can be obtained using the .iloc attribute which selects Pandas data by position (column index)." }, { "code": null, "e": 4268, "s": 4254, "text": "df.iloc[:, 0]" }, { "code": null, "e": 4324, "s": 4268, "text": "The alcohol variable is in position 0 (first variable)." }, { "code": null, "e": 4451, "s": 4324, "text": "The same result in Method 2 can be obtained using the .iloc attribute which selects Pandas data by positions (column indices)." }, { "code": null, "e": 4474, "s": 4451, "text": "df.iloc[:, [0, 2, 10]]" }, { "code": null, "e": 4520, "s": 4474, "text": "The general syntax of the .iloc attribute is:" }, { "code": null, "e": 4557, "s": 4520, "text": "df.iloc['row_index', 'column_index']" }, { "code": null, "e": 4626, "s": 4557, "text": "If there are multiple labels, they should be specified inside lists:" }, { "code": null, "e": 4711, "s": 4626, "text": "df.iloc[['row_index_1', 'row_index_2'], ['column_index_1', 'column_index_2']]" }, { "code": null, "e": 4906, "s": 4711, "text": "If we want to select all the rows or columns, it can be done with : notation. The most important thing about the .iloc attribute is that it selects Pandas data by position using numeric indices." }, { "code": null, "e": 4958, "s": 4906, "text": "We can select the first 5 columns of df as follows:" }, { "code": null, "e": 4986, "s": 4958, "text": "df.iloc[:, [0, 1, 2, 3, 4]]" }, { "code": null, "e": 5055, "s": 4986, "text": "We can also use the following easy method to obtain the same result." }, { "code": null, "e": 5071, "s": 5055, "text": "df.iloc[:, 0:5]" }, { "code": null, "e": 5239, "s": 5071, "text": "To use this, columns should be positioned consecutively. The 0:5 range includes 0 (first column), excludes 5 (sixth column) and selects every column between the range." }, { "code": null, "e": 5319, "s": 5239, "text": "Selecting the last column is often useful in many cases. There are two methods:" }, { "code": null, "e": 5407, "s": 5319, "text": "First, we can count the number of columns in the data frame using the .shape attribute." }, { "code": null, "e": 5435, "s": 5407, "text": "df.shape# Output: (178, 13)" }, { "code": null, "e": 5522, "s": 5435, "text": "The last column is the 13th one that can be accessed through index 12. By using .iloc," }, { "code": null, "e": 5537, "s": 5522, "text": "df.iloc[:, 12]" }, { "code": null, "e": 5639, "s": 5537, "text": "The second method is much easy. Here, we do not need to know the number of columns in the data frame." }, { "code": null, "e": 5654, "s": 5639, "text": "df.iloc[:, -1]" }, { "code": null, "e": 5689, "s": 5654, "text": "The -1 represents the last column." }, { "code": null, "e": 5837, "s": 5689, "text": "When we want to extract certain rows from the DataFrame, it refers to as Slicing. The extracted rows are called slices and contain all the columns." }, { "code": null, "e": 5952, "s": 5837, "text": "The easiest way to extract a single row is to use the row index inside the .iloc attribute. The general syntax is:" }, { "code": null, "e": 5971, "s": 5952, "text": "df.iloc[row_index]" }, { "code": null, "e": 6032, "s": 5971, "text": "The output is a Pandas Series which contains the row values." }, { "code": null, "e": 6043, "s": 6032, "text": "df.iloc[0]" }, { "code": null, "e": 6199, "s": 6043, "text": "The appearance is a bit confusing as the output is a Pandas Series. If you want this as a row itself, simply use the index values inside a list as follows:" }, { "code": null, "e": 6212, "s": 6199, "text": "df.iloc[[0]]" }, { "code": null, "e": 6281, "s": 6212, "text": "This is a Pandas DataFrame which contains 1 row and all the columns!" }, { "code": null, "e": 6393, "s": 6281, "text": "We can extract multiple rows of a Pandas DataFrame using its row indices. We include row indices inside a list:" }, { "code": null, "e": 6425, "s": 6393, "text": "[row_index_1, row_index_2, ...]" }, { "code": null, "e": 6469, "s": 6425, "text": "Then we include this list inside df.iloc[]." }, { "code": null, "e": 6510, "s": 6469, "text": "df.iloc[[row_index_1, row_index_2, ...]]" }, { "code": null, "e": 6544, "s": 6510, "text": "The output is a Pandas DataFrame." }, { "code": null, "e": 6566, "s": 6544, "text": "df.iloc[[0, 25, 100]]" }, { "code": null, "e": 6615, "s": 6566, "text": "The negative indices count rows from the bottom." }, { "code": null, "e": 6645, "s": 6615, "text": "df.iloc[[-1, -2, -3, -4, -5]]" }, { "code": null, "e": 6792, "s": 6645, "text": "When we combine column selection and row slicing, it is referred to as Indexing. Here, we can use .loc and .iloc attributes of a Pandas DataFrame." }, { "code": null, "e": 6876, "s": 6792, "text": "If we specify a single row and a single column, the intersection is a single value!" }, { "code": null, "e": 6890, "s": 6876, "text": "df.iloc[0, 0]" }, { "code": null, "e": 6994, "s": 6890, "text": "Keep in mind that we cannot use column or row names inside .iloc[]. Only the index numbers can be used." }, { "code": null, "e": 7188, "s": 6994, "text": "Here we can use row or column names inside .loc[]. Also keep in mind that, in our data, the row labels are the same as the row indices. The following code gives the same result as in Method 12." }, { "code": null, "e": 7209, "s": 7188, "text": "df.loc[0, 'alcohol']" }, { "code": null, "e": 7232, "s": 7209, "text": "The general syntax is:" }, { "code": null, "e": 7319, "s": 7232, "text": "df.iloc[[row_index_1, row_index_2, ...], [column_index_1, column_index_2, ...]]" }, { "code": null, "e": 7353, "s": 7319, "text": "The output is a Pandas DataFrame." }, { "code": null, "e": 7385, "s": 7353, "text": "df.iloc[[0, 5, 100], [0, 3, 7]]" }, { "code": null, "e": 7408, "s": 7385, "text": "The general syntax is:" }, { "code": null, "e": 7488, "s": 7408, "text": "df.loc[[row_name, row_name_2, ...], [column_name_1, column_name_2, ...]]" }, { "code": null, "e": 7522, "s": 7488, "text": "The output is a Pandas DataFrame." }, { "code": null, "e": 7569, "s": 7522, "text": "df.loc[[0, 5, 100], ['alcohol', 'ash', 'hue']]" }, { "code": null, "e": 7704, "s": 7569, "text": "Here we can use row or column names inside .loc[]. Also keep in mind that, in our data, the row names are the same as the row indices." }, { "code": null, "e": 7812, "s": 7704, "text": "This can be easily done with the : notation. For this, rows and columns should be positioned consecutively." }, { "code": null, "e": 7830, "s": 7812, "text": "df.iloc[0:6, 0:5]" }, { "code": null, "e": 7850, "s": 7830, "text": "Another example is:" }, { "code": null, "e": 7882, "s": 7850, "text": "df.loc[0:6, ['alcohol', 'ash']]" }, { "code": null, "e": 8047, "s": 7882, "text": "When we select rows and columns based on specific criteria or conditions, it is referred to as Filtering. We can also combine the above-discussed methods with this." }, { "code": null, "e": 8143, "s": 8047, "text": "Let’s subset our data when alcohol > 14.3. Here, we select all the columns when alcohol > 14.3." }, { "code": null, "e": 8164, "s": 8143, "text": "df['alcohol'] > 14.3" }, { "code": null, "e": 8273, "s": 8164, "text": "This is a Pandas Series of boolean data type. We can use this Series to get the required subset of the data." }, { "code": null, "e": 8298, "s": 8273, "text": "df[df['alcohol'] > 14.3]" }, { "code": null, "e": 8466, "s": 8298, "text": "Let’s subset our data when alcohol > 14.3. This time, we select only 3 columns when alcohol > 14.3. For this, we can combine the above filtering technique with .loc[]." }, { "code": null, "e": 8528, "s": 8466, "text": "df.loc[df['alcohol'] > 14.3, ['alcohol', 'ash', 'hue']]" }, { "code": null, "e": 8710, "s": 8528, "text": "Let’s subset our data when alcohol > 14.3 AND alcohol < 14.6. Here, we use two conditions and combine them with the AND operator. Each condition should be surrounded in parentheses." }, { "code": null, "e": 8762, "s": 8710, "text": "df[(df['alcohol'] > 14.3) & (df['alcohol'] < 14.6)]" }, { "code": null, "e": 8857, "s": 8762, "text": "A similar type of filtering discussed in Method 19 can be achieved using the between() method." }, { "code": null, "e": 8895, "s": 8857, "text": "df[df['alcohol'].between(14.3, 14.6)]" }, { "code": null, "e": 9120, "s": 8895, "text": "Here, the output is a bit different because the between() method includes the values of the lower bound (14.3) and upper bound (14.6) by default. However, we can pass inclusive=False if we don’t want the inclusive selection." }, { "code": null, "e": 9199, "s": 9120, "text": "df[df['alcohol'].between(14.3, 14.6, inclusive=False)]" }, { "code": null, "e": 9268, "s": 9199, "text": "This subset is exactly the same as the subset obtained in Method 19." }, { "code": null, "e": 9348, "s": 9268, "text": "Here, the two conditions are made using two different columns: alcohol and hue." }, { "code": null, "e": 9395, "s": 9348, "text": "df[(df['alcohol'] > 14.3) & (df['hue'] > 1.0)]" }, { "code": null, "e": 9561, "s": 9395, "text": "When we use the AND operator, the filtering happens considering both conditions to be true. If we want at least one condition to be true, we can use the OR operator." }, { "code": null, "e": 9608, "s": 9561, "text": "df[(df['alcohol'] > 14.5) | (df['hue'] > 1.4)]" }, { "code": null, "e": 9749, "s": 9608, "text": "Let’s subset our data based on the minimum and maximum values of the alcohol variable. First, we get the indices of the minimum and maximum:" }, { "code": null, "e": 9830, "s": 9749, "text": "df['alcohol'].idxmin() # Min value indexdf['alcohol'].idxmax() # Max value index" }, { "code": null, "e": 9851, "s": 9830, "text": "Then we use .iloc[]." }, { "code": null, "e": 9917, "s": 9851, "text": "df.iloc[[df['alcohol'].idxmin(), df['alcohol'].idxmax()]]" }, { "code": null, "e": 10302, "s": 9917, "text": "These are not the only ways of subsetting a Pandas DataFrame. There are many more. We can combine multiple methods for complex subsetting. This post helps you to be familiar with subsetting syntax. And also, you’re now familiar with the terms Selection, Slicing, Indexing and Filtering. Also, keep in mind that .iloc needs integer values (i for integer) while .loc needs label values." }, { "code": null, "e": 10497, "s": 10302, "text": "This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee." }, { "code": null, "e": 10559, "s": 10497, "text": "Sign-up link: https://rukshanpramoditha.medium.com/membership" }, { "code": null, "e": 10661, "s": 10559, "text": "Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!" } ]
Difference between Batch Gradient Descent and Stochastic Gradient Descent | by Aerin Kim | Towards Data Science
Let’s take the simplest example, which is Linear Regression. As always, we start with the cost function. Linear Regression Recap done. Now, what was the Gradient Descent algorithm? In the above algorithm says, to perform the GD, we need to calculate the gradient of the cost function J. And to calculate the gradient of the cost function, we need to sum (yellow circle!) the cost of each sample. If we have 3 million samples, we have to loop through 3 million times or use the dot product. Here is the Python code: def gradientDescent(X, y, theta, alpha, num_iters): """ Performs gradient descent to learn theta """ m = y.size # number of training examples for i in range(num_iters): y_hat = np.dot(X, theta) theta = theta - alpha * (1.0/m) * np.dot(X.T, y_hat-y) return theta Do you see np.dot(X.T, y_hat-y) above? That’s the vectorized version of “looping through (summing) 3 million samples”. Wait... just to move a single step towards the minimum, do we really have to calculate each cost 3 million times? Yes. If you insist to use GD. But if you use Stochastic GD, you don’t have to! Basically, in SGD, we are using the cost gradient of 1 example at each iteration, instead of using the sum of the cost gradient of ALL examples. def SGD(f, theta0, alpha, num_iters): """ Arguments: f -- the function to optimize, it takes a single argument and yield two outputs, a cost and the gradient with respect to the arguments theta0 -- the initial point to start SGD from num_iters -- total iterations to run SGD for Return: theta -- the parameter value after SGD finishes """ start_iter = 0 theta= theta0 for iter in xrange(start_iter + 1, num_iters + 1): _, grad = f(theta) theta = theta - (alpha * grad) # there is NO dot product! return theta Well, Stochastic Gradient Descent has a fancy name, but I guess it’s a pretty simple algorithm! A few things to note: a) In SGD, before for-looping, you need to randomly shuffle the training examples. b) In SGD, because it’s using only one example at a time, its path to the minima is noisier (more random) than that of the batch gradient. But it’s ok as we are indifferent to the path, as long as it gives us the minimum AND the shorter training time. c) Mini-batch gradient descent uses n data points (instead of 1 sample in SGD) at each iteration. If you like my post, could you please clap? It gives me motivation to write more. :)
[ { "code": null, "e": 233, "s": 172, "text": "Let’s take the simplest example, which is Linear Regression." }, { "code": null, "e": 277, "s": 233, "text": "As always, we start with the cost function." }, { "code": null, "e": 307, "s": 277, "text": "Linear Regression Recap done." }, { "code": null, "e": 353, "s": 307, "text": "Now, what was the Gradient Descent algorithm?" }, { "code": null, "e": 662, "s": 353, "text": "In the above algorithm says, to perform the GD, we need to calculate the gradient of the cost function J. And to calculate the gradient of the cost function, we need to sum (yellow circle!) the cost of each sample. If we have 3 million samples, we have to loop through 3 million times or use the dot product." }, { "code": null, "e": 687, "s": 662, "text": "Here is the Python code:" }, { "code": null, "e": 985, "s": 687, "text": "def gradientDescent(X, y, theta, alpha, num_iters): \"\"\" Performs gradient descent to learn theta \"\"\" m = y.size # number of training examples for i in range(num_iters): y_hat = np.dot(X, theta) theta = theta - alpha * (1.0/m) * np.dot(X.T, y_hat-y) return theta" }, { "code": null, "e": 1104, "s": 985, "text": "Do you see np.dot(X.T, y_hat-y) above? That’s the vectorized version of “looping through (summing) 3 million samples”." }, { "code": null, "e": 1218, "s": 1104, "text": "Wait... just to move a single step towards the minimum, do we really have to calculate each cost 3 million times?" }, { "code": null, "e": 1248, "s": 1218, "text": "Yes. If you insist to use GD." }, { "code": null, "e": 1297, "s": 1248, "text": "But if you use Stochastic GD, you don’t have to!" }, { "code": null, "e": 1442, "s": 1297, "text": "Basically, in SGD, we are using the cost gradient of 1 example at each iteration, instead of using the sum of the cost gradient of ALL examples." }, { "code": null, "e": 2042, "s": 1442, "text": "def SGD(f, theta0, alpha, num_iters): \"\"\" Arguments: f -- the function to optimize, it takes a single argument and yield two outputs, a cost and the gradient with respect to the arguments theta0 -- the initial point to start SGD from num_iters -- total iterations to run SGD for Return: theta -- the parameter value after SGD finishes \"\"\" start_iter = 0 theta= theta0 for iter in xrange(start_iter + 1, num_iters + 1): _, grad = f(theta) theta = theta - (alpha * grad) # there is NO dot product! return theta" }, { "code": null, "e": 2138, "s": 2042, "text": "Well, Stochastic Gradient Descent has a fancy name, but I guess it’s a pretty simple algorithm!" }, { "code": null, "e": 2160, "s": 2138, "text": "A few things to note:" }, { "code": null, "e": 2243, "s": 2160, "text": "a) In SGD, before for-looping, you need to randomly shuffle the training examples." }, { "code": null, "e": 2495, "s": 2243, "text": "b) In SGD, because it’s using only one example at a time, its path to the minima is noisier (more random) than that of the batch gradient. But it’s ok as we are indifferent to the path, as long as it gives us the minimum AND the shorter training time." }, { "code": null, "e": 2593, "s": 2495, "text": "c) Mini-batch gradient descent uses n data points (instead of 1 sample in SGD) at each iteration." } ]
Doubly linked list Insertion at given position | Practice | GeeksforGeeks
Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list. Example 1: Input: LinkedList: 2<->4<->5 p = 2, x = 6 Output: 2 4 5 6 Explanation: p = 2, and x = 6. So, 6 is inserted after p, i.e, at position 3 (0-based indexing). Example 2: Input: LinkedList: 1<->2<->3<->4 p = 0, x = 44 Output: 1 44 2 3 4 Explanation: p = 0, and x = 44 . So, 44 is inserted after p, i.e, at position 1 (0-based indexing). Your Task: The task is to complete the function addNode() which head reference, position and data to be inserted as the arguments, with no return type. Expected Time Complexity : O(N) Expected Auxilliary Space : O(1) Constraints: 1 <= N <= 104 0 <= p < N 0 mayank20211 week ago C++ : 0.1/1.19void addNode(Node *head, int pos, int data){ if(pos<0) pos=0; Node* newnode= new Node(data); Node* temp=head; while(pos--) temp=temp->next; newnode->prev=temp; newnode->next=temp->next; temp->next=newnode; if(newnode->next) newnode->next->prev=newnode; } +1 chouhanakshat211 month ago Easy Solution void addNode(Node head, int pos, int data) { Node node1 = new Node(data); if(head==null) { node1.prev = null; head = node1; return; } Node n=head; int count=0; while (count!=pos) { n=n.next; count++; } if(n.next==null) { //last k next me new node ka ref. n.next=node1; // new node k previous me last ka ref. node1.prev=n; return; } //new node k next me n ka next node1.next=n.next; //n k next ka previous ka ref me node1 k ref n.next.prev=node1; //n k next me node1 ka ref. n.next=node1; //node1 k prev me ka next ref. node1.prev=n; } +3 rmn51241 month ago //Function to insert a new node at given position in doubly linked list. void addNode(Node *head, int pos, int data) { if(!head) return; Node*temp=head; while(pos--){ temp=temp->next; } Node*node=new Node(data); if(!temp->next){ // if it's last node temp->next=node; node->prev=temp; node->next=NULL; return; } Node*nxt=temp->next; // else update 4 links temp->next=node; node->next=nxt; nxt->prev=temp; node->prev=temp; return; } 0 hpthor202011 month ago def addNode(head, p, data): # Code here temp=Node(data) if head==None and p==1: return temp if head==None and pos>1: return None current=head while p: p-=1 current=current.next if current.next==None: temp.prev=current current.next=temp return head temp.next=current.next current.next.prev=temp temp.prev=current current.next=temp return head +1 tarunkanade2 months ago 2.2/5.2 void addNode(Node head_ref, int pos, int data) { // Your code here Node cur = head_ref, temp = new Node(data); for(int i=1; i <= pos; i++){ cur = cur.next; } temp.next = cur.next; cur.next = temp; temp.prev = cur; } 0 sadiiqyare662 months ago void addNode(Node head, int pos, int data) { // Your code here Node temp = new Node(data); Node curr = head; for(int i = 0; i < pos; i++){ curr = curr.next; } if(curr.next != null){ temp.next = curr.next; curr.next = temp; temp.prev = curr; curr.next.prev = temp; } else{ curr.next = temp; temp.prev = curr; } } 0 priyeshanand92 months ago void addNode(Node *head, int pos, int data){ int c=0; pos++; Node *p=head; while(p){ c++; if(c==pos) break; p=p->next; } Node *q=new Node(data); Node *temp=p->next; p->next=q; q->prev=p; q->next=temp; if(temp!=NULL) temp->prev=q;} +2 madhukartemba2 months ago JAVA SOLUTION: class GfG { //Function to insert a new node at given position in doubly linked list. void addNode(Node head_ref, int pos, int data) { int count = 0; while(head_ref!=null && count!=pos) { count++; head_ref = head_ref.next; } Node nextnode = head_ref.next; head_ref.next = new Node(data); head_ref.next.prev = head_ref; head_ref.next.next = nextnode; if(nextnode!=null) nextnode.prev = head_ref.next; } } 0 surabhichoubey552 months ago void addNode(struct Node *head, int pos, int data){ if(head == NULL) { return; } if(pos == -1 && head!=NULL) { struct Node *newnode = new Node(data);//if the givin possision is -1 thats means //we wants to insert node after p which is head possision } struct Node*temp = head; while(temp!=NULL&& pos) { temp = temp->next; pos--; } if(temp->next!=NULL)//if temp next is not null thats mean after temp there is a node //which addres we will store in aftertempNode then do furthure task { struct Node *newnode = new Node(data); struct Node *aftertempNode = temp->next; temp->next = newnode; newnode->prev = temp; newnode->next = aftertempNode; aftertempNode->prev = newnode; } else{ //we will reach here when temp next is null thats mean we are inserting //a node at last of the linked list struct Node *newnode = new Node(data); temp->next = newnode; newnode->prev = temp; }} +1 krishnakantbha2 months ago Best C++ Solution void addNode(Node *head, int pos, int data){ Node* temp = new Node(data); Node* curr = head; int cnt = 0; while(cnt != pos){ curr = curr->next; cnt++; } temp->next = curr->next; if(curr->next != NULL) curr->next->prev = temp; curr->next = temp; temp->prev = curr;} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 404, "s": 238, "text": "Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list." }, { "code": null, "e": 415, "s": 404, "text": "Example 1:" }, { "code": null, "e": 572, "s": 415, "text": "Input:\nLinkedList: 2<->4<->5\np = 2, x = 6 \nOutput: 2 4 5 6\nExplanation: p = 2, and x = 6. So, 6 is\ninserted after p, i.e, at position 3\n(0-based indexing).\n" }, { "code": null, "e": 583, "s": 572, "text": "Example 2:" }, { "code": null, "e": 749, "s": 583, "text": "Input:\nLinkedList: 1<->2<->3<->4\np = 0, x = 44\nOutput: 1 44 2 3 4\nExplanation: p = 0, and x = 44 . So, 44\nis inserted after p, i.e, at position 1\n(0-based indexing)." }, { "code": null, "e": 901, "s": 749, "text": "Your Task:\nThe task is to complete the function addNode() which head reference, position and data to be inserted as the arguments, with no return type." }, { "code": null, "e": 966, "s": 901, "text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(1)" }, { "code": null, "e": 1004, "s": 966, "text": "Constraints:\n1 <= N <= 104\n0 <= p < N" }, { "code": null, "e": 1008, "s": 1006, "text": "0" }, { "code": null, "e": 1029, "s": 1008, "text": "mayank20211 week ago" }, { "code": null, "e": 1202, "s": 1029, "text": "C++ : 0.1/1.19void addNode(Node *head, int pos, int data){ if(pos<0) pos=0; Node* newnode= new Node(data); Node* temp=head; while(pos--) temp=temp->next;" }, { "code": null, "e": 1370, "s": 1202, "text": " newnode->prev=temp; newnode->next=temp->next; temp->next=newnode; if(newnode->next) newnode->next->prev=newnode; }" }, { "code": null, "e": 1373, "s": 1370, "text": "+1" }, { "code": null, "e": 1400, "s": 1373, "text": "chouhanakshat211 month ago" }, { "code": null, "e": 1414, "s": 1400, "text": "Easy Solution" }, { "code": null, "e": 2253, "s": 1414, "text": " void addNode(Node head, int pos, int data)\n\t{\n\t\t Node node1 = new Node(data);\n\n if(head==null)\n {\n node1.prev = null;\n head = node1;\n return;\n }\n\n Node n=head;\n int count=0;\n\n while (count!=pos)\n {\n n=n.next;\n count++;\n }\n\n if(n.next==null)\n {\n //last k next me new node ka ref.\n n.next=node1;\n // new node k previous me last ka ref.\n node1.prev=n;\n return;\n }\n\n //new node k next me n ka next\n node1.next=n.next;\n \n \n //n k next ka previous ka ref me node1 k ref\n n.next.prev=node1;\n\n //n k next me node1 ka ref.\n n.next=node1;\n\n //node1 k prev me ka next ref.\n node1.prev=n;\n\t}" }, { "code": null, "e": 2256, "s": 2253, "text": "+3" }, { "code": null, "e": 2275, "s": 2256, "text": "rmn51241 month ago" }, { "code": null, "e": 2786, "s": 2275, "text": "\n//Function to insert a new node at given position in doubly linked list.\nvoid addNode(Node *head, int pos, int data)\n{\n if(!head) return;\n \n Node*temp=head;\n while(pos--){\n temp=temp->next;\n }\n Node*node=new Node(data);\n if(!temp->next){ // if it's last node\n temp->next=node;\n node->prev=temp;\n node->next=NULL;\n return;\n }\n Node*nxt=temp->next; // else update 4 links\n temp->next=node;\n node->next=nxt;\n nxt->prev=temp;\n node->prev=temp;\n return;\n}" }, { "code": null, "e": 2788, "s": 2786, "text": "0" }, { "code": null, "e": 2811, "s": 2788, "text": "hpthor202011 month ago" }, { "code": null, "e": 3219, "s": 2811, "text": "def addNode(head, p, data): # Code here temp=Node(data) if head==None and p==1: return temp if head==None and pos>1: return None current=head while p: p-=1 current=current.next if current.next==None: temp.prev=current current.next=temp return head temp.next=current.next current.next.prev=temp temp.prev=current current.next=temp return head" }, { "code": null, "e": 3222, "s": 3219, "text": "+1" }, { "code": null, "e": 3246, "s": 3222, "text": "tarunkanade2 months ago" }, { "code": null, "e": 3254, "s": 3246, "text": "2.2/5.2" }, { "code": null, "e": 3498, "s": 3254, "text": "void addNode(Node head_ref, int pos, int data)\n\t{\n\t\t// Your code here\n\t\tNode cur = head_ref, temp = new Node(data);\n\t\t\n\t\tfor(int i=1; i <= pos; i++){\n\t\t cur = cur.next;\n\t\t}\n\t\t\n\t\ttemp.next = cur.next;\n\t\tcur.next = temp;\n\t\ttemp.prev = cur;\n\t}" }, { "code": null, "e": 3500, "s": 3498, "text": "0" }, { "code": null, "e": 3525, "s": 3500, "text": "sadiiqyare662 months ago" }, { "code": null, "e": 3971, "s": 3525, "text": "void addNode(Node head, int pos, int data)\n\t{\n\t\t// Your code here\n\t\tNode temp = new Node(data);\n\t\tNode curr = head;\n\t\t\n\t\t for(int i = 0; i < pos; i++){\n\t\t curr = curr.next;\n\t\t }\n\t\t \n\t\t if(curr.next != null){\n\t\t temp.next = curr.next;\n\t\t curr.next = temp;\n\t\t temp.prev = curr;\n\t\t curr.next.prev = temp;\n\t\t }\n\t\t else{\n\t\t curr.next = temp;\n\t\t temp.prev = curr;\n\t\t }\n\t\t \n\t\t\n\t}" }, { "code": null, "e": 3973, "s": 3971, "text": "0" }, { "code": null, "e": 3999, "s": 3973, "text": "priyeshanand92 months ago" }, { "code": null, "e": 4257, "s": 3999, "text": "void addNode(Node *head, int pos, int data){ int c=0; pos++; Node *p=head; while(p){ c++; if(c==pos) break; p=p->next; } Node *q=new Node(data); Node *temp=p->next; p->next=q; q->prev=p; q->next=temp; if(temp!=NULL) temp->prev=q;}" }, { "code": null, "e": 4262, "s": 4259, "text": "+2" }, { "code": null, "e": 4288, "s": 4262, "text": "madhukartemba2 months ago" }, { "code": null, "e": 4303, "s": 4288, "text": "JAVA SOLUTION:" }, { "code": null, "e": 4797, "s": 4303, "text": "class GfG\n{\n //Function to insert a new node at given position in doubly linked list.\n void addNode(Node head_ref, int pos, int data)\n\t{\n\t int count = 0;\n\t while(head_ref!=null && count!=pos)\n\t {\n\t count++;\n\t head_ref = head_ref.next;\n\t }\n\t \n\t Node nextnode = head_ref.next;\n\t head_ref.next = new Node(data);\n\t head_ref.next.prev = head_ref;\n\t head_ref.next.next = nextnode;\n\t if(nextnode!=null) nextnode.prev = head_ref.next;\n\t \n\t \n\t}\n}" }, { "code": null, "e": 4799, "s": 4797, "text": "0" }, { "code": null, "e": 4828, "s": 4799, "text": "surabhichoubey552 months ago" }, { "code": null, "e": 5824, "s": 4828, "text": "void addNode(struct Node *head, int pos, int data){ if(head == NULL) { return; } if(pos == -1 && head!=NULL) { struct Node *newnode = new Node(data);//if the givin possision is -1 thats means //we wants to insert node after p which is head possision } struct Node*temp = head; while(temp!=NULL&& pos) { temp = temp->next; pos--; } if(temp->next!=NULL)//if temp next is not null thats mean after temp there is a node //which addres we will store in aftertempNode then do furthure task { struct Node *newnode = new Node(data); struct Node *aftertempNode = temp->next; temp->next = newnode; newnode->prev = temp; newnode->next = aftertempNode; aftertempNode->prev = newnode; } else{ //we will reach here when temp next is null thats mean we are inserting //a node at last of the linked list struct Node *newnode = new Node(data); temp->next = newnode; newnode->prev = temp; }}" }, { "code": null, "e": 5827, "s": 5824, "text": "+1" }, { "code": null, "e": 5854, "s": 5827, "text": "krishnakantbha2 months ago" }, { "code": null, "e": 5872, "s": 5854, "text": "Best C++ Solution" }, { "code": null, "e": 6052, "s": 5874, "text": "void addNode(Node *head, int pos, int data){ Node* temp = new Node(data); Node* curr = head; int cnt = 0; while(cnt != pos){ curr = curr->next; cnt++; }" }, { "code": null, "e": 6179, "s": 6052, "text": " temp->next = curr->next; if(curr->next != NULL) curr->next->prev = temp; curr->next = temp; temp->prev = curr;}" }, { "code": null, "e": 6325, "s": 6179, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6361, "s": 6325, "text": " Login to access your submissions. " }, { "code": null, "e": 6371, "s": 6361, "text": "\nProblem\n" }, { "code": null, "e": 6381, "s": 6371, "text": "\nContest\n" }, { "code": null, "e": 6444, "s": 6381, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6592, "s": 6444, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6800, "s": 6592, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6906, "s": 6800, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find the unique pair combinations of an R data frame column values.
To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function. For Example, if we have a data frame called df that contains a column say x then we can find the unique pair combinations of all column values by using the command given below − combn(unique(df$x),2,FUN=paste,collapse=' ') Following snippet creates a sample data frame − Grp<-sample(c("I","II","III"),20,replace=TRUE) df1<-data.frame(Grp) df1 The following dataframe is created Grp 1 II 2 III 3 I 4 I 5 II 6 I 7 II 8 III 9 III 10 I 11 I 12 I 13 I 14 II 15 III 16 II 17 I 18 II 19 II 20 III To find unique pair combinations for values in column Grp of df1 on the above created data frame, add the following code to the above snippet − Grp<-sample(c("I","II","III"),20,replace=TRUE) df1<-data.frame(Grp) combn(unique(df1$Grp),2,FUN=paste,collapse=' ') If you execute all the above given snippets as a single program, it generates the following Output − [1] "II III" "II I" "III I" Following snippet creates a sample data frame − Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) df2<-data.frame(Class) df2 The following dataframe is created Class 1 Second 2 Fourth 3 Fourth 4 Second 5 Fourth 6 Third 7 Fourth 8 Third 9 First 10 Fifth 11 Second 12 Second 13 Third 14 Second 15 First 16 Second 17 Fourth 18 First 19 Fifth 20 First To find unique pair combinations for values in column Class of df2 on the above created data frame, add the following code to the above snippet − Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) df2<-data.frame(Class) combn(unique(df2$Class),2,FUN=paste,collapse=' ') If you execute all the above given snippets as a single program, it generates the following Output − [1] "Second Fourth" "Second Third" "Second First" "Second Fifth" [5] "Fourth Third" "Fourth First" "Fourth Fifth" "Third First" [9] "Third Fifth" "First Fifth" Following snippet creates a sample data frame − Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE) df3<-data.frame(Category) df3 The following dataframe is created Category 1 Large 2 Extra Small 3 Extra Small 4 Small 5 Large 6 Extra Small 7 Medium 8 Large 9 Large 10 Extra Large 11 Extra Small 12 Extra Small 13 Extra Small 14 Extra Large 15 Large 16 Extra Small 17 Large 18 Medium 19 Extra Large 20 Extra Large To find unique pair combinations for values in column Category of df3 on the above created data frame, add the following code to the above snippet − Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE) df3<-data.frame(Category) combn(unique(df3$Category),2,FUN=paste,collapse=' ') If you execute all the above given snippets as a single program, it generates the following Output − [1] "Large Extra Small" "Large Small" [3] "Large Medium" "Large Extra Large" [5] "Extra Small Small" "Extra Small Medium" [7] "Extra Small Extra Large" "Small Medium" [9] "Small Extra Large" "Medium Extra Large"
[ { "code": null, "e": 1187, "s": 1062, "text": "To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function." }, { "code": null, "e": 1365, "s": 1187, "text": "For Example, if we have a data frame called df that contains a column say x then we can find the unique pair combinations of all column values by using the command given below −" }, { "code": null, "e": 1410, "s": 1365, "text": "combn(unique(df$x),2,FUN=paste,collapse=' ')" }, { "code": null, "e": 1458, "s": 1410, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1530, "s": 1458, "text": "Grp<-sample(c(\"I\",\"II\",\"III\"),20,replace=TRUE)\ndf1<-data.frame(Grp)\ndf1" }, { "code": null, "e": 1565, "s": 1530, "text": "The following dataframe is created" }, { "code": null, "e": 1677, "s": 1565, "text": "Grp\n1 II\n2 III\n3 I\n4 I\n5 II\n6 I\n7 II\n8 III\n9 III\n10 I\n11 I\n12 I\n13 I\n14 II\n15 III\n16 II\n17 I\n18 II\n19 II\n20 III" }, { "code": null, "e": 1821, "s": 1677, "text": "To find unique pair combinations for values in column Grp of df1 on the above created data frame, add the following code to the above snippet −" }, { "code": null, "e": 1937, "s": 1821, "text": "Grp<-sample(c(\"I\",\"II\",\"III\"),20,replace=TRUE)\ndf1<-data.frame(Grp)\ncombn(unique(df1$Grp),2,FUN=paste,collapse=' ')" }, { "code": null, "e": 2038, "s": 1937, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 2066, "s": 2038, "text": "[1] \"II III\" \"II I\" \"III I\"" }, { "code": null, "e": 2114, "s": 2066, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 2217, "s": 2114, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\ndf2<-data.frame(Class)\ndf2" }, { "code": null, "e": 2252, "s": 2217, "text": "The following dataframe is created" }, { "code": null, "e": 2440, "s": 2252, "text": "Class\n1 Second\n2 Fourth\n3 Fourth\n4 Second\n5 Fourth\n6 Third\n7 Fourth\n8 Third\n9 First\n10 Fifth\n11 Second\n12 Second\n13 Third\n14 Second\n15 First\n16 Second\n17 Fourth\n18 First\n19 Fifth\n20 First" }, { "code": null, "e": 2586, "s": 2440, "text": "To find unique pair combinations for values in column Class of df2 on the above created data frame, add the following code to the above snippet −" }, { "code": null, "e": 2735, "s": 2586, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\ndf2<-data.frame(Class)\ncombn(unique(df2$Class),2,FUN=paste,collapse=' ')" }, { "code": null, "e": 2836, "s": 2735, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 2996, "s": 2836, "text": "[1] \"Second Fourth\" \"Second Third\" \"Second First\" \"Second Fifth\"\n[5] \"Fourth Third\" \"Fourth First\" \"Fourth Fifth\" \"Third First\"\n[9] \"Third Fifth\" \"First Fifth\"" }, { "code": null, "e": 3044, "s": 2996, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 3164, "s": 3044, "text": "Category<-sample(c(\"Extra Small\",\"Small\",\"Medium\",\"Large\",\"Extra Large\"),20,replace=TRUE)\ndf3<-data.frame(Category)\ndf3" }, { "code": null, "e": 3199, "s": 3164, "text": "The following dataframe is created" }, { "code": null, "e": 3447, "s": 3199, "text": "Category\n1 Large\n2 Extra Small\n3 Extra Small\n4 Small\n5 Large\n6 Extra Small\n7 Medium\n8 Large\n9 Large\n10 Extra Large\n11 Extra Small\n12 Extra Small\n13 Extra Small\n14 Extra Large\n15 Large\n16 Extra Small\n17 Large\n18 Medium\n19 Extra Large\n20 Extra Large" }, { "code": null, "e": 3596, "s": 3447, "text": "To find unique pair combinations for values in column Category of df3 on the above created data frame, add the following code to the above snippet −" }, { "code": null, "e": 3765, "s": 3596, "text": "Category<-sample(c(\"Extra Small\",\"Small\",\"Medium\",\"Large\",\"Extra Large\"),20,replace=TRUE)\ndf3<-data.frame(Category)\ncombn(unique(df3$Category),2,FUN=paste,collapse=' ')" }, { "code": null, "e": 3866, "s": 3765, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 4078, "s": 3866, "text": "[1] \"Large Extra Small\" \"Large Small\"\n[3] \"Large Medium\" \"Large Extra Large\"\n[5] \"Extra Small Small\" \"Extra Small Medium\"\n[7] \"Extra Small Extra Large\" \"Small Medium\"\n[9] \"Small Extra Large\" \"Medium Extra Large\"" } ]
Java Program to display date with day name in short format
Firstly, set the format with SimpleDateFormat class Format dateFormat = new SimpleDateFormat("EEE, dd/MM/yyyy"); Above, the “EEE” is set to display the name of the day i.e. Monday, Tuesday, Wednesday, etc. Now, to display the date − String res = dateFormat.format(new Date()); The following is an example − Live Demo import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] argv) throws Exception { Format dateFormat = new SimpleDateFormat("EEE, dd/MM/yyyy"); String res = dateFormat.format(new Date()); System.out.println("Date = " + res); } } Date = Thu, 22/11/2018
[ { "code": null, "e": 1114, "s": 1062, "text": "Firstly, set the format with SimpleDateFormat class" }, { "code": null, "e": 1175, "s": 1114, "text": "Format dateFormat = new SimpleDateFormat(\"EEE, dd/MM/yyyy\");" }, { "code": null, "e": 1268, "s": 1175, "text": "Above, the “EEE” is set to display the name of the day i.e. Monday, Tuesday, Wednesday, etc." }, { "code": null, "e": 1295, "s": 1268, "text": "Now, to display the date −" }, { "code": null, "e": 1339, "s": 1295, "text": "String res = dateFormat.format(new Date());" }, { "code": null, "e": 1369, "s": 1339, "text": "The following is an example −" }, { "code": null, "e": 1380, "s": 1369, "text": " Live Demo" }, { "code": null, "e": 1711, "s": 1380, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Format dateFormat = new SimpleDateFormat(\"EEE, dd/MM/yyyy\");\n String res = dateFormat.format(new Date());\n System.out.println(\"Date = \" + res);\n }\n}" }, { "code": null, "e": 1734, "s": 1711, "text": "Date = Thu, 22/11/2018" } ]
Mid-Square hashing in C++.
The mid-square method is a method of generating pseudorandom numbers. This method was invented by John von Neumann and was described at a conference in 1949 In this technique, an initial seed value is taken and it is squared. In this technique, an initial seed value is taken and it is squared. Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed.Let us take 3456 as seed. Its square is 11943936Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721Take middle 4 digits as new seed i.e. 0947Repeat this process Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed. Let us take 3456 as seed. Its square is 11943936 Let us take 3456 as seed. Its square is 11943936 Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721 Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721 Take middle 4 digits as new seed i.e. 0947 Take middle 4 digits as new seed i.e. 0947 Repeat this process Repeat this process 1. Choose initial seed value 2. Take the square of the seed value 3. Update seed by taking n digits from previous result #include <iostream> #include <ctime> using namespace std; long long getTime(){ time_t t = time(NULL); struct tm *tm = localtime(&t); long long x = (tm->tm_hour) * 50000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 5000 + (tm->tm_mday) * 50 + (tm->tm_year); return x; } long getHash(){ long long key = getTime(); key = key * key; key = key / 10000; key = key % 100000000; return key; } int main(){ cout << "Random number: " << getHash() << endl; return 0; } When you compile and execute the above program. It generates the following output− Random number: 10088419
[ { "code": null, "e": 1219, "s": 1062, "text": "The mid-square method is a method of generating pseudorandom numbers. This method was invented by John von Neumann and was described at a conference in 1949" }, { "code": null, "e": 1288, "s": 1219, "text": "In this technique, an initial seed value is taken and it is squared." }, { "code": null, "e": 1357, "s": 1288, "text": "In this technique, an initial seed value is taken and it is squared." }, { "code": null, "e": 1651, "s": 1357, "text": "Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed.Let us take 3456 as seed. Its square is 11943936Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721Take middle 4 digits as new seed i.e. 0947Repeat this process" }, { "code": null, "e": 1766, "s": 1651, "text": "Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed." }, { "code": null, "e": 1815, "s": 1766, "text": "Let us take 3456 as seed. Its square is 11943936" }, { "code": null, "e": 1864, "s": 1815, "text": "Let us take 3456 as seed. Its square is 11943936" }, { "code": null, "e": 1935, "s": 1864, "text": "Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721" }, { "code": null, "e": 2006, "s": 1935, "text": "Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721" }, { "code": null, "e": 2049, "s": 2006, "text": "Take middle 4 digits as new seed i.e. 0947" }, { "code": null, "e": 2092, "s": 2049, "text": "Take middle 4 digits as new seed i.e. 0947" }, { "code": null, "e": 2112, "s": 2092, "text": "Repeat this process" }, { "code": null, "e": 2132, "s": 2112, "text": "Repeat this process" }, { "code": null, "e": 2253, "s": 2132, "text": "1. Choose initial seed value\n2. Take the square of the seed value\n3. Update seed by taking n digits from previous result" }, { "code": null, "e": 2742, "s": 2253, "text": "#include <iostream>\n#include <ctime>\nusing namespace std;\nlong long getTime(){\n time_t t = time(NULL);\n struct tm *tm = localtime(&t);\n long long x = (tm->tm_hour) * 50000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 5000 +\n(tm->tm_mday) * 50 + (tm->tm_year);\n return x;\n}\nlong getHash(){\n long long key = getTime();\n key = key * key;\n key = key / 10000;\n key = key % 100000000;\n return key;\n}\nint main(){\n cout << \"Random number: \" << getHash() << endl;\n return 0;\n}" }, { "code": null, "e": 2825, "s": 2742, "text": "When you compile and execute the above program. It generates the following output−" }, { "code": null, "e": 2849, "s": 2825, "text": "Random number: 10088419" } ]
PyQt5 - Quick Guide
PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc. A list of frequently used modules is given below − QtCore − Core non-GUI classes used by other modules QtCore − Core non-GUI classes used by other modules QtGui − Graphical user interface components QtGui − Graphical user interface components QtMultimedia − Classes for low-level multimedia programming QtMultimedia − Classes for low-level multimedia programming QtNetwork − Classes for network programming QtNetwork − Classes for network programming QtOpenGL − OpenGL support classes QtOpenGL − OpenGL support classes QtScript − Classes for evaluating Qt Scripts QtScript − Classes for evaluating Qt Scripts QtSql − Classes for database integration using SQL QtSql − Classes for database integration using SQL QtSvg − Classes for displaying the contents of SVG files QtSvg − Classes for displaying the contents of SVG files QtWebKit − Classes for rendering and editing HTML QtWebKit − Classes for rendering and editing HTML QtXml − Classes for handling XML QtXml − Classes for handling XML QtWidgets − Classes for creating classic desktop-style UIs QtWidgets − Classes for creating classic desktop-style UIs QtDesigner − Classes for extending Qt Designer QtDesigner − Classes for extending Qt Designer PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license. The latest stable version is PyQt5-5.13.2. Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later. The recommended way to install is using PIP utility − pip3 install PyQt5 To install development tools such as Qt Designer to support PyQt5 wheels, following is the command − pip3 install pyqt5-tools You can also build PyQt5 on Linux/macOS from the source code www.riverbankcomputing.com/static/Downloads/PyQt5 PyQt5 API is not automatically compatible with earlier versions. Hence, Python code involving PyQt4 modules should be upgraded manually by making relevant changes. In this chapter, main differences between PyQt4 and PyQt5 have been listed. PyQt5 is not supported on versions of Python earlier than v2.6. PyQt5 doesn't support connect() method of QObject class for connection between signal and slot. Hence the usage can no more be implemented − QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function) Only the following syntax is defined − widget.signal.connect(slot_function) Classes defined in earlier QtGui module have been distributed in QtGui, QtPrintSupport an QtWidgets modules. In the new QFileDialog class, The getOpenFileNameAndFilter() method is replaced by getOpenFileName(), getOpenFileNamesAndFilter() by getOpenFileNames() and getSaveFileNameAndFilter() by getSaveFileName(). Older signatures of these methods also have changed. PyQt5 doesn’t have provision to define a class that is sub-classed from more than one Qt class. pyuic5 utility (to generates Python code from Designer's XML file) does not support the --pyqt3-wrapper flag. pyrcc5 does not support the -py2 and -py3 flags. The output of pyrcc5 is compatible with all versions of Python v2.6 onwards. PyQt5 always invokes sip.setdestroyonexit() automatically and calls the C++ destructor of all wrapped instances that it owns. Creating a simple GUI application using PyQt involves the following steps − Import QtCore, QtGui and QtWidgets modules from PyQt5 package. Import QtCore, QtGui and QtWidgets modules from PyQt5 package. Create an application object of QApplication class. Create an application object of QApplication class. A QWidget object creates top level window. Add QLabel object in it. A QWidget object creates top level window. Add QLabel object in it. Set the caption of label as "hello world". Set the caption of label as "hello world". Define the size and position of window by setGeometry() method. Define the size and position of window by setGeometry() method. Enter the mainloop of application by app.exec_() method. Enter the mainloop of application by app.exec_() method. Following is the code to execute Hello World program in PyQt − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) w = QWidget() b = QLabel(w) b.setText("Hello World!") w.setGeometry(100,100,200,50) b.move(50,20) w.setWindowTitle("PyQt5") w.show() sys.exit(app.exec_()) if __name__ == '__main__': window() The above code produces the following output − It is also possible to develop an object oriented solution of the above code. Import QtCore, QtGui and QtWidgets modules from PyQt5 package. Import QtCore, QtGui and QtWidgets modules from PyQt5 package. Create an application object of QApplication class. Create an application object of QApplication class. Declare window class based on QWidget class Declare window class based on QWidget class Add a QLabel object and set the caption of label as "hello world". Add a QLabel object and set the caption of label as "hello world". Define the size and position of window by setGeometry() method. Define the size and position of window by setGeometry() method. Enter the mainloop of application by app.exec_() method. Enter the mainloop of application by app.exec_() method. Following is the complete code of the object oriented solution − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class window(QWidget): def __init__(self, parent = None): super(window, self).__init__(parent) self.resize(200,50) self.setWindowTitle("PyQt5") self.label = QLabel(self) self.label.setText("Hello World") font = QFont() font.setFamily("Arial") font.setPointSize(16) self.label.setFont(font) self.label.move(50,20) def main(): app = QApplication(sys.argv) ex = window() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules. Following are some of the frequently used modules − QtCore Core non-GUI classes used by other modules QtGui Graphical user interface components QtMultimedia Classes for low-level multimedia programming QtNetwork Classes for network programming QtOpenGL OpenGL support classes QtScript Classes for evaluating Qt Scripts QtSql Classes for database integration using SQL QtSvg Classes for displaying the contents of SVG files QtWebKit Classes for rendering and editing HTML QtXml Classes for handling XML QtWidgets Classes for creating classic desktop-style UIs. QtDesigner Classes for extending Qt Designer QtAssistant Support for online help PyQt5 development tools is a collection of useful utilities for Qt development. Following is a select list of such utilities − assistant Qt Assistant documentation tool pyqt5designer Qt Designer GUI layout tool linguist Qt Linguist translation tool lrelease compile ts files to qm files pylupdate5 extract translation strings and generate or update ts files qmake Qt software build tool pyqt5qmlscene QML file viewer pyqmlviewer QML file viewer pyrcc5 Qt resource file compiler pyuic5 Qt User Interface Compiler for generating code from ui files pyqmltestrunner running unit tests on QML code qdbus command-line tool to list D-Bus services QDoc documentation generator for software projects. Qhelpgenerator generating and viewing Qt help files. qmlimportscanner parses and reports on QML imports PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can be painted. QApplication class manages the main settings and control flow of a GUI application. It contains main event loop inside which events generated by window elements and other sources are processed and dispatched. It also handles system-wide and application-wide settings. QWidget class, derived from QObject and QPaintDevice classes is the base class for all user interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their own sub-class system. Here is a select list of frequently used widgets QLabel Used to display text or image QLineEdit Allows the user to enter one line of text QTextEdit Allows the user to enter multi-line text QPushButton A command button to invoke action QRadioButton Enables to choose one from multiple options QCheckBox Enables choice of more than one options QSpinBox Enables to increase/decrease an integer value QScrollBar Enables to access contents of a widget beyond display aperture QSlider Enables to change the bound value linearly. QComboBox Provides a dropdown list of items to select from QMenuBar Horizontal bar holding QMenu objects QStatusBar Usually at bottom of QMainWindow, provides status information. QToolBar Usually at top of QMainWindow or floating. Contains action buttons QListView Provides a selectable list of items in ListMode or IconMode QPixmap Off-screen image representation for display on QLabel or QPushButton object QDialog Modal or modeless window which can return information to parent window A typical GUI based application’s top level window is created by QMainWindow widget object. Some widgets as listed above take their appointed place in this main window, while others are placed in the central widget area using various layout managers. The following diagram shows the QMainWindow framework − The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application. Start Qt Designer application which is a part of development tools and installed in scripts folder of the virtual environment. Start designing GUI interface by choosing File → New menu. You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form. The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic5 command line utility. This utility is a wrapper for uic module of Qt toolkit. The usage of pyuic5 is as follows − pyuic5 -x demo.ui -o demo.py In the above command, -x switch adds a small amount of additional code to the generated Python script (from XML) so that it becomes a self-executable standalone application. if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_()) The resultant python script is executed to show the following dialog box − python demo.py The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling. Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events. Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function. First design a simple form with a LineEdit control and a PushButton. It is desired that if button is pressed, contents of text box should be erased. The QLineEdit widget has a clear() method for this purpose. Hence, the button’s clicked signal is to be connected to clear() method of the text box. To start with, choose Edit signals/slots from Edit menu (or press F4). Then highlight the button with mouse and drag the cursor towards the textbox As the mouse is released, a dialog showing signals of button and methods of slot will be displayed. Select clicked signal and clear() method The Signal/Slot Editor window at bottom right will show the result − Save ui and Build and Python code from ui file as shown in the below code − pyuic5 -x signalslot.ui -o signalslot.py Generated Python code will have the connection between signal and slot by the following statement − self.pushButton.clicked.connect(self.lineEdit.clear) Run signalslot.py and enter some text in the LineEdit. The text will be cleared if the button is pressed. Instead of using Designer, you can directly establish signal-slot connection by following syntax − widget.signal.connect(slot_function) Suppose if a function is to be called when a button is clicked. Here, the clicked signal is to be connected to a callable function. It can be achieved in any of the following technique − button.clicked.connect(slot_function) In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_clicked() and b2_clicked() on clicking b1 and b2 respectively. When b1 is clicked, the clicked() signal is connected to b1_clicked() function − b1.clicked.connect(b1_clicked()) When b2 is clicked, the clicked() signal is connected to b2_clicked() function. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QDialog() b1 = QPushButton(win) b1.setText("Button1") b1.move(50,20) b1.clicked.connect(b1_clicked) b2 = QPushButton(win) b2.setText("Button2") b2.move(50,50) b2.clicked.connect(b2_clicked) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt5") win.show() sys.exit(app.exec_()) def b1_clicked(): print ("Button 1 clicked") def b2_clicked(): print ("Button 2 clicked") if __name__ == '__main__': window() The above code produces the following output − Button 1 clicked Button 2 clicked A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by setGeometry() method. QWidget.setGeometry(xpos, ypos, width, height) In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor. import sys from PyQt4 import QtGui def window(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() b = QtGui.QPushButton(w) b.setText("Hello World!") b.move(50,20) w.setGeometry(10,10,300,200) w.setWindowTitle(“PyQt”) w.show() sys.exit(app.exec_()) if __name__ == '__main__': window() A PushButton widget is added in the window and placed at a position 50 pixels towards right and 20 pixels below the top left position of the window. This Absolute Positioning, however, is not suitable because of following reasons − The position of the widget does not change even if the window is resized. The position of the widget does not change even if the window is resized. The appearance may not be uniform on different display devices with different resolutions. The appearance may not be uniform on different display devices with different resolutions. Modification in the layout is difficult as it may need redesigning the entire form. Modification in the layout is difficult as it may need redesigning the entire form. PyQt API provides layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are − Widgets inside the window are automatically resized. Widgets inside the window are automatically resized. Ensures uniform appearance on display devices with different resolutions. Ensures uniform appearance on display devices with different resolutions. Adding or removing widget dynamically is possible without having to redesign. Adding or removing widget dynamically is possible without having to redesign. Qt toolkit defines various layouts that can be used with Qt Designer utility. Here is the list of Classes which we will discuss one by one in this chapter. QBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally). A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. Here is the list of Widgets which we will discuss one by one in this chapter. A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required. In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function. A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class. A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item. A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right. QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. A horizontal QMenuBar just below the title bar of a QMainWindow object is reserved for displaying QMenu objects. A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets. This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter. Another commonly used dialog, a font selector widget is the visual appearance of QDialog class. Result of this dialog is a Qfont object, which can be consumed by the parent window. This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object. If a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area. Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area. This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls. A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information. QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable. A scrollbar control enables the user to access parts of the document that is outside the viewable area. It provides visual indicator to the current position. QCalendar widget is a useful date picker control. It provides a month-based view. The user can select the date by the use of the mouse or the keyboard, the default being today’s date. A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed). PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc. In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key. A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar. The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) w = QWidget() btn = QPushButton(w) btn.setText("Hello World!") btn.move(100,50) btn.clicked.connect(showdialog) w.setWindowTitle("PyQt Dialog demo") w.show() sys.exit(app.exec_()) def showdialog(): dlg = QDialog() b1 = QPushButton("ok",dlg) b1.move(50,50) dlg.setWindowTitle("Dialog") 9. PyQt5 — QDialog Class dlg.setWindowModality(Qt.ApplicationModal) dlg.exec_() if __name__ == '__main__': window() The above code produces the following output. Click on button in main window and dialog box pops up − QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number. Important methods and enumerations associated with QMessageBox class are given in the following table − setIcon() Displays predefined icon corresponding to severity of the message Question Information Warning Critical setText() Sets the text of the main message to be displayed setInformativeText() Displays additional information setDetailText() Dialog shows a Details button. This text appears on clicking it setTitle() Displays the custom title of dialog setStandardButtons() List of standard buttons to be displayed. Each button is associated with QMessageBox.Ok 0x00000400 QMessageBox.Open 0x00002000 QMessageBox.Save 0x00000800 QMessageBox.Cancel 0x00400000 QMessageBox.Close 0x00200000 QMessageBox.Yes 0x00004000 QMessageBox.No 0x00010000 QMessageBox.Abort 0x00040000 QMessageBox.Retry 0x00080000 QMessageBox.Ignore 0x00100000 setDefaultButton() Sets the button as default. It emits the clicked signal if Enter is pressed setEscapeButton() Sets the button to be treated as clicked if the escape key is pressed In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog. msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") setStandardButton() function displays desired buttons. msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal. msg.buttonClicked.connect(msgbtn) The complete code for the example is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) w = QWidget() b = QPushButton(w) b.setText("Show message!") b.move(100,50) b.clicked.connect(showdialog) w.setWindowTitle("PyQt MessageBox demo") w.show() sys.exit(app.exec_()) def showdialog(): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msg.buttonClicked.connect(msgbtn) retval = msg.exec_() def msgbtn(i): print ("Button pressed is:",i.text()) if __name__ == '__main__': window() The above code produces the following output. Message Box pops up when main windows’ button is clicked − If you click on Ok or Cancel button on MessageBox, the following output is produced on the console − Button pressed is: OK Button pressed is: Cancel A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden. One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc. MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea. QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion. The following table lists important methods of QMdiArea class and QMdiSubWindow class − addSubWindow() Adds a widget as a new subwindow in MDI area removeSubWindow() Removes a widget that is internal widget of a subwindow setActiveSubWindow() Activates a subwindow cascadeSubWindows() Arranges subwindows in MDiArea in a cascaded fashion tileSubWindows() Arranges subwindows in MDiArea in a tiled fashion closeActiveSubWindow() Closes the active subwindow subWindowList() Returns the list of subwindows in MDI Area setWidget() Sets a QWidget as an internal widget of a QMdiSubwindow instance QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object. In the following example, top level window comprising of QMainWindow has a menu and MdiArea. self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") Triggered() signal of the menu is connected to windowaction() function. file.triggered[QAction].connect(self.windowaction) The new action of menu adds a subwindow in MDI area with a title having an incremental number to it. MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("subwindow"+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively. The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class MainWindow(QMainWindow): count = 0 def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") file.triggered[QAction].connect(self.windowaction) self.setWindowTitle("MDI demo") def windowaction(self, q): print ("triggered") if q.text() == "New": MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("subwindow"+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() if q.text() == "cascade": self.mdi.cascadeSubWindows() if q.text() == "Tiled": self.mdi.tileSubWindows() def main(): app = QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Run above code and three windows in cascased and tiled formation − The 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. MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process. The following QMimeData class functions allow the MIME type to be detected and used conveniently. Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them. DragEnterEvent provides an event which is sent to the target widget as dragging action enters it. DragEnterEvent provides an event which is sent to the target widget as dragging action enters it. DragMoveEvent is used when the drag and drop action is in progress. DragMoveEvent is used when the drag and drop action is in progress. DragLeaveEvent is generated as the drag and drop action leaves the widget. DragLeaveEvent is generated as the drag and drop action leaves the widget. DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally. DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally. In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class combo(QComboBox): def __init__(self, title, parent): super(combo, self).__init__( parent) self.setAcceptDrops(True) def dragEnterEvent(self, e): print (e) if e.mimeData().hasText(): e.accept() else: e.ignore() def dropEvent(self, e): self.addItem(e.mimeData().text()) class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): lo = QFormLayout() lo.addRow(QLabel("Type some text in textbox and drag it into combo box")) edit = QLineEdit() edit.setDragEnabled(True) com = combo("Button", self) lo.addRow(edit,com) self.setLayout(lo) self.setWindowTitle('Simple drag and drop') def main(): app = QApplication(sys.argv) ex = Example() ex.show() app.exec_() if __name__ == '__main__': main() The above code produces the following output − PyQt5 library contains QtSql module. It is an elaborate class system to communicate with many SQL based databases. Its QSqlDatabase provides access through a Connection object. Following is the list of currently available SQL drivers − QDB2 IBM DB2 QIBASE Borland InterBase Driver QMYSQL MySQL Driver QOCI Oracle Call Interface Driver QODBC ODBC Driver (includes Microsoft SQL Server) QPSQL PostgreSQL Driver QSQLITE SQLite version 3 or above QSQLITE2 SQLite version 2 For this chapter, a connection with a SQLite database is established using the static method − db = QtSql.QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('sports.db') Other methods of QSqlDatabase class are as follows − setDatabaseName() Sets the name of the database with which connection is sought setHostName() Sets the name of the host on which the database is installed setUserName() Specifies the user name for connection setPassword() Sets the connection object’s password if any commit() Commits the transactions and returns true if successful rollback() Rolls back the database transaction close() Closes the connection QSqlQuery class has the functionality to execute and manipulate SQL commands. Both DDL and DML type of SQL queries can be executed. First step is to create SQlite database using the following statements − db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('sportsdatabase.db') Next, obtain Query object with QSqlQuery() method and call its most important method exec_(), which takes as an argument a string containing SQL statement to be executed. query = QtSql.QSqlQuery() query.exec_("create table sportsmen(id int primary key, " "firstname varchar(20), lastname varchar(20))") The following script creates a SQLite database sports.db with a table of sportsperson populated with five records. import sys from PyQt5.QtSql import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def createDB(): db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('sportsdatabase.db') if not db.open(): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error in Database Creation") retval = msg.exec_() return False query = QSqlQuery() query.exec_("create table sportsmen( id int primary key, ""firstname varchar(20), lastname varchar(20))") query.exec_("insert into sportsmen values(101, 'Roger', 'Federer')") query.exec_("insert into sportsmen values(102, 'Christiano', 'Ronaldo')") query.exec_("insert into sportsmen values(103, 'Ussain', 'Bolt')") query.exec_("insert into sportsmen values(104, 'Sachin', 'Tendulkar')") query.exec_("insert into sportsmen values(105, 'Saina', 'Nehwal')") return True if __name__ == '__main__': app = QApplication(sys.argv) createDB() To confirm that the SQLite database is created with above records added in sportsmen table in it, use a SQLite Gui utility called SQLiteStudio. QSqlTableModel class in PyQt is a high-level interface that provides editable data model for reading and writing records in a single table. This model is used to populate a QTableView object. It presents to the user a scrollable and editable view that can be put on any top level window. A QSqlTableModel object is declared in the following manner − model = QtSql.QSqlTableModel() Its editing strategy can be set to any of the following − In the following example, sportsperson table is used as a model and the strategy is set as − model.setTable('sportsmen') model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange) model.select() QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows − view = QtGui.QTableView() view.setModel(model) view.setWindowTitle(title) return view This QTableView object and two QPushButton widgets are added to the top level QDialog window. Clicked() signal of add button is connected to addrow() which performs insertRow() on the model table. button.clicked.connect(addrow) def addrow(): print model.rowCount() ret = model.insertRows(model.rowCount(), 1) print ret The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user. btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row())) The complete code is as follows − import sys from PyQt5.QtSql import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def initializeModel(model): model.setTable('sportsmen') model.setEditStrategy(QSqlTableModel.OnFieldChange) model.select() model.setHeaderData(0, Qt.Horizontal, "ID") model.setHeaderData(1, Qt.Horizontal, "First name") model.setHeaderData(2, Qt.Horizontal, "Last name") def createView(title, model): view = QTableView() view.setModel(model) view.setWindowTitle(title) return view def addrow(): print (model.rowCount()) ret = model.insertRows(model.rowCount(), 1) print (ret) def findrow(i): delrow = i.row() if __name__ == '__main__': app = QApplication(sys.argv) db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('sportsdatabase.db') model = QSqlTableModel() delrow = -1 initializeModel(model) view1 = createView("Table Model (View 1)", model) view1.clicked.connect(findrow) dlg = QDialog() layout = QVBoxLayout() layout.addWidget(view1) button = QPushButton("Add a row") button.clicked.connect(addrow) layout.addWidget(button) btn1 = QPushButton("del a row") btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row())) layout.addWidget(btn1) dlg.setLayout(layout) dlg.setWindowTitle("Database Demo") dlg.show() sys.exit(app.exec_()) The above code produces the following output − Try adding and deleting a few records and go back to SQLiteStudio to confirm the transactions. All the QWidget classes in PyQt are sub classed from QPaintDevice class. A QPaintDevice is an abstraction of two dimensional space that can be drawn upon using a QPainter. Dimensions of paint device are measured in pixels starting from the top-left corner. QPainter class performs low level painting on widgets and other paintable devices such as printer. Normally, it is used in widget’s paint event. The QPaintEvent occurs whenever the widget’s appearance is updated. The painter is activated by calling the begin() method, while the end() method deactivates it. In between, the desired pattern is painted by suitable methods as listed in the following table. begin() Starts painting on the target device drawArc() Draws an arc between the starting and the end angle drawEllipse() Draws an ellipse inside a rectangle drawLine() Draws a line with endpoint coordinates specified drawPixmap() Extracts pixmap from the image file and displays it at the specified position drwaPolygon() Draws a polygon using an array of coordinates drawRect() Draws a rectangle starting at the top-left coordinate with the given width and height drawText() Displays the text at given coordinates fillRect() Fills the rectangle with the QColor parameter setBrush() Sets a brush style for painting setPen() Sets the color, size and style of pen to be used for drawing In the following code, various methods of PyQt's drawing methods are used. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.text = "hello world" self.setGeometry(100,100, 400,300) self.setWindowTitle('Draw Demo') self.show() def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setPen(QColor(Qt.red)) qp.setFont(QFont('Arial', 20)) qp.drawText(10,50, "hello Python") qp.setPen(QColor(Qt.blue)) qp.drawLine(10,100,100,100) qp.drawRect(10,150,150,100) qp.setPen(QColor(Qt.yellow)) qp.drawEllipse(100,50,100,50) qp.drawPixmap(220,10,QPixmap("pythonlogo.png")) qp.fillRect(20,175,130,70,QBrush(Qt.SolidPattern)) qp.end() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − In this chapter, we shall learn Brush Style Constants. Given below are the Brush Style Constants − Given below are the Predefined QColor Styles − Given below are the Predefined QColor Objects − The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types. QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard. Following are the clipboard class methods that are commonly used − clear() Clears clipboard contents setImage() Copies QImage into clipboard setMimeData() Sets MIME data into clipboard setPixmap() Copies Pixmap object in clipboard setText() Copies QString in clipboard text() Retrieves text from clipboard Signal associated with clipboard object is − dataChanged() Whenever clipboard data changes In the following example, two TextEdit objects and two Pushbuttons are added to a top level window. To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): hbox = QVBoxLayout() self.edit1=QTextEdit() hbox.addWidget(self.edit1) self.btn1=QPushButton("Copy") hbox.addWidget(self.btn1) self.edit2=QTextEdit() self.btn2=QPushButton("Paste") hbox.addWidget(self.edit2) hbox.addWidget(self.btn2) self.btn1.clicked.connect(self.copytext) self.btn2.clicked.connect(self.pastetext) self.setLayout(hbox) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Clipboard') self.show() def copytext(self): #clipboard.setText(self.edit1.copy()) self.edit1.copy() print (clipboard.text()) msg=QMessageBox() msg.setText(clipboard.text()+" copied on clipboard") msg.exec_() def pastetext(self): self.edit2.setText(clipboard.text()) app = QApplication(sys.argv) clipboard=app.clipboard() ex = Example() ex.setWindowTitle("clipboard Example") sys.exit(app.exec_()) The above code produces the following output − QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button. Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible. The types of image files that can be read into a QPixmap object are as follows − Following methods are useful in handling QPixmap object − copy() Copies pixmap data from a QRect object fromImage() Converts QImage object into QPixmap grabWidget() Creates a pixmap from the given widget grabWindow() Create pixmap of data in a window Load() Loads an image file as pixmap save() Saves the QPixmap object as a file toImage Converts a QPixmap to QImage The most common use of QPixmap is to display image on a label/button. The following example shows an image displayed on a QLabel by using the setPixmap() method. The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() l1 = QLabel() l1.setPixmap(QPixmap("python.png")) vbox = QVBoxLayout() vbox.addWidget(l1) win.setLayout(vbox) win.setWindowTitle("QPixmap Demo") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2236, "s": 1963, "text": "PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com" }, { "code": null, "e": 2556, "s": 2236, "text": "PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc." }, { "code": null, "e": 2607, "s": 2556, "text": "A list of frequently used modules is given below −" }, { "code": null, "e": 2659, "s": 2607, "text": "QtCore − Core non-GUI classes used by other modules" }, { "code": null, "e": 2711, "s": 2659, "text": "QtCore − Core non-GUI classes used by other modules" }, { "code": null, "e": 2755, "s": 2711, "text": "QtGui − Graphical user interface components" }, { "code": null, "e": 2799, "s": 2755, "text": "QtGui − Graphical user interface components" }, { "code": null, "e": 2859, "s": 2799, "text": "QtMultimedia − Classes for low-level multimedia programming" }, { "code": null, "e": 2919, "s": 2859, "text": "QtMultimedia − Classes for low-level multimedia programming" }, { "code": null, "e": 2963, "s": 2919, "text": "QtNetwork − Classes for network programming" }, { "code": null, "e": 3007, "s": 2963, "text": "QtNetwork − Classes for network programming" }, { "code": null, "e": 3041, "s": 3007, "text": "QtOpenGL − OpenGL support classes" }, { "code": null, "e": 3075, "s": 3041, "text": "QtOpenGL − OpenGL support classes" }, { "code": null, "e": 3120, "s": 3075, "text": "QtScript − Classes for evaluating Qt Scripts" }, { "code": null, "e": 3165, "s": 3120, "text": "QtScript − Classes for evaluating Qt Scripts" }, { "code": null, "e": 3216, "s": 3165, "text": "QtSql − Classes for database integration using SQL" }, { "code": null, "e": 3267, "s": 3216, "text": "QtSql − Classes for database integration using SQL" }, { "code": null, "e": 3324, "s": 3267, "text": "QtSvg − Classes for displaying the contents of SVG files" }, { "code": null, "e": 3381, "s": 3324, "text": "QtSvg − Classes for displaying the contents of SVG files" }, { "code": null, "e": 3431, "s": 3381, "text": "QtWebKit − Classes for rendering and editing HTML" }, { "code": null, "e": 3481, "s": 3431, "text": "QtWebKit − Classes for rendering and editing HTML" }, { "code": null, "e": 3514, "s": 3481, "text": "QtXml − Classes for handling XML" }, { "code": null, "e": 3547, "s": 3514, "text": "QtXml − Classes for handling XML" }, { "code": null, "e": 3606, "s": 3547, "text": "QtWidgets − Classes for creating classic desktop-style UIs" }, { "code": null, "e": 3665, "s": 3606, "text": "QtWidgets − Classes for creating classic desktop-style UIs" }, { "code": null, "e": 3712, "s": 3665, "text": "QtDesigner − Classes for extending Qt Designer" }, { "code": null, "e": 3759, "s": 3712, "text": "QtDesigner − Classes for extending Qt Designer" }, { "code": null, "e": 3970, "s": 3759, "text": "PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license. The latest stable version is PyQt5-5.13.2." }, { "code": null, "e": 4132, "s": 3970, "text": "Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later. The recommended way to install is using PIP utility −" }, { "code": null, "e": 4152, "s": 4132, "text": "pip3 install PyQt5\n" }, { "code": null, "e": 4253, "s": 4152, "text": "To install development tools such as Qt Designer to support PyQt5 wheels, following is the command −" }, { "code": null, "e": 4279, "s": 4253, "text": "pip3 install pyqt5-tools\n" }, { "code": null, "e": 4390, "s": 4279, "text": "You can also build PyQt5 on Linux/macOS from the source code www.riverbankcomputing.com/static/Downloads/PyQt5" }, { "code": null, "e": 4630, "s": 4390, "text": "PyQt5 API is not automatically compatible with earlier versions. Hence, Python code involving PyQt4 modules should be upgraded manually by making relevant changes. In this chapter, main differences between PyQt4 and PyQt5 have been listed." }, { "code": null, "e": 4694, "s": 4630, "text": "PyQt5 is not supported on versions of Python earlier than v2.6." }, { "code": null, "e": 4835, "s": 4694, "text": "PyQt5 doesn't support connect() method of QObject class for connection between signal and slot. Hence the usage can no more be implemented −" }, { "code": null, "e": 4904, "s": 4835, "text": "QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function)\n" }, { "code": null, "e": 4943, "s": 4904, "text": "Only the following syntax is defined −" }, { "code": null, "e": 4981, "s": 4943, "text": "widget.signal.connect(slot_function)\n" }, { "code": null, "e": 5090, "s": 4981, "text": "Classes defined in earlier QtGui module have been distributed in QtGui, QtPrintSupport an QtWidgets modules." }, { "code": null, "e": 5348, "s": 5090, "text": "In the new QFileDialog class, The getOpenFileNameAndFilter() method is replaced by getOpenFileName(), getOpenFileNamesAndFilter() by getOpenFileNames() and getSaveFileNameAndFilter() by getSaveFileName(). Older signatures of these methods also have changed." }, { "code": null, "e": 5444, "s": 5348, "text": "PyQt5 doesn’t have provision to define a class that is sub-classed from more than one Qt class." }, { "code": null, "e": 5554, "s": 5444, "text": "pyuic5 utility (to generates Python code from Designer's XML file) does not support the --pyqt3-wrapper flag." }, { "code": null, "e": 5680, "s": 5554, "text": "pyrcc5 does not support the -py2 and -py3 flags. The output of pyrcc5 is compatible with all versions of Python v2.6 onwards." }, { "code": null, "e": 5806, "s": 5680, "text": "PyQt5 always invokes sip.setdestroyonexit() automatically and calls the C++ destructor of all wrapped instances that it owns." }, { "code": null, "e": 5882, "s": 5806, "text": "Creating a simple GUI application using PyQt involves the following steps −" }, { "code": null, "e": 5945, "s": 5882, "text": "Import QtCore, QtGui and QtWidgets modules from PyQt5 package." }, { "code": null, "e": 6008, "s": 5945, "text": "Import QtCore, QtGui and QtWidgets modules from PyQt5 package." }, { "code": null, "e": 6060, "s": 6008, "text": "Create an application object of QApplication class." }, { "code": null, "e": 6112, "s": 6060, "text": "Create an application object of QApplication class." }, { "code": null, "e": 6180, "s": 6112, "text": "A QWidget object creates top level window. Add QLabel object in it." }, { "code": null, "e": 6248, "s": 6180, "text": "A QWidget object creates top level window. Add QLabel object in it." }, { "code": null, "e": 6291, "s": 6248, "text": "Set the caption of label as \"hello world\"." }, { "code": null, "e": 6334, "s": 6291, "text": "Set the caption of label as \"hello world\"." }, { "code": null, "e": 6398, "s": 6334, "text": "Define the size and position of window by setGeometry() method." }, { "code": null, "e": 6462, "s": 6398, "text": "Define the size and position of window by setGeometry() method." }, { "code": null, "e": 6519, "s": 6462, "text": "Enter the mainloop of application by app.exec_() method." }, { "code": null, "e": 6576, "s": 6519, "text": "Enter the mainloop of application by app.exec_() method." }, { "code": null, "e": 6639, "s": 6576, "text": "Following is the code to execute Hello World program in PyQt −" }, { "code": null, "e": 6997, "s": 6639, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\ndef window():\n app = QApplication(sys.argv)\n w = QWidget()\n b = QLabel(w)\n b.setText(\"Hello World!\")\n w.setGeometry(100,100,200,50)\n b.move(50,20)\n w.setWindowTitle(\"PyQt5\")\n w.show()\n sys.exit(app.exec_())\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 7044, "s": 6997, "text": "The above code produces the following output −" }, { "code": null, "e": 7122, "s": 7044, "text": "It is also possible to develop an object oriented solution of the above code." }, { "code": null, "e": 7185, "s": 7122, "text": "Import QtCore, QtGui and QtWidgets modules from PyQt5 package." }, { "code": null, "e": 7248, "s": 7185, "text": "Import QtCore, QtGui and QtWidgets modules from PyQt5 package." }, { "code": null, "e": 7300, "s": 7248, "text": "Create an application object of QApplication class." }, { "code": null, "e": 7352, "s": 7300, "text": "Create an application object of QApplication class." }, { "code": null, "e": 7396, "s": 7352, "text": "Declare window class based on QWidget class" }, { "code": null, "e": 7440, "s": 7396, "text": "Declare window class based on QWidget class" }, { "code": null, "e": 7507, "s": 7440, "text": "Add a QLabel object and set the caption of label as \"hello world\"." }, { "code": null, "e": 7574, "s": 7507, "text": "Add a QLabel object and set the caption of label as \"hello world\"." }, { "code": null, "e": 7638, "s": 7574, "text": "Define the size and position of window by setGeometry() method." }, { "code": null, "e": 7702, "s": 7638, "text": "Define the size and position of window by setGeometry() method." }, { "code": null, "e": 7759, "s": 7702, "text": "Enter the mainloop of application by app.exec_() method." }, { "code": null, "e": 7816, "s": 7759, "text": "Enter the mainloop of application by app.exec_() method." }, { "code": null, "e": 7881, "s": 7816, "text": "Following is the complete code of the object oriented solution −" }, { "code": null, "e": 8487, "s": 7881, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nclass window(QWidget):\n def __init__(self, parent = None):\n super(window, self).__init__(parent)\n self.resize(200,50)\n self.setWindowTitle(\"PyQt5\")\n self.label = QLabel(self)\n self.label.setText(\"Hello World\")\n font = QFont()\n font.setFamily(\"Arial\")\n font.setPointSize(16)\n self.label.setFont(font)\n self.label.move(50,20)\ndef main():\n app = QApplication(sys.argv)\n ex = window()\n ex.show()\n sys.exit(app.exec_())\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 8593, "s": 8487, "text": "PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules." }, { "code": null, "e": 8645, "s": 8593, "text": "Following are some of the frequently used modules −" }, { "code": null, "e": 8652, "s": 8645, "text": "QtCore" }, { "code": null, "e": 8695, "s": 8652, "text": "Core non-GUI classes used by other modules" }, { "code": null, "e": 8701, "s": 8695, "text": "QtGui" }, { "code": null, "e": 8737, "s": 8701, "text": "Graphical user interface components" }, { "code": null, "e": 8750, "s": 8737, "text": "QtMultimedia" }, { "code": null, "e": 8795, "s": 8750, "text": "Classes for low-level multimedia programming" }, { "code": null, "e": 8805, "s": 8795, "text": "QtNetwork" }, { "code": null, "e": 8837, "s": 8805, "text": "Classes for network programming" }, { "code": null, "e": 8846, "s": 8837, "text": "QtOpenGL" }, { "code": null, "e": 8869, "s": 8846, "text": "OpenGL support classes" }, { "code": null, "e": 8878, "s": 8869, "text": "QtScript" }, { "code": null, "e": 8912, "s": 8878, "text": "Classes for evaluating Qt Scripts" }, { "code": null, "e": 8918, "s": 8912, "text": "QtSql" }, { "code": null, "e": 8961, "s": 8918, "text": "Classes for database integration using SQL" }, { "code": null, "e": 8967, "s": 8961, "text": "QtSvg" }, { "code": null, "e": 9016, "s": 8967, "text": "Classes for displaying the contents of SVG files" }, { "code": null, "e": 9025, "s": 9016, "text": "QtWebKit" }, { "code": null, "e": 9064, "s": 9025, "text": "Classes for rendering and editing HTML" }, { "code": null, "e": 9070, "s": 9064, "text": "QtXml" }, { "code": null, "e": 9095, "s": 9070, "text": "Classes for handling XML" }, { "code": null, "e": 9105, "s": 9095, "text": "QtWidgets" }, { "code": null, "e": 9153, "s": 9105, "text": "Classes for creating classic desktop-style UIs." }, { "code": null, "e": 9164, "s": 9153, "text": "QtDesigner" }, { "code": null, "e": 9198, "s": 9164, "text": "Classes for extending Qt Designer" }, { "code": null, "e": 9210, "s": 9198, "text": "QtAssistant" }, { "code": null, "e": 9234, "s": 9210, "text": "Support for online help" }, { "code": null, "e": 9361, "s": 9234, "text": "PyQt5 development tools is a collection of useful utilities for Qt development. Following is a select list of such utilities −" }, { "code": null, "e": 9371, "s": 9361, "text": "assistant" }, { "code": null, "e": 9403, "s": 9371, "text": "Qt Assistant documentation tool" }, { "code": null, "e": 9417, "s": 9403, "text": "pyqt5designer" }, { "code": null, "e": 9445, "s": 9417, "text": "Qt Designer GUI layout tool" }, { "code": null, "e": 9454, "s": 9445, "text": "linguist" }, { "code": null, "e": 9483, "s": 9454, "text": "Qt Linguist translation tool" }, { "code": null, "e": 9492, "s": 9483, "text": "lrelease" }, { "code": null, "e": 9521, "s": 9492, "text": "compile ts files to qm files" }, { "code": null, "e": 9532, "s": 9521, "text": "pylupdate5" }, { "code": null, "e": 9592, "s": 9532, "text": "extract translation strings and generate or update ts files" }, { "code": null, "e": 9598, "s": 9592, "text": "qmake" }, { "code": null, "e": 9621, "s": 9598, "text": "Qt software build tool" }, { "code": null, "e": 9635, "s": 9621, "text": "pyqt5qmlscene" }, { "code": null, "e": 9651, "s": 9635, "text": "QML file viewer" }, { "code": null, "e": 9663, "s": 9651, "text": "pyqmlviewer" }, { "code": null, "e": 9679, "s": 9663, "text": "QML file viewer" }, { "code": null, "e": 9686, "s": 9679, "text": "pyrcc5" }, { "code": null, "e": 9712, "s": 9686, "text": "Qt resource file compiler" }, { "code": null, "e": 9719, "s": 9712, "text": "pyuic5" }, { "code": null, "e": 9780, "s": 9719, "text": "Qt User Interface Compiler for generating code from ui files" }, { "code": null, "e": 9796, "s": 9780, "text": "pyqmltestrunner" }, { "code": null, "e": 9827, "s": 9796, "text": "running unit tests on QML code" }, { "code": null, "e": 9833, "s": 9827, "text": "qdbus" }, { "code": null, "e": 9874, "s": 9833, "text": "command-line tool to list D-Bus services" }, { "code": null, "e": 9879, "s": 9874, "text": "QDoc" }, { "code": null, "e": 9926, "s": 9879, "text": "documentation generator for software projects." }, { "code": null, "e": 9941, "s": 9926, "text": "Qhelpgenerator" }, { "code": null, "e": 9979, "s": 9941, "text": "generating and viewing Qt help files." }, { "code": null, "e": 9996, "s": 9979, "text": "qmlimportscanner" }, { "code": null, "e": 10030, "s": 9996, "text": "parses and reports on QML imports" }, { "code": null, "e": 10251, "s": 10030, "text": "PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can be painted." }, { "code": null, "e": 10519, "s": 10251, "text": "QApplication class manages the main settings and control flow of a GUI application. It contains main event loop inside which events generated by window elements and other sources are processed and dispatched. It also handles system-wide and application-wide settings." }, { "code": null, "e": 10732, "s": 10519, "text": "QWidget class, derived from QObject and QPaintDevice classes is the base class for all user interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their own sub-class system." }, { "code": null, "e": 10781, "s": 10732, "text": "Here is a select list of frequently used widgets" }, { "code": null, "e": 10788, "s": 10781, "text": "QLabel" }, { "code": null, "e": 10818, "s": 10788, "text": "Used to display text or image" }, { "code": null, "e": 10828, "s": 10818, "text": "QLineEdit" }, { "code": null, "e": 10870, "s": 10828, "text": "Allows the user to enter one line of text" }, { "code": null, "e": 10880, "s": 10870, "text": "QTextEdit" }, { "code": null, "e": 10921, "s": 10880, "text": "Allows the user to enter multi-line text" }, { "code": null, "e": 10933, "s": 10921, "text": "QPushButton" }, { "code": null, "e": 10967, "s": 10933, "text": "A command button to invoke action" }, { "code": null, "e": 10980, "s": 10967, "text": "QRadioButton" }, { "code": null, "e": 11024, "s": 10980, "text": "Enables to choose one from multiple options" }, { "code": null, "e": 11034, "s": 11024, "text": "QCheckBox" }, { "code": null, "e": 11074, "s": 11034, "text": "Enables choice of more than one options" }, { "code": null, "e": 11083, "s": 11074, "text": "QSpinBox" }, { "code": null, "e": 11129, "s": 11083, "text": "Enables to increase/decrease an integer value" }, { "code": null, "e": 11140, "s": 11129, "text": "QScrollBar" }, { "code": null, "e": 11203, "s": 11140, "text": "Enables to access contents of a widget beyond display aperture" }, { "code": null, "e": 11211, "s": 11203, "text": "QSlider" }, { "code": null, "e": 11255, "s": 11211, "text": "Enables to change the bound value linearly." }, { "code": null, "e": 11265, "s": 11255, "text": "QComboBox" }, { "code": null, "e": 11314, "s": 11265, "text": "Provides a dropdown list of items to select from" }, { "code": null, "e": 11323, "s": 11314, "text": "QMenuBar" }, { "code": null, "e": 11360, "s": 11323, "text": "Horizontal bar holding QMenu objects" }, { "code": null, "e": 11371, "s": 11360, "text": "QStatusBar" }, { "code": null, "e": 11434, "s": 11371, "text": "Usually at bottom of QMainWindow, provides status information." }, { "code": null, "e": 11443, "s": 11434, "text": "QToolBar" }, { "code": null, "e": 11510, "s": 11443, "text": "Usually at top of QMainWindow or floating. Contains action buttons" }, { "code": null, "e": 11520, "s": 11510, "text": "QListView" }, { "code": null, "e": 11580, "s": 11520, "text": "Provides a selectable list of items in ListMode or IconMode" }, { "code": null, "e": 11588, "s": 11580, "text": "QPixmap" }, { "code": null, "e": 11664, "s": 11588, "text": "Off-screen image representation for display on QLabel or QPushButton object" }, { "code": null, "e": 11672, "s": 11664, "text": "QDialog" }, { "code": null, "e": 11743, "s": 11672, "text": "Modal or modeless window which can return information to parent window" }, { "code": null, "e": 11994, "s": 11743, "text": "A typical GUI based application’s top level window is created by QMainWindow widget object. Some widgets as listed above take their appointed place in this main window, while others are placed in the central widget area using various layout managers." }, { "code": null, "e": 12050, "s": 11994, "text": "The following diagram shows the QMainWindow framework −" }, { "code": null, "e": 12363, "s": 12050, "text": "The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application." }, { "code": null, "e": 12490, "s": 12363, "text": "Start Qt Designer application which is a part of development tools and installed in scripts folder of the virtual environment." }, { "code": null, "e": 12549, "s": 12490, "text": "Start designing GUI interface by choosing File → New menu." }, { "code": null, "e": 12699, "s": 12549, "text": "You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form." }, { "code": null, "e": 13005, "s": 12699, "text": "The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic5 command line utility. This utility is a wrapper for uic module of Qt toolkit. The usage of pyuic5 is as follows −" }, { "code": null, "e": 13035, "s": 13005, "text": "pyuic5 -x demo.ui -o demo.py\n" }, { "code": null, "e": 13209, "s": 13035, "text": "In the above command, -x switch adds a small amount of additional code to the generated Python script (from XML) so that it becomes a self-executable standalone application." }, { "code": null, "e": 13400, "s": 13209, "text": "if __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n Dialog = QtGui.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())" }, { "code": null, "e": 13475, "s": 13400, "text": "The resultant python script is executed to show the following dialog box −" }, { "code": null, "e": 13491, "s": 13475, "text": "python demo.py\n" }, { "code": null, "e": 13695, "s": 13491, "text": "The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling." }, { "code": null, "e": 13978, "s": 13695, "text": "Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events." }, { "code": null, "e": 14308, "s": 13978, "text": "Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function." }, { "code": null, "e": 14377, "s": 14308, "text": "First design a simple form with a LineEdit control and a PushButton." }, { "code": null, "e": 14606, "s": 14377, "text": "It is desired that if button is pressed, contents of text box should be erased. The QLineEdit widget has a clear() method for this purpose. Hence, the button’s clicked signal is to be connected to clear() method of the text box." }, { "code": null, "e": 14754, "s": 14606, "text": "To start with, choose Edit signals/slots from Edit menu (or press F4). Then highlight the button with mouse and drag the cursor towards the textbox" }, { "code": null, "e": 14895, "s": 14754, "text": "As the mouse is released, a dialog showing signals of button and methods of slot will be displayed. Select clicked signal and clear() method" }, { "code": null, "e": 14964, "s": 14895, "text": "The Signal/Slot Editor window at bottom right will show the result −" }, { "code": null, "e": 15040, "s": 14964, "text": "Save ui and Build and Python code from ui file as shown in the below code −" }, { "code": null, "e": 15082, "s": 15040, "text": "pyuic5 -x signalslot.ui -o signalslot.py\n" }, { "code": null, "e": 15182, "s": 15082, "text": "Generated Python code will have the connection between signal and slot by the following statement −" }, { "code": null, "e": 15236, "s": 15182, "text": "self.pushButton.clicked.connect(self.lineEdit.clear)\n" }, { "code": null, "e": 15342, "s": 15236, "text": "Run signalslot.py and enter some text in the LineEdit. The text will be cleared if the button is pressed." }, { "code": null, "e": 15441, "s": 15342, "text": "Instead of using Designer, you can directly establish signal-slot connection by following syntax −" }, { "code": null, "e": 15479, "s": 15441, "text": "widget.signal.connect(slot_function)\n" }, { "code": null, "e": 15666, "s": 15479, "text": "Suppose if a function is to be called when a button is clicked. Here, the clicked signal is to be connected to a callable function. It can be achieved in any of the following technique −" }, { "code": null, "e": 15705, "s": 15666, "text": "button.clicked.connect(slot_function)\n" }, { "code": null, "e": 15888, "s": 15705, "text": "In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_clicked() and b2_clicked() on clicking b1 and b2 respectively." }, { "code": null, "e": 15969, "s": 15888, "text": "When b1 is clicked, the clicked() signal is connected to b1_clicked() function −" }, { "code": null, "e": 16003, "s": 15969, "text": "b1.clicked.connect(b1_clicked())\n" }, { "code": null, "e": 16083, "s": 16003, "text": "When b2 is clicked, the clicked() signal is connected to b2_clicked() function." }, { "code": null, "e": 16700, "s": 16083, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QDialog()\n b1 = QPushButton(win)\n b1.setText(\"Button1\")\n b1.move(50,20)\n b1.clicked.connect(b1_clicked)\n \n b2 = QPushButton(win)\n b2.setText(\"Button2\")\n b2.move(50,50)\n b2.clicked.connect(b2_clicked)\n \n win.setGeometry(100,100,200,100)\n\n win.setWindowTitle(\"PyQt5\")\n win.show()\n sys.exit(app.exec_())\n\ndef b1_clicked():\n print (\"Button 1 clicked\")\n\ndef b2_clicked():\n print (\"Button 2 clicked\")\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 16747, "s": 16700, "text": "The above code produces the following output −" }, { "code": null, "e": 16782, "s": 16747, "text": "Button 1 clicked\nButton 2 clicked\n" }, { "code": null, "e": 16990, "s": 16782, "text": "A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by setGeometry() method." }, { "code": null, "e": 17038, "s": 16990, "text": "QWidget.setGeometry(xpos, ypos, width, height)\n" }, { "code": null, "e": 17172, "s": 17038, "text": "In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor." }, { "code": null, "e": 17499, "s": 17172, "text": "import sys\nfrom PyQt4 import QtGui\n\ndef window():\n app = QtGui.QApplication(sys.argv)\n w = QtGui.QWidget()\n\t\n b = QtGui.QPushButton(w)\n b.setText(\"Hello World!\")\n b.move(50,20)\n\t\n w.setGeometry(10,10,300,200)\n w.setWindowTitle(“PyQt”)\n w.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 17648, "s": 17499, "text": "A PushButton widget is added in the window and placed at a position 50 pixels towards right and 20 pixels below the top left position of the window." }, { "code": null, "e": 17731, "s": 17648, "text": "This Absolute Positioning, however, is not suitable because of following reasons −" }, { "code": null, "e": 17805, "s": 17731, "text": "The position of the widget does not change even if the window is resized." }, { "code": null, "e": 17879, "s": 17805, "text": "The position of the widget does not change even if the window is resized." }, { "code": null, "e": 17970, "s": 17879, "text": "The appearance may not be uniform on different display devices with different resolutions." }, { "code": null, "e": 18061, "s": 17970, "text": "The appearance may not be uniform on different display devices with different resolutions." }, { "code": null, "e": 18145, "s": 18061, "text": "Modification in the layout is difficult as it may need redesigning the entire form." }, { "code": null, "e": 18229, "s": 18145, "text": "Modification in the layout is difficult as it may need redesigning the entire form." }, { "code": null, "e": 18404, "s": 18229, "text": "PyQt API provides layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −" }, { "code": null, "e": 18457, "s": 18404, "text": "Widgets inside the window are automatically resized." }, { "code": null, "e": 18510, "s": 18457, "text": "Widgets inside the window are automatically resized." }, { "code": null, "e": 18584, "s": 18510, "text": "Ensures uniform appearance on display devices with different resolutions." }, { "code": null, "e": 18658, "s": 18584, "text": "Ensures uniform appearance on display devices with different resolutions." }, { "code": null, "e": 18736, "s": 18658, "text": "Adding or removing widget dynamically is possible without having to redesign." }, { "code": null, "e": 18814, "s": 18736, "text": "Adding or removing widget dynamically is possible without having to redesign." }, { "code": null, "e": 18892, "s": 18814, "text": "Qt toolkit defines various layouts that can be used with Qt Designer utility." }, { "code": null, "e": 18970, "s": 18892, "text": "Here is the list of Classes which we will discuss one by one in this chapter." }, { "code": null, "e": 19161, "s": 18970, "text": "QBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally)." }, { "code": null, "e": 19368, "s": 19161, "text": "A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell." }, { "code": null, "e": 19592, "s": 19368, "text": "QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field." }, { "code": null, "e": 19670, "s": 19592, "text": "Here is the list of Widgets which we will discuss one by one in this chapter." }, { "code": null, "e": 19832, "s": 19670, "text": "A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets." }, { "code": null, "e": 20013, "s": 19832, "text": "QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required." }, { "code": null, "e": 20140, "s": 20013, "text": "In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function." }, { "code": null, "e": 20329, "s": 20140, "text": "A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class." }, { "code": null, "e": 20486, "s": 20329, "text": "A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button." }, { "code": null, "e": 20651, "s": 20486, "text": "A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item." }, { "code": null, "e": 20762, "s": 20651, "text": "A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right." }, { "code": null, "e": 20900, "s": 20762, "text": "QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value." }, { "code": null, "e": 21013, "s": 20900, "text": "A horizontal QMenuBar just below the title bar of a QMainWindow object is reserved for displaying QMenu objects." }, { "code": null, "e": 21115, "s": 21013, "text": "A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets." }, { "code": null, "e": 21302, "s": 21115, "text": "This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter." }, { "code": null, "e": 21483, "s": 21302, "text": "Another commonly used dialog, a font selector widget is the visual appearance of QDialog class. Result of this dialog is a Qfont object, which can be consumed by the parent window." }, { "code": null, "e": 21720, "s": 21483, "text": "This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object." }, { "code": null, "e": 21915, "s": 21720, "text": "If a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area." }, { "code": null, "e": 22031, "s": 21915, "text": "Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area." }, { "code": null, "e": 22260, "s": 22031, "text": "This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls." }, { "code": null, "e": 22473, "s": 22260, "text": "A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows." }, { "code": null, "e": 22624, "s": 22473, "text": "QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information." }, { "code": null, "e": 22801, "s": 22624, "text": "QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable." }, { "code": null, "e": 22959, "s": 22801, "text": "A scrollbar control enables the user to access parts of the document that is outside the viewable area. It provides visual indicator to the current position." }, { "code": null, "e": 23143, "s": 22959, "text": "QCalendar widget is a useful date picker control. It provides a month-based view. The user can select the date by the use of the mouse or the keyboard, the default being today’s date." }, { "code": null, "e": 23353, "s": 23143, "text": "A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed)." }, { "code": null, "e": 23457, "s": 23353, "text": "PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc." }, { "code": null, "e": 23710, "s": 23457, "text": "In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key." }, { "code": null, "e": 23869, "s": 23710, "text": "A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar." }, { "code": null, "e": 23983, "s": 23869, "text": "The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal." }, { "code": null, "e": 24572, "s": 23983, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n w = QWidget()\n btn = QPushButton(w)\n btn.setText(\"Hello World!\")\n btn.move(100,50)\n btn.clicked.connect(showdialog)\n w.setWindowTitle(\"PyQt Dialog demo\")\n w.show()\n sys.exit(app.exec_())\n\ndef showdialog():\n dlg = QDialog()\n b1 = QPushButton(\"ok\",dlg)\n b1.move(50,50)\n dlg.setWindowTitle(\"Dialog\") 9. PyQt5 — QDialog Class\n dlg.setWindowModality(Qt.ApplicationModal)\n dlg.exec_()\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 24674, "s": 24572, "text": "The above code produces the following output. Click on button in main window and dialog box pops up −" }, { "code": null, "e": 24945, "s": 24674, "text": "QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number." }, { "code": null, "e": 25049, "s": 24945, "text": "Important methods and enumerations associated with QMessageBox class are given in the following table −" }, { "code": null, "e": 25059, "s": 25049, "text": "setIcon()" }, { "code": null, "e": 25125, "s": 25059, "text": "Displays predefined icon corresponding to severity of the message" }, { "code": null, "e": 25134, "s": 25125, "text": "Question" }, { "code": null, "e": 25146, "s": 25134, "text": "Information" }, { "code": null, "e": 25154, "s": 25146, "text": "Warning" }, { "code": null, "e": 25163, "s": 25154, "text": "Critical" }, { "code": null, "e": 25173, "s": 25163, "text": "setText()" }, { "code": null, "e": 25223, "s": 25173, "text": "Sets the text of the main message to be displayed" }, { "code": null, "e": 25244, "s": 25223, "text": "setInformativeText()" }, { "code": null, "e": 25276, "s": 25244, "text": "Displays additional information" }, { "code": null, "e": 25292, "s": 25276, "text": "setDetailText()" }, { "code": null, "e": 25356, "s": 25292, "text": "Dialog shows a Details button. This text appears on clicking it" }, { "code": null, "e": 25367, "s": 25356, "text": "setTitle()" }, { "code": null, "e": 25403, "s": 25367, "text": "Displays the custom title of dialog" }, { "code": null, "e": 25424, "s": 25403, "text": "setStandardButtons()" }, { "code": null, "e": 25497, "s": 25424, "text": "List of standard buttons to be displayed. Each button is associated with" }, { "code": null, "e": 25523, "s": 25497, "text": "QMessageBox.Ok 0x00000400" }, { "code": null, "e": 25551, "s": 25523, "text": "QMessageBox.Open 0x00002000" }, { "code": null, "e": 25579, "s": 25551, "text": "QMessageBox.Save 0x00000800" }, { "code": null, "e": 25609, "s": 25579, "text": "QMessageBox.Cancel 0x00400000" }, { "code": null, "e": 25638, "s": 25609, "text": "QMessageBox.Close 0x00200000" }, { "code": null, "e": 25665, "s": 25638, "text": "QMessageBox.Yes 0x00004000" }, { "code": null, "e": 25691, "s": 25665, "text": "QMessageBox.No 0x00010000" }, { "code": null, "e": 25720, "s": 25691, "text": "QMessageBox.Abort 0x00040000" }, { "code": null, "e": 25749, "s": 25720, "text": "QMessageBox.Retry 0x00080000" }, { "code": null, "e": 25779, "s": 25749, "text": "QMessageBox.Ignore 0x00100000" }, { "code": null, "e": 25798, "s": 25779, "text": "setDefaultButton()" }, { "code": null, "e": 25874, "s": 25798, "text": "Sets the button as default. It emits the clicked signal if Enter is pressed" }, { "code": null, "e": 25892, "s": 25874, "text": "setEscapeButton()" }, { "code": null, "e": 25962, "s": 25892, "text": "Sets the button to be treated as clicked if the escape key is pressed" }, { "code": null, "e": 26095, "s": 25962, "text": "In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog." }, { "code": null, "e": 26336, "s": 26095, "text": "msg = QMessageBox()\nmsg.setIcon(QMessageBox.Information)\nmsg.setText(\"This is a message box\")\nmsg.setInformativeText(\"This is additional information\")\nmsg.setWindowTitle(\"MessageBox demo\")\nmsg.setDetailedText(\"The details are as follows:\")\n" }, { "code": null, "e": 26391, "s": 26336, "text": "setStandardButton() function displays desired buttons." }, { "code": null, "e": 26452, "s": 26391, "text": "msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n" }, { "code": null, "e": 26562, "s": 26452, "text": "buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal." }, { "code": null, "e": 26597, "s": 26562, "text": "msg.buttonClicked.connect(msgbtn)\n" }, { "code": null, "e": 26647, "s": 26597, "text": "The complete code for the example is as follows −" }, { "code": null, "e": 27496, "s": 26647, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n w = QWidget()\n b = QPushButton(w)\n b.setText(\"Show message!\")\n \n b.move(100,50)\n b.clicked.connect(showdialog)\n w.setWindowTitle(\"PyQt MessageBox demo\")\n w.show()\n sys.exit(app.exec_())\n\ndef showdialog():\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n \n msg.setText(\"This is a message box\")\n msg.setInformativeText(\"This is additional information\")\n msg.setWindowTitle(\"MessageBox demo\")\n msg.setDetailedText(\"The details are as follows:\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msg.buttonClicked.connect(msgbtn)\n\n retval = msg.exec_()\n\ndef msgbtn(i):\n print (\"Button pressed is:\",i.text())\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 27601, "s": 27496, "text": "The above code produces the following output. Message Box pops up when main windows’ button is clicked −" }, { "code": null, "e": 27702, "s": 27601, "text": "If you click on Ok or Cancel button on MessageBox, the following output is produced on the console −" }, { "code": null, "e": 27751, "s": 27702, "text": "Button pressed is: OK\nButton pressed is: Cancel\n" }, { "code": null, "e": 27966, "s": 27751, "text": "A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden." }, { "code": null, "e": 28205, "s": 27966, "text": "One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc." }, { "code": null, "e": 28407, "s": 28205, "text": "MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea." }, { "code": null, "e": 28700, "s": 28407, "text": "QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion." }, { "code": null, "e": 28788, "s": 28700, "text": "The following table lists important methods of QMdiArea class and QMdiSubWindow class −" }, { "code": null, "e": 28803, "s": 28788, "text": "addSubWindow()" }, { "code": null, "e": 28848, "s": 28803, "text": "Adds a widget as a new subwindow in MDI area" }, { "code": null, "e": 28866, "s": 28848, "text": "removeSubWindow()" }, { "code": null, "e": 28922, "s": 28866, "text": "Removes a widget that is internal widget of a subwindow" }, { "code": null, "e": 28943, "s": 28922, "text": "setActiveSubWindow()" }, { "code": null, "e": 28965, "s": 28943, "text": "Activates a subwindow" }, { "code": null, "e": 28985, "s": 28965, "text": "cascadeSubWindows()" }, { "code": null, "e": 29038, "s": 28985, "text": "Arranges subwindows in MDiArea in a cascaded fashion" }, { "code": null, "e": 29055, "s": 29038, "text": "tileSubWindows()" }, { "code": null, "e": 29105, "s": 29055, "text": "Arranges subwindows in MDiArea in a tiled fashion" }, { "code": null, "e": 29128, "s": 29105, "text": "closeActiveSubWindow()" }, { "code": null, "e": 29156, "s": 29128, "text": "Closes the active subwindow" }, { "code": null, "e": 29172, "s": 29156, "text": "subWindowList()" }, { "code": null, "e": 29215, "s": 29172, "text": "Returns the list of subwindows in MDI Area" }, { "code": null, "e": 29227, "s": 29215, "text": "setWidget()" }, { "code": null, "e": 29292, "s": 29227, "text": "Sets a QWidget as an internal widget of a QMdiSubwindow instance" }, { "code": null, "e": 29414, "s": 29292, "text": "QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object." }, { "code": null, "e": 29507, "s": 29414, "text": "In the following example, top level window comprising of QMainWindow has a menu and MdiArea." }, { "code": null, "e": 29682, "s": 29507, "text": "self.mdi = QMdiArea()\nself.setCentralWidget(self.mdi)\nbar = self.menuBar()\nfile = bar.addMenu(\"File\")\n\nfile.addAction(\"New\")\nfile.addAction(\"cascade\")\nfile.addAction(\"Tiled\")" }, { "code": null, "e": 29754, "s": 29682, "text": "Triggered() signal of the menu is connected to windowaction() function." }, { "code": null, "e": 29806, "s": 29754, "text": "file.triggered[QAction].connect(self.windowaction)\n" }, { "code": null, "e": 29907, "s": 29806, "text": "The new action of menu adds a subwindow in MDI area with a title having an incremental number to it." }, { "code": null, "e": 30086, "s": 29907, "text": "MainWindow.count = MainWindow.count+1\nsub = QMdiSubWindow()\nsub.setWidget(QTextEdit())\nsub.setWindowTitle(\"subwindow\"+str(MainWindow.count))\nself.mdi.addSubWindow(sub)\nsub.show()" }, { "code": null, "e": 30208, "s": 30086, "text": "Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively." }, { "code": null, "e": 30242, "s": 30208, "text": "The complete code is as follows −" }, { "code": null, "e": 31380, "s": 30242, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass MainWindow(QMainWindow):\n count = 0\n\n def __init__(self, parent = None):\n super(MainWindow, self).__init__(parent)\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n bar = self.menuBar()\n\n file = bar.addMenu(\"File\")\n file.addAction(\"New\")\n file.addAction(\"cascade\")\n file.addAction(\"Tiled\")\n file.triggered[QAction].connect(self.windowaction)\n self.setWindowTitle(\"MDI demo\")\n\n def windowaction(self, q):\n print (\"triggered\")\n \n if q.text() == \"New\":\n MainWindow.count = MainWindow.count+1\n sub = QMdiSubWindow()\n sub.setWidget(QTextEdit())\n sub.setWindowTitle(\"subwindow\"+str(MainWindow.count))\n self.mdi.addSubWindow(sub)\n sub.show()\n\n if q.text() == \"cascade\":\n self.mdi.cascadeSubWindows()\n\n if q.text() == \"Tiled\":\n self.mdi.tileSubWindows()\n\ndef main():\n app = QApplication(sys.argv)\n ex = MainWindow()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 31447, "s": 31380, "text": "Run above code and three windows in cascased and tiled formation −" }, { "code": null, "e": 31619, "s": 31447, "text": "The 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." }, { "code": null, "e": 31826, "s": 31619, "text": "MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process." }, { "code": null, "e": 31924, "s": 31826, "text": "The following QMimeData class functions allow the MIME type to be detected and used conveniently." }, { "code": null, "e": 32192, "s": 31924, "text": "Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them." }, { "code": null, "e": 32290, "s": 32192, "text": "DragEnterEvent provides an event which is sent to the target widget as dragging action enters it." }, { "code": null, "e": 32388, "s": 32290, "text": "DragEnterEvent provides an event which is sent to the target widget as dragging action enters it." }, { "code": null, "e": 32456, "s": 32388, "text": "DragMoveEvent is used when the drag and drop action is in progress." }, { "code": null, "e": 32524, "s": 32456, "text": "DragMoveEvent is used when the drag and drop action is in progress." }, { "code": null, "e": 32599, "s": 32524, "text": "DragLeaveEvent is generated as the drag and drop action leaves the widget." }, { "code": null, "e": 32674, "s": 32599, "text": "DragLeaveEvent is generated as the drag and drop action leaves the widget." }, { "code": null, "e": 32810, "s": 32674, "text": "DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally." }, { "code": null, "e": 32946, "s": 32810, "text": "DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally." }, { "code": null, "e": 33148, "s": 32946, "text": "In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox." }, { "code": null, "e": 34141, "s": 33148, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass combo(QComboBox):\n def __init__(self, title, parent):\n super(combo, self).__init__( parent)\n self.setAcceptDrops(True)\n\n def dragEnterEvent(self, e):\n print (e)\n\n if e.mimeData().hasText():\n e.accept()\n else:\n e.ignore()\n\n def dropEvent(self, e):\n self.addItem(e.mimeData().text())\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n\n self.initUI()\n\n def initUI(self):\n lo = QFormLayout()\n lo.addRow(QLabel(\"Type some text in textbox and drag it into combo box\"))\n \n edit = QLineEdit()\n edit.setDragEnabled(True)\n com = combo(\"Button\", self)\n lo.addRow(edit,com)\n self.setLayout(lo)\n self.setWindowTitle('Simple drag and drop')\ndef main():\n app = QApplication(sys.argv)\n ex = Example()\n ex.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 34188, "s": 34141, "text": "The above code produces the following output −" }, { "code": null, "e": 34424, "s": 34188, "text": "PyQt5 library contains QtSql module. It is an elaborate class system to communicate with many SQL based databases. Its QSqlDatabase provides access through a Connection object. Following is the list of currently available SQL drivers −" }, { "code": null, "e": 34429, "s": 34424, "text": "QDB2" }, { "code": null, "e": 34437, "s": 34429, "text": "IBM DB2" }, { "code": null, "e": 34444, "s": 34437, "text": "QIBASE" }, { "code": null, "e": 34469, "s": 34444, "text": "Borland InterBase Driver" }, { "code": null, "e": 34476, "s": 34469, "text": "QMYSQL" }, { "code": null, "e": 34489, "s": 34476, "text": "MySQL Driver" }, { "code": null, "e": 34494, "s": 34489, "text": "QOCI" }, { "code": null, "e": 34523, "s": 34494, "text": "Oracle Call Interface Driver" }, { "code": null, "e": 34529, "s": 34523, "text": "QODBC" }, { "code": null, "e": 34573, "s": 34529, "text": "ODBC Driver (includes Microsoft SQL Server)" }, { "code": null, "e": 34579, "s": 34573, "text": "QPSQL" }, { "code": null, "e": 34597, "s": 34579, "text": "PostgreSQL Driver" }, { "code": null, "e": 34605, "s": 34597, "text": "QSQLITE" }, { "code": null, "e": 34631, "s": 34605, "text": "SQLite version 3 or above" }, { "code": null, "e": 34640, "s": 34631, "text": "QSQLITE2" }, { "code": null, "e": 34657, "s": 34640, "text": "SQLite version 2" }, { "code": null, "e": 34752, "s": 34657, "text": "For this chapter, a connection with a SQLite database is established using the static method −" }, { "code": null, "e": 34832, "s": 34752, "text": "db = QtSql.QSqlDatabase.addDatabase('QSQLITE')\ndb.setDatabaseName('sports.db')\n" }, { "code": null, "e": 34885, "s": 34832, "text": "Other methods of QSqlDatabase class are as follows −" }, { "code": null, "e": 34903, "s": 34885, "text": "setDatabaseName()" }, { "code": null, "e": 34965, "s": 34903, "text": "Sets the name of the database with which connection is sought" }, { "code": null, "e": 34979, "s": 34965, "text": "setHostName()" }, { "code": null, "e": 35040, "s": 34979, "text": "Sets the name of the host on which the database is installed" }, { "code": null, "e": 35054, "s": 35040, "text": "setUserName()" }, { "code": null, "e": 35093, "s": 35054, "text": "Specifies the user name for connection" }, { "code": null, "e": 35107, "s": 35093, "text": "setPassword()" }, { "code": null, "e": 35152, "s": 35107, "text": "Sets the connection object’s password if any" }, { "code": null, "e": 35161, "s": 35152, "text": "commit()" }, { "code": null, "e": 35217, "s": 35161, "text": "Commits the transactions and returns true if successful" }, { "code": null, "e": 35228, "s": 35217, "text": "rollback()" }, { "code": null, "e": 35264, "s": 35228, "text": "Rolls back the database transaction" }, { "code": null, "e": 35272, "s": 35264, "text": "close()" }, { "code": null, "e": 35294, "s": 35272, "text": "Closes the connection" }, { "code": null, "e": 35499, "s": 35294, "text": "QSqlQuery class has the functionality to execute and manipulate SQL commands. Both DDL and DML type of SQL queries can be executed. First step is to create SQlite database using the following statements −" }, { "code": null, "e": 35581, "s": 35499, "text": "db = QSqlDatabase.addDatabase('QSQLITE')\ndb.setDatabaseName('sportsdatabase.db')\n" }, { "code": null, "e": 35752, "s": 35581, "text": "Next, obtain Query object with QSqlQuery() method and call its most important method exec_(), which takes as an argument a string containing SQL statement to be executed." }, { "code": null, "e": 35885, "s": 35752, "text": "query = QtSql.QSqlQuery()\nquery.exec_(\"create table sportsmen(id int primary key, \" \"firstname varchar(20), lastname varchar(20))\")\n" }, { "code": null, "e": 36000, "s": 35885, "text": "The following script creates a SQLite database sports.db with a table of sportsperson populated with five records." }, { "code": null, "e": 37000, "s": 36000, "text": "import sys\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef createDB():\n db = QSqlDatabase.addDatabase('QSQLITE')\n db.setDatabaseName('sportsdatabase.db')\n\n if not db.open():\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"Error in Database Creation\")\n retval = msg.exec_()\n return False\n query = QSqlQuery()\n\n query.exec_(\"create table sportsmen(\n id int primary key, \"\"firstname varchar(20), lastname varchar(20))\")\n\n query.exec_(\"insert into sportsmen values(101, 'Roger', 'Federer')\")\n query.exec_(\"insert into sportsmen values(102, 'Christiano', 'Ronaldo')\")\n query.exec_(\"insert into sportsmen values(103, 'Ussain', 'Bolt')\")\n query.exec_(\"insert into sportsmen values(104, 'Sachin', 'Tendulkar')\")\n query.exec_(\"insert into sportsmen values(105, 'Saina', 'Nehwal')\")\n return True\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n createDB()" }, { "code": null, "e": 37144, "s": 37000, "text": "To confirm that the SQLite database is created with above records added in sportsmen table in it, use a SQLite Gui utility called SQLiteStudio." }, { "code": null, "e": 37432, "s": 37144, "text": "QSqlTableModel class in PyQt is a high-level interface that provides editable data model for reading and writing records in a single table. This model is used to populate a QTableView object. It presents to the user a scrollable and editable view that can be put on any top level window." }, { "code": null, "e": 37494, "s": 37432, "text": "A QSqlTableModel object is declared in the following manner −" }, { "code": null, "e": 37526, "s": 37494, "text": "model = QtSql.QSqlTableModel()\n" }, { "code": null, "e": 37584, "s": 37526, "text": "Its editing strategy can be set to any of the following −" }, { "code": null, "e": 37677, "s": 37584, "text": "In the following example, sportsperson table is used as a model and the strategy is set as −" }, { "code": null, "e": 37782, "s": 37677, "text": "model.setTable('sportsmen') \nmodel.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)\n model.select()" }, { "code": null, "e": 37886, "s": 37782, "text": "QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows −" }, { "code": null, "e": 37972, "s": 37886, "text": "view = QtGui.QTableView()\nview.setModel(model)\nview.setWindowTitle(title)\nreturn view" }, { "code": null, "e": 38169, "s": 37972, "text": "This QTableView object and two QPushButton widgets are added to the top level QDialog window. Clicked() signal of add button is connected to addrow() which performs insertRow() on the model table." }, { "code": null, "e": 38300, "s": 38169, "text": "button.clicked.connect(addrow)\ndef addrow():\n print model.rowCount()\n ret = model.insertRows(model.rowCount(), 1)\n print ret" }, { "code": null, "e": 38421, "s": 38300, "text": "The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user." }, { "code": null, "e": 38496, "s": 38421, "text": "btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))\n" }, { "code": null, "e": 38530, "s": 38496, "text": "The complete code is as follows −" }, { "code": null, "e": 39924, "s": 38530, "text": "import sys\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef initializeModel(model):\n model.setTable('sportsmen')\n model.setEditStrategy(QSqlTableModel.OnFieldChange)\n model.select()\n model.setHeaderData(0, Qt.Horizontal, \"ID\")\n model.setHeaderData(1, Qt.Horizontal, \"First name\")\n model.setHeaderData(2, Qt.Horizontal, \"Last name\")\n\ndef createView(title, model):\n view = QTableView()\n view.setModel(model)\n view.setWindowTitle(title)\n return view\n\ndef addrow():\n print (model.rowCount())\n ret = model.insertRows(model.rowCount(), 1)\n print (ret)\n\ndef findrow(i):\n delrow = i.row()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n db = QSqlDatabase.addDatabase('QSQLITE')\n db.setDatabaseName('sportsdatabase.db')\n model = QSqlTableModel()\n delrow = -1\n initializeModel(model)\n\n view1 = createView(\"Table Model (View 1)\", model)\n view1.clicked.connect(findrow)\n\n dlg = QDialog()\n layout = QVBoxLayout()\n layout.addWidget(view1)\n\n button = QPushButton(\"Add a row\")\n button.clicked.connect(addrow)\n layout.addWidget(button)\n\n btn1 = QPushButton(\"del a row\")\n btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))\n layout.addWidget(btn1)\n\n dlg.setLayout(layout)\n dlg.setWindowTitle(\"Database Demo\")\n dlg.show()\n sys.exit(app.exec_())" }, { "code": null, "e": 39971, "s": 39924, "text": "The above code produces the following output −" }, { "code": null, "e": 40066, "s": 39971, "text": "Try adding and deleting a few records and go back to SQLiteStudio to confirm the transactions." }, { "code": null, "e": 40323, "s": 40066, "text": "All the QWidget classes in PyQt are sub classed from QPaintDevice class. A QPaintDevice is an abstraction of two dimensional space that can be drawn upon using a QPainter. Dimensions of paint device are measured in pixels starting from the top-left corner." }, { "code": null, "e": 40536, "s": 40323, "text": "QPainter class performs low level painting on widgets and other paintable devices such as printer. Normally, it is used in widget’s paint event. The QPaintEvent occurs whenever the widget’s appearance is updated." }, { "code": null, "e": 40728, "s": 40536, "text": "The painter is activated by calling the begin() method, while the end() method deactivates it. In between, the desired pattern is painted by suitable methods as listed in the following table." }, { "code": null, "e": 40736, "s": 40728, "text": "begin()" }, { "code": null, "e": 40773, "s": 40736, "text": "Starts painting on the target device" }, { "code": null, "e": 40783, "s": 40773, "text": "drawArc()" }, { "code": null, "e": 40835, "s": 40783, "text": "Draws an arc between the starting and the end angle" }, { "code": null, "e": 40849, "s": 40835, "text": "drawEllipse()" }, { "code": null, "e": 40885, "s": 40849, "text": "Draws an ellipse inside a rectangle" }, { "code": null, "e": 40896, "s": 40885, "text": "drawLine()" }, { "code": null, "e": 40945, "s": 40896, "text": "Draws a line with endpoint coordinates specified" }, { "code": null, "e": 40958, "s": 40945, "text": "drawPixmap()" }, { "code": null, "e": 41036, "s": 40958, "text": "Extracts pixmap from the image file and displays it at the specified position" }, { "code": null, "e": 41050, "s": 41036, "text": "drwaPolygon()" }, { "code": null, "e": 41096, "s": 41050, "text": "Draws a polygon using an array of coordinates" }, { "code": null, "e": 41107, "s": 41096, "text": "drawRect()" }, { "code": null, "e": 41193, "s": 41107, "text": "Draws a rectangle starting at the top-left coordinate with the given width and height" }, { "code": null, "e": 41204, "s": 41193, "text": "drawText()" }, { "code": null, "e": 41243, "s": 41204, "text": "Displays the text at given coordinates" }, { "code": null, "e": 41254, "s": 41243, "text": "fillRect()" }, { "code": null, "e": 41300, "s": 41254, "text": "Fills the rectangle with the QColor parameter" }, { "code": null, "e": 41311, "s": 41300, "text": "setBrush()" }, { "code": null, "e": 41343, "s": 41311, "text": "Sets a brush style for painting" }, { "code": null, "e": 41352, "s": 41343, "text": "setPen()" }, { "code": null, "e": 41413, "s": 41352, "text": "Sets the color, size and style of pen to be used for drawing" }, { "code": null, "e": 41488, "s": 41413, "text": "In the following code, various methods of PyQt's drawing methods are used." }, { "code": null, "e": 42450, "s": 41488, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n self.initUI()\n\n def initUI(self):\n self.text = \"hello world\"\n self.setGeometry(100,100, 400,300)\n self.setWindowTitle('Draw Demo')\n self.show()\n\n def paintEvent(self, event):\n qp = QPainter()\n qp.begin(self)\n qp.setPen(QColor(Qt.red))\n qp.setFont(QFont('Arial', 20))\n qp.drawText(10,50, \"hello Python\")\n qp.setPen(QColor(Qt.blue))\n qp.drawLine(10,100,100,100)\n qp.drawRect(10,150,150,100)\n qp.setPen(QColor(Qt.yellow))\n qp.drawEllipse(100,50,100,50)\n qp.drawPixmap(220,10,QPixmap(\"pythonlogo.png\"))\n qp.fillRect(20,175,130,70,QBrush(Qt.SolidPattern))\n qp.end()\n\ndef main():\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 42497, "s": 42450, "text": "The above code produces the following output −" }, { "code": null, "e": 42552, "s": 42497, "text": "In this chapter, we shall learn Brush Style Constants." }, { "code": null, "e": 42596, "s": 42552, "text": "Given below are the Brush Style Constants −" }, { "code": null, "e": 42643, "s": 42596, "text": "Given below are the Predefined QColor Styles −" }, { "code": null, "e": 42691, "s": 42643, "text": "Given below are the Predefined QColor Objects −" }, { "code": null, "e": 42895, "s": 42691, "text": "The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types." }, { "code": null, "e": 43059, "s": 42895, "text": "QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard." }, { "code": null, "e": 43126, "s": 43059, "text": "Following are the clipboard class methods that are commonly used −" }, { "code": null, "e": 43134, "s": 43126, "text": "clear()" }, { "code": null, "e": 43160, "s": 43134, "text": "Clears clipboard contents" }, { "code": null, "e": 43171, "s": 43160, "text": "setImage()" }, { "code": null, "e": 43200, "s": 43171, "text": "Copies QImage into clipboard" }, { "code": null, "e": 43214, "s": 43200, "text": "setMimeData()" }, { "code": null, "e": 43244, "s": 43214, "text": "Sets MIME data into clipboard" }, { "code": null, "e": 43256, "s": 43244, "text": "setPixmap()" }, { "code": null, "e": 43290, "s": 43256, "text": "Copies Pixmap object in clipboard" }, { "code": null, "e": 43300, "s": 43290, "text": "setText()" }, { "code": null, "e": 43328, "s": 43300, "text": "Copies QString in clipboard" }, { "code": null, "e": 43335, "s": 43328, "text": "text()" }, { "code": null, "e": 43365, "s": 43335, "text": "Retrieves text from clipboard" }, { "code": null, "e": 43410, "s": 43365, "text": "Signal associated with clipboard object is −" }, { "code": null, "e": 43424, "s": 43410, "text": "dataChanged()" }, { "code": null, "e": 43456, "s": 43424, "text": "Whenever clipboard data changes" }, { "code": null, "e": 43556, "s": 43456, "text": "In the following example, two TextEdit objects and two Pushbuttons are added to a top level window." }, { "code": null, "e": 43788, "s": 43556, "text": "To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object." }, { "code": null, "e": 44960, "s": 43788, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n\n self.initUI()\n\n def initUI(self):\n hbox = QVBoxLayout()\n self.edit1=QTextEdit()\n hbox.addWidget(self.edit1)\n self.btn1=QPushButton(\"Copy\")\n hbox.addWidget(self.btn1)\n self.edit2=QTextEdit()\n self.btn2=QPushButton(\"Paste\")\n hbox.addWidget(self.edit2)\n hbox.addWidget(self.btn2)\n self.btn1.clicked.connect(self.copytext)\n self.btn2.clicked.connect(self.pastetext)\n self.setLayout(hbox)\n \n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Clipboard')\n self.show()\n \n def copytext(self):\n\n #clipboard.setText(self.edit1.copy())\n self.edit1.copy()\n print (clipboard.text())\n\n msg=QMessageBox()\n msg.setText(clipboard.text()+\" copied on clipboard\")\n msg.exec_()\n\n def pastetext(self):\n self.edit2.setText(clipboard.text())\n\napp = QApplication(sys.argv)\nclipboard=app.clipboard()\nex = Example()\nex.setWindowTitle(\"clipboard Example\")\nsys.exit(app.exec_())" }, { "code": null, "e": 45007, "s": 44960, "text": "The above code produces the following output −" }, { "code": null, "e": 45179, "s": 45007, "text": "QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button." }, { "code": null, "e": 45379, "s": 45179, "text": "Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible." }, { "code": null, "e": 45460, "s": 45379, "text": "The types of image files that can be read into a QPixmap object are as follows −" }, { "code": null, "e": 45518, "s": 45460, "text": "Following methods are useful in handling QPixmap object −" }, { "code": null, "e": 45525, "s": 45518, "text": "copy()" }, { "code": null, "e": 45564, "s": 45525, "text": "Copies pixmap data from a QRect object" }, { "code": null, "e": 45576, "s": 45564, "text": "fromImage()" }, { "code": null, "e": 45612, "s": 45576, "text": "Converts QImage object into QPixmap" }, { "code": null, "e": 45625, "s": 45612, "text": "grabWidget()" }, { "code": null, "e": 45664, "s": 45625, "text": "Creates a pixmap from the given widget" }, { "code": null, "e": 45677, "s": 45664, "text": "grabWindow()" }, { "code": null, "e": 45711, "s": 45677, "text": "Create pixmap of data in a window" }, { "code": null, "e": 45718, "s": 45711, "text": "Load()" }, { "code": null, "e": 45748, "s": 45718, "text": "Loads an image file as pixmap" }, { "code": null, "e": 45755, "s": 45748, "text": "save()" }, { "code": null, "e": 45790, "s": 45755, "text": "Saves the QPixmap object as a file" }, { "code": null, "e": 45798, "s": 45790, "text": "toImage" }, { "code": null, "e": 45827, "s": 45798, "text": "Converts a QPixmap to QImage" }, { "code": null, "e": 45897, "s": 45827, "text": "The most common use of QPixmap is to display image on a label/button." }, { "code": null, "e": 45989, "s": 45897, "text": "The following example shows an image displayed on a QLabel by using the setPixmap() method." }, { "code": null, "e": 46023, "s": 45989, "text": "The complete code is as follows −" }, { "code": null, "e": 46426, "s": 46023, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n l1 = QLabel()\n l1.setPixmap(QPixmap(\"python.png\"))\n\n vbox = QVBoxLayout()\n vbox.addWidget(l1)\n win.setLayout(vbox)\n win.setWindowTitle(\"QPixmap Demo\")\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 46473, "s": 46426, "text": "The above code produces the following output −" }, { "code": null, "e": 46510, "s": 46473, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 46520, "s": 46510, "text": " ALAA EID" }, { "code": null, "e": 46527, "s": 46520, "text": " Print" }, { "code": null, "e": 46538, "s": 46527, "text": " Add Notes" } ]
Could Neptune Really Replace Jupyter? | by Emmett Boudreau | Towards Data Science
Last year in October, I took a look at a Julia package called Pluto.jl. Pluto.jl is a notebook server for the Julia programming language that has a lot of unique features that set it apart from its competition. As I am an IJulia user primarily, I of course ended up comparing this solution to Jupyter Notebooks. In a lot of ways, I believe the notebooks traded blows. However, there were some fundamental issues I was facing with Pluto.jl and the ideas behind it that made the notebooks much less usable when compared to their Jupyter counter-part for me personally. If you would like to read that article, you may do that here: towardsdatascience.com I found that in my experience with Pluto.jl, it was much more tedious to use than just about any other solution I have worked with. Once again, I would like to note that this was my preference, not the fault of the package. However, I found that the reactive nature of the notebook often got in the way of executing just about any cell of code. This was very frustrating to deal with, because on paper Pluto.jl sounds amazing. The notebook is reactive, so there are no state issues that can make notebooks be less reproducible. This concern is something I adopted from one of my favorite machine-learning enthusiasts, Joel Grus, who is also the author of one of my favorite books from O’Reilly. To quote Grus directly, “ We can completely mislead our output by simply changing the order of execution of these cells.” Of course, a concept like that is pretty terrible for something like science, especially in terms of creating reproducible research. Pluto.jl attempted to solve this by adding the reactive feature, but in my opinion it falls a bit short by not keeping up with what you are doing effectively enough. Additionally, having to begin and end any multi-line cells is also rather tedious and annoying. Despite the failing of the reactive feature in this regard, I think there are a lot of other redeeming qualities to Pluto notebooks. This is where Neptune.jl takes the cake and wins for me. Neptune.jl is a new modification of Pluto notebooks that has the primary purpose of being Pluto without the reactive feature. This means that the ability to use notebook cells in pure Julia is now possible without having to deal with the reactivity of Pluto getting between you and your code. This is desirable to me because we can effectively cut out Python as the bridge between the Julia language and the kernel, and instead work with pure Julia through and through. More exciting is how Neptune and Pluto notebooks save files. Neptune files are not stored in an IPython notebook containing a bunch of JSON data that tells Jupyter how to decode all of your cells. Instead, Neptune files are stored safely and securely, nested inside of a .JL file, with markdown cells made into multi-line strings. For me, this is a pretty big selling point of utilizing something like Neptune or Pluto over Jupyter Notebooks. Furthermore, this can be a huge advancement because now we can have applications and notebooks in the same file. Not only that, our applications can be very well documented right off the bat, because all of our comments are now retained within this .JL file! We could always run this file by calling it with Julia. We could even include it, it is a Julia file! A Julia file is going to be a lot more diverse in this regard than something like a notebook file. The only concern I hold with this is viewing this notebook from different applications. There have been times where I have looked at the source of a notebook inside of Github. This would not be possible with Neptune or Pluto. However, viewing the Julia code in most situations I believe would actually be apt, and perhaps that might even be a preference on Github so long as no show() method is used to show something HTML or image-wise. Neptune also has a few other changes that have been made, but in order to check out those changes we will need to add the package with Pkg. For a while, the package was not available in the Julia General registry, but as of now it is registered, and we can add it via the Pkg REPL. julia > ]pkg > add Neptune Now we will import Neptune and use the Neptune.run() method in order to start a new notebook server. using Neptune; Neptune.run() You might recognize this home screen if you have ever worked with Pluto.jl, as it is the exact same one with the exception of the text in the middle. Here, we also get a pretty good description of exactly what Neptune is. Neptune is a notebook server that follows the ideas presented by Jupyter, which serves as the inspiration for the package, but the server is also powered by a fork of Pluto.jl. Creating a new notebook, we quickly see that the reactivity from Pluto.jl is nowhere to be seen — which for me personally, is quite a sight for sore eyes. However, one issue that I still get frustrated by is the inability to use the shift+enter hot-keys to create a new cell. It is easy to see why this is not the case, I think that measuring the input of a cell like this prior to execution in order to check for hot-key input might cause a lot more headache than it is actually worth. That being said, I do believe that most Data Scientists use this hot-key very frequently, so it is certainly something I would note as a frustration. Reaching over to my mouse every time I want to add more code is incredibly tedious in my opinion. The stylistic choice to put the output above the input is also something I have a bone to pick with. It seems nonsensical to me. The output is a direct result of the input, and always comes after it, we do not read a page bottom to top, so it really does not make much sense for the output to be above the cell. I continuously think that cells have not ran when they actually have, the output is just simply above the cell rather than below it. Of course, this is a complaint of Pluto.jl, not Neptune.jl, but Neptune.jl being a fork of Pluto.jl means that it also inherits its problems. One thing I will say about Neptune that is negative, however, is that the favicon is really ugly. That might sound like a bad critique for something like this, and it is, but I would prefer there not to be one instead of having a picture with a white background behind it that has the wrong aspect ratio. Fortunately, there is one thing that has been taken out of Neptune.jl that was in Pluto.jl. This removed feature is one that I despised with Pluto.jl, and it was the inability to create multi-line code cells without a begin and end. It is easy to see why this was, I imagine it was likely due to the way Pluto.jl saves its files. However, I did find it rather annoying to need to write begin and end every time I wanted to write a new line of code. Funny enough, I might have actually been the one to suggest this change, so I am incredibly happy to see it pull through so flawlessly in Neptune. In the spirit of open source, we have received a fork to Pluto that I believe features a lot of dramatic improvements to the original notebooks. While a lot of concepts in Pluto.jl are pretty cool, I think that a lot of them also get in the way more than they actually help with Julia programming. In a lot of cases, I was incredibly annoyed to have the reactivity be included as part of the notebooks. I think that the reactivity is actually still a great idea, but likely still needs some elbow grease and intelligent programming put into it to truly be remarkable. So the question is, can this really replace Jupyter notebooks and IJulia for Julian Data Science? For now, I would have to say my answer is no. The main reason I say this is because there are still some output bugs with Neptune.jl that have carried over from Pluto. Sometimes, output just will not appear — and of course, this can be frustrating. I think the concept of notebooks in a .jl file is certainly alluring, and I am sure I can see notebook solutions like these working out very well some day. However, today might not be that day, unfortunately. Writing this article has actually made me want to create my own notebook server in order to create it exactly how I would want it to be. That would certainly be an interesting project! Although I think that Neptune is a better solution for me personally, I will still be sticking with IJulia. I think that there are some flaws from Pluto that carry over into Neptune, unfortunately, but there surely is a future for both packages — which I am excited for! I think that with just a few tweaks, both of these notebook servers could be apt replacements for me to use instead of Jupyter. I will say, however, I think that a lot of this comes down to personal preference. I just happen to prefer Jupyter over both of these packages, and others might not end up feeling the same way, so I do encourage readers to try out both of these notebooks and make up their own mind on which is better! Thank you for reading, I hope this article helps in finding the best notebooks to write Julia in for you!
[ { "code": null, "e": 675, "s": 46, "text": "Last year in October, I took a look at a Julia package called Pluto.jl. Pluto.jl is a notebook server for the Julia programming language that has a lot of unique features that set it apart from its competition. As I am an IJulia user primarily, I of course ended up comparing this solution to Jupyter Notebooks. In a lot of ways, I believe the notebooks traded blows. However, there were some fundamental issues I was facing with Pluto.jl and the ideas behind it that made the notebooks much less usable when compared to their Jupyter counter-part for me personally. If you would like to read that article, you may do that here:" }, { "code": null, "e": 698, "s": 675, "text": "towardsdatascience.com" }, { "code": null, "e": 1417, "s": 698, "text": "I found that in my experience with Pluto.jl, it was much more tedious to use than just about any other solution I have worked with. Once again, I would like to note that this was my preference, not the fault of the package. However, I found that the reactive nature of the notebook often got in the way of executing just about any cell of code. This was very frustrating to deal with, because on paper Pluto.jl sounds amazing. The notebook is reactive, so there are no state issues that can make notebooks be less reproducible. This concern is something I adopted from one of my favorite machine-learning enthusiasts, Joel Grus, who is also the author of one of my favorite books from O’Reilly. To quote Grus directly," }, { "code": null, "e": 1515, "s": 1417, "text": "“ We can completely mislead our output by simply changing the order of execution of these cells.”" }, { "code": null, "e": 2100, "s": 1515, "text": "Of course, a concept like that is pretty terrible for something like science, especially in terms of creating reproducible research. Pluto.jl attempted to solve this by adding the reactive feature, but in my opinion it falls a bit short by not keeping up with what you are doing effectively enough. Additionally, having to begin and end any multi-line cells is also rather tedious and annoying. Despite the failing of the reactive feature in this regard, I think there are a lot of other redeeming qualities to Pluto notebooks. This is where Neptune.jl takes the cake and wins for me." }, { "code": null, "e": 2570, "s": 2100, "text": "Neptune.jl is a new modification of Pluto notebooks that has the primary purpose of being Pluto without the reactive feature. This means that the ability to use notebook cells in pure Julia is now possible without having to deal with the reactivity of Pluto getting between you and your code. This is desirable to me because we can effectively cut out Python as the bridge between the Julia language and the kernel, and instead work with pure Julia through and through." }, { "code": null, "e": 3473, "s": 2570, "text": "More exciting is how Neptune and Pluto notebooks save files. Neptune files are not stored in an IPython notebook containing a bunch of JSON data that tells Jupyter how to decode all of your cells. Instead, Neptune files are stored safely and securely, nested inside of a .JL file, with markdown cells made into multi-line strings. For me, this is a pretty big selling point of utilizing something like Neptune or Pluto over Jupyter Notebooks. Furthermore, this can be a huge advancement because now we can have applications and notebooks in the same file. Not only that, our applications can be very well documented right off the bat, because all of our comments are now retained within this .JL file! We could always run this file by calling it with Julia. We could even include it, it is a Julia file! A Julia file is going to be a lot more diverse in this regard than something like a notebook file." }, { "code": null, "e": 3911, "s": 3473, "text": "The only concern I hold with this is viewing this notebook from different applications. There have been times where I have looked at the source of a notebook inside of Github. This would not be possible with Neptune or Pluto. However, viewing the Julia code in most situations I believe would actually be apt, and perhaps that might even be a preference on Github so long as no show() method is used to show something HTML or image-wise." }, { "code": null, "e": 4193, "s": 3911, "text": "Neptune also has a few other changes that have been made, but in order to check out those changes we will need to add the package with Pkg. For a while, the package was not available in the Julia General registry, but as of now it is registered, and we can add it via the Pkg REPL." }, { "code": null, "e": 4220, "s": 4193, "text": "julia > ]pkg > add Neptune" }, { "code": null, "e": 4321, "s": 4220, "text": "Now we will import Neptune and use the Neptune.run() method in order to start a new notebook server." }, { "code": null, "e": 4350, "s": 4321, "text": "using Neptune; Neptune.run()" }, { "code": null, "e": 4749, "s": 4350, "text": "You might recognize this home screen if you have ever worked with Pluto.jl, as it is the exact same one with the exception of the text in the middle. Here, we also get a pretty good description of exactly what Neptune is. Neptune is a notebook server that follows the ideas presented by Jupyter, which serves as the inspiration for the package, but the server is also powered by a fork of Pluto.jl." }, { "code": null, "e": 5484, "s": 4749, "text": "Creating a new notebook, we quickly see that the reactivity from Pluto.jl is nowhere to be seen — which for me personally, is quite a sight for sore eyes. However, one issue that I still get frustrated by is the inability to use the shift+enter hot-keys to create a new cell. It is easy to see why this is not the case, I think that measuring the input of a cell like this prior to execution in order to check for hot-key input might cause a lot more headache than it is actually worth. That being said, I do believe that most Data Scientists use this hot-key very frequently, so it is certainly something I would note as a frustration. Reaching over to my mouse every time I want to add more code is incredibly tedious in my opinion." }, { "code": null, "e": 6376, "s": 5484, "text": "The stylistic choice to put the output above the input is also something I have a bone to pick with. It seems nonsensical to me. The output is a direct result of the input, and always comes after it, we do not read a page bottom to top, so it really does not make much sense for the output to be above the cell. I continuously think that cells have not ran when they actually have, the output is just simply above the cell rather than below it. Of course, this is a complaint of Pluto.jl, not Neptune.jl, but Neptune.jl being a fork of Pluto.jl means that it also inherits its problems. One thing I will say about Neptune that is negative, however, is that the favicon is really ugly. That might sound like a bad critique for something like this, and it is, but I would prefer there not to be one instead of having a picture with a white background behind it that has the wrong aspect ratio." }, { "code": null, "e": 6972, "s": 6376, "text": "Fortunately, there is one thing that has been taken out of Neptune.jl that was in Pluto.jl. This removed feature is one that I despised with Pluto.jl, and it was the inability to create multi-line code cells without a begin and end. It is easy to see why this was, I imagine it was likely due to the way Pluto.jl saves its files. However, I did find it rather annoying to need to write begin and end every time I wanted to write a new line of code. Funny enough, I might have actually been the one to suggest this change, so I am incredibly happy to see it pull through so flawlessly in Neptune." }, { "code": null, "e": 7540, "s": 6972, "text": "In the spirit of open source, we have received a fork to Pluto that I believe features a lot of dramatic improvements to the original notebooks. While a lot of concepts in Pluto.jl are pretty cool, I think that a lot of them also get in the way more than they actually help with Julia programming. In a lot of cases, I was incredibly annoyed to have the reactivity be included as part of the notebooks. I think that the reactivity is actually still a great idea, but likely still needs some elbow grease and intelligent programming put into it to truly be remarkable." }, { "code": null, "e": 8281, "s": 7540, "text": "So the question is, can this really replace Jupyter notebooks and IJulia for Julian Data Science? For now, I would have to say my answer is no. The main reason I say this is because there are still some output bugs with Neptune.jl that have carried over from Pluto. Sometimes, output just will not appear — and of course, this can be frustrating. I think the concept of notebooks in a .jl file is certainly alluring, and I am sure I can see notebook solutions like these working out very well some day. However, today might not be that day, unfortunately. Writing this article has actually made me want to create my own notebook server in order to create it exactly how I would want it to be. That would certainly be an interesting project!" } ]
Python Program to Create a class performing Calculator Operations
When it is required to create a class that performs calculator operations, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations. Below is a demonstration for the same − Live Demo class calculator_implementation(): def __init__(self,in_1,in_2): self.a=in_1 self.b=in_2 def add_vals(self): return self.a+self.b def multiply_vals(self): return self.a*self.b def divide_vals(self): return self.a/self.b def subtract_vals(self): return self.a-self.b input_1 = int(input("Enter the first number: ")) input_2 = int(input("Enter the second number: ")) print("The entered first and second numbers are : ") print(input_1, input_2) my_instance = calculator_implementation(input_1,input_2) choice=1 while choice!=0: print("0. Exit") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice=int(input("Enter your choice... ")) if choice==1: print("The computed addition result is : ",my_instance.add_vals()) elif choice==2: print("The computed subtraction result is : ",my_instance.subtract_vals()) elif choice==3: print("The computed product result is : ",my_instance.multiply_vals()) elif choice==4: print("The computed division result is : ",round(my_instance.divide_vals(),2)) elif choice==0: print("Exit") else: print("Sorry, invalid choice!") print() Enter the first number: 70 Enter the second number: 2 The entered first and second numbers are : 70 2 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 1 The computed addition result is : 72 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 2 The computed subtraction result is : 68 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 3 The computed product result is : 140 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 4 The computed division result is : 35.0 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 0 Exit A class named ‘calculator_implementation’ class is defined, that has functions like ‘add_vals’, ‘subtract_vals’, ‘multiply_vals’, and ‘divide_vals’. These are used to perform calculator operations such as addition, subtraction, multiplication, and division respectively. An instance of this class is created. The value for the two numbers are entered and operations are performed on it. Relevant messages and output is displayed on the console.
[ { "code": null, "e": 1393, "s": 1062, "text": "When it is required to create a class that performs calculator operations, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations." }, { "code": null, "e": 1433, "s": 1393, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1444, "s": 1433, "text": " Live Demo" }, { "code": null, "e": 2675, "s": 1444, "text": "class calculator_implementation():\n def __init__(self,in_1,in_2):\n self.a=in_1\n self.b=in_2\n def add_vals(self):\n return self.a+self.b\n def multiply_vals(self):\n return self.a*self.b\n def divide_vals(self):\n return self.a/self.b\n def subtract_vals(self):\n return self.a-self.b\ninput_1 = int(input(\"Enter the first number: \"))\ninput_2 = int(input(\"Enter the second number: \"))\nprint(\"The entered first and second numbers are : \")\nprint(input_1, input_2)\nmy_instance = calculator_implementation(input_1,input_2)\nchoice=1\nwhile choice!=0:\n print(\"0. Exit\")\n print(\"1. Addition\")\n print(\"2. Subtraction\")\n print(\"3. Multiplication\")\n print(\"4. Division\")\n choice=int(input(\"Enter your choice... \"))\n if choice==1:\n print(\"The computed addition result is : \",my_instance.add_vals())\n elif choice==2:\n print(\"The computed subtraction result is : \",my_instance.subtract_vals())\n elif choice==3:\n print(\"The computed product result is : \",my_instance.multiply_vals())\n elif choice==4:\n print(\"The computed division result is : \",round(my_instance.divide_vals(),2))\n elif choice==0:\n print(\"Exit\")\n else:\n print(\"Sorry, invalid choice!\")\nprint()" }, { "code": null, "e": 3375, "s": 2675, "text": "Enter the first number: 70\nEnter the second number: 2\nThe entered first and second numbers are :\n70 2\n0. Exit\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nEnter your choice... 1\nThe computed addition result is : 72\n0. Exit\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nEnter your choice... 2\nThe computed subtraction result is : 68\n0. Exit\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nEnter your choice... 3\nThe computed product result is : 140\n0. Exit\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nEnter your choice... 4\nThe computed division result is : 35.0\n0. Exit\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nEnter your choice... 0\nExit" }, { "code": null, "e": 3524, "s": 3375, "text": "A class named ‘calculator_implementation’ class is defined, that has functions like ‘add_vals’, ‘subtract_vals’, ‘multiply_vals’, and ‘divide_vals’." }, { "code": null, "e": 3646, "s": 3524, "text": "These are used to perform calculator operations such as addition, subtraction, multiplication, and division respectively." }, { "code": null, "e": 3684, "s": 3646, "text": "An instance of this class is created." }, { "code": null, "e": 3762, "s": 3684, "text": "The value for the two numbers are entered and operations are performed on it." }, { "code": null, "e": 3820, "s": 3762, "text": "Relevant messages and output is displayed on the console." } ]
iText - Drawing a Line
In this chapter, we will see how to draw a line on a PDF document using iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. To draw a line on a PdfDocument Instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and create a line using the moveTo() and lineTO() methods of this class. Following are the steps to draw a line on the pdf document. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/drawingLine.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing above created PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below. // Creating a Document Document document = new Document(pdfDoc); Create a new PdfPage class using the addNewPage() method of the PdfDocument class. Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the above created PdfPage object to the constructor of this class, as shown below. // Creating a new page PdfPage pdfPage = pdfDoc.addNewPage(); // Creating a PdfCanvas object PdfCanvas canvas = new PdfCanvas(pdfPage); Set the initial point of the line using the moveTO() method of the Canvas class, as shown below. // Initial point of the line canvas.moveTo(100, 300); Now, draw a line from this point to another point using the lineTo() method, as shown below. // Drawing the line canvas.lineTo(500, 300); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to draw a line in a PDF document using the iText library. It creates a PDF document with the name drawingLine.pdf, draws an arc in it, and saves it in the path C:/itextExamples/ Save this code in a file with name DrawingLine.java. import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Document; public class DrawingLine { public static void main(String args[]) throws Exception { // Creating a PdfWriter String dest = "C:/itextExamples/drawingLine.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document object Document doc = new Document(pdfDoc); // Creating a new page PdfPage pdfPage = pdfDoc.addNewPage(); // Creating a PdfCanvas object PdfCanvas canvas = new PdfCanvas(pdfPage); // Initial point of the line canvas.moveTo(100, 300); // Drawing the line canvas.lineTo(500, 300); // Closing the path stroke canvas.closePathStroke(); // Closing the document doc.close(); System.out.println("Object drawn on pdf successfully"); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac DrawingLine.java java DrawingLine Upon execution, the above program creates a PDF document, displaying the following message. Object drawn on pdf successfully If you verify the specified path, you can find the created PDF document, as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2455, "s": 2368, "text": "In this chapter, we will see how to draw a line on a PDF document using iText library." }, { "code": null, "e": 2635, "s": 2455, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor." }, { "code": null, "e": 2818, "s": 2635, "text": "To draw a line on a PdfDocument Instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and create a line using the moveTo() and lineTO() methods of this class." }, { "code": null, "e": 2878, "s": 2818, "text": "Following are the steps to draw a line on the pdf document." }, { "code": null, "e": 3107, "s": 2878, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3256, "s": 3107, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3374, "s": 3256, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/drawingLine.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3514, "s": 3374, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3766, "s": 3514, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3878, "s": 3766, "text": "Instantiate the PdfDocument class by passing above created PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 3953, "s": 3878, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer);\n" }, { "code": null, "e": 4124, "s": 3953, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4318, "s": 4124, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4442, "s": 4318, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below." }, { "code": null, "e": 4512, "s": 4442, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4595, "s": 4512, "text": "Create a new PdfPage class using the addNewPage() method of the PdfDocument class." }, { "code": null, "e": 4768, "s": 4595, "text": "Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the above created PdfPage object to the constructor of this class, as shown below." }, { "code": null, "e": 4920, "s": 4768, "text": "// Creating a new page \nPdfPage pdfPage = pdfDoc.addNewPage(); \n\n// Creating a PdfCanvas object \nPdfCanvas canvas = new PdfCanvas(pdfPage); \n" }, { "code": null, "e": 5017, "s": 4920, "text": "Set the initial point of the line using the moveTO() method of the Canvas class, as shown below." }, { "code": null, "e": 5074, "s": 5017, "text": "// Initial point of the line \ncanvas.moveTo(100, 300); \n" }, { "code": null, "e": 5167, "s": 5074, "text": "Now, draw a line from this point to another point using the lineTo() method, as shown below." }, { "code": null, "e": 5215, "s": 5167, "text": "// Drawing the line \ncanvas.lineTo(500, 300); \n" }, { "code": null, "e": 5298, "s": 5215, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 5343, "s": 5298, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 5565, "s": 5343, "text": "The following Java program demonstrates how to draw a line in a PDF document using the iText library. It creates a PDF document with the name drawingLine.pdf, draws an arc in it, and saves it in the path C:/itextExamples/" }, { "code": null, "e": 5618, "s": 5565, "text": "Save this code in a file with name DrawingLine.java." }, { "code": null, "e": 6983, "s": 5618, "text": "import com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfPage; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.canvas.PdfCanvas; \nimport com.itextpdf.layout.Document; \n\npublic class DrawingLine { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter \n String dest = \"C:/itextExamples/drawingLine.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(writer); \n \n // Creating a Document object \n Document doc = new Document(pdfDoc); \n \n // Creating a new page \n PdfPage pdfPage = pdfDoc.addNewPage(); \n \n // Creating a PdfCanvas object \n PdfCanvas canvas = new PdfCanvas(pdfPage); \n \n // Initial point of the line \n canvas.moveTo(100, 300); \n \n // Drawing the line \n canvas.lineTo(500, 300); \n \n // Closing the path stroke \n canvas.closePathStroke(); \n \n // Closing the document \n doc.close(); \n \n System.out.println(\"Object drawn on pdf successfully\"); \n } \n}" }, { "code": null, "e": 7078, "s": 6983, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 7120, "s": 7078, "text": "javac DrawingLine.java \njava DrawingLine\n" }, { "code": null, "e": 7212, "s": 7120, "text": "Upon execution, the above program creates a PDF document, displaying the following message." }, { "code": null, "e": 7247, "s": 7212, "text": "Object drawn on pdf successfully \n" }, { "code": null, "e": 7336, "s": 7247, "text": "If you verify the specified path, you can find the created PDF document, as shown below." }, { "code": null, "e": 7343, "s": 7336, "text": " Print" }, { "code": null, "e": 7354, "s": 7343, "text": " Add Notes" } ]