code-rag-bench/online-tutorials huggingface dataset:
Database Management Systems | Set 8 - GeeksforGeeks

27 Mar, 2017
Following questions have been asked in GATE 2005 CS exam.
1) Which one of the following statements about normal forms is FALSE?(a) BCNF is stricter than 3NF(b) Lossless, dependency-preserving decomposition into 3NF is always possible(c) Lossless, dependency-preserving decomposition into BCNF is always possible(d) Any relation with two attributes is in BCNF
Answer (c)It is not always possible to decompose a table in BCNF and preserve dependencies. For example, a set of functional dependencies {AB –> C, C –> B} cannot be decomposed in BCNF. See this for more details.
2) The following table has two attributes A and C where A is the primary key and C is the foreign key referencing A with on-delete cascade.
A   C
-----
2   4
3   4
4   3
5   2
7   2
9   5
6   4

The set of all tuples that must be additionally deleted to preserve referential integrity when the tuple (2,4) is deleted is:(a) (3,4) and (6,4)(b) (5,2) and (7,2)(c) (5,2), (7,2) and (9,5)(d) (3,4), (4,3) and (6,4)
Answer (C)When (2,4) is deleted. Since C is a foreign key referring A with delete on cascade, all entries with value 2 in C must be deleted. So (5, 2) and (7, 2) are deleted. As a result of this 5 and 7 are deleted from A which causes (9, 5) to be deleted.
3) The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list?
  select title
  from book as B
  where (select count(*)
     from book as T
     where T.price > B.price) < 5

(a) Titles of the four most expensive books(b) Title of the fifth most inexpensive book(c) Title of the fifth most expensive book(d) Titles of the five most expensive books
Answer (d)When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query.The outer query selects all titles from book table. For every selected book, the subquery returns count of those books which are more expensive than the selected book. The where clause of outer query will be true for 5 most expensive book. For example count (*) will be 0 for the most expensive book and count(*) will be 1 for second most expensive book.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2005
DBMS
GATE CS
MCQ
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Semaphores in Process Synchronization
Perl exec Function

This function executes a system command (directly, not within a shell) and never returns to the calling script, except if the command specified does not exist and has been called directly, instead of indirectly through a shell. The operation works as follows −
If there is only one scalar argument that contains no shell metacharacters, then the argument is converted into a list and the command is executed directly, without a shell.
If there is only one scalar argument that contains shell metacharacters, then the argument is executed through the standard shell, usually /bin/sh on Unix.
If LIST is more than one argument, or an array with more than one value, then the command is executed directly without the use of a shell.
Following is the simple syntax for this function −
exec EXPR LIST

exec LIST

This function returns 0 only if the command specified cannot be executed.

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Can I import same package twice? Will JVM load the package twice at runtime?

In Java classes and interfaces related to each other are grouped under a package. Package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in java.io package.
You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as −
package com.tutorialspoint.mypackage;
public class Sample{
   public void demo(){
      System.out.println("This is a method of the sample class");
   }
   public static void main(String args[]){
      System.out.println("Hello how are you......");
   }
}
Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package.
javac –d . Sample.java
If you haven’t mentioned the destination path the package will be created in the current directory.
To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword.
import com.tutorialspoint.mypackage.Sample;
public class Test{
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.demo();
   }
}
This is a method of the sample class
Yes, you can import a class twice in Java, it doesn’t create any issues but, irrespective of the number of times you import, JVM loads the class only once.
In the following Java program, we are trying to import the Sample class of the com.tutorialspoint.mypackage package only once.
import com.tutorialspoint.mypackage.Sample;
import com.tutorialspoint.mypackage.Sample;
public class Test{
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.demo();
   }
}
Sample class loaded
This is a method of the sample class
Directories in Python

All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.
os.mkdir("newdir")
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("test")
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.
os.chdir("newdir")

Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
The getcwd() method displays the current working directory.
os.getcwd()

Following is the example to give current directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
os.rmdir('dirname')

Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
C program to find out cosine and sine values using math.h library.

