code-rag-bench/online-tutorials huggingface dataset:
Perl stat Function

This function returns a 13-element array giving the status info for a file, specified by either FILEHANDLE, EXPR, or $_. The list of values returned is shown below in Table. If used in a scalar context, returns 0 on failure, 1 on success.
Note that support for some of these elements is system dependent. Check the documentation for a complete list.
Element Description
0 	Device number of file system
1 	Inode number
2 	File mode (type and permissions)
3 	Number of (hard) links to the file
4 	Numeric user ID of file.s owner
5 	Numeric group ID of file.s owner
6 	The device identifier (special files only)
7 	File size, in bytes
8 	Last access time since the epoch
9 	Last modify time since the epoch
10 	Inode change time (not creation time!) since the epoch
11 	Preferred block size for file system I/O
12	Actual number of blocks allocated

Following is the simple syntax for this function −
stat FILEHANDLE

stat EXPR

stat

This function returns ARRAY, ($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

($device, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime,
   $ctime, $blksize, $blocks) = stat("/etc/passwd");

print("stat() $device, $inode, $ctime\n");
When above code is executed, it produces the following result −
stat() 2065, 5374250, 1508051555


    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
Tk - Geometry Manager

The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose.
The syntax for positioning and sizing window is shown below −
wm geometry . wxh+/-x+/-y

Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y position on screen
A simple example is shown below for the above Statement −.
#!/usr/bin/wish

wm geometry . 300x200+100+100
When we run the above program, we will get the following output −
The syntax for grid geometry is shown below −
grid gridName -column number -row number -columnspan number -rowspan number

The column, row, columnspan, or rowspan helps in providing the grid geometry.
A simple example is shown below for the above statement −
#!/usr/bin/wish

frame .myFrame1 -background red  -height 100 -width 100
frame .myFrame2 -background blue -height 100 -width 50
grid .myFrame1 -columnspan 10 -rowspan 10 -sticky w
grid .myFrame2 -column 10 -row 2
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
Find sum of fields inside array in MongoDB?

To find sum of fields inside array, use $sum. Let us create a collection with documents −
> db.demo96.insertOne(
... {
...
...    "Name" : "Chris",
...    "Details" : [
...       {
...          Marks:67
...       },
...       {
...          Marks:33
...       },
...       {
...          Marks:50
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d6aadb8903cdd865577ad")
}
Display all documents from a collection with the help of find() method −
> db.demo96.find();
This will produce the following output −
{
   "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "Details" : [
      { "Marks" : 67 }, { "Marks" : 33 }, { "Marks" : 50 }
   ] 
}
Following is the query to find sum of fields inside array in MongoDB −
> db.demo96.aggregate([
... { "$project": {
...    "Name": 1,
...    "TotalMarks": {
...       "$sum": "$Details.Marks"
...       }
...    }}
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "TotalMarks" : 150 }
Groovy - concat()

Concatenates the specified String to the end of this String.
String concat(String str)

str - the String that is concatenated to the end of this String.
This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      String s = "Hello ";
      s = s.concat("World");
      System.out.println(s);
   } 
}
When we run the above program, we will get the following result −
Python | os.fsdecode() method

25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.fsdecode() method in Python is used to decode the specified filename from the filesystem encoding with ‘surrogateescape‘ error handler, or ‘strict‘ on Windows;
Syntax: os.fsdecode(filename)
Parameter:filename: A path-like object representing an encoded file. A path-like object is either a str or bytes object representing a path.
Return Type: This method returns a string which represents the decoded filename.
Code: use of os.fsdecode() method
# Python program to explain os.fsdecode() method     # importing os module import os  # Filename encoded to the filesystem encoding# with 'surrogateescape' error handler# or 'strict' error handlerfilename = b"/home / user / F\xc3\x8e\xe2\x95\x9a\xc3\x88.txt"  # Decode the above filename# form the filesystem encoding   # with 'surrogateescape' error handler,# or 'strict' (On Windows)decode = os.fsdecode(filename)  # Print the decoded filenameprint("Decoded filename:", decode)  # To encode a filename to the filesystem # encoding with 'surrogateescape' error handler# or 'strict' error handler os.encode() method# can be used
Encoded filename: b'/home/user/F\xc3\x8e\xe2\x95\x9a\xc3\x88.txt'
Decoded filename: /home/user/FÎ?È.txt

Reference: https://docs.python.org/3/library/os.html#os.fsdecode
python-os-module
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
PostgreSQL – Describe Table

08 Feb, 2021
In PostgreSQL, there is no DESCRIBE statement as in MySQL. But users can query the information on columns of a table in a couple of ways. In this article we will look into them.
The information on various columns of a table can be achieved any of the below commands:
Syntax: \d or \d+

Example:
In this example, we will describe the table city of the sample database, ie, dvdrental:
First log into the PostgreSQL server using the pSQL shell:
Now shift to the dvdrental database using the below command:
\c dvdrental

Now use the below command to describe the city table:
\d city;

This will result in the below:
The below command can also be used for the same purpose:
\d+ city

Output:
The information_schema.columns catalog contains the information on columns of all tables. To get information on columns of a table, you query the information_schema.columns catalog.
Syntax:
SELECT 
   table_name, 
   column_name, 
   data_type 
FROM 
   information_schema.columns
WHERE 
   table_name = 'table_name';

Example:
Use the below statement to get information on the film table of the dvdrental database:
SELECT 
   table_name, 
   column_name, 
   data_type 
FROM 
   information_schema.columns
WHERE 
   table_name = 'film';

Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - ROW_NUMBER Function
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
CREATE and DROP INDEX Statement in SQL

31 Aug, 2020
1. CREATE INDEX Statement :The CREATE INDEX statement will create indexes in tables. Indexes are used for data procurement from the databases faster. The users cannot see the indexes, they are running in the background of queries, used to speed up searches/queries.
Syntax :Create an index on a table :
CREATE INDEX indexname
ON tablename (columnname1, columnname2, ...);
Create a unique index on a table –
CREATE UNIQUE INDEX indexname
ON tablename (columnname1, columnname2, ...);
Example –Below SQL statement would create an index named “idx_name” on the “LastName” column in the “GeeksTab” table –
CREATE INDEX idx_name
ON GeeksTab (LastName);
To create an index on multiple columns –
CREATE INDEX idx_pname
ON GeeksTab (LastName, FirstName);
2. DROP INDEX Statement :The DROP INDEX statement could be used to remove an index from any table.
Syntax :
DROP INDEX tablename.indexname;
Example –
DROP INDEX GeeksTab.idx_pname;
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relational Model in DBMS
Introduction of Relational Algebra in DBMS
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
MySQL | Regular expressions (Regexp)
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
Window functions in SQL
SQL | DDL, DML, TCL and DCL
C++ Program to count Vowels in a string using Pointer

27 Sep, 2019
Pre-requisite: Pointers in C++
Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers
Examples:
Input : str = "geeks"
Output : 2

Input : str = "geeksforgeeks"
Output : 5 

Approach:
Initialize the string using a character array.Create a character pointer and initialize it with the first element in array of character (string).Create a counter to count vowels.Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.Print the count.
Initialize the string using a character array.
Create a character pointer and initialize it with the first element in array of character (string).
Create a counter to count vowels.
Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.
Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.
Print the count.
Below is the implementation of the above approach:
// CPP program to print count of// vowels using pointers  #include <iostream>  using namespace std;  int vowelCount(char *sptr){    // Create a counter    int count = 0;      // Iterate the loop until null character encounter    while ((*sptr) != '\0') {          // Check whether character pointer finds any vowels        if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i'            || *sptr == 'o' || *sptr == 'u') {              // If vowel found increment the count            count++;        }          // Increment the pointer to next location        // of address        sptr++;    }      return count;}  // Driver Codeint main(){    // Initialize the string    char str[] = "geeksforgeeks";      // Display the count    cout << "Vowels in above string: " << vowelCount(str);      return 0;}
Vowels in above string: 5

shubham_singh
cpp-pointer
cpp-string
C++
GATE
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
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 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
What is the use of constructor in Java?

A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
There are two types of constructors parameterized constructors and no-arg constructors the main purpose of a constructor is to initialize the instance variables of a class.
In the following example we are trying to initialize the instance variables of a class using no-arg constructor.
Live Demo
public class Test {
   int num;
   String data;
   Test(){
      num = 100;
      data = "sample";
   }
   public static void main(String args[]){
      Test obj = new Test();
      System.out.println(obj.num);
      System.out.println(obj.data);
   }
}
100
sample
In the following example we are trying to initialize the instance variables of a class using parameterized constructor.
Live Demo
import java.util.Scanner;
public class Test {
   int num;
   String data;
   Test(int num, String data){
      this.num = num;
      this.data = data;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String data = sc.nextLine();
      System.out.println("Enter an integer value: ");
      int num = sc.nextInt();
     
      Test obj = new Test(num, data);
      System.out.println(obj.num);
      System.out.println(obj.data);
   }
}
Enter a string value:
sample
Enter an integer value:
1023
1023
sample
Python | First occurrence of True number

06 Apr, 2022
Many times we require to find the first occurring non-zero number to begin the processing with. This has mostly use case in Machine Learning domain in which we require to process data excluding None or 0 values. Let’s discuss certain ways in which this can be performed. Method #1 : Using next() + enumerate() The next function can be used to iterate through the list and enumerate along with it checks for the list if the number is a non zero element and returns the number of 0s before a True value i.e a non zero value. 
Python3
# Python3 code to demonstrate# finding first True value# using next() and enumerate() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint ("The original list is : " + str(test_list)) # finding first True value# using next() and enumerate()res = next((i for i, j in enumerate(test_list) if j), None) # printing resultprint ("The values till first True value : " + str(res))
The original list is : [0, 0, 5, 6, 0]
The values till first True value : 2
  Method #2 : Using filter() + lambda + index() Using the combination of the above functions, one can easily perform this particular task. The filter function can be used to screen out the True value that is processed by the lambda functions and index function returns the first occurrence of this. 
Python3
# Python3 code to demonstrate# finding first True value# using filter() + lambda + index() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint ("The original list is : " + str(test_list)) # finding first True value# using filter() + lambda + index()res = test_list.index(next(filter(lambda i: i != 0, test_list))) # printing resultprint ("The values till first True value : " + str(res))
The original list is : [0, 0, 5, 6, 0]
The values till first True value : 2
sagartomar9927
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
PHP | ob_end_flush(), ob_end_clean() Functions

08 Mar, 2018
In the previous article on ob_start(), we learned how to start the output buffer; now we need to end the output buffering and send the whole HTML to the browser to render. We can do this by the help of functions ob_end_flush() and ob_end_clean().
ob_end_flush() Function
Syntax:
bool ob_end_flush ()

Parameters: The function doesn’t take any parameter.
Return Type: This function sends the HTML stored to browser and turns off output buffering. On success, TRUE is returned otherwise FALSE.
ob_end_clean() Function
Syntax:
bool ob_end_clean()

Parameters: The function doesn’t take any parameter.
Return Type: This function cleans the HTML stored and turns off output buffering. On success, TRUE is returned otherwise FALSE.
Below program illustrates the working of ob_end_flush() and ob_end_clean() in PHP:
<?php  // PHP code to illustrate the working of // ob_end_flush() and ob_end_clean()  // ob_end_flush()ob_start();echo "Hello Geek!"; //This will get printed.ob_end_flush();  // ob_end_clean() ob_start();echo "Hi Geek!";  //This will not get printed.ob_end_clean();  ?>
Output:
Hello Geek!

Important points to note:
ob_end_flush() or ob_end_clean() are not necessary functions i.e. if a developer ever uses ob_start() without using the mentioned functions the webpage will appear to be working correctly displaying every content, but what happens in the back is nowhere near optimized. When PHP encounters ob_start() it allocates a new output buffer and concatenates every HTML that appears after it, if there is no terminating function then upon reaching the end the stored data is sent to the browser as a default action. Developers can create optimized web pages by terminating the output buffering when not required thus keeping the global stack clear.
There raises a question, if we use ob_end_clean() to clean the whole output buffer then why even use output buffering. We use ob_end_clean() with ob_get_contents() which first gets the contents as a string and then the output buffer is cleaned and turned off, this clears the global stack and keeps the whole content in a variable to be processed further.
Reference:
http://php.net/manual/en/function.ob-end-flush.php
http://php.net/manual/en/function.ob-end-clean.php
PHP-function
PHP-output
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2005 | Question 32

28 Jun, 2021
Consider the following C-program:
double foo (double); /* Line 1 */  int main(){      double da, db;      // input da      db = foo(da);  }  double foo(double a){    return a;}
The above code compiled without any error or warning. If Line 1 is deleted, the above code will show:(A) no compile warning or error(B) some compiler-warnings not leading to unintended results(C) some compiler-warnings due to type-mismatch eventually leading to unintended results(D) compiler errorsAnswer: (D)Explanation: Refer What happens when a function is called before its declaration in C?Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Image Translation using OpenCV | Python

20 May, 2019
Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. where tx denotes the shift along the x-axis and ty denotes shift along the y-axis i.e. the number of pixels by which we need to shift about in that direction.Now, we can use the cv2.wrapAffine() function to implement these translations. This function requires a 2×3 array. The numpy array should be of float type.
Below is the Python code for Image Translation:
import cv2import numpy as np  image = cv2.imread('C:\\gfg\\tomatoes.jpg')  # Store height and width of the imageheight, width = image.shape[:2]  quarter_height, quarter_width = height / 4, width / 4  T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]])  # We use warpAffine to transform# the image using the matrix, Timg_translation = cv2.warpAffine(image, T, (width, height))  cv2.imshow("Originalimage", image)cv2.imshow('Translation', img_translation)cv2.waitKey()  cv2.destroyAllWindows()
Output:
Advantages/application of image translation are:
Hiding a part of the image
Cropping an image
Shifting an image
Animating an image using image translations in loop.
Image-Processing
OpenCV
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to create Dialog Box in ReactJS?

05 Mar, 2021
A Dialog is a type of modal window which appears in front of app content to provide critical information or ask for a decision. Material UI for React has this component available for us, and it is very easy to integrate. We can create Dialog Box in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Dialog from "@material-ui/core/Dialog";import DialogContentText from "@material-ui/core/DialogContentText";import DialogTitle from "@material-ui/core/DialogTitle";import DialogActions from "@material-ui/core/DialogActions";import DialogContent from "@material-ui/core/DialogContent";import Button from "@material-ui/core/Button";  export default function App() {  const [open, setOpen] = React.useState(false);    const handleClickToOpen = () => {    setOpen(true);  };    const handleToClose = () => {    setOpen(false);  };    return (    <div stlye={{}}>      <h4>How to create Dialog Box in ReactJS?</h4>      <Button variant="outlined" color="primary"               onClick={handleClickToOpen}>        Open Demo Dialog      </Button>      <Dialog open={open} onClose={handleToClose}>        <DialogTitle>{"How are you?"}</DialogTitle>        <DialogContent>          <DialogContentText>            I am Good, Hope the same for you!          </DialogContentText>        </DialogContent>        <DialogActions>          <Button onClick={handleToClose}                   color="primary" autoFocus>            Close          </Button>        </DialogActions>      </Dialog>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/dialogs/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
How to create a table in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
How to Convert java.sql.Date to java.util.Date in Java?

04 Sep, 2021
If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object.
java.util.Date  utilDate = new java.util.Date(sqlDate.getTime());
It will give us util Date object.
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throw any exception.
Java
// Java program to Convert java.sql.Date to java.util.Date import java.sql.*;import java.text.*;import java.util.*;public class GFG {     public static void main(String[] args)    {         // sql date object takes time in milliseconds        long millis = System.currentTimeMillis();         // creating sql date object        java.sql.Date sqlDate = new java.sql.Date(millis);         // creating util date object by passing gettime()        // method of sql date class        java.util.Date utilDate = new java.util.Date(sqlDate.getTime());         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");               // converting the util date into string format        final String stringDate = dateFormat.format(utilDate);         // printing both dates        System.out.println("utilDate:" + stringDate);        System.out.println("sqlDate:" + sqlDate);    }}
Output:
utilDate:2021-01-20
sqlDate:2021-01-20
sooda367
Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java Connection getCatalog() method with example

In general, a catalog is a directory which holds information about data sets, file or, a database. Whereas in a database catalog holds the list of all the databases, base tables, views (virtual tables), synonyms, value ranges, indexes, users, and user groups.
The getCatalog() method of the Connection interface returns the name of the current catalog/database, of the current connection object.
This method returns a Sting value representing the name of the catalog. It returns null if there is no catalog.
To get the catalog name −
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Retrieve the connection objects catalog name using the getCatalog() method as −
//Retrieving the current catalog name
String catalogName = con.getCatalog();
Let us create a database with name mydatabase in MySQL using CREATE statement as shown below.
create database mydatabase;
Following JDBC program establishes connection with MySQL database, retrieves and, displays the name of the underlying catalog.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_getCatalog {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Setting the auto commit false
      con.setAutoCommit(false);
      //Retrieving the current catalog name
      String catalogName = con.getCatalog();
      System.out.println("Current catalog name is: "+catalogName);
   }
}
Connection established......
Current catalog name is: mydatabase
C program to add all perfect square elements in an array.

Write a program to find the sum of perfect square elements in an array.
Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output.
For example,
Input= 1, 2, 3, 4, 5, 9,10,11,16
The perfect squares are 1, 4, 9, 16.
Sum = 1 + 4 + 9 +16 = 30
Output: 30
Refer an algorithm given below to add the perfect square elements in an array.
Step 1 − Read number of elements in array at runtime.
Step 2 − Input the elements.
Step 3 − Declare and initialize the sum=0
Step 4 − Check, whether the array element is a perfect square or not.
Step 5 − If it is a perfect square, then, compute sum=sum+number.
Step 6 − Return sum.
Following is the C program to find the sum of perfect square elements in an array −
#include<stdio.h>
#include<math.h>
int isPerfectSquare(int number){
   int iVar;
   float fVar;
   fVar=sqrt((double)number);
   iVar=fVar;
   if(iVar==fVar)
      return number;
   else
   return 0;
}
int main(){
   int n;
   printf("enter no: of elements:");
   scanf("%d",&n);
   int arr[n];
   int i;
   printf("enter the elements in an array:\n");
   for(i = 0; i < n; i++){
      scanf("%d",&arr[i]);
   }
   int sum = 0;
   for(i = 0; i < n; i++){
      sum = sum + isPerfectSquare(arr[i]);
   }
   printf("sum=%d",sum);
   return 0;
}
When the above program is executed, it produces the following output −
Run 1:
enter no: of elements:5
enter the elements in an array:
1
3
5
9
10
sum=10
Run 2:
enter no: of elements:5
enter the elements in an array:
1
4
9
16
25
sum=55
How can I avoid too many OR statements in a MySQL query?

Use MySQL IN() to avoid too many OR statements. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(40)
);
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
|  3 | Mike   |
|  4 | Sam    |
|  5 | David  |
+----+--------+
5 rows in set (0.00 sec)
Following is the query to avoid too many OR statements in a MySQL query i.e. using IN() −
mysql> select *from DemoTable where Id IN(1,3,5);
This will produce the following output −
+----+-------+
| Id | Name  |
+----+-------+
|  1 | Chris |
|  3 | Mike  |
|  5 | David |
+----+-------+
3 rows in set (0.00 sec)
Python | Word location in String

22 Apr, 2020
Sometimes, while working with Python strings, we can have problem in which we need to find location of a particular word. This can have application in domains such as day-day programming. Lets discuss certain ways in which this task can be done.
Method #1 : Using re.findall() + index()This is one of the way in which we can find the location where word exists. In this we look for substring pattern using findall() and its position using index().
# Python3 code to demonstrate working of # Word location in String# Using findall() + index()import re  # initializing stringtest_str = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string is : " + test_str)  # initializing word wrd = 'best'  # Word location in String# Using findall() + index()test_str = test_str.split()res = -1for idx in test_str:    if len(re.findall(wrd, idx)) > 0:        res = test_str.index(idx) + 1  # printing result print("The location of word is : " + str(res)) 
The original string is : geeksforgeeks is best for geeks
The location of word is : 3

 
Method #2 : Using re.sub() + index()This performs this task in similar way as above method. In this also regex is employed. We use different regex function in this method.
# Python3 code to demonstrate working of # Word location in String# Using re.sub() + index()import re  # initializing stringtest_str = 'geeksforgeeks is best for geeks'  # printing original stringprint("The original string is : " + test_str)  # initializing word wrd = 'best'  # Word location in String# Using re.sub() + index()res = re.sub("[^\w]", " ",  test_str).split()res = res.index(wrd) + 1  # printing result print("The location of word is : " + str(res)) 
The original string is : geeksforgeeks is best for geeks
The location of word is : 3

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
route command in Linux with Examples

17 May, 2020
route command in Linux is used when you want to work with the IP/kernel routing table. It is mainly used to set up static routes to specific hosts or networks via an interface. It is used for showing or update the IP/kernel routing table.
Many Linux distributions do not have route command pre-installed. To install it use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install net-tools
In case of CentOS/RedHat
$sudo yum install net-tools
In case of Fedora OS
$sudo dnf install net-tools
1. To display the IP/kernel routing table.
$route
It displays the routing table entries.
2. To display routing table in full numeric form.
$route -n
It is even useful when you have to determine why the route to nameserver has even vanished.
3. To add a default gateway.
$sudo route add default gw 169.254.0.0
This assigns a gateway address on which all the packets that do not belong to the network are forwarded.
Note: In this case the, We wish to choose 169.254.0.0 as the default gateway. You may choose as per your need.
4. To list kernel’s routing cache information.
$route -Cn

To route the packets faster, Kernel maintains this routing cache information. The above command will print the cache information. In this case, the cache information is maintained.
5. To reject routing to a particular host or network.
$sudo route add -host 192.168.1.51 reject

Now if you will ping to the above-mentioned IP it will display “Network is unreachable”.
6. To get details of the kernel/IP routing table using ip command.
$ip route

This will give the details of the kernel/IP routing table and in this case, we have used IP command.
7. To delete the default gateway.
$route del default

Caution: This may lead to some malfunctioning of internet. Keep a note of your default gateway before proceeding with the command.
This will remove the default gateway.
8. To get the details of the local table with destination addresses assigned to the localhost.
$ip route show table local

This will print the details of the local table.
9. To get output related to IPv4.
$ip -4 route

This will only display the entries with ipv4.
10. To get output related to IPv6.
$ip -6 route

This will only display the entries with ipv6.
linux-command
Linux-networking-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
Basic Operators in Shell Scripting
Lower bound for comparison based sorting algorithms

06 Jul, 2021
The problem of sorting can be viewed as following. 
Input: A sequence of n numbers <a1, a2, . . . , an>. Output: A permutation (reordering) <a‘1, a‘2, . . . , a‘n> of the input sequence such that a‘1 <= a‘2 ..... <= a’n. 
A sorting algorithm is comparison based if it uses comparison operators to find the order between two numbers.  Comparison sorts can be viewed abstractly in terms of decision trees. A decision tree is a full binary tree that represents the comparisons between elements that are performed by a particular sorting algorithm operating on an input of a given size. The execution of the sorting algorithm corresponds to tracing a path from the root of the decision tree to a leaf. At each internal node, a comparison ai <= aj is made. The left subtree then dictates subsequent comparisons for ai <= aj, and the right subtree dictates subsequent comparisons for ai > aj. When we come to a leaf, the sorting algorithm has established the ordering. So we can say following about the decision tree. 
1) Each of the n! permutations on n elements must appear as one of the leaves of the decision tree for the sorting algorithm to sort properly. 
2) Let x be the maximum number of comparisons in a sorting algorithm. The maximum height of the decision tree would be x. A tree with maximum height x has at most 2^x leaves. 
After combining the above two facts, we get following relation.  
  
      n!  <= 2^x

 Taking Log on both sides.
      log2(n!)  <= x

 Since log2(n!)  = Θ(nLogn),  we can say
      x = Ω(nLog2n)
Therefore, any comparison based sorting algorithm must make at least nLog2n comparisons to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison sorts. 
References: Introduction to Algorithms, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein 
sooda367
Merge Sort
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
StringBuilder.ToString Method in C#

29 Jan, 2019
This method is used to converts the value of this instance to a String. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by ToString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.
Syntax: public override string ToString ();
Return Value: This method returns the String representing the data contained by StringBuilder Object.
Below programs illustrate the StringBuilder.ToString() method:
Example 1:
// C# program to demonstrate// the ToString() Methodusing System;using System.Text;  class GFG {      // Main Method    public static void Main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder str          = new StringBuilder("GeeksForGeeks");          // print string        Console.WriteLine("String contains = "                            + str.ToString());    }}
String contains = GeeksForGeeks

Example 2:
// C# program to demonstrate// the ToString() Methodusing System;using System.Text;  class GFG {      // Main Method    public static void Main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder str =              new StringBuilder("GeeksforGeeks Contribute");                                          // print string        Console.WriteLine("String contains = "                          + str.ToString());    }}
String contains = GeeksforGeeks Contribute

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.tostring?view=netframework-4.7.2
CSharp-method
CSharp-StringBuilder-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Iterate over Tuples in Dictionary - GeeksforGeeks

24 Jan, 2022
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. 
We can get the particular tuples by using an index:
Syntax:
dictionary_name[index]
To iterate the entire tuple values in a particular index
for i in range(0, len(dictionary_name[index])):
    print(dictionary_name[index][i]
 Example:
Python
# Initializing a dictionarymyDict = {1: ("Apple", "Boy", "Cat"),          2: ("Geeks", "For", "Geeks"),          3: ("I", "Am", "Learning", "Python")} print("Tuple mapped with the key 1 =>"), # Directly printing entire tuple mapped# with the key 1print(myDict[1]) print("Tuple mapped with the key 2 =>"), # Printing tuple elements mapped with# the key 2 one by onefor each in myDict[2]:    print(each), print("")print("Tuple mapped with the key 3 =>"), # Accessing tuple elements mapped with# the key 3 using indexfor i in range(0, len(myDict[3])):    print(myDict[3][i]),
Output:
Tuple mapped with the key 1 =>
('Apple', 'Boy', 'Cat')
Tuple mapped with the key 2 =>
Geeks
For
Geeks

Tuple mapped with the key 3 =>
I
Am
Learning
Python
we can use dictionary.values() to iterate over the tuples in a dictionary with for loop
Syntax:
for i in dictionary_name.values():
  for j in i:
      print(j)
  print(" ")
Example:
Python3
# Initializing a dictionarymyDict = {1: ("Apple", "Boy", "Cat"),          2: ("Geeks", "For", "Geeks"),          3: ("I", "Am", "Learning", "Python")} # iterate over all tuples using# values() methodfor i in myDict.values():    for j in i:        print(j)    print(" ")
Output:
Apple
Boy
Cat
 
Geeks
For
Geeks
 
I
Am
Learning
Python
surinderdawra388
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to Install Tkinter on MacOS? - GeeksforGeeks

22 Sep, 2021
In this article, we will learn how to install Tkinter in Python on MacOS. Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de-facto standard GUI.
Follow the below steps to install the Tkinter package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Tkinter using pip3.
pip3 install tk
Follow the below steps to install the yesTkinter package on macOS using the setup.py file:
Step 1: Download the latest source package of Tkinter for python3 from here.
curl https://files.pythonhosted.org/packages/a0/81/742b342fd642e672fbedecde725ba44db44e800dc4c936216c3c6729885a/tk-0.1.0.tar.gz > tk.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf tk.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd tk-0.1.0
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import tk
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
PHP | strtolower() Function - GeeksforGeeks

01 Aug, 2021
The strtolower() function is used to convert a string into lowercase. This function takes a string as parameter and converts all the uppercase english alphabets present in the string to lowercase. All other numeric characters or special characters in the string remains unchanged.
Syntax:
string strtolower( $string )

Parameter: The only parameter to this function is a string that is to be converted to lower case.
Return value: This function returns a string in which all the alphabets are lower case.
Examples:
Input : $str  = "GeeksForGeeks"
        strtolower($str)
Output: geeksforgeeks

Input : $str  = "going BACK he SAW THIS 123$#%"
        strtolower($str)
Output: going back he saw this 123$#%

Below programs illustrate the strtolower() function in PHP:
Program 1:
<?php  // original string$str = "GeeksForGeeks";  // string converted to lower case$resStr = strtolower($str);  print_r($resStr);  ?>
Output:
geeksforgeeks

Program 2:
<?php  // original string$str = "going BACK he SAW THIS 123$#%";  // string converted to lower case$resStr = strtolower($str);  print_r($resStr);  ?>
Output:
going back he saw this 123$#%

Reference:http://php.net/manual/en/function.strtolower.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Vaibhav Bajpai
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills