code-rag-bench/online-tutorials huggingface dataset:
Python MySQL - Cursor Object

The MySQLCursor of mysql-connector-python (and similar libraries) is used to execute statements to communicate with the MySQL database.
Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures.
You can create Cursor object using the cursor() method of the Connection object/class.
import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
Following are the various methods provided by the Cursor class/object.
callproc()
This method is used to call existing procedures MySQL database.
close()
This method is used to close the current cursor object.
Info()
This method gives information about the last query.
executemany()
This method accepts a list series of parameters list. Prepares an MySQL query and executes it with all the parameters.
execute()
This method accepts a MySQL query as a parameter and executes the given query.
fetchall()
This method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)
fetchone()
This method fetches the next row in the result of a query and returns it as a tuple.
fetchmany()
This method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row.
etchwarnings()
This method returns the warnings generated by the last executed query.
Following are the properties of the Cursor class −
column_names
This is a read only property which returns the list containing the column names of a result-set.
description
This is a read only property which returns the list containing the description of columns in a result-set.
lastrowid
This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation.
rowcount
This returns the number of rows returned/updated in case of SELECT and UPDATE operations.
statement
This property returns the last executed statement.
How to Upgrade R Installation to R 4.0 on Windows? - GeeksforGeeks

12 Jan, 2021
R is a programming language and free software environment for statistical computing and graphics supported by the R Foundation for Statistical Computing. The R language is heavily utilized by analysts and data engineers/miners for creating statistical software and data/info analysis. This article will serve as a step-by-step guide to update your existing version of the R Language on Windows.
Step 1: Check your existing installation version by heading over to RStudio and typing the version in the console. This should give you the information about your major and minor R installed versions. Something like this:
As we can see here the initial installed version was R 3.6.3
Step 2: Head over to RGui, (remember do not go to RStudio, search for RGui in your Windows Start Menu). Install and load a package called installr, using these commands:
R
# Install the *installr* packageinstall.packages("installr")  # Load the packagelibrary("installr")
Step 3: Simply run the command installr::updateR() and wait for the Information Dialogue Box to show up.
R
# The below command will check your # installed version against the latest # version available and will show you # an information dialogue boxinstallr::updateR()
Prompt received after writing updateR()
Step 4: Navigate through all the installation procedures as shown below:
Step 4.1: If you like to keep yourself spam-free, then press No.
Step 4.2: Click on Yes, if you want to update your R installation version
Step 4.3: Unless you have a new and clean installation, definitely click on Yes
Step 4.4: If you weren’t working on production-grade projects at the time, then press No.
Step 4.5: This is related to RShiny. Click on Yes.
Step 4.6: Although the packages should have backward compatibility, still click on Yes.
Step 5: After all the installation is done, close your RGui and head back to RStudio and again run the command version to check whether your R installation has been updated or not. 
Type version in the RStudio console and as is visible here, we have upgraded to R 4.0.3
Congratulations!! You have successfully upgraded your R installation to the newest R version available. Now go on ahead and write some awesome R scripts.
R-basics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Removing duplicates from tuple in Python

When it is required to remove duplicates from a tuple, the list comprehension is used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration of the same −
Live Demo
my_list_1 = [(11, 14), (0, 78), (33, 11), (0, 78)]

print("The list of tuple is : ")
print(my_list_1)

my_unique_list = list(set([i for i in my_list_1]))

print("The list of tuples after removing duplicates is :")
print(my_unique_list)
The list of tuple is :
[(11, 14), (0, 78), (33, 11), (0, 78)]
The list of tuples after removing duplicates is :
[(33, 11), (11, 14), (0, 78)]
A list of tuple is defined and is displayed on the console.
The list is iterated through, and is converted to set.
This way, only unique elements are stored.
This is again converted to a list.
This is assigned to a value.
It is displayed on the console.
How to calculate and plot a Cumulative Distribution function with Matplotlib in Python ?

24 Jan, 2021
Prerequisites: Matplotlib 
Matplotlib is a library in Python and it is a numerical — mathematical extension for the NumPy library.  The cumulative distribution function (CDF) of a real-valued random variable X, or just distribution function of X, evaluated at x, is the probability that X will take a value less than or equal to x.
Properties of CDF:
Every cumulative distribution function F(X) is non-decreasing
If maximum value of the cdf function is at x, F(x) = 1.
The CDF ranges from 0 to 1.
CDF can be calculated using PDF (Probability Distribution Function). Each point of random variable will contribute cumulatively to form CDF.
Example : 
A combination set containing 2 balls which can be either red or blue can be in the following set.
{RR, RB, BR, BB}
t -> No of red balls.
P(x = t) -> t = 0 : 1 / 4 [BB] 
            t = 1 : 2 / 4 [RB, BR]
            t = 2 : 1 / 4 [RR]
            