To find the cosine and sine values for every 10 degrees from 0 to 150.
The logic used to find the cosine values is as follows −
Declare MAX and PI value at the starting of a program
while(angle <= MAX){
   x = (PI/MAX)*angle;
   y = cos(x);
   printf("%15d %13.4f\n", angle, y);
   angle = angle + 10;
}
The logic used to find the sine values is as follows −
Declare MAX and PI value at the starting of a program.
while(angle <= MAX){
   x = (PI/MAX)*angle;
   y = sin(x);
   printf("%15d %13.4f\n", angle, y);
   angle = angle + 10;
}
Following is the C program to find the cosine values −
//cosine values
#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
main ( ) {
   int angle;
   float x,y;
   angle = 0;
   printf("Angle cos(angle)\n\n");
   while(angle <= MAX) {
      x = (PI/MAX)*angle;
      y = cos(x);
      printf("%15d %13.4f\n", angle, y);
      angle = angle + 10;
   }
}
When the above program is executed, it produces the following output −
Angle cos(angle)
0 1.0000
10 0.9781
20 0.9135
30 0.8090
40 0.6691
50 0.5000
60 0.3090
70 0.1045
80 -0.1045
90 -0.3090
100 -0.5000
110 -0.6691
120 -0.8090
130 -0.9135
140 -0.9781
150 -1.0000
Following is the C program to find the sine values −
//sine values
#include<stdio.h>
#include <math.h>
#define PI 3.1416
#define MAX 150
main ( ){
   int angle;
   float x,y;
   angle = 0;
   printf("Angle sin(angle)\n\n");
   while(angle <= MAX){
      x = (PI/MAX)*angle;
      y = sin(x);
      printf("%15d %13.4f\n", angle, y);
      angle = angle + 10;
   }
}
When the above program is executed, it produces the following output −
Angle sin(angle)

0 0.0000
10 0.2079
20 0.4067
30 0.5878
40 0.7431
50 0.8660
60 0.9511
70 0.9945
80 0.9945
90 0.9511
100 0.8660
110 0.7431
120 0.5878
130 0.4067
140 0.2079
150 -0.0000
How to get the list of all databases using JDBC?

You can get the list of databases in MySQL using the SHOW DATABASES query.
show databases;
Following JDBC program retrieves the list of databases by executing the show databases query.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ShowDatabasesExample {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("Show Databases");
      System.out.println("List of databases: ");
      while(rs.next()) {
         System.out.print(rs.getString(1));
         System.out.println();
      }
   }
}
Connection established......
List of databases:
information_schema
base
details
errors
logging
mydatabase
mydb
mysql
performance_schema
sample_database
sampledb
students
sys
testdb
world
Or, You can use the getCatalogs() method of the DatabaseMetaData interface.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class ListOfAllDatabases {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      //Retrieving the list of database names
      ResultSet tables = metaData.getCatalogs();
      while (tables.next()) {
         System.out.println(tables.getString("TABLE_CAT"));
      }
   }
}
Connection established......
List of databases:
information_schema
base
details
errors
logging
mydatabase
mydb
mysql
performance_schema
sample_database
sampledb
students
sys
testdb
world
Working with RxJS & ReactJS

In this chapter, we will see how to use RxJs with ReactJS. We will not get into the installation process for Reactjs here, to know about ReactJS Installation refer this link: /reactjs/reactjs_environment_setup.htm
We will directly work on an example below, where will use Ajax from RxJS to load data.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
class App extends Component {
   constructor() {
      super();
      this.state = { data: [] };
   }
   componentDidMount() {
      const response = ajax('https://jsonplaceholder.typicode.com/users').pipe(map(e => e.response));
      response.subscribe(res => {
         this.setState({ data: res });
      });
   }
   render() {
      return (
         <div>
            <h3>Using RxJS with ReactJS</h3>
            <ul>
               {this.state.data.map(el => (
                  <li>
                     {el.id}: {el.name}
                  </li>
               ))}
            </ul>
         </div>
      );
   }
}
ReactDOM.render(<App />, document.getElementById("root"));
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8" />
      <title>ReactJS Demo</title>
   <head>
   <body>
      <div id = "root"></div>
   </body>
