code-rag-bench/online-tutorials huggingface dataset:
How to create a JSON using JsonObjectBuilder and JsonArrayBuilder in Java?

The JsonObjectBuilder can be used for creating JsonObject models whereas the JsonArrayBuilder can be used for creating JsonArray models. The JsonObjectBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonObject instance using the Json.createObjectBuilder().build(). The JsonArrayBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonArray instance using Json.createArrayBuilder().build().
import java.io.*;
import javax.json.*;
public class JsonObjectTest {
   public static void main(String[] args) {
      JsonObject empObject = Json.createObjectBuilder().add("empName", "Jai")
                                 .add("empAge", "25")
                                 .add("empSalary", "40000")
                                 .add("empAddress",
                                      Json.createObjectBuilder().add("street", "IDPL Colony")
                                                           .add("city", "Hyderabad")
                                                           .add("pinCode", "500072")
                                                           .build()
                                     )
                                 .add("phoneNumber",
                                      Json.createArrayBuilder().add("9959984000")
                                                               .add("7702144400")
                                                               .build()
                                      )
                                 .build();
      System.out.println(empObject);
   }
}
{"empName":"Jai","empAge":"25","empSalary":"40000","empAddress":{"street":"IDPL Colony","city":"Hyderabad","pinCode":"500072"},"phoneNumber":["9959984000","7702144400"]}
Tcl - Basic Syntax

Tcl is quite simple to learn and let's start creating our first Tcl program!
Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file.
#!/usr/bin/tclsh

puts "Hello, World!" 
Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using −
$ tclsh test.tcl

We will get the following output −
Hello, World!

Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command.
Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning.
#!/usr/bin/tclsh

# my first program in Tcl
puts "Hello World!" 
When the above code is executed, it produces the following result −
Hello World!

Multiline or block comment is written using 'if' with condition '0'. An example is shown below.
#!/usr/bin/tclsh

if 0 {
   my first program in Tcl program
   Its very simple
}
puts "Hello World!" 
When the above code is executed, it produces the following result −
Hello World!

Inline comments use ;#. An example is given below.
#!/usr/bin/tclsh

puts "Hello World!" ;# my first print in Tcl program
When the above code is executed, it produces the following result −
Hello World!

A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9).
Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers −
mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it.
Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement −
#!/usr/bin/tclsh

puts "Hello World!" 
There must be at least one whitespace character (usually a space) between “puts” and "Hello World!" for the interpreter to be able to distinguish them. On the other hand, in the following statement −
#!/usr/bin/tclsh

puts [expr 3 + 2] ;# print sum of the 3 and 2
When the above code is executed, it produces the following result −
5

No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose.
 Print
 Add Notes
 Bookmark this page
Python | os.path.normcase() method

09 Mar, 2022
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.path module is sub module of OS module in Python used for common path name manipulation.os.path.normcase() method in Python is used to normalize the case of specified path name. On windows, this method converts all characters in the specified path to the lowercase and forward slash (‘/’) to backslash (‘\’). This method returns the specified path unchanged on operating systems other than Windows.  
Syntax: os.path.normcase(path)Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the normalized case in the specified path.  
Code #1: Use of os.path.normcase() method (On Windows)  
Python3
# Python program to explain os.path.normcase() method   # importing os.path moduleimport os.path # Pathpath = r'C:\User\admin\Documents'  # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/'  # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = r'C:\Users/Desktop' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path)
c:\\user\\admin\\documents
\\home\\user
c:\\users\\desktop
 
Code #2: Use of os.path.normcase() method (On operating systems other than Windows)  
Python3
# Python program to explain os.path.normcase() method   # importing os.path moduleimport os.path # Pathpath = '/home/UseR/Documents'  # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/'  # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # os.path.norcase() method will return# the specified path as it as# on operating systems# other than Windows
/home/UseR/Documents
/hoMe/UseR/
 