CDF :
F(x) = P(x<=t)
x = 0 : P(0)               -> 1 / 4
x = 1 : P(1) + P(0)        -> 3 / 4
x = 2 : P(2) + P(1) + P(0) -> 1
Approach
Import modules
Declare number of data points
Initialize random values
Plot histogram using above data
Get histogram data
Finding PDF using histogram data
Calculate CDF
Plot CDF
Example:
Python3
# defining the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd%matplotlib inline  # No of Data pointsN = 500  # initializing random valuesdata = np.random.randn(N)  # getting data of the histogramcount, bins_count = np.histogram(data, bins=10)  # finding the PDF of the histogram using count valuespdf = count / sum(count)  # using numpy np.cumsum to calculate the CDF# We can also find using the PDF values by looping and addingcdf = np.cumsum(pdf)  # plotting PDF and CDFplt.plot(bins_count[1:], pdf, color="red", label="PDF")plt.plot(bins_count[1:], cdf, label="CDF")plt.legend()
Output:
Histogram plot of the PDF and CDF :
Plotted CDF:
CDF plotting
This method depicts how CDF can be calculated and plotted using sorted data. For this, we first sort the data and then handle further calculations.
Approach
Import module
Declare number of data points
Create data
Sort data in ascending order
Get CDF
Plot CDF
Display plot
Example:
Python3
# defining the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd%matplotlib inline  # No of data points usedN = 500  # normal distributiondata = np.random.randn(N)  # sort the data in ascending orderx = np.sort(data)  # get the cdf values of yy = np.arange(N) / float(N)  # plottingplt.xlabel('x-axis')plt.ylabel('y-axis')  plt.title('CDF using sorting the data')  plt.plot(x, y, marker='o')
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
map count() function in C++ STL

12 Jul, 2018
The map::count() is a built-in function in C++ STL which returns 1 if the element with key K is present in the map container. It returns 0 if the element with key K is not present in the container.
Syntax:
map_name.count(key k)
Parameters: The function accepts a mandatory parameter k which specifies the key to be searched in the map container.
Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.
Below program illustrates the above function:
// C++ program to illustrate// the map::count() function#include <bits/stdc++.h>using namespace std;  int main(){      // initialize container    map<int, int> mp;      // insert elements in random order    mp.insert({ 2, 30 });    mp.insert({ 1, 40 });    mp.insert({ 3, 60 });    mp.insert({ 4, 20 });    mp.insert({ 5, 50 });      // checks if key 1 is present or not    if (mp.count(1))        cout << "The key 1 is present\n";    else        cout << "The key 1 is not present\n";      // checks if key 100 is present or not    if (mp.count(100))        cout << "The key 100 is present\n";    else        cout << "The key 100 is not present\n";      return 0;}
The key 1 is present
The key 100 is not present

CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Inheritance in C++
vector erase() and clear() in C++
C++ Classes and Objects
The C++ Standard Template Library (STL)
Substring in C++
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Perl | join() Function

25 Jun, 2019
join() function in Perl combines the elements of LIST into a single string using the value of VAR to separate each element. It is effectively the opposite of split.
Note that VAR is only placed between pairs of elements in the LIST; it will not be placed either before the first element or after the last element of the string. Supply an empty string rather than undef, to join together strings without a separator.
Syntax: join(VAR, LIST)
Parameters:
VAR : Separator to be placed between list elements.
LIST : LIST to be converted into String.
Return: Returns the joined string
Example 1:
#!/usr/bin/perl  # Joining string with a separator$string = join( "-", "Geeks", "for", "Geeks" );print"Joined String is $string\n";  # Joining string without a separator$string = join( "", "Geeks", "for", "Geeks" );print"Joined String is $string\n";
Output:
Joined String is Geeks-for-Geeks
Joined String is GeeksforGeeks