</html>
We have used ajax from RxJS that will load data from this Url − https://jsonplaceholder.typicode.com/users.
When you compile, the display is as shown below −

    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
How to plot contourf and log color scale in Matplotlib?

To plot contourf and log scale in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable,N, for number of sample data.
Create x, y, X, Y, Z1, Z2 and z data points using numpy.
Create a figure and a set of subplots.
Plot contours using contourf() method.
Create a colorbar for a scalar mappable instance.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
from numpy import ma
from matplotlib import ticker, cm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 100
x = np.linspace(-3.0, 3.0, N)
y = np.linspace(-2.0, 2.0, N)

X, Y = np.meshgrid(x, y)

Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)

z = Z1 + 50 * Z2
z[:5, :5] = -1
z = ma.masked_where(z <= 0, z)
fig, ax = plt.subplots()

cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)
cbar = fig.colorbar(cs)

plt.show()
Implementing Vignere Cipher

In this chapter, let us understand how to implement Vignere cipher. Consider the text This is basic implementation of Vignere Cipher is to be encoded and the key used is PIZZA.
You can use the following code to implement a Vignere cipher in Python −
import pyperclip

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
   myMessage = "This is basic implementation of Vignere Cipher"
   myKey = 'PIZZA'
   myMode = 'encrypt'
   
   if myMode == 'encrypt':
      translated = encryptMessage(myKey, myMessage)
   elif myMode == 'decrypt':
      translated = decryptMessage(myKey, myMessage)
   
   print('%sed message:' % (myMode.title()))
   print(translated)
   print()
def encryptMessage(key, message):
   return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
   return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
   translated = [] # stores the encrypted/decrypted message string
   keyIndex = 0
   key = key.upper()
   
   for symbol in message:
      num = LETTERS.find(symbol.upper())
      if num != -1:
         if mode == 'encrypt':
            num += LETTERS.find(key[keyIndex])
				elif mode == 'decrypt':
               num -= LETTERS.find(key[keyIndex])
            num %= len(LETTERS)
            
            if symbol.isupper():
               translated.append(LETTERS[num])
            elif symbol.islower():
               translated.append(LETTERS[num].lower())
            keyIndex += 1
            
            if keyIndex == len(key):
               keyIndex = 0
         else:
            translated.append(symbol)
      return ''.join(translated)
if __name__ == '__main__':
   main()
You can observe the following output when you implement the code given above −
The possible combinations of hacking the Vignere cipher is next to impossible. Hence, it is considered as a secure encryption mode.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML dotted table borders
C | Operators | Question 18 - GeeksforGeeks

10 Sep, 2020
In C, two integers can be swapped using minimum(A) 0 extra variable(B) 1 extra variable(C) 2 extra variable(D) 4 extra variableAnswer: (A)Explanation: We can swap two variables without any extra variable using bitwise XOR operator ‘^’. Let X and Y be two variables to be swapped. Following steps swap X and Y.
  X = X ^ Y;
  Y = X ^ Y;
  X = X ^ Y;

See http://en.wikipedia.org/wiki/XOR_swap_algorithmQuiz of this Question
C-Operators
Operators
C Quiz
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C | Advanced Pointer | Question 1
C | File Handling | Question 2
C | Pointer Basics | Question 1
C | Operators | Question 1
C | Loops & Control Structure | Question 8
C | Advanced Pointer | Question 2
C Quiz - 101 | Question 2
C | Dynamic Memory Allocation | Question 7
C | Advanced Pointer | Question 4
C | Advanced Pointer | Question 9
HTML <button> value Attribute

The value attribute of the <button> element is used to set the initial value of a button. You can set this in a <form>. Here, we will be showing an example without using a form.
Following is the syntax −
<button value="value">
Above, value is the initial value.
Let us now see an example to implement value attribute in <button> −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Click below to get details about the learning content...</p></br></br>
<button id = "button1" value = "Learning" onclick = "demo1()">Get Tutorials</button>
<button id = "button2" value = "InterviewAnswers" onclick = "demo2()">Get InterviewQA</button>
<p id = "myid"></p>
<script>
   function demo1() {
      var val1 = document.getElementById("button1").value;
      document.getElementById("myid").innerHTML = val1;
   }
   function demo2() {
      var val1 = document.getElementById("button2").value;
      document.getElementById("myid").innerHTML = val1;
   }