Reference: https://docs.python.org/3/library/os.path.html 
ManasChhabra2
sumitgumber28
Python OS-path-module
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
SQL Snapshots

23 Oct, 2020
Snapshot is a recent copy of the table from the database or a subset of rows/columns of a table. The SQL statement that creates and subsequently maintains a snapshot normally reads data from the database residing server. A snapshot is created on the destination system with the create snapshot SQL command. The remote table is immediately defined and populated from the master table.
These are used to dynamically replicate data between distributed databases. Two types of snapshots are available.
Simple snapshotsComplex snapshots
Simple snapshots
Complex snapshots
Simple snapshot :In simple snapshot, each row is based on a single row in a single remote table. This consists of either a single table or a simple SELECT of rows from a single table.
Example –
CREATE SNAPSHOT emp_snap 
as select * from emp;

Complex snapshot :In complex snapshot, a row may be based on more than one row in a remote table via GROUP BY operation or result of Multi-Table Join. This consists of joined tables, views, or grouped and complex SELECT statement queries.
Example –
CREATE SNAPSHOT sampleSnps1 
AS SELECT student.rollno, student.name 
FROM student
UNION ALL
SELECT new_student.rollno, new_student.name 
FROM new_student;

Advantages :
Response time is improved when local read-only copy of table exists.
Once snapshot is built on remote database, if node containing data from which the snapshot is built is not available. Snapshot can be used without need to access the unavailable database.
Ease network loads.
Data subsetting.
Disconnected computing.
Mass deployment.
Disadvantages :
Snapshots are not reachable when primary database goes offline.
It does not support full text indexing.
Snapshot runs out of disk if data changes frequently faster.
As no.of snapshots increases, disk space becomes problematic.
Applications :
Protects data.
Maintains history of data.
Used in testing application software.
Used in data mining.
Recovers data when information is lost because of human error or corruption of data.
DBMS-SQL
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?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to run bash script in Python?

26 Mar, 2021
If you are using any major operating system you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python code. The module designed to spawn new processes and communicate with them has a name subprocess.
Let’s consider such a simple example, presenting a recommended approach to invoking subprocesses. As an argument, you have to pass the command you want to invoke and its arguments, all wrapped in a list.
Python3
import subprocess    # execute commandsubprocess.run(["echo", "Geeks for geeks"])
Output:
CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0)
A new process is created and command echo is invoked with the argument “Geeks for geeks”. Although, the command’s result is not captured by the python script. We can do it by adding optional keyword argument capture_output=True to run the function, or by invoking check_output function from the same module. Both functions invoke the command, but the first one is available in Python3.7 and newer versions.
Python3
import subprocess    # From Python3.7 you can add # keyword argument capture_outputprint(subprocess.run(["echo", "Geeks for geeks"],                      capture_output=True))  # For older versions of Python:print(subprocess.check_output(["echo",                                "Geeks for geeks"]))
Output:
CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0, stdout=b’Geeks for geeks\n’, stderr=b”)
b’Geeks for geeks\n’
What about invoking already existing shell script from python code? It’s also done by run command!
Python3
import subprocess    # If your shell script has shebang, # you can omit shell=True argument.subprocess.run(["/path/to/your/shell/script",                 "arguments"], shell=True)
Output:
CompletedProcess(args=[‘/path/to/your/shell/script’, ‘arguments’], returncode=127)
Common problems with invoking shell script and how to solve them:
Permission denied when invoking script — don’t forget to make your script executable! Use chmod +x /path/to/your/script
OSError: [Errno 8] Exec format error — run functions lacks shell=True option or script has no shebang.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
How to create the boilerplate code in VS Code?

