code-rag-bench/online-tutorials huggingface dataset:
Python MySQL – Create Database

04 Jul, 2021
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector interface.Syntax:  
CREATE DATABASE DATABASE_NAME
Example: 
Python
# importing required librariesimport mysql.connector dataBase = mysql.connector.connect(  host ="localhost",  user ="user",  passwd ="gfg") # preparing a cursor objectcursorObject = dataBase.cursor() # creating databasecursorObject.execute("CREATE DATABASE geeks4geeks")
Output: 
The above program illustrates the creation of MySQL database geeks4geeks in which host-name is localhost, the username is user and password is gfg.Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a program to create a table in the geeks4geeks database which was created in the above program. 
Python
# importing required libraryimport mysql.connector # connecting to the databasedataBase = mysql.connector.connect(                     host = "localhost",                     user = "user",                     passwd = "gfg",                     database = "geeks4geeks" )  # preparing a cursor objectcursorObject = dataBase.cursor() # creating table studentRecord = """CREATE TABLE STUDENT (                   NAME  VARCHAR(20) NOT NULL,                   BRANCH VARCHAR(50),                   ROLL INT NOT NULL,                   SECTION VARCHAR(5),                   AGE INT                   )""" # table createdcursorObject.execute(studentRecord)  # disconnecting from serverdataBase.close()
Output: 
 
abhaderiya46
gabaa406
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
PostgreSQL – BETWEEN operator

28 Aug, 2020
PostgreSQL BETWEEN operator is used to match a value against a range of values.
Syntax: value BETWEEN low AND high;

Or,

Syntax: value >= low and value;
The BETWEEN operator is used generally with WHERE clause with association with SELECT, INSERT, UPDATE or DELETE statement.For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for the payment whose amount is between 3 USD and 5 USD, using the BETWEEN operator in the “Payment” table of our sample database.
SELECT
    customer_id,
    payment_id,
    amount
FROM
    payment
WHERE
    amount BETWEEN 3
AND 5;
Output:
Example 2:Here we will query for getting the payment whose payment date is between 2007-02-07 and 2007-02-15 using the BETWEEN operator in the “Payment” table of our sample database.
SELECT
    customer_id,
    payment_id,
    amount,
 payment_date
FROM
    payment
WHERE
    payment_date BETWEEN '2007-02-07'
AND '2007-02-15';
Output:
Note: While making date queries the literal date in ISO 8601 format i.e., YYYY-MM-DD should be used in PostgreSQL.
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function
Matcher groupCount() method in Java with Examples

26 Nov, 2018
The groupCount() method of Matcher Class is used to get the number of capturing groups in this matcher’s pattern.
Syntax:
public int groupCount()

Parameters: This method do not takes any parameter.
Return Value: This method returns the number of capturing groups in this matcher’s pattern.
Below examples illustrate the Matcher.groupCount() method:
Example 1:
// Java code to illustrate groupCount() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "Geeks";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the number of capturing groups        // using groupCount() method        System.out.println(matcher.groupCount());    }}
0

Example 2:
// Java code to illustrate groupCount() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "GFG";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the number of capturing groups        // using groupCount() method        System.out.println(matcher.groupCount());    }}
0

Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.backward() method in Python

16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.backward() method is used to move the turtle backward by the value of the argument that it takes. It gives a line on moving to another position or direction with backward motion.
Syntax:
turtle.backward(distance)

The argument it takes is distance { a number (integer or float) }. So, it moves the turtle backward by the specified distance, in the opposite direction the turtle is headed. Below is the implementation of the above method with some examples :
Example 1:
Python3
# importing packagesimport turtle    # move turtle backward with # distance = 100turtle.backward(100)
Output :
Example 2:
Python3
# importing packageimport turtle    # move the turtle backward by 50turtle.backward(50)  # change the directionturtle.right(90)  # move the turtle backward by 50 againturtle.backward(50)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unused variable in for loop in Python