</script>
</body>
</html>
This will produce the following output initially −
The output is as follows when “Get Tutorials” button is clicked −
The output is as follows when “Get InterviewQA” button is clicked −
In the above example, we have created JavaScript functions to get the value in a variable. One of them is demo1()
function demo1() {
   var val1 = document.getElementById("button1").value;
   document.getElementById("myid").innerHTML = val1;
}
The result of the above gets displayed on the click of a button. The onclick property is set to call the above function demo1() −
<button id = "button1" value = "Learning" onclick = "demo1()">
   Get Tutorials
</button>
How to create an unordered list with circle bullets in HTML?

To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles.
For creating an unordered list with circle bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to add circle bullets to an unordered list. 
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to create an unordered list with circle bullets in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Unordered List</title>
   </head>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries:</p>
      <ul style="list-style-type:circle">
         <li>US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ul>
   </body>
</html>
Transitive closure of a Graph

Transitive Closure it the reachability matrix to reach from vertex u to vertex v of a graph. One graph is given, we have to find a vertex v which is reachable from another vertex u, for all vertex pairs (u, v).
The final matrix is the Boolean type. When there is a value 1 for vertex u to vertex v, it means that there is at least one path from u to v.
Input:
1 1 0 1
0 1 1 0
0 0 1 1
0 0 0 1

Output:
The matrix of transitive closure
1 1 1 1
0 1 1 1
0 0 1 1
0 0 0 1
transColsure(graph)
Input: The given graph.Output: Transitive Closure matrix.
Begin
   copy the adjacency matrix into another matrix named transMat
   for any vertex k in the graph, do
      for each vertex i in the graph, do
         for each vertex j in the graph, do
            transMat[i, j] := transMat[i, j] OR (transMat[i, k]) AND transMat[k, j])
         done
      done
   done
   Display the transMat
End


<2>Example
#include<iostream>
#include<vector>
#define NODE 4
using namespace std;

/* int graph[NODE][NODE] = {
   {0, 1, 1, 0},
   {0, 0, 1, 0},
   {1, 0, 0, 1},
   {0, 0, 0, 0}
}; */

int graph[NODE][NODE] = {
   {1, 1, 0, 1},
   {0, 1, 1, 0},
   {0, 0, 1, 1},
   {0, 0, 0, 1}
};

int result[NODE][NODE];

void transClosure() {
   for(int i = 0; i<NODE; i++)
      for(int j = 0; j<NODE; j++)
         result[i][j] = graph[i][j];    //initially copy the graph to the result matrix
   for(int k = 0; k<NODE; k++)
      for(int i = 0; i<NODE; i++)
         for(int j = 0; j<NODE; j++)
            result[i][j] = result[i][j] || (result[i][k] && result[k][j]);
   for(int i = 0; i<NODE; i++) {          //print the result matrix
      for(int j = 0; j<NODE; j++)
         cout << result[i][j] << " ";
      cout << endl;
   }
}

int main() {
   transClosure();
}
1 1 1 1
0 1 1 1
0 0 1 1
0 0 0 1
{{ form.as_table }} – Render Django Forms as table

13 Feb, 2020
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as table in the template.
Illustration of {{ form.as_table }} using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code
from django import forms   # creating a form class InputForm(forms.Form):       first_name = forms.CharField(max_length = 200)    last_name = forms.CharField(max_length = 200)    roll_number = forms.IntegerField(                     help_text = "Enter 6 digit roll number"                     )    password = forms.CharField(widget = forms.PasswordInput())
Now we need a View to render this form into a template. Let’s create a view,
from django.shortcuts import renderfrom .forms import InputForm   # Create your views here.def home_view(request):    context ={}    context['form']= InputForm()    return render(request, "home.html", context)
Finally, we will create the template where we need the form to be placed. In templates > home.html,
<form action = "" method = "post">    {% csrf_token %}    <table>        {{ form.as_table }}    </table>    <input type="submit" value="Submit"></form>
Here {{ form.as_table }} will render them as table cells wrapped in <tr> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/
Let’s check the source code whether the form is rendered as a table or not. By rendering as a table it is meant that all input fields will be enclosed in <tr> tags.Here is the demonstration,
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check if string matches regex list