31 May, 2021
While programming, there is often a piece of code that needs to be written repetitively. For example, loops (for loop, while loop, do-while loop), or classes and functions. To write such a piece of code, again and again, becomes a daunting task, and often copy and paste is done, which definitely takes a lot of time and effort. The above problem can be solved using Code-Snippets or boilerplates.
Boilerplate or a code-snippet are solution provided by IDEs like VS Code, where a repetitive code can be called within a program by typing prefix names.
Code snippets for loops and classes are already provided in the IDE.
C++
// C++ program to demonstrate the// boilerplate code#include <iostream>using namespace std;  // Driver Codeint main(){    return 0;}
Let’s see how to create a Code-Snippet/ Boilerplate for our basic C++ programs in the VS Code.
Step 1: Locating the C++ JSON file for adding the snippet:
Open your VS Code and click on the settings button in the bottom-left corner.
Click on User Snippets.
You’ll see a dropdown at the top of a list of various JSON files.
Click on cpp.json
Step 2: Adding the C++ code to the JSON file:
Remove all the code from this file and write down the code given below.
C++
// Write this code in the cpp.json file{    "cpp snippets":    {        "prefix" : "boilerplate",                   "body" : [                       "#include<iostream>",                       "using namespace std;",                       "int main()",                       "{",                       "    return 0;",                       "}"                     ],                            "description" : "to produce the main snippet for cpp"    }}
After writing the code, press Ctrl + S to save the changes that have been made.
Explanation of the above code:
prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)body: It contains the reusable code, which we’ll call with the help of a prefix.description: It contains a small definition of the snippet, which explains the purpose behind it.
prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)
body: It contains the reusable code, which we’ll call with the help of a prefix.
description: It contains a small definition of the snippet, which explains the purpose behind it.
Step 3: Calling the Boilerplate in our program:
Create a new C++ file in the current folder. Type in the prefix which we used for our Boilerplate. You will notice that VS Code automatically suggests your prefix name while you are halfway typing the name.
Now press ENTER.
Now we have created a basic boilerplate for everyday programming.
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Grab where current date and the day before with MySQL?

You can grab the current date with CURDATE() and the day before with MySQL using DATE_SUB() with INTERVAL 1 DAY. The syntax is as follows:
SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY);
The syntax is as follows to get curdate and the day before with date_sub().
SELECT *FROM yourTableName WHERE yourColumnName = CURDATE() OR yourColumnName = DATE_SUB(CURDATE(),INTERVAL 1 DAY);
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table ProductDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(20),
   -> ProductOfferDate datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command. Here, we have added the products and the product offer date. The query is as follows:
mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-11','2017-05-21');
Query OK, 1 row affected (0.25 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-22','2019-01-15');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-21','2019-01-14');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-91','2018-10-23');
Query OK, 1 row affected (0.26 sec)

mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-133','2019-01-24');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from ProductDemo;
The following is the output:
+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
| 1 | Product-11 | 2017-05-21 00:00:00 |
| 2 | Product-22 | 2019-01-15 00:00:00 |
| 3 | Product-21 | 2019-01-14 00:00:00 |
| 4 | Product-91 | 2018-10-23 00:00:00 |
| 5 | Product-133 | 2019-01-24 00:00:00 |
+----+-------------+---------------------+
5 rows in set (0.00 sec)
The following is the query to grab the product with current date and the day before:
mysql> select *from ProductDemo
   -> where ProductOfferDate = CURDATE() OR ProductOfferDate = date_sub(curdate(),interval 1 day);
The following is the output:
+----+-------------+---------------------+
| Id | ProductName | ProductOfferDate    |
+----+-------------+---------------------+
|  2 | Product-22  | 2019-01-15 00:00:00 |
|  3 | Product-21  | 2019-01-14 00:00:00 |
+----+-------------+---------------------+
2 rows in set (0.00 sec)
Java program to find the average of given numbers using arrays