01 Oct, 2020
Prerequisite: Python For loops
The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop.  
Example:
Python3
# i,j - loop variable  # loop-1print("Using the loop variable inside :")  # used loop variablefor i in range(0, 5):      x = (i+1)*2    print(x, end=" ")  # loop-2print("\nUsing the loop variable only for iteration :")  # unsused loop variablefor j in range(0, 5):      print('*', end=" ")
Using the loop variable inside :
2 4 6 8 10 
Using the loop variable only for iteration :
* * * * * 
In the code snippet above, in loop-1, the loop control variable ‘i‘ is used inside the loop for computation. But in loop-2, the loop control variable ‘j‘ is concerned only with keeping tracking of the iteration number. Thus, ‘j’ is an unused variable in for loop. It is good practice to avoid declaring variables that are of no use.  Some IDEs like Pycharm, PyDev, VSCode produce warning messages for such unused variables in the looping structure. The warning may look like something given below:
To avoid such warnings, the convention of naming the unused variable with an underscore(‘_’) alone can be used. This avoids the problem of unused variables in for loops. Consider the following script with an unused loop variable tested with the Vulture module in Python. Once the vulture module is installed using the pip command, it can be used for testing .py scripts in the anaconda prompt. 
Example: trial1.py
Python3
# unused functiondef my_func():      # unused local variable    a = 5    b = 2    c = b+2    print(b, c)    # unused loop variable 'i'for i in range(0, 5):    print("*", end=" ")
* * * * * 
To avoid this unused variable ‘i’ warning, the loop variable can simply be replaced by an underscore (‘_’). Look at the code snippet below
Python3
# unused functiondef my_func():    b = 2    c = b+2    print(b, c)    # unused loop variable 'i'for _ in range(0, 5):    print("*", end=" ")
Some use pylint, a tool to keep track of code styles and dead code in Python. Such a tool can raise a warning when the variable in for loop is not used. To suppress that, it is better to use the underscore naming conventions for the unused variables.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
IntStream mapToObj() in Java

06 Dec, 2018
IntStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function.
Note : IntStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax :
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)

Parameters :
U : The element type of the new stream.Stream : A sequence of elements supporting sequential and parallel aggregate operations.IntFunction : Represents a function that accepts an int-valued argument and produces a result.mapper : A stateless function to apply to each element.
U : The element type of the new stream.
Stream : A sequence of elements supporting sequential and parallel aggregate operations.
IntFunction : Represents a function that accepts an int-valued argument and produces a result.
mapper : A stateless function to apply to each element.
Return Value : The function returns an object-valued Stream consisting of the results of applying the given function.
Example 1 :
// Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*;import java.util.stream.Stream;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(3, 8);          // Creating a Stream of Strings        // Using IntStream mapToObj(IntFunction mapper)        // to store binary representation of        // elements in IntStream        Stream<String> stream1 = stream.mapToObj(num                                                 -> Integer.toBinaryString(num));          // Displaying an object-valued Stream        // consisting of the results of        // applying the given function.        stream1.forEach(System.out::println);    }}
Output :
11
100
101
110
111

Example 2 :
// Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*;  import java.math.BigInteger;import java.util.stream.Stream;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(3, 5, 7, 9, 11);          // Creating a Stream        // Using IntStream mapToObj(IntFunction mapper)        Stream<BigInteger> stream1 = stream                                         .mapToObj(BigInteger::valueOf);          // Displaying an object-valued Stream        // consisting of the results of        // applying the given function.        stream1.forEach(num -> System.out.println(num.add(BigInteger.TEN)));    }}
Output :
13
15
17
19
21

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Pyspark – Converting JSON to DataFrame