Example 2:
#!/usr/bin/perl  # Joining string with '~' separator$string = join( "~", "Geeks", "for", "Geeks" );print"Joined String is $string\n";  # Joining string with '***' separator$string = join( "***", "Geeks", "for", "Geeks" );print"Joined String is $string\n";
Output :
Joined String is Geeks~for~Geeks
Joined String is Geeks***for***Geeks
Perl-function
Perl-List-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Perl | Subroutines or Functions
Perl | length() Function
Perl | Boolean Values
Introduction to Perl
Perl | substitution Operator
Perl | ne operator
Python | Pandas dataframe.get()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.get() function is used to get item from object for given key. The key could be one or more than one dataframe column. It returns default value if not found.
Syntax: DataFrame.get(key, default=None)
Parameters :key : object
Returns : value : type of items contained in object
For link to CSV file Used in Code, click here
Example #1: Use get() function to extract a column out of the dataframe
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
Output :
Now apply the get() function. We are going to extract the “Salary” column from the dataframe.
# applying get() function df.get("Salary")
Output :
Notice, the output is not a dataframe but a pandas series object. Example #2: Use get() function to extract multiple columns at a time in random order
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  df.get(["Salary", "Team", "Name"])
Output :A dataframe is returned as output. The ordering of the columns is not according to the actual dataframe but it follows the ordering that we provided to it in the function input.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C program to delete an array element using Pointers

Write a C program to delete an element from an array at runtime by the user and the result to be displayed on the screen after deletion. If the deleted element is not in an array, then we need to display Invalid Input.
An array is used to hold the group of common elements under one name.
The array operations are as follows −
Insert
Delete
Search
Refer an algorithm to delete the elements into an array with the help of pointers.
Step 1 − Declare and read the number of elements.
Step 2 − Declare and read the array size at runtime.
Step 3 − Input the array elements.
Step 4 − Declare a pointer variable.
Step 5 − Allocate the memory dynamically at runtime.
Step 6 − Enter an element that to be deleted.
Step 7 − After deletion, the elements are shifted to left by one position.
Size of array is: 5
The array elements are as follows −
1 2 3 4 5
Enter the position the element that to be deleted: 4
The output is as follows −
After deletion the array elements are:
1 2 3 5
Following is the C program to insert the elements into an array with the help of pointers −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void delete(int n,int *a,int pos);
int main(){
   int *a,n,i,pos;
   printf("enter the size of array:");
   scanf("%d",&n);
   a=(int*)malloc(sizeof(int)*n);
   printf("enter the elements:\n");
   for(i=0;i<n;i++){
      scanf("%d",(a+i));
   }
   printf("enter the position of element to be deleted:");
   scanf("%d",&pos);
   delete(n,a,pos);
   return 0;
}
void delete(int n,int *a,int pos){
   int i,j;
   if(pos<=n){
      for(i=pos-1;i<n;i++){
         j=i+1;
         *(a+i)=*(a+j);
      }
      printf("after deletion the array elements is:\n");
      for(i=0;i<n-1;i++){
         printf("%d\n",(*(a+i)));
      }
   }
   else{
      printf("Invalid Input");
   }
}
When the above program is executed, it produces the following output −
enter the size of array:5
enter the elements:
12
34
56
67
78
enter the position of element to be deleted:4
After deletion the array elements are:
12
34
56
78
numpy.save() - GeeksforGeeks

29 Nov, 2018
numpy.save()function is used to store the input array in a disk file with npy extension(.npy).
Syntax : numpy.save(file, arr, allow_pickle=True, fix_imports=True)
Parameters:file : : File or filename to which the data is saved. If file is a string or Path, a .npy extension will be appended to the file name if it does not already have one.If file is a file-object, then the filename is unchanged.allow_pickle : : Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations). Default: Truefix_imports : Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way.arr : Array data to be saved.
Return : Stores the input array in a disk file with npy extension(.npy).
Code #1: Working
# Python program explaining # save() function   import numpy as geek  a = geek.arange(5)  # a is printed.print("a is:")print(a)  # the array is saved in the file geekfile.npy geek.save('geekfile', a)  print("the array is saved in the file geekfile.npy")  
Output :
a is:
[0 1 2 3 4]
the array is saved in the file geekfile.npy

 Code #2
# Python program explaining # save() function   import numpy as geek  # the array is loaded into bb = geek.load('geekfile.npy')  print("b is:")print(b)  # b is printed from geekfile.npyprint("b is printed from geekfile.npy")
Output :
b is:
[0 1 2 3 4]
b is printed from geekfile.npy

Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to get min, seconds and milliseconds from datetime.now() in Python?

You can get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it.
        
In this case, you can use these directives in the strftime function as follows −
from datetime import datetime
curr_time = datetime.now()
formatted_time = curr_time.strftime('%M:%S.%f')
print(formatted_time)
This will give the output −
31:15.093393
How to count the number of items in a C# list?