You can read data from the user using scanner class.
Using the nextInt() method of this class get the number of elements from the user.
Create an empty array.
Store the elements entered by the user in the array created above.
Finally, Add all the elements in the array and divide the sub by the number of elements.
import java.util.Scanner;
public class AverageUsingArrays {
   public static void main(String args[]){

      //Reading total no.of elements
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of elements/numbers");
      int num = sc.nextInt();

      //Creating an array
      int[] myArray = new int[num];

      //Read numbers from user and store it in an array
      System.out.println("Enter the numbers one by one : ");
      System.out.println("Press Enter button after each number : ");

      for(int i =0; i<num; i++){
         myArray[i] = sc.nextInt();
      }

      //Calculate the average
      double average = 0;
      for(int i =0; i<num; i++){
         average = average + myArray[i];
      }

      average = average/num;
      System.out.println("Average of given numbers :: "+average);
   }
}
Enter the number of elements/numbers
5
Enter the numbers one by one :
Press Enter button after each number :
55
66
55
55
66
Average of given numbers :: 59.4
Python - Add a prefix to column names in a Pandas DataFrame

To add a prefix to all the column names, use the add_prefix() method. At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with 4 columns −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250]
})
Add a prefix to _column to every column using add_prefix() −
dataFrame.add_prefix('column_')

Following is the code −
import pandas as pd

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250]
})

print"DataFrame ...\n",dataFrame

print"\nUpdated DataFrame...\n",dataFrame.add_prefix('column_')
This will produce the following output −
DataFrame ...
        Car   Cubic_Capacity   Reg_Price   Units_Sold
0       BMW             2000        7000          100
1     Lexus             1800        1500          120
2     Tesla             1500        5000          150
3   Mustang             2500        8000          110
4  Mercedes             2200        9000          200
5    Jaguar             3000        6000          250

Updated DataFrame...
  column_Car   column_Cubic_Capacity   column_Reg_Price   column_Units_Sold
0       BMW                     2000               7000                 100
1     Lexus                     1800               1500                 120
2     Tesla                     1500               5000                 150
3   Mustang                     2500               8000                 110
4  Mercedes                     2200               9000                 200
5    Jaguar                     3000               6000                 250
How to make a Tkinter window not resizable?

Tkinter initially creates a resizable window for every application. Let us suppose that we want to make a non-resizable window in an application. In this case, we can use resizable(height, width) and pass the value of height=None and width=None. The method also works by passing Boolean values as resizable(False, False).
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("600x250")

#Set the resizable property False
win.resizable(False, False)

#Create a label for the window or frame
Label(win, text="Hello World!", font=('Helvetica bold',20),
anchor="center").pack(pady=20)

win.mainloop()
Running the above code will display a non-resizable window.
MySQLi - SSL Set

bool mysqli_ssl_set ( 
   mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )

It is used for establishing secure connections using SSL
Try out following example −
<?php
   $servername = "localhost:3306";
   $username = "root";
   $password = "";
   $dbname = "TUTORIALS";
   $con = mysqli_init();

   if (!$con){
      die("mysqli_init failed");
   }
   mysqli_ssl_set($con,"key.pem","cert.pem","cacert.pem",NULL,NULL); 
   $conn = new mysqli($servername, $username, $password, $dbname);
   
   if (!$conn->real_connect($con,$servername, $username, $password, $dbname)) {
      die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
   }
   echo "Database connected";
   printf("Client version: %d\n", mysqli_get_client_version());

   mysqli_close($con);
?>
The sample output of the above code should be like this −
Database connected Client version: 50011


    14 Lectures 
     1.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python - math.atan() function - GeeksforGeeks

28 May, 2020
Math module contains a number of functions which is used for mathematical operations. The math.atan() function returns the arctangent of a number as a value. The value passed in this function should be between -PI/2 and PI/2 radians.
Syntax: math.atan(x)
Parameter:This method accepts only single parameters.
x :This parameter is the value to be passed to atan()
Returns:This function returns the arctangent of a number as a value.
Below examples illustrate the use of above function:
Example 1:
# Python code to implement# the atan()function  # importing "math"# for mathematical operations  import math         a = math.pi / 6       # returning the value of arctangent  of pi / 6  print ("The value of tangent of pi / 6 is : ", end ="")  print (math.atan(a))  
Output:
The value of tangent of pi / 6 is : 0.48234790710102493