29 Jun, 2021
In this article, we are going to convert JSON String to DataFrame in Pyspark.
Method 1: Using read_json()
We can read JSON files using pandas.read_json. This method is basically used to read JSON files through pandas.
Syntax: pandas.read_json(“file_name.json”)
Here we are going to use this JSON file for demonstration:
Code:
Python3
# import pandas to read json fileimport pandas as pd  # 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()    # creating a dataframe from the json file named studentdataframe = spark.createDataFrame(pd.read_json('student.json'))  # display the dataframe (Pyspark dataframe)dataframe.show()
Output:
Method 2: Using spark.read.json()
This is used to read a json data from a file and display the data in the form of a dataframe
Syntax: spark.read.json(‘file_name.json’)
JSON file for demonstration:
Code:
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()  # read json filedata = spark.read.json('college.json')  # display json datadata.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Matplotlib.colors.to_hex() in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.colors.to_hex() function is used to convert numbers between 0 to 1 into hex color code. It uses the #rrggbb format if keep_alpha is set to False(its also the default) else it uses #rrggbbaa.
Syntax: matplotlib.colors.to_hex(c, keep_alpha=False)
Parameters:
c: This represents an array of color sequence between 0 to 1.keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values.
c: This represents an array of color sequence between 0 to 1.
keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values.
Example 1:
import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np  # dummy data to build the griddata = np.random.rand(10, 10) * 20  # converting into hex color codehex_color=matplotlib.colors.to_hex([ 0.47,                                     0.0,                                     1.0 ])  # create discrete colormapcmap = colors.ListedColormap([hex_color,                               'green'])  bounds = [0,10,20]norm = colors.BoundaryNorm(bounds, cmap.N)  fig, ax = plt.subplots()ax.imshow(data, cmap=cmap, norm=norm)  # draw gridlinesax.grid(which='major', axis='both',         linestyle='-', color='k',        linewidth=2)  ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1));  plt.show()
Output:
Example 2:
import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np  # dummy data to build the griddata = np.random.rand(10, 10) * 20  # converting into hex color# code with alpha set to Truehex_color = matplotlib.colors.to_hex([ 0.47,                                      0.0,                                       1.0,                                       0.5 ],                                     keep_alpha = True)  # create discrete colormapcmap = colors.ListedColormap([hex_color,                               'red'])  bounds = [0, 10, 20]norm = colors.BoundaryNorm(bounds, cmap.N)  fig, ax = plt.subplots()ax.imshow(data, cmap = cmap, norm = norm)  # draw gridlinesax.grid(which ='major', axis ='both',         linestyle ='-', color ='k',         linewidth = 2)  ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1));  plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Similarities and Difference between Java and C++
list size() function in C++ STL

14 Jun, 2022
The list::size() is a built-in function in C++ STL which is used to find the number of elements present in a list container. That is, it is used to find the size of the list container. Syntax:
list_name.size();
Time Complexity – Linear O(N)
Parameters: This function does not accept any parameter. Return Value: This function returns the number of elements present in the list container list_name. Below program illustrate the list::size() function in C++ STL: 
CPP
// CPP program to illustrate the// list::size() function#include <bits/stdc++.h>using namespace std; int main(){    // Creating a list    list<int> demoList;     // Add elements to the List    demoList.push_back(10);    demoList.push_back(20);    demoList.push_back(30);    demoList.push_back(40);     // getting size of the list    int size = demoList.size();     cout << "The list contains " << size << " elements";     return 0;}
utkarshgupta110092
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Mongoose count() Function

10 Sep, 2020
The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query.
Syntax: 
Query.prototype.count()

Parameters: This function accepts one array parameter i.e. callback function. 
Return Value: This function returns Query Object. 
Installation of mongoose module: 
You can visit the link to Install mongoose module. You can install this package by using this command. 
npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command. 
npm version mongoose

After that, you can just create a folder and add a file for example, index.js as shown below.
Database: The sample database used here is shown below:  
Example 1: Filename: index.js  
javascript
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  var query = User.find();query.count(function (err, count) {    if (err) console.log(err)    else console.log("Count is", count)});
Steps to run the program: 
The project structure will look like this: 
Run index.js file using below command: 
node index.js

Output: 
Count is 4

Example 2: Filename: index.js  
javascript
const express = require('express');const mongoose = require('mongoose');const app = express()  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  var query = User.find();query.count(function (err, count) {    if (err) console.log(err)    else console.log("Count:", count)});  app.listen(3000, function(error ) {    if(error) console.log(error)    console.log("Server listening on PORT 3000")});
Steps to run the program: 
The project structure will look like this: 
Run index.js file using below command: 
node index.js

Output: 
Server listening on PORT 3000
Count: 4

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-count
Mongoose
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
GATE | GATE-CS-2002 | Question 35

28 Jun, 2021
Consider the following algorithm for searching for a given number x in an unsorted array A[1.....n] having n distinct values:
   1. Choose an i uniformaly at random from 1..... n;
   2. If A[i] = x then Stop else Goto 1; 