Use the Array.Count property in C# to count the number of items in a list in C# −
Set the list
List<string> myList = new List<string>() {
   "electronics",
   "clothing",
   "appliances",
   "accessories"
};
Now count the number of items in a list in C# −
myList.Count
The following is the complete code to count the number of items in a list −
using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      List myList = new List() {
         "electronics",
         "clothing",
         "appliances",
         "accessories"
      };
      Console.WriteLine(myList.Count);
   }
}
Command Line arguments in Java programming


A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
The following program displays all of the command-line arguments that it is called with -
public class CommandLine {
   public static void main(String args[]) {
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " + args[i]);
      }
   }
}
Try executing this program as shown here -
$java CommandLine this is a command line 200 -100
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Count total number of Links In Webpage Using Selenium In Python - GeeksforGeeks

04 Jan, 2021
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
Installation
1.1 Selenium Bindings in PythonSelenium Python bindings provide a convenient API to access Selenium Web Driver like Firefox,Chrome,etc.
Pip install Selenium 

1.2 Web DriversSelenium requires a web driver to interface with the chosen browser. Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice.
Chrome:    https://sites.google.com/a/chromium.org/chromedriver/downloads
Firefox: https://github.com/mozilla/geckodriver/releases
Safari:    https://webkit.org/blog/6900/webdriver-support-in-safari-10/
Step-by-step Approach:
Import required modules
Python3
# import modules from selenium import webdriver from selenium.webdriver.common.by import By import time
Taking any URL.
Python3
# assign web page url driver.get("https://www.geeksforgeeks.org/")
using By.TAG_NAME find web link in webpage.
Implementation:
Python3
#import modulefrom selenium import webdriverfrom selenium.webdriver.common.by import By    driver = webdriver.Chrome()  # urldriver.get('https://www.geeksforgeeks.org/')  # find web linkslink = driver.find_elements(By.TAG_NAME, 'a')  # using len function count how many linksprint(len(link))
Output:
Python Selenium-Exercises
Python-selenium
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
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
K and -K in Python

Suppose we have a list of numbers called nums, we have to find the largest number k where k
and -k both exist in nums (they can be the same number). If there's no such element, return -1.
So, if the input is like [-5, 2, 9, -6, 5, -9], then the output will be 9.
To solve this, we will follow these steps −
L1:= a list of 0 and positive elements in nums
L2:= a list of 0 and negative elements in nums
sort L1 in reverse order
sort the list L2
for each i in L1, dofor each j in L2, doif i+j is same as 0, thenreturn iotherwise when i+j > 0 , thencome out from the current loop
for each j in L2, doif i+j is same as 0, thenreturn iotherwise when i+j > 0 , thencome out from the current loop
if i+j is same as 0, thenreturn i
return i
otherwise when i+j > 0 , thencome out from the current loop
come out from the current loop
return -1
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      L1=[i for i in nums if i>=0]
      L2=[i for i in nums if i<=0]
      L1.sort(reverse=True)
      L2.sort()
      for i in L1:
         for j in L2:
            if i+j==0:
               return i
            elif i+j>0:
               break
      return -1
ob = Solution()
nums = [-5, 2, 9, -6, 5, -9]
print(ob.solve(nums))
[-5, 2, 9, -6, 5, -9]
9
Check whether a Table exists in SQL Server database or not - GeeksforGeeks

20 Oct, 2020
Before creating a TABLE, it is always advisable to check whether the table exists in SQL Server database or not.
Alternative 1 :Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not.
Query :
USE [DB_NAME]
GO
IF OBJECT_ID('table_name', 'U') IS NOT NULL
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Alternative 2 :Using the INFORMATION_SCHEMA.TABLES and SQL EXISTS Operator to check whether a table exists or not.
Query :
USE [DB_NAME]
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'table_name')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Alternative 3 :Using the sys.Objects to check whether a table exists in SQL Server or not.
Query :
USE [DB_NAME]
GO
IF EXISTS(SELECT 1 FROM sys.Objects
WHERE Object_id = OBJECT_ID(N'table_name')
AND Type = N'U')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Output :
Table does not exists.
Alternative 4 :Using the sys.Tables to check whether a table exists or not.
Query :
USE [DB_NAME]
GO
IF EXISTS(SELECT 1 FROM sys.Tables
WHERE Name = N'table_name')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Example :Let us assume we have database name “SQL_DBA” and we need to create a new table “geek_demo” –
Input-1 :
USE [SQL_DBA]
GO
IF OBJECT_ID('geek_demo', 'U') IS NOT NULL
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Output-1 :
Table does not exists.
Let us create the table.
Create table geek_demo (id int, name varchar(200));
Now, let us check whether the table is created or not –
Input-2 :
USE [DB_NAME]
GO
IF EXISTS(SELECT 1 FROM sys.Objects
WHERE Object_id = OBJECT_ID(N'table_name')
AND Type = N'U')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