03 Oct, 2019
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let’s discuss a way in which this task can be performed.
Method : Using join regex + loop + re.match()This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.
# Python3 code to demonstrate working of# Check if string matches regex list# Using join regex + loop + re.match()import re  # initializing list test_list = ["gee*", "gf*", "df.*", "re"]  # printing list print("The original list : " + str(test_list))  # initializing test_str test_str = "geeksforgeeks"  # Check if string matches regex list# Using join regex + loop + re.match()temp = '(?:% s)' % '|'.join(test_list)res = Falseif re.match(temp, test_str):    res = True  # Printing resultprint("Does string match any of regex in list ? : " + str(res))
 
The original list : ['gee*', 'gf*', 'df.*', 're']
Does string match any of regex in list ? : True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – 3D Matrix to Coordinate List

02 Sep, 2020
Given a Matrix, row’s each element is list, pair each column to form coordinates.
Input : test_list = [[[9, 2], [10, 3]], [[13, 6], [19, 7]]]Output : [(9, 10), (2, 3), (13, 19), (6, 7)]Explanation : Column Mapped Pairs.
Input : test_list = [[[13, 6], [19, 7]]]Output : [(13, 19), (6, 7)]Explanation : Column Mapped Pairs.
Method #1 : Using loop + zip()
In this, we iterate for all the paired elements in inner tuples list, which is paired using zip(), and append the result list.
Python3
# Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip()  # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]  # printing original listprint("The original list is : " + str(test_list))  res = []for sub1, sub2 in test_list:          # zip() used to form pairing    for ele in zip(sub1, sub2):        res.append(ele)  # printing result print("Constructed Pairs : " + str(res))
The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]

Method #2 : Using list comprehension
In this, we perform task of of above method in shorthand using list comprehension.
Python3
# Python3 code to demonstrate working of # 3D Matrix to Coordinate List# Using loop + zip()  # initializing listtest_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]  # printing original listprint("The original list is : " + str(test_list))  # list comprehension to perform task in shorthandres = [ele for sub1, sub2 in test_list for ele in zip(sub1, sub2)]  # printing result print("Constructed Pairs : " + str(res))
The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove brackets from text file in Python ?

21 Feb, 2022
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. 
Syntax:
# import re module for using regular expression
import re
patn =  re.sub(pattern, repl, sentence)
# pattern is the special RE expression for finding the brackets.
# repl is a string which replaces with the selected things by pattern
# RE is searched in sentence string
The regex pattern used for performing our task:
Note: Here, we have used 2 syntactic characters of regex for doing this-
[...] is a character class that is used to match any one of the characters presents between them
\ is used for matching the special characters for this, we have brackets as a special character
Here is how it works:
Example 1: Program for removing the brackets with regular expressions from the string
Python3
# importing re module for creating# regex expressionimport re # string for passingtext = "Welcome to geeks for geeks [GFG] A (computer science portal)" # creating the regex pattern & use re.sub()# [\([{})\]] is a RE pattern for selecting# '{', '}', '[', ']', '(', ')' brackets.patn = re.sub(r"[\([{})\]]", "", text) print(patn)
Output:
Welcome to geeks for geeks GFG A computer science portal
Now seems like our script is working well. Let’s try the same in a text file. Python enables us to handle files. 
Note: For more information, refer File handling in Python.
Example 2: Program for removing brackets from the text file
File Used: 
Python3
# importing re module for creating# regex expressionimport re # reading line by linewith open('data.txt', 'r') as f:       # looping the para and iterating    # each line    text = f.read()         # getting the pattern for [],(),{}    # brackets and replace them to empty    # string    # creating the regex pattern & use re.sub()    patn = re.sub(r"[\([{})\]]", "", text) print(patn)
  