Assuming that x is present in A, what is the expected number of comparisons made by the algorithm before it terminates ?(A) n(B) n – 1(C) 2n(D) n/2Answer: (A)Explanation:
If you remember the coin and dice questions, you can just guess the answer for the above.
Below is proof for the answer.
Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases.
number_of_comparisons_for_a_case * probability_for_the_case 

Case 1
  If A[i] is found in the first attempt 
  number of comparisons = 1
  probability of the case  = 1/n

Case 2
  If A[i] is found in the second attempt 
  number of comparisons = 2
  probability of the case  = (n-1)/n*1/n

Case 3
  If A[i] is found in the third attempt 
  number of comparisons = 2
  probability of the case  = (n-1)/n*(n-1)/n*1/n

There are actually infinite such cases. So, we have following infinite series for E.
E  = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + ....  (1)

After multiplying equation (1) with (n-1)/n, we get
E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 + 
                                 [(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ..........(2)

Subtracting (2) from (1), we get
E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + ............

The expression on right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r))
  E/n = [1/n]/[1-(n-1)/n]  = 1
  E = n

Quiz of this Question
GATE-CS-2002
GATE-GATE-CS-2002
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE IT 2006 | Question 20
GATE | GATE-CS-2016 (Set 1) | Question 45
SQL Query to Add a New Column After an Existing Column in SQL

29 Sep, 2021
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.
Step 1: Create a database
Let’s create a database employee.
Query:
CREATE DATABASE employee;
Step 2: Create a table
Now create a table employee_info.
Query:
CREATE TABLE employee_info
( Employee_id INT,
First_Name VARCHAR(25),
Last_Name VARCHAR(25),
Salary INT,
City VARCHAR(20)); 

INSERT INTO employee_info
VALUES (1,'Monika','Singh',800000,'Nashik'),
(2,'Rahul','Kumar',450000,'Mumbai'),
(3,'Sushant','Kumar',500000,'Pune'),
(4,'Ajay','Mehta',600000,'Mumbai');
Step 3: To view a database schema we use the following query.
Query:
EXEC sp_help 'dbo.employee_info';
Output:
Now, let’s add a new column Gender in the table. Then we use ALTER table command. 
Step 4: Alter table.
ALTER TABLE employee_info ADD Gender CHAR(1) CHECK (Gender IN ('M','F'));
Output:
Now, the new column gets added after City i.e. at the last successfully.
Take another case using a query, If we want the Gender column after Last_Name, then we can write the query as shown below.
Query:
SELECT Employee_Id,First_Name,Last_Name,Gender,Salary,City FROM employee_info;
Output:
Blogathon-2021
Picked
SQL-Query
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Data Mining - Cluster Analysis
Explain the purpose of render() in ReactJS
How to build a basic CRUD app with Node.js and ReactJS ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
How to convert string to binary in Python?

To convert a string to binary, you need to iterate over each character and convert it to binary. Then join these characters together in a single string. You can use format(ord(x), 'b') to format the character x as binary. For example:
>>>st = "hello world"
>>>' '.join(format(ord(x), 'b') for x in st)
'11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
 You can alsomap all characters to bin(number) using bytearray to get the array of allcharacters in binary. For example:
>>>st = "hello world"
>>>map(bin,bytearray(st))
['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']
C++ Pointer to Pointer (Multiple Indirection)

A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a  pointer to a pointer of type int −
int **var;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −
#include <iostream>
 
using namespace std;
 