Output-2 :
Table exists.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
How to Select Data Between Two Dates and Times in SQL Server?
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Delete Duplicate Rows
C++ Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph

Topological sorting of DAG (Directed Acyclic Graph) is a linear ordering of vertices such that for every directed edge uv, where vertex u comes before v in the ordering. If the graph is not a DAG, Topological Sorting for a graph is not possible.
Begin
   function topologicalSort():
   a) Mark the current node as visited.
   b) Recur for all the vertices adjacent to this vertex.
   c) Push current vertex to stack which stores result.
End
Begin
   function topoSort() which uses recursive topological sort() function:
   a) Mark all the vertices which are not visited.
   b) Call the function topologicalSort().
   c) Print the content.
End
#include<iostream>
#include <list>
#include <stack>
using namespace std;
class G {
   int n;
   list<int> *adj;
   //declaration of functions
   void topologicalSort(int v, bool visited[], stack<int> &Stack);
   public:
   G(int n); //constructor
   void addEd(int v, int w);
   void topoSort();
};
G::G(int n) {
   this->n = n;
   adj = new list<int> [n];
}
void G::addEd(int v, int w) // add the edges to the graph. {
   adj[v].push_back(w); //add w to v’s list
}
void G::topologicalSort(int v, bool visited[], stack<int> &Stack) {
   visited[v] = true; //mark current node as visited
   list<int>::iterator i;
   //Recur for all the vertices adjacent to this vertex.
   for (i = adj[v].begin(); i != adj[v].end(); ++i)
      if (!visited[*i])
         topologicalSort(*i, visited, Stack);
         Stack.push(v);
}
void G::topoSort() {
   stack<int> Stack;
   bool *visited = new bool[n];
   //Mark all the vertices which are not visited.
   for (int i = 0; i < n; i++)
      visited[i] = false;
      for (int i = 0; i < n; i++)
         if (visited[i] == false)
            //Call the function topologicalSort().
            topologicalSort(i, visited, Stack);
         while (Stack.empty() == false) {
            cout << Stack.top() << " "; //print the element
            Stack.pop();
         }
}
int main() {
   G g(6);
   g.addEd(4, 2);
   g.addEd(5, 1);
   g.addEd(4, 0);
   g.addEd(3, 1);
   g.addEd(1, 3);
   g.addEd(3, 2);
   cout << " Topological Sort of the given graph \n";
   g.topoSort();
   return 0;
}
Topological Sort of the given graph
5 4 1 3 2 0
How to create a filter table with JavaScript?

To create a filter table with JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   * {
      box-sizing: border-box;
   }
   .searchField {
      width: 100%;
      font-size: 16px;
      padding: 12px 20px 12px 40px;
      border: 1px solid #ddd;
      margin-bottom: 12px;
   }
   .birthDayTable {
      border-collapse: collapse;
      width: 100%;
      font-size: 18px;
   }
   .birthDayTable th, .birthDayTable td {
      text-align: left;
      padding: 12px;
   }
   .birthDayTable tr {
      border-bottom: 4px solid #ddd;
   }
   .birthDayTable tr.header, .birthDayTable tr:hover {
      background-color: #f1f1f1;
   }
</style>
</head>
<body>
<h1>Filter table example</h1>
<input type="text" class="searchField" placeholder="Friend Name:" />
<table class="birthDayTable">
<tr class="header">
<th style="width:60%;">Friends</th>
<th style="width:40%;">Birthday Month</th>
</tr>
<tr>
<td>Shawn</td>
<td>January</td>
</tr>
<tr>
<td>Ron</td>
<td>March</td>
</tr>
<tr>
<td>Jack</td>
<td>December</td>
</tr>
<tr>
<td>Simon</td>
<td>February</td>
</tr>
<tr>
<td>Ricky</td>
<td>November</td>
</tr>
</table>
<script>
   document .querySelector(".searchField") .addEventListener("keyup", searchFunction);
   function searchFunction() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.querySelector(".searchField");
      filter = input.value.toUpperCase();
      table = document.querySelector(".birthDayTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
         td = tr[i].getElementsByTagName("td")[0];
         if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
               tr[i].style.display = "";
            } else {
               tr[i].style.display = "none";
            }
         }
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On entering something in the search field −
How to insert element as a last child using jQuery?