Example 2:
# Python code to implement# the atan()functionimport math import numpy as np import matplotlib.pyplot as plt       in_array = np.linspace(0, np.pi, 10)       out_array = []      for i in range(len(in_array)):     out_array.append(math.atan(in_array[i]))     i += 1        print("Input_Array : \n", in_array)  print("\nOutput_Array : \n", out_array)      plt.plot(in_array, out_array, "go:")  plt.title("math.atan()")  plt.xlabel("X")  plt.ylabel("Y")  plt.show()  
Output:
Input_Array : 
 [0.         0.34906585 0.6981317  1.04719755 1.3962634  1.74532925
 2.0943951  2.44346095 2.7925268  3.14159265]

Output_Array : 
 [0.0, 0.3358423725664079, 0.6094709714274295, 0.808448792630022, 0.9492822422213403, 1.0504981725497873, 1.1253388328842984, 1.1823365638628716, 1.2269249964859286, 1.2626272556789118]

Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
PostgreSQL - Size of tablespace - GeeksforGeeks

22 Feb, 2021
In this article, we will look into the function that is used to get the size of the PostgreSQL database tablespace. The pg_tablespace_size() function is used to get the size of a tablespace of a table. This function accepts a tablespace name and returns the size in bytes. 
Syntax: select pg_tablespace_size('tablespace_name');
Example 1: Here we will query for the size of the pg_default tablespace using the below command: 
SELECT
    pg_size_pretty (
        pg_tablespace_size ('pg_default')
    );
Output: 
Notice we used to make the pg_size_pretty() function to make the result humanly readable. The pg_size_pretty() function takes the result of another function and formats it using bytes, KB, MB, GB, or TB as required. 
Note: There is generally not much point in creating more than one tablespace per logical file system, since one cannot control the location of every individual file within a logical file system. However, PostgreSQL does not enforce limitations on creation of new tablespace, and indeed it is not directly aware of the file system boundaries on one’s system. It just stores files in the directories where one wants them to be stored. 
But for the sake of example, we will create a new tablespace and find its size. To create a new tablespace use the below command: 
CREATE TABLESPACE new_tablespace LOCATION 'C:\sample_tablespace\';
Now that we have created a new tablespace named new_tablespace, let’s find its size. Example 2: 
SELECT
    pg_size_pretty (
        pg_tablespace_size ('new_tablespace')
    );
Output: 
RajuKumar19
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - LEFT JOIN
PostgreSQL - Cursor
PostgreSQL - Record type variable
PostgreSQL - Copy Table
PostgreSQL - Select Into
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
PostgreSQL - TIME Data Type
Python Program to Read Two Numbers and Print Their Quotient and Remainder

When it is required to read two numbers and print the quotient and remainder when they are divided, the ‘//’ and ‘%’ operators can be used.
Below is a demonstration of the same −
 Live Demo
first_num = int(input("Enter the first number..."))
second_num = int(input("Enter the second number..."))
print("The first number is ")
print(first_num)
print("The second number is ")
print(second_num)
quotient_val = first_num//second_num
remainder_val = first_num%second_num

print("The quotient is :")
print(quotient_val)
print("The remainder is :")
print(remainder_val)
Enter the first number...44
Enter the second number...56
The first number is
44
The second number is
56
The quotient is :
0
The remainder is :
44
The first and second numbers are taken as input from the user.
The first and second numbers are taken as input from the user.
They are displayed on the console.
They are displayed on the console.
To find the quotient, the ‘//’ operator is used.
To find the quotient, the ‘//’ operator is used.
To find the remainder, the ‘%’ operator is used.
To find the remainder, the ‘%’ operator is used.
The operations output is assigned to two variables respectively.
The operations output is assigned to two variables respectively.
This is displayed as output on the console.
This is displayed as output on the console.
How to convert from Unix timestamp to MySQL timestamp value?