Output:
 
 
Example 2: Appending the changes to a new text file
 
File Used:
 
 
Python3
# importing re module for creating# regex expressionimport re # reading line by linewith open('input.txt', 'r') as f:       # store in text variable    text = f.read()         # getting the pattern for [],(),{}    # brackets and replace them to empty string    # creating the regex pattern & use re.sub()    pattern = re.sub(r"[\([{})\]]", "", text)  # Appending the changes in new file# It will create new file in the directory# and write the changes in the file.with open('output.txt', 'w') as my_file:    my_file.write(pattern)
Output:
rs1686740
as5853535
Picked
python-file-handling
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Enum, Constructor, Instance Variable & Method in Java?

16 Sep, 2021
Enumerations serve the purpose of representing a group of named constants in a programming language. Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java, enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).
Note: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block.
Now coming to our problem description as it is to illustrate how to use enum Constructor, Instance Variable & Method in Java. So, for this solution, we will see the below example initializes enum using a constructor & totalPrice() method & displays values of enums.
Example
Java
// Java program to Illustrate Usage of Enum// Constructor, Instance Variable & Method // Importing required classesimport java.io.*;import java.util.*; // Enumenum fruits {    // Attributes associated to enum    Apple(120),    Kiwi(60),    Banana(20),    Orange(80);     // internal data    private int price;     // Constructor    fruits(int pr) { price = pr; }     // Method    int totalPrice() { return price; }} // Main classclass GFG {     // main driver method    public static void main(String[] args)    {        // Print statement        System.out.println("Total price of fruits : ");         // Iterating using enhanced for each loop        for (fruits f : fruits.values())             // Print anddispaly the cost and perkg cost of            // fruits            System.out.println(f + " costs "                               + f.totalPrice()                               + " rupees per kg.");    }}
Total price of fruits : 
Apple costs 120 rupees per kg.
Kiwi costs 60 rupees per kg.
Banana costs 20 rupees per kg.
Orange costs 80 rupees per kg.
vsai5120
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bootstrap - Glyphicons

This chapter will discuss about Glyphicons, its use and some examples. Bootstrap bundles 200 glyphs in font format. Let us now understand what Glyphicons are.
Glyphicons are icon fonts which you can use in your web projects. Glyphicons Halflings are not free and require licensing, however their creator has made them available for Bootstrap projects free of cost.
Now that we have downloaded Bootstrap 3.x version and understand its directory structure from the chapter  Environment Setup, glyphicons can be found within the fonts folder. This contains the following files −
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
glyphicons-halflings-regular.woff
Associated CSS rules are present within bootstrap.css and bootstrap-min.css files within css folder of dist folder. You can see the available glyphicons at this link GLYPHICONS.
To use the icons, simply use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding.
<span class = "glyphicon glyphicon-search"></span>
The following example demonstrates this −
<p>
   <button type = "button" class = "btn btn-default">
      <span class = "glyphicon glyphicon-sort-by-attributes"></span>
   </button>
   
   <button type = "button" class = "btn btn-default">
      <span class = "glyphicon glyphicon-sort-by-attributes-alt"></span>
   </button>
   
   <button type = "button" class = "btn btn-default">
      <span class = "glyphicon glyphicon-sort-by-order"></span>
   </button>
   
   <button type = "button" class = "btn btn-default">
      <span class = "glyphicon glyphicon-sort-by-order-alt"></span>
   </button>
</p>

<button type = "button" class = "btn btn-default btn-lg">
   <span class = "glyphicon glyphicon-user"></span>
   
   User
</button>

<button type = "button" class = "btn btn-default btn-sm">
   <span class = "glyphicon glyphicon-user"></span> 
   
   User
</button>

<button type ="button" class = "btn btn-default btn-xs">
   <span class = "glyphicon glyphicon-user"></span> 
   
   User
</button>















    26 Lectures 
     2 hours 

 Anadi Sharma

    54 Lectures 
     4.5 hours 

 Frahaan Hussain

    161 Lectures 
     14.5 hours 

 Eduonix Learning Solutions

    20 Lectures 
     4 hours 

 Azaz Patel

    15 Lectures 
     1.5 hours 

 Muhammad Ismail

    62 Lectures 
     8 hours 

 Yossef Ayman Zedan
 Print
 Add Notes
 Bookmark this page