To insert element as a last child using jQuery, use the append() method. The append( content ) method appends content to the inside of every matched element.
You can try to run the following code to learn how to insert element as a last child using jQuery:
Live Demo
<html>

   <head>
      <title>jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         var x = 0;
         $(document).ready(function() {
            $('.add').on('click', function (event) {
        var html = "<div class='child-div'>demo text " + x++ + "</div>";
        $("#parent-div").append(html);
    });
         });
      </script>    
      <style>
         .div{
            margin:10px;
            padding:12px;
            border:2px solid #F38B00;
            width:60px;
         }
      </style>
   </head>    
   <body>
      <div id="parent-div">
        <div>Hello World</div>
      </div>
      <input type="button" value="Click to add" class="add" />
   </body>
</html>
How to print a value for a given key for Python dictionary?

Python dictionary is collection of key value pairs. Value associated with a certain key is returned by get() method.
>>> D1={'a':11,'b':22,'c':33}
>>> D1.get('b')
22
You can also obtain value by using key inside square brackets.
>>> D1['c']
33
glob() function in PHP

The glob() function returns an array of filenames or directories matching a specified pattern. The glob() function returns.
An array containing the matched files/directories,
Returns an empty array if no file is matched,
FALSE on error.
glob(pattern,flags)
pattern − The pattern to search for.
pattern − The pattern to search for.
flags − The following are the flags:GLOB_MARK - Adds a slash to each item returnedGLOB_NOSORT - Return files as they appear in the directory (unsorted)GLOB_NOCHECK - Returns the search pattern if no match were foundGLOB_NOESCAPE - Backslashes do not quote metacharactersGLOB_BRACE - Expands {p,q,r} to match 'p', 'q', or 'r'GLOB_ONLYDIR - Return only directories which match the patternGLOB_ERR - Stop on errors. The errors are ignored by default.
flags − The following are the flags:
GLOB_MARK - Adds a slash to each item returned
GLOB_NOSORT - Return files as they appear in the directory (unsorted)
GLOB_NOCHECK - Returns the search pattern if no match were found
GLOB_NOESCAPE - Backslashes do not quote metacharacters
GLOB_BRACE - Expands {p,q,r} to match 'p', 'q', or 'r'
GLOB_ONLYDIR - Return only directories which match the pattern
GLOB_ERR - Stop on errors. The errors are ignored by default.
The glob() function returns an array containing the matched files/directories. Returns an empty array if no file is matched and FALSE on error.
<?php
   print_r(glob("*.htm"));
?>
Array
(
   [0] => one.htm
   [1] => two.htm
   [2] => three.htm
)
Let us see another example.
<?php
   foreach (glob("*.*") as $myfiles) {
      echo "$myfiles filesize = " . filesize($myfiles) . "\n";
   }
?>
one.htm filesize = 56790
two.htm filesize = 432987
new.docx filesize = 184256
students.csv filesize = 4626
php.int filesize = 1287
settings.ini filesize = 3516
How do you find continuous sub array whose sum is equal to a given number in Java?

To find continuous sub array whose sum is equal to a given number −
Iterate through the array.
At each element add the next n elements one by one, when the sum equals to the required value print the sub array.
import java.util.Arrays;
import java.util.Scanner;
public class sub_arrays {
   public static void main(String args[]){
      //Reading the array from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      //Reading the number
      System.out.println("Enter the required sum: ");
      int reqSum = sc.nextInt();
      System.out.println("The array created is: "+Arrays.toString(myArray));
      System.out.println("sub arrays whose sum is: "+reqSum);
      for(int i=0; i<myArray.length; i++){
         int sum = 0;
         for (int j=i; j<myArray.length; j++){
            sum = sum + myArray[j];
            if(sum == reqSum){
               System.out.println(Arrays.toString(Arrays.copyOfRange(myArray, i, j+1)));
            }
         }
      }
   }
}
Enter the size of the array that is to be created:
10
Enter the elements of the array:
5
4
1
2
3
4
1
4
5
5
Enter the required sum:
10
The array created is: [5, 4, 1, 2, 3, 4, 1, 4, 5, 5]
sub arrays whose sum is: 10
[5, 4, 1]
[4, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 1]
[1, 4, 5]
[5, 5]
LISP - Returning Values Functions

By default, a function in LISP returns the value of the last expression evaluated as the return value. The following example would demonstrate this.
Create a new source code file named main.lisp and type the following code in it.
(defun add-all(a b c d)
   (+ a b c d)
)
(setq sum (add-all 10 20 30 40))
(write sum)
(terpri)
(write (add-all 23.4 56.7 34.9 10.0))
When you execute the code, it returns the following result −
100
125.0