MySQL converts Unix timestamp to timestamp data type value with the help of  FROM_UNIXTIME() function.
mysql> Select FROM_UNIXTIME(1508622563);
+-----------------------------+
| FROM_UNIXTIME(1508622563)   |
+-----------------------------+
| 2017-10-22 03:19:23         |
+-----------------------------+
1 row in set (0.00 sec)
Python | Pandas Series.str.center() - GeeksforGeeks

27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.center() function is used for filling left and right side of strings in the Series/Index with an additional character. The function is equivalent to Python’s str.center().
Syntax: Series.str.center(width, fillchar=’ ‘)
Parameter :width : Minimum width of resulting string; additional characters will be filled with fillcharfillchar : Additional character for filling, default is whitespace
Returns : filled
Example #1: Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])  # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string.
# fill '*' in the left and right side of stringresult = sr.str.center(width = 13, fillchar = '*')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object.
Example #2 : Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])  # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string.
# fill '*' in the left and right side of string# width after filling should be 5result = sr.str.center(width = 5, fillchar = '*')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object.
Note : If the value of width is smaller than the length of actual string then the whole string is printed without truncating it.
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Can we have an empty catch block in Java?

Yes, we can have an empty catch block. But this is a bad practice to implement in Java.
Generally, the try block has the code which is capable of producing exceptions, if anything wrong in the try block, for instance, divide by zero, file not found, etc. It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code.
public class EmptyCatchBlockTest {
   public static void main(String[] args) {
      try {
         int a = 4, b = 0;
         int c = a/b;
      } catch(ArithmeticException ae) {
         // An empty catch block
      }
   }
}
In the above code, the catch block catches the exception but doesn’t print anything in the console. This makes the user think that there is no exception in the code. So it's a good practice to print corresponding exception messages in the catch block.
// An empty catch block
Build a Basic React App that Display “Hello World!” - GeeksforGeeks

30 Sep, 2021
React is a Javascript Library that was created by Facebook for building better User Interface(UI) web applications and mobile applications. It is an open source library for creating interactive and dynamic applications.
In this article, we will see how to build a basic react app that shows hello world.
To create a react application, Node.js version of at least 10 or higher need to be installed on your system. If it is installed you can check by using the following command in your command line.
node -v 
Make sure you have a code editor for working on your project files.
To build a react application follow the below steps:
Step 1:  Create a react application using the following command 
npx create-react-app foldername
It takes a couple of minutes to install the packages.
Step 2:  Once it is done change your directory to the newly created application using the following command 
cd foldername
Project Structure: It is created as shown below.
Project file structure
Step 3: Now inside App.js and write down the following code as shown below:
Javascript
import React from 'react';import './App.css';  function App() {    return (       <h1> Hello World! </h1>    );}  export default App;
Step to run the application: Enter the following command to run the application.
npm start
Output: You will see the following output in your browser.
Congratulations,  you have created your first react app. You have learnt something new today. Don’t stop learning Go ahead. Learn React.js
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
React-Router Hooks
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Axios in React: A Guide for Beginners
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
MySQL query to fetch the latest date from a table with date records

Let us first create a table −
mysql> create table DemoTable
(
   DueDate date
);
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2018-10-01');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2016-12-31');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-07-02');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('2015-01-12');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2019-04-26');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 2018-10-01 |
| 2016-12-31 |
| 2019-07-02 |
| 2015-01-12 |
| 2019-04-26 |
+------------+
5 rows in set (0.00 sec)
Let’s say the current date is 2019-08-15. Now we will fetch the latest date −
mysql> select *from DemoTable order by DueDate DESC limit 1;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 2019-07-02 |
+------------+
1 row in set (0.03 sec)
C++ Program to Convert Km/hr to miles/hr and vice versa