Difference between Normal def defined function and Lambda - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss the difference between normal def defined function and lambda in Python.
In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions must be declared in the namespace. The def functions can perform any python task including multiple conditions, nested conditions or loops of any level, printing, importing libraries, raising Exceptions, etc. 
Example:
Python3
# Define function to calculate cube root# using def keyword  def calculate_cube_root(x):    return x**(1/3)  # Call the def function to calculate cube# root and print itprint(calculate_cube_root(27))  # Define function to check if language is present in# language list using def keywordlanguages = ['Sanskrut', 'English', 'French', 'German']  def check_language(x):    if x in languages:        return True    return False  # Call the def function to check if keyword 'English'# is present in the languages list and print itprint(check_language('English'))
Output:
3.0
True
The lambda functions can be used without any declaration in the namespace. The lambda functions defined above are like single-line functions. These functions do not have parenthesis like the def defined functions but instead, take parameters after the lambda keyword as shown above. There is no return keyword defined explicitly because the lambda function does return an object by default.
Example:
Python3
# Define function using lambda for cube rootcube_root= lambda x: x**(1/3)  # Call the lambda functionprint(cube_root(27))    languages = ['Sanskrut', 'English', 'French', 'German']    # Define function using lambdal_check_language = lambda x: True if x in languages else False  # Call the lambda functionprint(l_check_language('Sanskrut'))
Output:
3.0
True
def defined functions
lambda functions
Easy to interpret
Interpretation might be tricky
Can consists of any number of execution statements inside the function definition
The limited operation can be performed using lambda functions
To return an object from the function, return should be explicitly defined
No need of using the return statement
Execution time is relatively slower for the same operation performed using lambda functions
Execution time of the program is fast for the same operation
Defined using the keyword def and holds a function name in the local namespace
Defined using the keyword lambda and does not compulsorily hold a function name in the local namespace
Picked
Python-Functions
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Python Program that Displays which Letters are in the First String but not in the Second

When it is required to display the letters that are present in the first string but not in the second string, two string inputs are taken from user. The ‘set’ is used to find the difference between the two strings.
Python comes with a datatype known as ‘set’. This ‘set’ contains elements that are unique only.
The set is useful in performing operations such as intersection, difference, union and symmetric difference.
Below is a demonstration for the same −
 Live Demo
my_str_1 = input("Enter the first string...")
my_str_2 = input("Enter the second string...")
my_result = list(set(my_str_1)-set(my_str_2))
print("The letters in first string but not in second string :")
for i in my_result:
   print(i)
Enter the first string...Jane
Enter the second string...Wane
The letters in first string but not in second string :
J
Two strings are taken as input from the user.
They are converted to a set, and their difference is computed.
This difference is converted to a list.
This value is assigned to a variable.
This is iterated over, and displayed on the console.
Comments in MATLAB - GeeksforGeeks

20 Aug, 2020
Comments are generic English sentences, mostly written in a program to explain what it does or what a piece of code is supposed to do. More specifically, information that programmer should be concerned with and it has nothing to do with the logic of the code. They are completely ignored by the compiler and are thus never reflected on to the input.
In MATLAB, comments are of two types:
Single-line Comments
Block Comments
Spanning MUltiple Lines
Single-line comments are comments that require only one line. They are usually drafted to explain what a single line of code does or what it is supposed to produce so that it can help someone to refer to the source code. Use % operator for adding single-line comments. This can be written in a separate line or appended to code on the same line.
Syntax :
% single line comment

Example :
MATLAB
disp("Below is the comment using %"); % this is a comment
Output :
Below is the comment using %

To make a block comment just put a ‘%{‘ in the starting of the block and ‘%}’ at the end of the block.
Syntax: 
%{
multiline
comment
%}

Example :
MATLAB
disp("Below is the block comment using %"); %{ this is a comment using % %}
Output :
Below is the block comment using %