int main () {
   int  var;
   int  *ptr;
   int  **pptr;

   var = 3000;

   // take the address of var
   ptr = &var;

   // take the address of ptr using address of operator &
   pptr = &ptr;

   // take the value using pptr
   cout << "Value of var :" << var << endl;
   cout << "Value available at *ptr :" << *ptr << endl;
   cout << "Value available at **pptr :" << **pptr << endl;

   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
numpy.random.triangular() in Python - GeeksforGeeks

18 Aug, 2020
With the help of numpy.random.triangular() method, we can get the random samples from triangular distribution from interval [left, right] and return the random samples by using this method.
Syntax : numpy.random.triangular(left, mode, right, size=None)
Parameters :
1) left – lower limit of the triangle.
2) mode – peak value of the distribution.
3) right – upper limit of the triangle.
4) size – total number of samples required.
Return : Return the random samples as numpy array.
Example #1 :
In this example we can see that by using numpy.random.triangular() method, we are able to get the random samples of triangular distribution and return the numpy array.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  # Using triangular() methodgfg = np.random.triangular(-5, 0, 5, 5000)  plt.hist(gfg, bins = 50, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt  # Using triangular() methodgfg = np.random.triangular(-10, 8, 10, 15000)  plt.hist(gfg, bins = 100, density = True)plt.show()
Output :
Python numpy-Random
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()
Java Program to Get System IP Address in Windows and Linux Machine - GeeksforGeeks

19 Aug, 2021
IP Address: An Internet Protocol address is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. 
Packages used:
io (input-output): This package provides for system input and output through data streams, serialization, and the file system.net (network): This package provides the classes for implementing networking applications.util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
io (input-output): This package provides for system input and output through data streams, serialization, and the file system.
net (network): This package provides the classes for implementing networking applications.
util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
Methods Used:
1. getInetAddresses()
Syntax:
public Enumeration getInetAddresses()
Return Type: It returns an Enumeration of InetAddress.
2. getInterfaceAddresses()
Syntax:
public List getInterfaceAddresses()
Return Type: It returns a list of java.net.InterfaceAddress instances.
Below is the implementation of the problem statement:
Java
// Java Program to Get System IP Address// in Windows and Linux Machineimport static java.lang.System.out; import java.io.*;import java.net.*;import java.util.*; public class gfg {    public static void main(String args[]) // main method        throws SocketException    {        // fetching network interface        Enumeration<NetworkInterface> nets            = NetworkInterface.getNetworkInterfaces();         for (NetworkInterface netint :             Collections.list(nets))            displayInterfaceInformation(netint);    }     // Display Internet Information method    static void    displayInterfaceInformation(NetworkInterface netint)        throws SocketException    {        out.printf("Display name: %s\n",                   netint.getDisplayName());        out.printf("Name: %s\n", netint.getName());        Enumeration<InetAddress> inetAddresses            = netint.getInetAddresses();        // Output System IP        for (InetAddress inetAddress :             Collections.list(inetAddresses)) {            out.printf("System IP: %s\n", inetAddress);        }        out.printf("\n");    }}
Display name: eth0
Name: eth0

Display name: lo
Name: lo
System IP: /127.0.0.1
Output in Windows: 
Output in Linux: 
 
rajeev0719singh
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.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Simplest way to detect keypresses in JavaScript?

The easiest way to detect keypresses in JavaScript, use the onKeyPress event handler −
document.onkeypress
The key press is matched with the keyCode property, which returns the Unicode character code
of the key that triggered the onkeypress event.
 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>
</head>
<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>
<body>
<script>
   document.onkeypress = function (eventKeyName) {
      eventKeyName = eventKeyName || window.event;
      if(eventKeyName.keyCode==13){
         console.log('You have pressed enter key');
      } else {
         alert(String.fromCharCode(eventKeyName.keyCode))
   }
};
</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 −
Case 1 − On pressing ENTER key, you will get the following output on console.
Case 2 − When you press any other key except ENTER, example letter g, then the same would be visible on console −
Vertically stack pills with Bootstrap

Use the .nav-stacked class in Bootstrap to vertically stack pills:
You can try to run the following code to implement the .nav-stacked class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Database</h2>
         <p>The following are the database technologies:</p>
         <ul class = "nav nav-pills nav-stacked" role = "tablist">
            <li class = "active"><a href = "#">DB2</a></li>
            <li><a href = "#">MySQL</a></li>
            <li><a href = "#">SQL</a></li>
            <li><a href = "#">CouchDB</a></li>
         </ul>
      </div>
   </body>
</html>
Difference between 1NF and 3NF in DBMS - GeeksforGeeks