If input is in km/hr convert it to miles/hr else input will be in miles/hr convert it to km/hr. There are formulas that can be used for this conversion.
Conversion Formulas −
1 kilo-metre = 0.621371 miles
1 miles = 1.60934 Kilo-meter
Input-: kmph= 50.00
   Mph = 10.00
Output-: speed in m/ph is 31.07
   speed in km/ph is 16.0934
Start
Step 1 -> Declare function to convert km/ph to m/ph
   double km_mph(double km)
      return 0.6214 * km
step 2 -> Declare function to convert m/ph to km/ph
   double m_km(double m_ph)
      return m_ph * 1.60934
step 3 -> In main()
   declare variable as double kmph = 50 and double mph = 10
   print km_mph(kmph)
   print m_km(mph)
Stop
#include <bits/stdc++.h>
using namespace std;
// convert km/ph to m/ph
double km_mph(double km){
   return 0.6214 * km;
}
//convert mph to kmph
double m_km(double m_ph){
   return m_ph * 1.60934;
}
int main(){
   double kmph = 50.00;
   double mph = 10.00;
   cout << "speed in m/ph is " << km_mph(kmph) << endl;
   cout << "speed in km/ph is " << m_km(mph);
   return 0;
}
speed in m/ph is 31.07
speed in km/ph is 16.0934
NP complete problems - GeeksQuiz

06 May, 2017
1. The problem of determining whether there exists
   a cycle in an undirected graph is in P.
2. The problem of determining whether there exists
   a cycle in an undirected graph is in NP.
3. If a problem A is NP-Complete, there exists a 
   non-deterministic polynomial time algorithm to solve A. 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Python Program for Breadth First Search or BFS for a Graph
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is "network ID" and "host ID" in IP Addresses?
What is Transmission Control Protocol (TCP)?
How to Calculate Number of Host in a Subnet?
Bash Scripting - How to check If File Exists
Python Raise Keyword
Python OpenCV - Canny() Function
list insert() in C++ STL - GeeksforGeeks

24 Oct, 2018
The list::insert() is used to insert the elements at any position of list. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1.
Syntax:
insert(pos_iter, ele_num, ele)

Parameters: This function takes in three parameters:
pos_iter: Position in the container where the new elements are inserted.
ele_num: Number of elements to insert. Each element is initialized to a copy of val.
ele: Value to be copied (or moved) to the inserted elements.
Return Value: This function returns an iterator that points to the first of the newly inserted elements.
// C++ code to demonstrate the working of// insert() function  #include <iostream>#include <list> // for list operationsusing namespace std;  int main(){    // declaring list    list<int> list1;      // using assign() to insert multiple numbers    // creates 3 occurrences of "2"    list1.assign(3, 2);      // initializing list iterator to beginning    list<int>::iterator it = list1.begin();      // iterator to point to 3rd position    advance(it, 2);      // using insert to insert 1 element at the 3rd position    // inserts 5 at 3rd position    list1.insert(it, 5);      // Printing the new list    cout << "The list after inserting"         << " 1 element using insert() is : ";    for (list<int>::iterator i = list1.begin();         i != list1.end();         i++)        cout << *i << " ";      cout << endl;      // using insert to insert    // 2 element at the 4th position    // inserts 2 occurrences    // of 7 at 4th position    list1.insert(it, 2, 7);      // Printing the new list    cout << "The list after inserting"         << " multiple elements "         << "using insert() is : ";      for (list<int>::iterator i = list1.begin();         i != list1.end();         i++)        cout << *i << " ";      cout << endl;}
The list after inserting 1 element using insert() is : 2 2 5 2 
The list after inserting multiple elements using insert() is : 2 2 5 7 7 2

CPP-Functions
cpp-list
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
Polymorphism in C++
Python | Check if list contains consecutive numbers - GeeksforGeeks