However, you can use the return-from special operator to immediately return any value from the function.
Create a new source code file named main.lisp and type the following code in it −
(defun myfunc (num)
   (return-from myfunc 10)
   num
)
(write (myfunc 20))
When you execute the code, it returns the following result −
10

Change the code a little −
(defun myfunc (num)
   (return-from myfunc 10)
   write num
)
(write (myfunc 20))
It still returns −
10


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Difference between JavaScript and VBScript

07 Aug, 2020
JavaScript is a lightweight and object-oriented scripting language used to create dynamic HTML pages with interactive effects within a webpage. It is an interpreted scripting language and its code is run in a web browser only. It is also called a browser’s language and can be used for client-side developments as well as server-side developments. It was developed by Brendan Eich at Netscape and was first released in 1995. JavaScript Example: 
Javascript
<script type="text/javascript">     document.write("Hello geeks, greeting from GeeksforGeeks") </script> 
VBScript is an active scripting language introduced by Microsoft. It is developed based on Visual Basic and is also called a Visual Basic scripting language. It does not support all browsers, supports only Internet Explorer. It is generally used in Microsoft environments and uses a component object model to access system objects and variables of the environment. VBScript Example:
Javascript
<script type="text/vbscript">     document.write("Hello geeks, greeting from GeeksforGeeks") </script> 
Difference between JavaScript and VBScript: 
JavaScript-Misc
Difference Between
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python | Numpy matrix.view()

29 May, 2019
With the help of Numpy matrix.view() method, we can find the new view of a the matrix by using the matrix.view() method.
Syntax : matrix.view()Return : Return new view for same matrix
Example #1 :In this example we can see that by using matrix.view() method we are able to find the new view of the given matrix.
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]')              # applying matrix.view() methodgeek = gfg.view()    print(geek)
[[ 4  1]
 [12  3]]

