code-rag-bench/online-tutorials huggingface dataset:
Stack elements() method in Java with Example

24 Dec, 2018
The Java.util.Stack.elements() method of Stack class in Java is used to get the enumeration of the values present in the Stack.
Syntax:
Enumeration enu = Stack.elements()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the values of the Stack.
Below programs are used to illustrate the working of the java.util.Stack.elements() method:
Program 1:
// Java code to illustrate the elements() methodimport java.util.*;  public class Stack_Demo {    public static void main(String[] args)    {          // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Inserting elements into the table        stack.add("Geeks");        stack.add("4");        stack.add("Geeks");        stack.add("Welcomes");        stack.add("You");          // Displaying the Stack        System.out.println("The Stack is: " + stack);          // Creating an empty enumeration to store        Enumeration enu = stack.elements();          System.out.println("The enumeration of values are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
The Stack is: [Geeks, 4, Geeks, Welcomes, You]
The enumeration of values are:
Geeks
4
Geeks
Welcomes
You

Program 2 :
import java.util.*;  public class Stack_Demo {    public static void main(String[] args)    {          // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Inserting elements into the table        stack.add(10);        stack.add(15);        stack.add(20);        stack.add(25);        stack.add(30);          // Displaying the Stack        System.out.println("The Stack is: " + stack);          // Creating an empty enumeration to store        Enumeration enu = stack.elements();          System.out.println("The enumeration of values are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
The Stack is: [10, 15, 20, 25, 30]
The enumeration of values are:
10
15
20
25
30

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Remote Procedure Call

Remote Procedure Call (RPC) system enables you to call a function available on a remote server using the same syntax which is used when calling a function in a local library. This is useful in two situations.
You can utilize the processing power from multiple machines using rpc without changing the code for making the call to the programs located in the remote systems.
The data needed for the processing is available only in the remote system.
So in python we can treat one machine as a server and another machine as a client which will make a call to the server to run the remote procedure. In our example we will take the localhost and use it as both a server and client. 
The python language comes with an in-built server which we can run as a local server. The script to run this server is located under the bin folder of python installation and named as classic.py. We can run it in the python prompt and check its running as a local server.
python bin/classic.py
When we run the above program, we get the following output −
INFO:SLAVE/18812:server started on [127.0.0.1]:18812


 Next we run the client using the rpyc module to execute a remote procedure call. In the below example we execute the print function in the remote server.
import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute("print('Hello from Tutorialspoint')")
When we run the above program, we get the following output −
Hello from Tutorialspoint

Using the above code examples we can use python’s in-built functions for execution and evaluation of expressions through rpc.
import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute('import math')
conn.eval('2*math.pi')
When we run the above program, we get the following output −
expr command in Linux with examples

15 May, 2019
The expr command in Unix evaluates a given expression and displays its corresponding output. It is used for:
Basic operations like addition, subtraction, multiplication, division, and modulus on integers.
Evaluating regular expressions, string operations like substring, length of strings etc.
Syntax:
$expr expression

Options:
Option –version : It is used to show the version information.Syntax:$expr --version
Example:
Syntax:
$expr --version

Example:
Option –help : It is used to show the help message and exit.Syntax:$expr --help
Example:
Syntax:
$expr --help

Example:
Below are some examples to demonstrate the use of “expr” command:
1. Using expr for basic arithmetic operations :
Example: Addition
$expr 12 + 8 

Example: Multiplication
$expr 12 \* 2

Output
Note:The multiplication operator * must be escaped when used in an arithmetic expression with expr.
2. Performing operations on variables inside a shell script
Example: Adding two numbers in a script
echo "Enter two numbers"

read x 

read y

sum=`expr $x + $y`

echo "Sum = $sum"

Output:
Note: expr is an external program used by Bourne shell. It uses expr external program with the help of backtick. The backtick(`) is actually called command substitution.
3. Comparing two expressions
Example:
x=10

y=20

# matching numbers with '='
res=`expr $x = $y`
echo $res

# displays 1 when arg1 is less than arg2
res=`expr $x \< $y`
echo $res

# display 1 when arg1 is not equal to arg2
res=`expr $x \!= $y`
echo $res

Output:
Example: Evaluating boolean expressions
# OR operation
$expr length  "geekss"  "<"  5  "|"  19  -  6  ">"  10

Output:
# AND operation
$expr length  "geekss"  "<"  5  "&"  19  -  6  ">"  10

Output:
4. For String operations
Example: Finding length of a string
x=geeks

len=`expr length $x`

echo $len

Output:
Example: Finding substring of a string
x=geeks

sub=`expr substr $x 2 3` 
#extract 3 characters starting from index 2

echo $sub

Output:
Example: Matching number of characters in two strings
$ expr geeks : geek

Output:
linux-command
Linux-Shell-Commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
How to create comma separated list from an array in PHP ?

31 Jul, 2021
The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.If we have an array of elements, we can use the implode() function to join them all to form one string. We basically join array elements with a string. Just like join() function , implode() function also returns a string formed from the elements of an array.
Syntax:
string implode( separator, array )

Return Type: The return type of implode() function is string. It will return the joined string formed from the elements of array.
Example 1: This example adds comma separator to the array elements.
<?php  // Declare an array and initialize it$Array = array( "GFG1", "GFG2", "GFG3" );  // Display the array elementsprint_r($Array);  // Use implode() function to join// comma in the array$List = implode(', ', $Array);  // Display the comma separated listprint_r($List);  ?>
Array
(
    [0] => GFG1
    [1] => GFG2
    [2] => GFG3
)
GFG1, GFG2, GFG3

Example 2:
<?php  // Declare an array and initialize it$Array = array(0, 1, 2, 3, 4, 5, 6, 7);  // Display the array elementsprint_r($Array);  // Use implode() function to join// comma in the array$List = implode(', ', $Array);  // Display the comma separated listprint_r($List);  ?>
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
)
0, 1, 2, 3, 4, 5, 6, 7

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.
Picked
PHP
PHP Programs
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
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?
How to call PHP function on the click of a Button ?
Wand shadow() function – Python

22 Aug, 2021
The shadow() function is an inbuilt function in the Python Wand ImageMagick library which is used to generates an image shadow.
Syntax:
shadow(alpha, sigma, x, y)
Parameters: This function accepts four parameters as mentioned above and defined below:
alpha: This parameter stores the ratio of the transparency.
sigma: This parameter stores the sigma level of the sharpen image.
x: This parameter stores the x-offset.
y: This parameter stores the y-offset.
Return Value: This function returns the Wand ImageMagick object.
Original Image:Example 1:
# Import library from Image from wand.image import Image  # Import the imagewith Image(filename ='../geeksforgeeks.png') as image:    # Clone the image in order to process    with image.clone() as shadow:        # Invoke shadow function        shadow.shadow(0.8, 0.2, 10, 40)        # Save the image        shadow.save(filename ='shadow1.jpg')
Output:
Example 2:
# Import libraries from the wand  from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color  with Drawing() as draw:    # Set Stroke color the circle to black    draw.stroke_color = Color('black')    # Set Width of the circle to 2     draw.stroke_width = 1    # Set the fill color to 'White (# FFFFFF)'    draw.fill_color = Color('white')      # Invoke Circle function with center at 50, 50 and radius 25    draw.circle((200, 200), # Center point                (100, 100)) # Perimeter point    # Set the font style    draw.font = '../Helvetica.ttf'    # Set the font size     draw.font_size = 30          with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic:        # Set the text and its location        draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !')        # Draw the picture        draw(pic)        # Invoke shadow function method         pic.shadow(0.3, .1, 1, 2)        # Save the image         pic.save(filename ='shadow2.jpg')
Output:
sagartomar9927
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sciPy stats.sem() function | Python

18 Feb, 2019
scipy.stats.sem(arr, axis=0, ddof=0) function is used to compute the standard error of the mean of the input data.
Parameters :arr : [array_like]Input array or object having the elements to calculate the standard error.axis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation.
Results : standard error of the mean of the input data.
Example:
# stats.sem() method import numpy as npfrom scipy import stats      arr1 = [[20, 2, 7, 1, 34],        [50, 12, 12, 34, 4]]  arr2 = [50, 12, 12, 34, 4]  print ("\narr1 : ", arr1)print ("\narr2 : ", arr2)  print ("\nsem ratio for arr1 : ",        stats.sem(arr1, axis = 0, ddof = 0))  print ("\nsem ratio for arr1 : ",        stats.sem(arr1, axis = 1, ddof = 0))  print ("\nsem ratio for arr1 : ",        stats.sem(arr2, axis = 0, ddof = 0)) 
Output :
arr1 :  [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]

arr2 :  [50, 12, 12, 34, 4]

sem ratio for arr1 :  [10.60660172  3.53553391  1.76776695 11.66726189 10.60660172]

sem ratio for arr1 :  [5.62423328 7.61892381]

sem ratio for arr1 :  7.618923808517841
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NumPy.histogram() Method in Python

16 Dec, 2021
A histogram is the best way to visualize the frequency distribution of a dataset by splitting it into small equal-sized intervals called bins. The Numpy histogram function is similar to the hist() function of matplotlib library, the only difference is that the Numpy histogram gives the numerical representation of the dataset while the hist() gives graphical representation of the dataset. 
Numpy has a built-in numpy.histogram() function which represents the frequency of data distribution in the graphical form. The rectangles having equal horizontal size corresponds to class interval called bin and variable height corresponding to the frequency.Syntax:
numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)
Attributes of the above function are listed below: 
The function has two return values hist which gives the array of values of the histogram, and edge_bin which is an array of float datatype containing the bin edges having length one more than the hist.Example:
Python3
# Import librariesimport numpy as np  # Creating dataseta = np.random.randint(100, size =(50)) # Creating histogramnp.histogram(a, bins = [0, 10, 20, 30, 40,                        50, 60, 70, 80, 90,                        100]) hist, bins = np.histogram(a, bins = [0, 10,                                     20, 30,                                     40, 50,                                     60, 70,                                     80, 90,                                     100]) # printing histogramprint()print (hist)print (bins)print()
Output: 
The above numeric representation of histogram can be converted into a graphical form.The plt() function present in pyplot submodule of Matplotlib takes the array of dataset and array of bin as parameter and creates a histogram of the corresponding data values.Example:
Python3
# import librariesfrom matplotlib import pyplot as pltimport numpy as np   # Creating dataseta = np.random.randint(100, size =(50)) # Creating plotfig = plt.figure(figsize =(10, 7)) plt.hist(a, bins = [0, 10, 20, 30,                    40, 50, 60, 70,                    80, 90, 100]) plt.title("Numpy Histogram") # show plotplt.show()
Output: 
as5853535
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw a Chessboard in Java Applet - GeeksforGeeks

22 Apr, 2022
Given task is to draw a Chessboard in Java Applet 
Approach:
Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess.As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE
Create a rectangle with length and breadth of 20 unit each, with 10 rows and columns of chess.
As soon as even position occurs in row and column change the color of a rectangle with BLACK, else it will be WHITE
Below is the implementation of the above approach: 
Applet Program: 
Java
import java.applet.*;import java.awt.*;/*<applet code="Chess" width=600 height=600></applet>*/// Extends Applet Classpublic class Chess extends Applet {     static int N = 10;     // Use paint() method    public void paint(Graphics g)    {        int x, y;        for (int row = 0; row & lt; N; row++) {             for (int col = 0; col & lt; N; col++) {                 // Set x coordinates of rectangle                // by 20 times                x = row * 20;                 // Set y coordinates of rectangle                // by 20 times                y = col * 20;                 // Check whether row and column                // are in even position                // If it is true set Black color                if ((row % 2 == 0) == (col % 2 == 0))                    g.setColor(Color.BLACK);                else                    g.setColor(Color.WHITE);                 // Create a rectangle with                // length and breadth of 20                g.fillRect(x, y, 20, 20);            }        }    }}
Output:
 
Note: To run the applet in command line use the following commands.
> javac Chess.java
> appletviewer Chess.java
You can also refer to: https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program.
java-applet
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples
How to delay a JavaScript function call using JavaScript?

To delay a function call, use setTimeout() function.
setTimeout(functionname, milliseconds, arg1, arg2, arg3...)
The following are the parameters −
functionname − The function name for the function to be executed.
milliseconds − The number of milliseconds.
arg1, arg2, arg3 − These are the arguments passed to the function.
You can try to run the following code to delay a JavaScript function call with a setTimeout() callback.
 Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="timeFunction()">Submit</button>
      <script>
         function timeFunction() {
            setTimeout(function(){ alert("After 5 seconds!"); }, 5000);
        }
</script>
<p>Click the above button and wait for 5 seconds.</p>
</body>
</html>
Is it mandatory to close JDBC connections?

At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects.
Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object.
To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not.
To close a JDBC connection, you should call close() method as:
conn.close();
How to cast a list of strings to a string array?

The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs.
You can convert a list to array using this method of the List class −
 Live Demo
import java.util.ArrayList;
import java.util.List;

public class ListOfStringsToStringArray {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      
      list.add("JavaFX");
      list.add("HBase");
      list.add("OpenCV");
      
      String[] myArray = new String[list.size()];
      
      list.toArray(myArray );
      System.out.println("Contents of the String array are :: ");

      for(int i = 0; i<myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}
Contents of the String array are ::
JavaFX
HBase
OpenCV
How do I use the conditional operator in C/C++?

This conditional operator is also known as the Ternary Operator. This operator has three phase.
Exp1 ? Exp2 : Exp3;
where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form
if(condition) {
   var = X;
} else {
     var = Y;
}
For example, consider the following code
if(y < 10) {
   var = 30;
} else {
  var = 40;
}
Above code can be rewritten like this
var = (y < 10) ? 30 : 40;
#include <iostream>
using namespace std;
int main () {
   // Local variable declaration:
   int x, y = 10;
   x = (y < 10) ? 30 : 40;
   cout << "value of x: " << x << endl;
   return 0;
}
value of x: 40
CONCAT() function in MySQL - GeeksforGeeks

07 Oct, 2020
CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. If a numeric argument is given then it is converted to its equivalent nonbinary string form.
Syntax :
CONCAT(str1, str2, ...)

Parameter : This method accepts N argument.  
str1, str2.str3.... : The input sting which we want to concatenate.
Returns : It returns a new string after concatenating all input string. If any of the input string is NULL then it returns NULL.
Example-1 :Concatenating 3 string using CONCAT Function.
SELECT CONCAT('geeks', 'for', 'geeks') AS ConcatenatedString ;

Output :
Example-2 :Concatenating numeric string using CONCAT Function.
SELECT CONCAT(19, 10, 5.60) AS ConcatenatedNumber ;

Output :
Example-3 :Concatenating string which includes a NULL String using CONCAT Function.
SELECT CONCAT('geeks', 'for', 'geeks', NULL) AS ConcatenatedString ;

Output :
Example-4 :In this example we are going to concatenate string between column of a table. To demonstrate create a table named Student.
CREATE TABLE Student(

StudentId INT AUTO_INCREMENT,  
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100) NOT NULL,
Class VARCHAR(20) NOT NULL,
City VARCHAR(20) NOT NULL,
State VARCHAR(20) NOT NULL,
PinNo INT  NOT NULL,
PRIMARY KEY(StudentId )

);

Now inserting some data to the Student table :
INSERT INTO  
Student(FirstName, LastName, Class, City, State, PinNo )
VALUES
('Sayantan', 'Maity', 'X', 'Kolkata', 'WestBengal', 700001 ),
('Nitin', 'Shah', 'XI', 'Jalpaiguri', 'WestBengal', 735102 ),
('Aniket', 'Sharma', 'XI', 'Midnapore', 'WestBengal', 721211 ),
('Abdur', 'Ali', 'X', 'Malda', 'WestBengal', 732101 ),
('Sanjoy', 'Sharama', 'X', 'Kolkata', 'WestBengal', 700004 ) ;

So, the Student table is :
Select * From Student ;

Now, we will concatenate FirstName and LastName to get FullName and City, State and PinNo to get Address using CONCAT Function.
Select 
    StudentId, FirstName, LastName, 
    CONCAT(FirstName, ' ', LastName) AS FullName,
    CONCAT(City, ' ', State, ' ', PinNO) AS Address

    FROM Student;    

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
Common string operations in Python

The string module in Python’s standard library provides following useful constants, classes and a helper function called capwords()
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'
This function performs following −
Splits the given string argument into words using str.split().
Splits the given string argument into words using str.split().
Capitalizes each word using str.capitalize()
Capitalizes each word using str.capitalize()
and joins the capitalized words using str.join().
and joins the capitalized words using str.join().
>>> text='All animals are equal. Some are more equal'
>>> string.capwords(text)
'All Animals Are Equal. Some Are More Equal'
Python’s built-in str class has format() method using which string can be formatted. Formatter object behaves similarly. This may be useful to write customized formatter class by subclassing this Formatter class.
>>> from string import Formatter
>>> f=Formatter()
>>> f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50)
'name:Rahul, age:30, marks:50'
This class is used to create a string template. It proves useful for simpler string substitutions.
>>> from string import Template
>>> text='My name is $name. I am $age years old'
>>> t=Template(text)
>>> t.substitute(name='Rahul', age=30)
'My name is Rahul. I am 30 years old'
What is the MySQL SELECT INTO Equivalent?

The SELECT INTO equivalent is CREATE TABLE AS SELECT statement. The syntax is as follows −
CREATE TABLE yourNewTableName AS SELECT *FROM yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table selectIntoEquivalentDemo
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20),
   -> ClientAge int
   -> );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into selectIntoEquivalentDemo(ClientName,ClientAge) values('Larry',34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into selectIntoEquivalentDemo(ClientName,ClientAge) values('Maxwell',44);
Query OK, 1 row affected (0.06 sec)
mysql> insert into selectIntoEquivalentDemo(ClientName,ClientAge) values('Bob',38);
Query OK, 1 row affected (0.07 sec)
mysql> insert into selectIntoEquivalentDemo(ClientName,ClientAge) values('David',39);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from selectIntoEquivalentDemo
Here is the output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
| 1        | Larry      | 34        |
| 2        | Maxwell    | 44        |
| 3        | Bob        | 38        |
| 4        | David      | 39        |
+----------+------------+-----------+
4 rows in set (0.00 sec)
The following is the query of SELECT INTO equivalent in MySQL −
mysql> create table Client_information AS select *from selectIntoEquivalentDemo;
Query OK, 4 rows affected (0.57 sec)
Records: 4 Duplicates: 0 Warnings: 0
Now let us check the table records from the new table. The query is as follows −
mysql> select *from Client_information;
Here is the output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
| 1        | Larry      | 34        |
| 2        | Maxwell    | 44        |
| 3        | Bob        | 38        |
| 4        | David      | 39        |
+----------+------------+-----------+
4 rows in set (0.00 sec)
HTML - <video> Tag

The HTML <video> tag is used to embed video into your web page, it has several video sources.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML video Tag</title>
   </head>

   <body>
      <p>Run your first program using an Online Compiler (compileonline.com)</p>
      <br />
      
      <video width = "500" height = "300" controls>
         <source src = "/html/compileonline.mp4" type = "video/mp4">
         This browser doesn't support video tag.
      </video>
   </body>

</html>
This will produce the following result −
Run your first program using an Online Compiler (compileonline.com)
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <video> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
ReactJS – Cleaning up with useEffect hook

In this article, we are going to see how to clean up the subscriptions set up in the useEffect hook in the functional component.
Once the effects are created, then they are needed to be cleaned up before the component gets removed from the DOM. For this, cleaning up effect is used to remove the previous useEffect hook’s effect before using this hook of the same component again.
useEffect(()=>{
   return ()=>{}
}
,[]);
In this example, we will build a React application which displays the coordinates of the mouse pointer when it is moved over the screen. For this to implement, we will write the code with both cleanup effects and without it.
Example
App.jsx
import React, { useEffect, useState } from 'react';

function App() {
   return (
      <div className="App">
      <Comp />
      </div>
   );
}

function Comp() {

   useEffect(() => {
      document.addEventListener('mousemove', mouseHandler);
   }, []);

   const mouseHandler = (e) => {
      console.log(e.clientX, e.clientY);
   };

   return (
      <div>
         <h1>Tutorialspoint</h1>
      </div>
   );
}
export default App;
In the above example, we are not removing the previous useEffect hook’s data, which is affecting the new data returned by this hook.
This will produce the following result.
Example
App.jsx
import React, { useEffect, useState } from 'react';

function App() {
   return (
      <div className="App">
         <Comp />
      </div>
   );
}

function Comp() {

   useEffect(() => {
      document.addEventListener('mousemove', mouseHandler);
      return () => {
         document.removeEventListener('mousemove', mouseHandler);
      };
   }, []);

   const mouseHandler = (e) => {
      console.log(e.clientX, e.clientY);
   };
   return (
      <div>
         <h1>Tutorialspoint</h1>
      </div>
   );
}
export default App;
In the above example, useEffect hook is called with the cleanup effect and thus, the effect of this hook will get removed every time the component gets destroyed.
This will produce the following result.
Java Examples - Extending an Array

How to extend an array after initialisation?
Following example shows how to extend an array after initialization by creating an new array.
public class Main {
   public static void main(String[] args) {
      String[] names = new String[] { "A", "B", "C" };
      String[] extended = new String[5];
      extended[3] = "D";
      extended[4] = "E";
      System.arraycopy(names, 0, extended, 0, names.length);
      
      for (String str : extended){
         System.out.println(str);
      }
   }
}
The above code sample will produce the following result.
A
B
C
D
E

The following is an another Sample example of arrays expansion
public class Main {
   public void extendArraySize() {
      String[] names = new String[] {"Sai", "Ram", "Krishna"};
      String[] extended = new String[5];
      extended[3] = "Prasad";
      extended[4] = "Mammahe";
      System.arraycopy(names, 0, extended, 0, names.length);
      
      for (String str : extended) System.out.println(str);
   } 
   public static void main(String[] args) {
      new Main().extendArraySize();
   }
}
The above code sample will produce the following result.
Sai
Ram
Krishna
Prasad
Mammahe

 Print
 Add Notes
 Bookmark this page
How to reset or change the MySQL root password?

To reset or change the root password, first we need to open MySQL in the Administrator mode. There, we can see all the users as well as the host. The following is the query −
mysql> USE mysql;
Database changed
mysql> SELECT user,host from user;
Here is the output.
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| John             | %         |
| Mac              | %         |
| Manish           | %         |
| mysql.infoschema | %         |
| mysql.session    | %         |
| mysql.sys        | %         |
| root             | %         |
| am               | localhost |
+------------------+-----------+
8 rows in set (0.00 sec)

Now, let us see the query to change the password.
mysql> ALTER USER 'root'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.13 sec)

mysql> ALTER USER 'Manish'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.14 sec)
As you saw above, ‘Manish’ is a root and we have altered the password. The above query works in MySQL 5.7.6 and higher versions.
To check if the password is reset or changed, we need to open the CMD and reach the directory in the system where the bin is present. Let us first try to login with the old password.
As you can see in the above screenshot, the previous password that has been reset or changed is tried. The same won’t work. Now, we will try to open MySQL with the new password i.e ‘123456’ and it works.
LISP - Do Construct

The do construct is also used for performing iteration using LISP. It provides a structured form of iteration.
The syntax for do statement −
(do ((variable1    value1   updated-value1)
      (variable2   value2   updated-value2)
      (variable3   value3   updated-value3)
   ...)
   (test return-value)
   (s-expressions)
)

The initial values of each variable is evaluated and bound to the respective variable. The updated value in each clause corresponds to an optional update statement that specifies how the values of the variables will be updated with each iteration.
After each iteration, the test is evaluated, and if it returns a non-nil or true, the return-value is evaluated and returned.
The last s-expression(s) is optional. If present, they are executed after every iteration, until the test value returns true.
Create a new source code file named main.lisp and type the following code in it −
(do ((x 0 (+ 2 x))
   (y 20 ( - y 2)))
   ((= x y)(- x y))
   (format t "~% x = ~d  y = ~d" x y)
)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
x = 0  y = 20
x = 2  y = 18
x = 4  y = 16
x = 6  y = 14
x = 8  y = 12


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Pascal - Arithmetic Operators

Following table shows all the arithmetic operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then −
The following example illustrates the arithmetic operators −
program calculator;
var
a,b,c : integer;
d: real;

begin
   a:=21;
   b:=10;
   c := a + b;
   
   writeln(' Line 1 - Value of c is ', c );
   c := a - b;
   
   writeln('Line 2 - Value of c is ', c );
   c := a * b;
   
   writeln('Line 3 - Value of c is ', c );
   d := a / b;
   
   writeln('Line 4 - Value of d is ', d:3:2 );
   c := a mod b;
   
   writeln('Line 5 - Value of c is ' , c );
   c := a div b;
   
      writeln('Line 6 - Value of c is ', c );
end.
Please note that Pascal is very strongly typed programming language, so it would give an error if you try to store the results of a division in an integer type variable. When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.10
Line 5 - Value of c is 1
Line 6 - Value of c is 2


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
SAS - DO WHILE Loop

This DO WHILE loop uses a WHILE condition. The SAS statements are repeatedly executed until the while condition becomes false.
DO WHILE (variable  condition);
. . . SAS statements . . . ;
END;

DATA MYDATA;
SUM = 0;
VAR = 1;
DO WHILE(VAR<6) ;
   SUM = SUM+VAR;
   VAR+1;
END;
   PROC PRINT;
   RUN;
When the above code is executed, it produces the following result



    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
MongoDB - Covered Queries

In this chapter, we will learn about covered queries.
As per the official MongoDB documentation, a covered query is a query in which −
All the fields in the query are part of an index.
All the fields returned in the query are in the same index.
Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents.
To test covered queries, consider the following document in the users collection −
{
   "_id": ObjectId("53402597d852426020000003"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "gender": "M",
   "name": "Tom Benzamin",
   "user_name": "tombenzamin"
}
We will first create a compound index for the users collection on the fields gender and user_name using the following query −
>db.users.createIndex({gender:1,user_name:1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
Now, this index will cover the following query −
>db.users.find({gender:"M"},{user_name:1,_id:0})
{ "user_name" : "tombenzamin" }
That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast.
Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above −
>db.users.find({gender:"M"},{user_name:1})
{ "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" }
Lastly, remember that an index cannot cover a query if −
Any of the indexed fields is an array
Any of the indexed fields is a subdocument

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Addition in Nested Tuples - Python - GeeksforGeeks

11 Nov, 2019
Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using zip() + nested generator expression
The combination of above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and summation logic is provided by generator expression.
# Python3 code to demonstrate working of# Addition in nested tuples# using zip() + nested generator expression  # initialize tuplestest_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Addition in nested tuples# using zip() + nested generator expressionres = tuple(tuple(a + b for a, b in zip(tup1, tup2))\      for tup1, tup2 in zip(test_tup1, test_tup2))  # printing resultprint("The resultant tuple after summation : " + str(res))
The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after summation : ((7, 10), (7, 14), (3, 10), (8, 13))

 
Method #2 : Using isinstance() + zip() + loop + list comprehensionThe combination of above functions can be used to perform this particular task. In this, we check for the nesting type and perform recursion. This method can give flexibility of more than 1 level nesting.
# Python3 code to demonstrate working of# Addition in nested tuples# using isinstance() + zip() + loop + list comprehension  # function to perform task def tup_sum(tup1, tup2):    if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):       return tuple(tup_sum(x, y) for x, y in zip(tup1, tup2))    return tup1 + tup2  # initialize tuplestest_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Addition in nested tuples# using isinstance() + zip() + loop + list comprehensionres = tuple(tup_sum(x, y) for x, y in zip(test_tup1, test_tup2))  # printing resultprint("The resultant tuple after summation : " + str(res))
The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after summation : ((7, 10), (7, 14), (3, 10), (8, 13))

Python tuple-programs
Python
Python Programs
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Copy Elements of One ArrayList to Another ArrayList with Java Collections Class

In order to copy elements of ArrayList to another ArrayList, we use the Collections.copy() method. It is used to copy all elements of a collection into another.
Declaration −The java.util.Collections.copy() method is declared as follows −
public static <T> void copy(List<? super T> dest,Lis<? extends T> src)
where src is the source list object and dest is the destination list object.
Let us see a program to copy elements of one ArrayList to Another ArrayList with Java Collections Class −
 Live Demo
import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<String> zoo = new ArrayList<String>();
      zoo.add("Zebra");
      zoo.add("Lion");
      zoo.add("Tiger");
      List<String> list = new ArrayList<String>();
      list.add("Hello");
      list.add("Hi");
      list.add("World");
      Collections.copy(list,zoo); // copying the ArrayList zoo to the ArrayList list
      System.out.println(list);
   }
}
Zebra, Lion, Tiger]
How to convert an integer to an ASCII value in Python?

ASCII character associated to an integer is obtained by chr() function. The argument for this function can be any number between 0 to 0xffff
>>> chr(0xaa)
'a'
>>> chr(0xff)
'ÿ'
>>> chr(200)
'È'
>>> chr(122)
'z'
How to identify the nth sub element using xpath?

We can identify the nth sub element using xpath in the following ways −
By adding square brackets with index.
By adding square brackets with index.
By using position () method in xpath.
By using position () method in xpath.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class SubElement {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // xpath using position() targeting the first element with type text
      driver.findElement(By.xpath("//input[@type='text'][position()=1]"))
      .click();
      driver.close();
   }
}
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class RowCount {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // xpath with index appended to get the data from the row 2 of table
      List<WebElement> rows =
      driver.findElements(By.xpath("//table/tbody/tr[2]/td"));
      System.out.println(“The number of data in row 2 is “+ rows.size());
      driver.close();
   }
}
How to change a column in an R data frame with some conditions?

Sometimes, the column value of a particular column has some relation with another column and we might need to change the value of that particular column based on some conditions. We need to make this change to check how the change in the values of a column can make an impact on the relationship between the two columns under consideration. In R, we can use single square brackets to make the changes in the column values.
Consider the below data frame −
> set.seed(1)
> x1<-rpois(20,5)
> x2<-rpois(20,2)
> x3<-runif(20,2,5)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 4 4 4.462839
2 4 1 3.941181
3 5 2 4.348798
4 8 0 3.659109
5 3 1 3.589159
6 8 1 4.368069
7 9 0 2.069994
8 6 1 3.431690
9 6 4 4.196941
10 2 1 4.078195
11 3 2 3.432859
12 3 2 4.583628
13 6 2 3.314291
14 4 1 2.734392
15 7 3 2.212037
16 5 2 2.298398
17 6 3 2.948815
18 11 0 3.555903
19 4 3 3.986015
20 7 2 3.220491
Suppose we want to subtract 2 from column 2 (x2) values if the column 3 values are greater than 3, then it can be done as shown below −
> df$x2[df$x3 > 3] <- (df$x2[df$x3 > 3] - 2)
> df
x1 x2 x3
1 4 -2.375000 4.462839
2 4 -2.562500 3.941181
3 5 -2.400000 4.348798
4 8 -2.281250 3.659109
5 3 -2.777778 3.589159
6 8 -2.265625 4.368069
7 9 0.000000 2.069994
8 6 -2.234568 3.431690
9 6 -2.277778 4.196941
10 2 -2.361111 4.078195
11 3 -3.000000 3.432859
12 3 -2.666667 4.583628
13 6 -2.666667 3.314291
14 4 1.000000 2.734392
15 7 3.000000 2.212037
16 5 2.000000 2.298398
17 6 3.000000 2.948815
18 11 -2.388889 3.555903
19 4 -2.437500 3.986015
20 7 -2.285714 3.220491
If we want to multiple column 1 (x1) values to 2 for the values where x3 is less than 3 then it can be done as shown below −
> df$x1[df$x3 < 3] <- (df$x1[df$x3 < 3]*2)
> df
x1 x2 x3
1 4 -1.0937500 4.462839
2 4 -1.1406250 3.941181
3 5 -0.8800000 4.348798
4 8 -0.5351562 3.659109
5 3 -1.5925926 3.589159
6 8 -0.5332031 4.368069
7 18 0.0000000 2.069994
8 6 -0.4705075 3.431690
9 6 -0.7129630 4.196941
10 2 -0.7268519 4.078195
11 3 -2.5000000 3.432859
12 3 -1.5555556 4.583628
13 6 -1.5555556 3.314291
14 8 1.0000000 2.734392
15 14 3.0000000 2.212037
16 10 2.0000000 2.298398
17 12 3.0000000 2.948815
18 11 -0.7314815 3.555903
19 4 -1.1093750 3.986015
20 7 -0.6122449 3.220491