19 Oct, 2020
1. First Normal Form (1NF) :An entity that does not have any repeating columns or data groups can be termed as the First Norm. 1NF is the First normal form, which provides the minimum set of requirements for normalizing a relational database. A table that complies with 1NF assures that it actually represents a relation (i.e. it does not contain any records that are repeating), but there is no universally accepted definition for 1NF. One important property is that a table that comply with 1NF could not contain any attributes that are relational valued i.e. all the attributes should have atomic values.
Some rules to be followed are :
There should be a unique name to be specified for each attribute within the table.
It should not contain any composite attributes.
Example :
As this relation does not contain any composite or multi-valued attributes then this relation is in 1NF.
2. Third Normal Form (3NF) :It mean a table is considered in third normal if the table/entity is already in the second normal form and the columns of the table/entity are non-transitively dependent on the primary key.
If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant Most of the 3NF tables are free of insertion, update, and deletion anomalies. 3NF is used to reduce data duplication and to attain data integrity.
Example : Consider relation R (E, F, G, H, I)
E -> FG, 
GH -> I, 
F -> H, 
I -> E 

All possible candidate keys in above relation are {E, I, GH, FG} All attribute are on right sides of all functional dependencies are prime.
Difference between 1NF and 3NF :
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
Layers of OSI Model
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Differences between TCP and UDP
C Program for Iterative Quick Sort - GeeksforGeeks

04 Dec, 2018
// An iterative implementation of quick sort#include <stdio.h>  // A utility function to swap two elementsvoid swap(int* a, int* b){    int t = *a;    *a = *b;    *b = t;}  /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){    int x = arr[h];    int i = (l - 1);      for (int j = l; j <= h - 1; j++) {        if (arr[j] <= x) {            i++;            swap(&arr[i], &arr[j]);        }    }    swap(&arr[i + 1], &arr[h]);    return (i + 1);}  /* A[] --> Array to be sorted,    l  --> Starting index,    h  --> Ending index */void quickSortIterative(int arr[], int l, int h){    // Create an auxiliary stack    int stack[h - l + 1];      // initialize top of stack    int top = -1;      // push initial values of l and h to stack    stack[++top] = l;    stack[++top] = h;      // Keep popping from stack while is not empty    while (top >= 0) {        // Pop h and l        h = stack[top--];        l = stack[top--];          // Set pivot element at its correct position        // in sorted array        int p = partition(arr, l, h);          // If there are elements on left side of pivot,        // then push left side to stack        if (p - 1 > l) {            stack[++top] = l;            stack[++top] = p - 1;        }          // If there are elements on right side of pivot,        // then push right side to stack        if (p + 1 < h) {            stack[++top] = p + 1;            stack[++top] = h;        }    }}  // A utility function to print contents of arrvoid printArr(int arr[], int n){    int i;    for (i = 0; i < n; ++i)        printf("%d ", arr[i]);}  // Driver program to test above functionsint main(){    int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 };    int n = sizeof(arr) / sizeof(*arr);    quickSortIterative(arr, 0, n - 1);    printArr(arr, n);    return 0;}
1 2 2 3 3 3 4 5

The above mentioned optimizations for recursive quick sort can also be applied to iterative version.
1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version.
2) To reduce the stack size, first push the indexes of smaller half.
3) Use insertion sort when the size reduces below a experimentally calculated threshold.
Please refer complete article on Iterative Quick Sort for more details!
C Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
Perl glob Function

This function returns a list of files matching EXPR as they would be expanded by the standard Bourne shell. If the EXPR does not specify a path, uses the current directory. If EXPR is omitted, the value of $_ is used.
From Perl 5.6 on, expansion is done internally, rather than using an external script. Expansion follows the csh (and any derivatives, including tcsh and bash) style of expansion, which translates as the following −
Files beginning with a single period are ignored unless EXPR explicitly matches.
Files beginning with a single period are ignored unless EXPR explicitly matches.
The * character matches zero or more characters of any type.
The * character matches zero or more characters of any type.
The ? character matches one character of any type.
The ? character matches one character of any type.
The [..] construct matches the characters listed, including ranges, as per regular expressions.
The [..] construct matches the characters listed, including ranges, as per regular expressions.
The ~ characters matches the home directory; ~name matches the home directory for the user name.
The ~ characters matches the home directory; ~name matches the home directory for the user name.
The {..} construct matches against any of the comma-separated words enclosed in the braces.
The {..} construct matches against any of the comma-separated words enclosed in the braces.
Following is the simple syntax for this function −
glob EXPR