Example #2 :
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')              # applying matrix.view() methodgeek = gfg.view()    print(geek)
[[ 4  1  9]
 [12  3  1]
 [ 4  5  6]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.random.rand() in Python

28 Mar, 2022
The numpy.random.rand() function creates an array of specified shape and fills it with random values. Syntax : 
numpy.random.rand(d0, d1, ..., dn)
Parameters : 
d0, d1, ..., dn : [int, optional]Dimension of the returned array we require, 
     If no argument is given a single Python float is returned.
Return : 
Array of defined shape, filled with random values.
Code 1 : Randomly constructing 1D array 
Python
# Python Program illustrating# numpy.random.rand() method  import numpy as geek  # 1D Arrayarray = geek.random.rand(5)print("1D Array filled with random values : \n", array);
Output : 
1D Array filled with random values : 
 [ 0.84503968  0.61570994  0.7619945   0.34994803  0.40113761]
Code 2 : Randomly constructing 2D array 
Python
# Python Program illustrating# numpy.random.rand() method  import numpy as geek  # 2D Array  array = geek.random.rand(3, 4)print("\n\n2D Array filled with random values : \n", array);
Output : 
2D Array filled with random values : 
 [[ 0.94739375  0.5557614   0.69812121  0.86902435]
 [ 0.94758176  0.22254413  0.21605843  0.44673235]
 [ 0.61683839  0.40570269  0.34369248  0.46799524]]
Code 3 : Randomly constructing 3D array 
Python
# Python Program illustrating# numpy.random.rand() method  import numpy as geek  # 3D Array    array = geek.random.rand(2, 2 ,2)print("\n\n3D Array filled with random values : \n", array);
Output : 
3D Array filled with random values : 
 [[[ 0.97942627  0.01068711]
  [ 0.35749073  0.22484643]]

 [[ 0.99733022  0.8029555 ]
  [ 0.44111692  0.90537128]]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.rand.html#numpy.random.rand 
Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. 
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
Python numpy-Random sampling
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calendar setTimeZone() Method in Java with Examples - GeeksforGeeks

06 Mar, 2019
The setTimeZone(TimeZone time_zone) method in Calendar class takes a Time Zone value as a parameter and modifies or set the timezone represented by this Calendar.
Syntax:
public void setTimeZone(TimeZone time_zone)
Parameters: The method takes one parameter time_zone of Date type and refers to the given date that is to be set.
Return Value: The method does not return any value.
Below programs illustrate the working of setTimeZone() Method of Calendar class:Example 1:
// Java code to illustrate// setTime() method  import java.util.*;  public class Calendar_Demo {    public static void main(String[] args)    {          // Creating calendar object        Calendar calndr = Calendar.getInstance();          // Displaying the current time zone        String tz_name = calndr.getTimeZone()                             .getDisplayName();          System.out.println("The Current Time"                           + " Zone: " + tz_name);          TimeZone time_zone            = TimeZone.getTimeZone("GMT");          // Modifying the time zone        calndr.setTimeZone(time_zone);          // Displaying the modified zone        System.out.println("Modified Zone: "                           + calndr.getTimeZone()                                 .getDisplayName());    }}
The Current Time Zone: Coordinated Universal Time
Modified Zone: Greenwich Mean Time

Example 2:
// Java code to illustrate// setTimeZone() method  import java.util.*;  public class Calendar_Demo {    public static void main(String[] args)    {          // Creating calendar object        Calendar calndr = Calendar.getInstance();          // Displaying the current time zone        String tz_name = calndr.getTimeZone()                             .getDisplayName();          System.out.println("The Current Time"                           + " Zone: " + tz_name);          TimeZone time_zone            = TimeZone.getTimeZone("Pacific/Tahiti");          // Modifying the time zone        calndr.setTimeZone(time_zone);          // Displaying the modified zone        System.out.println("Modified Zone: "                           + calndr.getTimeZone()                                 .getDisplayName());    }}
The Current Time Zone: Coordinated Universal Time
Modified Zone: Tahiti Time

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeZone(java.util.TimeZone)
Java - util package
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Overriding in Java
LinkedList in Java
\phantom - Tex Command

\phantom - Used to create space. 
{ \phantom #1}
\phantom command draws space. The box created by  \phantom   has width, height and depth equal to its argument. In other words, \phantom   creates horizontal and vertical space equal to that of its argument, even though the argument isn't visible.

\Gamma^{\phantom{i}j}_{i\phantom{j}k}

Γijkij


\matrix{1&-1\cr 2&\phantom{-}3}

1−12−3



\Gamma^{\phantom{i}j}_{i\phantom{j}k}

Γijkij


\Gamma^{\phantom{i}j}_{i\phantom{j}k}
\matrix{1&-1\cr 2&\phantom{-}3}

1−12−3


\matrix{1&-1\cr 2&\phantom{-}3}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
MongoDB aggregation to fetch documents with specific field value?

For this, use aggregate(). Let’s say we have to fetch documents with a field “Age” with value “21”.
Let us now create a collection with documents −
> db.demo685.insertOne(
...    {
...       "details":
...       [
...          {
...             Name:"Chris",
...             Age:21
...          },
...          {
...             Name:"David",
...             Age:23
...          },
...          {
...             Name:"Bob",
...             Age:21
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea54f6fa7e81adc6a0b395b")
}
Display all documents from a collection with the help of find() method −
> db.demo685.find();
This will produce the following output −
{ "_id" : ObjectId("5ea54f6fa7e81adc6a0b395b"), "details" : [
   { "Name" : "Chris", "Age" : 21 },
   { "Name" : "David", "Age" : 23 },
   { "Name" : "Bob", "Age" : 21 } 
] }
Following is the query for MongoDB aggregation −
> db.demo685.aggregate([ { $unwind: "$details" }, { $match: { "details.Age": 21 } }, { $project: {_id: 0}} ]).pretty();
This will produce the following output −
{ "details" : { "Name" : "Chris", "Age" : 21 } }
{ "details" : { "Name" : "Bob", "Age" : 21 } }
Java Program to compare two Byte Arrays

To compare two Byte Arrays, use the Arrays.equals() method. Here we have declared and initialized a total of 4 arrays.
byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 };
byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33};
byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 };
byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 };
Now, using the Arrays.equals() method, we will be compare two arrays.
Arrays.equals(arr1, arr2);
In the same way, other arrays would be compared one by one.
Let us see the complete example to compare two Byte Arrays.
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      byte[] arr1 = new byte[] { 11, 13, 30, 45, 77, 89 };
      byte[] arr2 = new byte[] { 12, 13, 34, 87, 99, 33};
      byte[] arr3 = new byte[] { 11, 13, 30, 45, 77, 89 };
      byte[] arr4 = new byte[] { 13, 16, 56, 78, 98, 99 };
      System.out.println("Array1 is equal to Array2 = "+Arrays.equals(arr1, arr2));
      System.out.println("Array1 is equal to Array3 = "+Arrays.equals(arr1, arr3));
      System.out.println("Array1 is equal to Array4 = "+Arrays.equals(arr1, arr4));
      System.out.println("Array2 is equal to Array3 = "+Arrays.equals(arr2, arr3));
   }
}
Array1 is equal to Array2 = false
Array1 is equal to Array3 = true
Array1 is equal to Array4 = false
Array2 is equal to Array3 = false