Commenting part of a statement spanning multiple lines uses ellipsis (...). 
Example :
MATLAB
%{a = [1 2 3]b = 5%}  x = ['Matlab is a '...'programming langauge'......'invented by Cleve Moler'...', it is user friendly']
Output :
Matlab is a programming language, it is user friendly
To comment out the lines of code in a script, press Ctrl + R, to uncomment them press Ctrl + T. 
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
OpenCV - Overview
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
Mounting a Volume Inside Docker Container
Q-Learning in Python
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman
Graph Minimum Spanning Tree - GeeksforGeeks

19 Nov, 2018
v1
  \
    v2
      \
       v3
         \
          v4
            .
              .
                .
                 vn
 
there is one counter example when the graph has only one edge.  
         In that case, the two values are same. 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Get Hired With GeeksforGeeks and Win Exciting Rewards!
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
Selenium Webdriver - Handling Checkboxes

We can handle checkboxes with Selenium webdriver. A checkbox is represented by input tagname in the html code and its type attribute should have the value as checkbox.
The methods to handle the checkboxes are listed below −
Click − Used to check a checkbox.
Click − Used to check a checkbox.
is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked.
is_selected − Used to check if a checkbox is checked or not. It returns a boolean value, true is returned in case a checkbox is checked.
Let us see the html code of a checkbox, which is as follows −
The code implementation for handling checkboxes is as follows −
from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://the-internet.herokuapp.com/checkboxes")
#identify element
l = driver.find_element_by_xpath("//input[@type='checkbox']")
l.click()
if l.is_selected():
   print('Checkbox is checked')
else:
   print('Checkbox is not checked')
#close driver
driver.close()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the message - Checkbox is checked is printed since the is_selected method applied on the checkbox returned true value.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
How to check if a value exists in an R data frame or not?

There are many small objectives that helps us to achieve a greater objective in data analysis. One such small objective is checking if a value exists in the data set or not. In R, we have many objects for data set such as data frame, matrix, data.table object etc. If we want to check if a value exists in an R data frame then any function can be used.
Consider the below data frame:
Live Demo
> set.seed(3654)
> x1<-rpois(20,5)
> x2<-rpois(20,8)
> x3<-rpois(20,10)
> x4<-rpois(20,3)
> df1<-data.frame(x1,x2,x3,x4)
> df1
  x1 x2 x3 x4
1  4  5 16  2
2  5  4 15  2
3  6  6 13  3
4  2  6  7  4
5  5  4  9  4
6  6  8  9  5
7  5  6 12  3
8  4  5  8  7
9  2  9 12  1
10 6  7  6  1
11 3  4  9  3
12 2  5  5  3
13 3  7  7  4
14 4  7  8  2
15 6 12  9  1
16 8  4 15  1
17 5  8 10  4
18 3 12 11  2
19 3  8 12  3
20 8 13 11  1
Checking whether a particular value exists in df1 or not:
> any(df1==4)
[1] TRUE
> any(df1==5)
[1] TRUE
> any(df1==20)
[1] FALSE
> any(df1==8)
[1] TRUE
> any(df1==15)
[1] TRUE
> any(df1==12)
[1] TRUE
Let’s have a look at another example:
Live Demo
> S1<-sample(LETTERS[1:10],20,replace=TRUE)
> S2<-sample(LETTERS[21:26],20,replace=TRUE)
> df2<-data.frame(S1,S2)
> df2
  S1 S2
1  G W
2  C V
3  J W
4  E Y
5  H W
6  H V
7  H U
8  C W
9  A W
10 J W
11 J U
12 D V
13 C U
14 J W
15 G U
16 E X
17 D Y
18 B X
19 E U
20 I U
> any(df2=="A")
[1] TRUE
> any(df2=="B")
[1] TRUE
> any(df2=="C")
[1] TRUE
> any(df2=="c")
[1] FALSE
> any(df2=="e")
[1] FALSE
> any(df2=="F")
[1] FALSE
> any(df2=="J")
[1] TRUE
> any(df2=="M")
[1] FALSE
> any(df2=="N")
[1] FALSE