glob

This function returns undef on error otherwise First file in the list of expanded names in scalar context and Empty list on error otherwise List of expanded file names in list context.
Following is the example code showing its basic usage −
#!/usr/bin/perl

(@file_list) = glob "perl_g*";

print "Returned list of file @file_list\n";
When above code is executed, it produces the following result −
Returned list of file


    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
Perl hex Function

This function interprets EXPR as a hexadecimal string and returns the value, or converts $_ if EXPR is omitted.
Following is the simple syntax for this function −
hex EXPR

hex

This function returns numeric value equivalent to hexa in scalar context.
Following is the example code showing its basic usage −
#!/usr/bin/perl

print hex '0xAf'; # prints '175'
print "\n";
print hex 'aF';   # same
When above code is executed, it produces the following result −
175
175


    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
Python Program to Find All Connected Components using DFS in an Undirected Graph

When it is required to find all the connected components using depth first search in an undirected graph, a class is defined that contains methods to initialize values, perform depth first search traversal, find the connected components, add nodes to the graph and so on. The instance of the class can be created and the methods can be accessed and operations and be performed on it.
Below is a demonstration of the same −
 Live Demo
class Graph_struct:
   def __init__(self, V):
      self.V = V
      self.adj = [[] for i in range(V)]

   def DFS_Utililty(self, temp, v, visited):

      visited[v] = True

      temp.append(v)

      for i in self.adj[v]:
         if visited[i] == False:
            temp = self.DFS_Utililty(temp, i, visited)
      return temp

   def add_edge(self, v, w):
      self.adj[v].append(w)
      self.adj[w].append(v)

   def connected_components(self):
      visited = []
      conn_compnent = []
      for i in range(self.V):
         visited.append(False)
      for v in range(self.V):
         if visited[v] == False:
            temp = []
            conn_compnent.append(self.DFS_Utililty(temp, v, visited))
      return conn_compnent

my_instance = Graph_struct(5)
my_instance.add_edge(1, 0)
my_instance.add_edge(2, 3)
my_instance.add_edge(3, 0)
print("1-->0")
print("2-->3")
print("3-->0")
conn_comp = my_instance.connected_components()
print("The connected components are :")
print(conn_comp)
1-->0
2-->3
3-->0
The connected components are :
[[0, 1, 3, 2], [4]]
A class named ‘Graph_struct’ is defined.
A class named ‘Graph_struct’ is defined.
A method named ‘add_edge’ is defined that helps add elements to the tree.
A method named ‘add_edge’ is defined that helps add elements to the tree.
The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach.
The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach.
A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other.
A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other.
An instance of the class is created, and the methods are called on it.
An instance of the class is created, and the methods are called on it.
The node are displayed on the console.
The node are displayed on the console.
The connected components are displayed as output on the console.
The connected components are displayed as output on the console.
How to count SQL table columns using Python?

It may be required to count the number of columns present in a SQL table.
This is done using count(*) function with information_schema.columns and the WHERE clause. The WHERE clause is used to specify the name of the table whose columns are to be counted.
SELECT COUNT(*) FROM information_schema.columns WHERE table_name= ‘your_table_name’
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Suppose we have a table named “Students” as below −
+----------+---------+-----------+------------+
|    Name  | Class   | City      | Marks      |
+----------+---------+-----------+------------+
|    Karan |    4    |  Amritsar |    95      |
|    Sahil |    6    |  Amritsar |    93      |
|    Kriti |    3    |    Batala |    88      |
|   Khushi |    9    |     Delhi |    90      |
|    Kirat |    5    |     Delhi |    85      |
+----------+---------+-----------+------------+
We want to count the number of columns in the above table.
import mysql.connector

db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT COUNT(*) FROM information_schema.columns WHERE table_name= "Students" "
cursor.execute(query)

col=cursor.fetchall()

for x in col:
   print(x)

db.close()
The above returns the number of columns present in the table named “Students”.
4