19 Mar, 2019
Given a list of numbers, write a Python program to check if the list contains consecutive integers.
Examples:
Input : [2, 3, 1, 4, 5]
Output : True

Input : [1, 2, 3, 5, 6]
Output : False

Let’s discuss the few ways we can do this task. Approach #1 : using sorted()
This approach uses sorted() function of Python. We compare the sorted list with list of range of minimum and maximum integer of the list and return it.
# Python3 Program to Create list # with integers within given range   def checkConsecutive(l):    return sorted(l) == list(range(min(l), max(l)+1))      # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst))
True

 Approach #2 : Using numpy.diff()
Numpy module provides a function diff() that calculate the n-th discrete difference along the given axis. We find the iterative difference of the sorted list and check if it is equal to 1.
# Python3 Program to Create list # with integers within given range import numpy as np  def checkConsecutive(l):    n = len(l) - 1    return (sum(np.diff(sorted(l)) == 1) >= n)       # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst))
True

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
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 block comments in YAML ? - GeeksforGeeks

11 Jun, 2020
YAML is a human-friendly data serialization standard for all programming languages. It is commonly used for configuration files and in applications where data is being stored or transmitted.
The Normal Way for commenting in YAML is Inline commenting with the “#” symbol, however, if you want to comment blocks then we have a list of ways in which it can be done.
Step 1: Select the blockStep 2: Press cmd plus / on Mac or press ctrl plus / on Linux & Windows.
Note: This method works on the following editors –
Sublime Text Editor
Atom Editor
Eclipse (with YEdit plugin)
JetBrains IDEs: RubyMine and Gogland
Visual Studio Code
At any level of the code, you may add a new block text named like “Description” or “Comment” or “Notes” or whatever that you wish
Example:
Instead of
# This comment
# is too long

use
Description: >
This comment
is too long

or
Comment: >
This comment is also too long
and newlines survive from parsing!
Advantages:
If the comments become too large and too complex and have a lot of repeating pattern, you may want to promote them from plain text blocks to objects.
Your app may need to read/update the comments in the future.
This method is very handy especially if anyone wants these comments to appear in JSON or XML if one is to transform from YAML to these two.
Picked
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Remove elements from a JavaScript Array
How to apply style to parent if it has child with CSS?
How to Open URL in New Tab using JavaScript ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
Python MongoDB - find_one_and_update Query - GeeksforGeeks

26 May, 2020
The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in original form and to return the updated document return_document have to be implemented in the code.
Syntax: coll.find_one_and_update(filter, update, options)
Parameters:
col- collection in MongoDB
filter- criteria to find the document which needs to be updated
update- The operations which need to be implemented for updating the document
options- projection or upsert can be used here
projection- a mapping which informs about which fields are included and excluded, it is 1/TRUE for including a field and 0/FALSE for excluding
upsert- for inserting a new document if no file is found with the mentioned criteria upsert is TRUE
Example 1:
Sample Database:
from pymongo import MongoClientfrom pymongo import ReturnDocument    # Create a pymongo clientclient = MongoClient('localhost', 27017)  # Get the database instancedb = client['GFG']  # Create a collectiondoc = db['Student']  print(doc.find_one_and_update({'name':"Raju"},                        { '$set': { "Branch" : 'ECE'} },                         return_document = ReturnDocument.AFTER))
Output:
{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’}
Example 2:
from pymongo import MongoClientfrom pymongo import ReturnDocument    # Create a pymongo clientclient = MongoClient('localhost', 27017)  # Get the database instancedb = client['GFG']  # Create a collectiondoc = db['Student']  print(# Increasing marks of Ravi by 10 doc.find_one_and_update({'name': "Raju"},                         { '$set': { "Branch" : 'CSE'} },                         projection = { "name" : 1, "Branch" : 1 },                         return_document = ReturnDocument.AFTER))
Output:
{'_id': 5, 'name': 'Raju', 'Branch': 'CSE'}

Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()