code-rag-bench/online-tutorials huggingface dataset:
Remove Consecutive Duplicates in Python

Suppose we have a string s, this string consisting of "R" and "L", we have to remove the
minimum number of characters such that there's no consecutive "R" and no consecutive "L".
So, if the input is like "LLLRLRR", then the output will be "LRLR"
To solve this, we will follow these steps −
seen := first character of s
ans := first character of s
for each character i from index 1 to end of s, doif i is not same as seen, thenans := ans + iseen := i
if i is not same as seen, thenans := ans + iseen := i
ans := ans + i
seen := i
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s):
      seen = s[0]
      ans = s[0]
      for i in s[1:]:
         if i != seen:
            ans += i
            seen = i
      return ans
ob = Solution()
print(ob.solve("LLLRLRR"))
"LLLRLRR"
LRLR
Java 12 - String methods

Java 12 introduces following new methods to String for easy formatting.
Adjust the indention of each line of string based on argument passed.
string.indent(n)

n > 0 - insert space at the begining of each line.
n > 0 - insert space at the begining of each line.
n < 0 - remove space at the begining of each line.
n < 0 - remove space at the begining of each line.
n < 0 and n < available spaces - remove all leading space of each line.
n < 0 and n < available spaces - remove all leading space of each line.
n = 0 - no change.
n = 0 - no change.
Transforms a string to give result as R.
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());

Returns Optional Object containing description of String instance.
Optional<String> optional = message.describeConstable();

Returns descriptor instance string of given string.
String constantDesc = message.resolveConstantDesc(MethodHandles.lookup());

Consider the following example −
ApiTester.java
import java.lang.invoke.MethodHandles;
import java.util.Optional;

public class APITester {
   public static void main(String[] args) {
      String str = "Welcome \nto Tutorialspoint!";
      System.out.println(str.indent(0));
      System.out.println(str.indent(3));

      String text = "Java";
      String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
      System.out.println(transformed);

      Optional<String> optional = text.describeConstable();
      System.out.println(optional);

      String cDescription = text.resolveConstantDesc(MethodHandles.lookup());
      System.out.println(cDescription);
   }
}
Welcome 
to Tutorialspoint!

   Welcome 
   to Tutorialspoint!

avaJ
Optional[Java]
Java


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
MySQL SELECT query to return records with specific month and year

For specific month, use MONTH() and for year, use YEAR() method. Let us first create a table −
mysql> create table DemoTable
(
   StudentName varchar(40),
   StudentAdmissionDate date
);
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','2019-01-21');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Robert','2018-09-05');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Mike','2019-09-05');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('David','2019-10-04');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Chris       | 2019-01-21           |
| Robert      | 2018-09-05           |
| Mike        | 2019-09-05           |
| David       | 2019-10-04           |
+-------------+----------------------+
4 rows in set (0.00 sec)
Following is the query to return records with specific month and year −
mysql> select *from DemoTable where month(StudentAdmissionDate)=09 and year(StudentAdmissionDate)=2019;
This will produce the following output −
+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Mike        | 2019-09-05           |
+-------------+----------------------+
1 row in set (0.00 sec)
Refresh page after clearing all form fields in jQuery?

To refresh page, use the location.reload() in JavaScript. The sample JavaScript code is as follows −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<form>
<label for="userId">
UserName:
<input type="text" >
</label>
<br>
<label for="pass">
Password:
<input type="password" >
</label>
<br>
<button type="submit" id="RefreshPage" >Refresh Page</button>
</form>
<script>
   $('#RefreshPage').click(function() {
      location.reload();
   });
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
After filling the form, the snapshot is as follows −
When you click the button “Refresh Page”, the page will refresh and the following output is
visible −
Python | Check if element exists in list of lists

20 Mar, 2019
Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task.Method #1: Using any()
any() method return true whenever a particular element is present in a given iterator.
# Python code to demonstrate# finding whether element# exists in listof list  # initialising nested listsini_list = [[1, 2, 5, 10, 7],            [4, 3, 4, 3, 21],            [45, 65, 8, 8, 9, 9]]  elem_to_find = 8elem_to_find1 = 0  # element exists in listof listor not?res1 = any(elem_to_find in sublist for sublist in ini_list)res2 = any(elem_to_find1 in sublist for sublist in ini_list)  # printing resultprint(str(res1), "\n", str(res2))
True 
 False

 Method #2: Using operator in
The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.
# Python code to demonstrate# finding whether element# exists in listof list  # initialising nested listsini_list = [[1, 2, 5, 10, 7],            [4, 3, 4, 3, 21],            [45, 65, 8, 8, 9, 9]]  elem = 8elem1 = 0  # element exists in listof listor not?res1 = elem in (item for sublist in ini_list for item in sublist)res2 = elem1 in (item for sublist in ini_list for item in sublist)  # printing resultprint(str(res1), "\n", str(res2))
True 
 False

 Method #3: Using itertools.chain()
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.
# Python code to demonstrate# finding whether element# exists in listof listfrom  itertools import chain  # initialising nested listsini_list = [[1, 2, 5, 10, 7],             [4, 3, 4, 3, 21],            [45, 65, 8, 8, 9, 9]]  elem_to_find = 8elem_to_find1 = 0  # element exists in listof listor not?res1 = elem_to_find in chain(*ini_list)res2 = elem_to_find1 in chain(*ini_list)  # printing resultprint(str(res1), "\n", str(res2))
True 
 False

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Pascal - if-then Statement

The if-then statement is the simplest form of control statement, frequently used in decision making and changing the control flow of the program execution.
Syntax for if-then statement is −
if condition then S

Where condition is a Boolean or relational condition and S is a simple or compound statement. Example of an if-then statement is −
if (a <= 20) then
   c:= c+1;
If the boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end;) will be executed.
Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil, then it is assumed as false value.
Let us try a complete example that would illustrate the concept −
program ifChecking;

var
{ local variable declaration }
   a:integer;

begin
   a:= 10;
   (* check the boolean condition using if statement *)
   
   if( a < 20 ) then
      (* if condition is true then print the following *) 
      writeln('a is less than 20 ' );
   writeln('value of a is : ', a);
end.
When the above code is compiled and executed, it produces the following result −
a is less than 20
value of a is : 10


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to plot a wav file using Matplotlib?

To plot a .wav file using matplotlib, we can take following the steps −
To read a .wav file, we can use the read() method.
To read a .wav file, we can use the read() method.
After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data.
After reading the .wav file, we will get a tuple. At the 0 th index, rate would be there and at the 1st index, array sample data.
Use the plot() method to plot the .wav file.
Use the plot() method to plot the .wav file.
Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively.
Set y and x labels using ylabel and xlabel with “Amplitude” and “Time” label, respectively.
To display the figure, use the show() method.
To display the figure, use the show() method.
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
input_data = read("my_audio.wav")
audio = input_data[1]
plt.plot(audio[0:1024])
plt.ylabel("Amplitude")
plt.xlabel("Time")
plt.show()
Count Hexadecimal Number in C++

We are given a range having start and end and the task is to calculate the count of
hexadecimal numbers or alphabets present in the given range.
In computer terms, hexadecimal numbers are those numbers that are having base 16
which means the binary digit can be represented in 16-bit. It consists of integer numbers
starting from 0-15. Where 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E
and 15 as F.
So, in the below program our task is to find whether the range consists of hexadecimal
alphabets or not.
Input − start = 10, End = 13
Output − 4
Explanation − There are 4 hexadecimal numbers between 10 and 13 i.e. 10 being A, 11 being B, 12 being C and 13 being D.
Input − start = 15, End = 16
Output − 1
Explanation − There is only one hexadecimal alphabet i.e. 15 as F and 16 is represented as 10 respectively.
Input the range starting from variable let’s say, start and end.
Input the range starting from variable let’s say, start and end.
Declare a variable count to store the count and initialises it with 0
Declare a variable count to store the count and initialises it with 0
Start a loop for with i to start and till i is less than or equals to end
Start a loop for with i to start and till i is less than or equals to end
Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1
Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1
Else, check if i is greater than 15
Else, check if i is greater than 15
Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0
Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0
And check if k%16 is greater than or equals to 10
And check if k%16 is greater than or equals to 10
Increase the count by 1
Increase the count by 1
and , set the temp by temp/16
and , set the temp by temp/16
Return the value of count
Return the value of count
Print the result .
Print the result .
 Live Demo
#include <iostream>
using namespace std;
// Function to count the
// total number hexadecimal alphabet
int counthexa(int start, int end){
   int result = 0;
   for (int i = start; i <= end; i++){
      // All hexadecimal alphabets
      // from 10 to 15
      if (i >= 10 && i <= 15){
         result++;
      }
      // If i > 15 then perform mod by 16 repeatedly
      // till the number is > 0
      // If number % 16 > 10 then increase count
      else if (i > 15){
         int k = i;
         while (k != 0){
            if (k % 16 >= 10){
               result++;
            }
            k = k / 16;
         }
      }
   }
   return result;
}
// Main Function
int main(){
   int start = 10, end = 60;
   cout << "count is: "<<counthexa(start, end);
   return 0;
}
If we run the above code it will generate the following output −
count is: 21
Console.SetError() Method in C# - GeeksforGeeks

11 Mar, 2019
The Console.SetError(TextWriter) Method sets the Error property of the specified StreamWriter i.e., it redirects the standard error stream to a file. As the console is set with this StreamWriter object, the WriteLine() method can be called to write the error into the file.
Syntax: public static void SetError (System.IO.StreamWriter newError);
Parameter:newError: It is a stream which is the new standard error output.
Exception: This method will throw the ArgumentNullException if the parameter passed is null. Also, since it uses the StreamWriter object, it’s exceptions should also be taken care of.
Example: In this example, the SetError() method is used to set the StreamWriter object to the console, and the error messages will be written into a log file from the Console.
// C# program to demonstrate // the SetError() methodusing System;using System.IO;  class GFG {      // Main Method    static void Main()    {        // Define file to receive error stream.        string fn = "F:\\gfg_error.log";          // Define the new error StreamWriter object        StreamWriter errStream = new StreamWriter(fn);          // Redirect standard error stream to file.        Console.SetError(errStream);          // Write the error message into the Log file        Console.Error.WriteLine("Error line is written into the log file.");        Console.Error.WriteLine("Keep coding geeks!");          // Close redirected error stream.        Console.Error.Close();    }}
Output: The gfg_error.log file will now have the error messages in it.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.seterror?view=netframework-4.7.2#System_Console_SetError_System_IO_TextWriter_
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
What is the meaning of invalid literal for int() with base = ' '? - GeeksforGeeks

20 Aug, 2020
ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError.
Example 1 : ValueError with base 10.
# ValueError caused by conversion of # String representation of float to intint('23.5')
Output :
ValueError: invalid literal for int() with base 10: '23.5'
One can think that while executing the above code, the decimal part ‘.5’ should be truncated and the code should give output as 23 only. But the point to be noted is that the int( ) function uses the decimal number system as its base for conversion ie. base = 10 is the default value for conversion. And in the decimal number system, we have numbers from 0 to 9 excluding the decimal (.) and other characters(alphabets and special chars). Therefore, int() with base = 10 can only convert a string representation of int and not floats or chars.
We can first convert the string representation of float into float using float() function and then convert it into an integer using int().
print(int(float('23.5')))
Output :
23
Example 2 : Passing alphabets in int().
int('abc')
Output :
invalid literal for int() with base 10: 'abc'
The chars a, b, c, d, e, and f are present in the base =16 system and therefore only these chars along with digits 0 to 9 can be converted from their string representation to integer in hexadecimal form. We have to pass an parameter base with value 16.
print(int('abc', base = 16))
Output :
2748
python-string
Program Output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java Program | Set 11
Output of C++ programs | Set 34 (File Handling)
Output of Java program | Set 28
Output of Java Programs | Set 12
Output of Java Programs | Set 48 (Static keyword)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Program to Find and Print Address of Variable - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to find and print the address of the Python variable. 
It can be done in these ways:
Using id() function
Using addressof() function
Using hex() function
We can get an address using id() function, id() function gives the address of the particular object.
Syntax: id(object)
where, object is the data variables.
Here we are going to find the address of the list, variable, tuple and dictionary.
Python3
# get id of lista = [1, 2, 3, 4, 5]print(id(a))  # get id of a variablea = 12print(id(a))  # get id of tuplea = (1, 2, 3, 4, 5)print(id(a))  # get id of a dictionarya = {'a' : 1, 'b' : 2}print(id(a))
Output:
140234866534752
94264748411744
140234904267376
140234866093264
we can also get memory addresses using these functions, ctypes is a foreign function library for Python. It provides C-compatible data types and allows calling functions in DLLs or shared libraries.
Syntax:addressof(c_int(object))
where object is the data variables
Python3
# import addressof,# c_int modules from ctypes modulefrom ctypes import c_int, addressof  # get memory address of variablea = 44print(addressof(c_int(a)))
Output:
140234866278064
Here we will call the hex(address) function, to convert the memory address to hexadecimal representation.
Syntax: hex(id(object))
where,
hex() is the memory hexadecimal representation to the address
id is used to get the memory of the object
object is the data
Python3
# get id of list in hexadecimal representationa = [1, 2, 3, 4, 5]print(hex(id(a)))  # get id of a variable in hexadecimal representationa = 12print(hex(id(a)))  # get id of tuple in hexadecimal representationa = (1, 2, 3, 4, 5)print(hex(id(a)))  # get id of a dictionary in hexadecimal representationa = {'a': 1,'b' : 2}print(hex(id(a)))
Output:
0x7fba9b0ae8c0
0x5572da858b60
0x7fba9f3c4a10
0x7fba9b05b8c0
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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()
Python | Extract length of longest string in list - GeeksforGeeks

29 Nov, 2019
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using max() + generator expressionThe combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return maximum of them using max().
# Python3 code to demonstrate working of# Extracting length of longest string in list# using max() + generator expression  # initialize list test_list = ['gfg', 'is', 'best']  # printing original list print("The original list : " + str(test_list))  # Extracting length of longest string in list# using max() + generator expressionres = max(len(ele) for ele in test_list)  # printing resultprint("Length of maximum string is : " + str(res))
The original list : ['gfg', 'is', 'best']
Length of maximum string is : 4

 
Method #2 : Using len() + key argument + max()The combination of above functions can be used to perform this task. In this, we extract the maximum length using len() and max(). It is faster than above method as it performs more task built in rather than overhead by generator expression.
# Python3 code to demonstrate working of# Extracting length of longest string in list# using len() + key argument + max()  # initialize list test_list = ['gfg', 'is', 'best']  # printing original list print("The original list : " + str(test_list))  # Extracting length of longest string in list# using len() + key argument + max()res = len(max(test_list, key = len))  # printing resultprint("Length of maximum string is : " + str(res))
The original list : ['gfg', 'is', 'best']
Length of maximum string is : 4

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
Convert Decimal to the equivalent 64-bit unsigned integer in C#

To convert the value of the specified Decimal to the equivalent 64-bit unsigned integer, the code is as follows −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      Decimal val = 99.29m;
      Console.WriteLine("Decimal value = "+val);
      ulong res = Decimal.ToUInt64(val);
      Console.WriteLine("64-bit unsigned integer = "+res);
   }
}
This will produce the following output −
Decimal value = 99.29
64-bit unsigned integer = 99
Let us see another example −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      Decimal val = 0.001m;
      Console.WriteLine("Decimal value = "+val);
      ulong res = Decimal.ToUInt64(val);
      Console.WriteLine("64-bit unsigned integer = "+res);
   }
}
This will produce the following output −
Decimal value = 0.001
64-bit unsigned integer = 0
What is Bitwise XOR Operator (^) in JavaScript?

It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
You can try to run the following code to learn how to work with Bitwise XOR Operator
Live Demo
<html>
   <body>
      <script>
         <!--
         var a = 2;   // Bit presentation 10
         var b = 3;  // Bit presentation 11
         document.write("(a ^ b) => ");
         result = (a ^ b);
         document.write(result);
      </script>
   </body>
</html>
Console Class in C#

14 Mar, 2019
A console is an operating system window through which a user can communicate with the operating system or we can say a console is an application in which we can give text as an input from the keyboard and get the text as an output from the computer end. The command prompt is an example of a console in the windows and which accept MS-DOS commands. The console contains two attributes named as screen buffer and a console window.In C#, the Console class is used to represent the standard input, output, and error streams for the console applications. You are not allowed to inherit Console class. This class is defined under System namespace. This class does not contain any constructor. Instead of the constructor, this class provides different types of properties and methods to perform operations.
Example:
// C# program to illustrate how to get// Background and Foreground color// of the consoleusing System;  public class GFG {      static public void Main()    {          // Get the Background and foreground         // color of Console Using BackgroundColor        // and ForegroundColor property of Console        Console.WriteLine("Background color  :{0}",                        Console.BackgroundColor);          Console.WriteLine("Foreground color : {0}",                         Console.ForegroundColor);    }}
Background color : Black
Foreground color : Black

Example:
// C# program to illustrate the concept// of WriteLine(String) method in consoleusing System;  public class GFG {      static public void Main()    {          // WriteLine(String) method is used         // to display the string        Console.WriteLine("Welcome to GeeksforGeeks");        Console.WriteLine("This is a tutorial of Console Class");    }}
Welcome to GeeksforGeeks
This is a tutorial of Console Class

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console?view=netframework-4.7.2#definition
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack firstElement() method in Java with Example

24 Dec, 2018
The Java.util.Stack.firstElement() method in Java is used to retrieve or fetch the first element of the Stack. It returns the element present at the 0th index of the Stack
Syntax:
Stack.firstElement()
Parameters: The method does not take any parameter.
Return Value: The method returns the first element present in the Stack.
Below programs illustrate the Java.util.Stack.firstElement() method:
Program 1:
// Java code to illustrate firstElement()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements into the Stack        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("4");        stack.add("Geeks");          // Displaying the Stack        System.out.println("Stack: " + stack);          // Displaying the first element        System.out.println("The first element is: "                           + stack.firstElement());    }}
Stack: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome

Program 2:
// Java code to illustrate firstElement()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Use add() method to add elements into the Stack        stack.add(10);        stack.add(15);        stack.add(30);        stack.add(20);        stack.add(5);          // Displaying the Stack        System.out.println("Stack: " + stack);          // Displaying the first element        System.out.println("The first element is: "                           + stack.firstElement());    }}
Stack: [10, 15, 30, 20, 5]
The first element is: 10

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.
MoviePy – Resizing Video File

29 Dec, 2021
In this article, we will see how we can resize video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Resizing video files means. Image/frame interpolation occurs when you resize or distort your frame of video from one-pixel grid to another. Video resizing is necessary when we need to increase or decrease the total number of pixels, whereas remapping can occur when you are correcting for lens distortion or rotating a video.
In order to do this we will use resize method with the VideoFileClip object
Syntax : clip.resize(n)
Argument : It takes float value i.e multiplier 
Return : It returns VideoFileClip object  
Below is the implementation  
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro video# and getting only first 5 secondsclip1 = VideoFileClip("dsa_geek.webm").subclip(0, 5) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print("Width x Height of clip 1 : ", end = " ")print(str(w1) + " x ", str(h1)) print("---------------------------------------") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print("Width x Height of clip 2 : ", end = " ")print(str(w2) + " x ", str(h2)) print("---------------------------------------") # showing final clipclip2.ipython_display(width = 480)
Output : 
Width x Height of clip 1 :  854 x  480
---------------------------------------
Width x Height of clip 2 :  427 x  240
---------------------------------------
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4


Moviepy - Done !
Moviepy - video ready __temp__.mp4 
Another example  
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclipclip1 = clip.subclip(0, 7) # getting width and height of clip 1w1 = clip1.wh1 = clip1.h print("Width x Height of clip 1 : ", end = " ")print(str(w1) + " x ", str(h1)) print("---------------------------------------") # resizing video downsize 50 %clip2 = clip1.resize(0.5) # getting width and height of clip 1w2 = clip2.wh2 = clip2.h print("Width x Height of clip 2 : ", end = " ")print(str(w2) + " x ", str(h2)) print("---------------------------------------") # showing final clipclip2.ipython_display()
Output : 
Width x Height of clip 1 :  656 x  404
---------------------------------------
Width x Height of clip 2 :  328 x  202
---------------------------------------
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3

MoviePy - Done.
Moviepy - Writing video __temp__.mp4


Moviepy - Done !
Moviepy - video ready __temp__.mp4
sagarkarn9
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make a placeholder for a ‘select’ box?

04 Jan, 2022
There is no placeholder attribute in ‘select’ tag but it can make the placeholder for a ‘select’ box. There are many ways to create the placeholder for a ‘select’ box.
Example 1:
html
<!DOCTYPE html><html>    <head>        <title>make placeholder</title>        <style>            body {                border:black;                justify-content: center;                text-align: center;            }            div {                max-width: 18em;            }            h1 {                color:green;            }            select {                margin-left:130px;            }        </style>    </head>    <body>        <h1>GeeksforGeeks<h1>        <div include="form-input-select()">            <select required>                <option value="">Example Placeholder</option>                                  <!-- Available Options -->                <option value="1">GeeksforGeeks</option>                <option value="2">w3skul</option>                <option value="3">tuitorial point</option>                <option value="4">CodeComunity</option>                <option value="5">Coders</option>                </select>        </div>    </body></html>                     
Example 2: Using JavaScript to create placeholder in select box.
html
<!DOCTYPE html><html>    <head>        <script type="text/javascript">            function populate(s, s1) {                var s = document.getElementById(s);                var s1 = document.getElementById(s1);                s1.innerHTML = "";                if(s.value == "Database") {                    var arr = ["|Select","mysql|MySQL","oracle|Oracle"];                }                for(var option in arr) {                    var pair = arr[option].split("|");                    var new_op = document.createElement("option");                    new_op.value = pair[0];                    new_op.innerHTML = pair[1];                    s1.options.add(new_op);                }            }        </script>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>Choose Subject:</h2>        <select id = "slct" name = "slct"            onchange = "populate(this.id, 'slct1')">            <option value="">Select</option>            <option value="Database">Database</option>            <option value="Java">Java</option>            <option value="Python">Python</option>        </select>        <h2>Choose topics:</h2>        <select id = "slct1" name = "slct1"></select>    </body></html>                                        
sumitgumber28
Picked
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get HTML content of an iFrame using JavaScript ?

05 Jun, 2020
The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document.
Code snippet:
function getIframeContent(frameId) {
    var frameObj = 
        document.getElementById(frameId);

    var frameContent = frameObj.
        contentWindow.document.body.innerHTML;
        
    alert("frame content : " + frameContent);
}

Some of the definitions are given below:
getIframeContent(frameId): It is used to get the object reference of an iframe.
contentWindow: It is a property which returns the window object of the iframe.
contentWindow.document: It returns the document object of iframe window.
contentWindow.document.body.innerHTML: It returns the HTML content of iframe body.
Example: The following example demonstrates to include separate HTML file into existing document.
<!DOCTYPE html><html>  <head>    <title>        How to get HTML content of         an iFrame using javascript?    </title></head>  <body>    <iframe id="frameID" src=        "ContentOfFrame.html">    </iframe>      <a href="#" onclick=        "getIframeContent('frameID');">        Get the content of Iframe    </a>      <script>        function getIframeContent(frameID) {            var frameObj =                 document.getElementById(frameID);            var frameContent = frameObj                .contentWindow.document.body.innerHTML;              alert("frame content : " + frameContent);        }    </script></body>  </html>
ContentOfFrame.html The following example demonstrates the HTML code content of file “ContentOfFrame.html”
<!DOCTYPE html><html>  <body>    GeeksForGeeks: A Computer     Science Portal For Geeks    (It is loaded inside the     iframe)</body>  </html>
Output:
Before clicking the link:
After clicking the link:
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove all leading zeros in a string in PHP ?

20 Sep, 2019
Given a number in string format and the task is to remove all leading zeros from the given string in PHP.
Examples:
Input : str = 00006665555
Output : 6665555

Input : str = 00775505
Output : 775505

Method 1: Using ltrim() function: The ltrim() function is used to remove whitespaces or other characters (if specified) from the left side of a string.
Syntax:
ltrim( "string", "character which to be remove from the left side of string");
Program:
<?php  // Store the number string with// leading zeros into variable$str = "00775505";  // Passing the string as first// argument and the character// to be removed as second// parameter$str = ltrim($str, "0");           // Display the resultecho $str;  ?>
775505

Method 2: First convert the given string into number typecast the string to int which will automatically remove all the leading zeros and then again typecast it to string to make it string again.
Program:
<?php  // Store the number string with// leading zeros into variable$str = "00775505";  // First typecast to int and // then to string$str = (string)((int)($str));          // Display the resultecho $str;  ?>
775505

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS ::before selector - GeeksforGeeks

02 Nov, 2021
The ::before selector CSS pseudo-element, is used to add the same content multiple times before the content of other elements. This selector is the same as ::after selector. It helps to create the pseudo-element that represents the first child of the selected element & is generally used for adding decorative content to an element using the content property. Its default value is inline.
Syntax:
::before{
        content:
}
Example: The below HTML/CSS code shows the functionality of ::before selector.
HTML
<!DOCTYPE html><html>  <head>    <style>    p::before {        content: " - Remember this";        background-color: blue;    }    </style></head>  <body>    <h3>Before Selector</h3>    <p>User ID: @dmor1</p>      <p>Name: dharam</p>  </body>  </html>
Output:
Supported Browsers:
Google Chrome 4.0
Edge 12.0
Internet Explorer 9.0
Firefox 3.5
Safari 3.1
Opera 7.0
Note: Internet Explorer 8 and Opera 4-6 supports with single-colon.(::before). 
arorakashish0911
bhaskargeeksforgeeks
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
vars() function in Python - GeeksforGeeks

13 Feb, 2022
This is an inbuilt function in Python. The vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be can a module, a class, an instance, or any object having __dict__ attribute. Syntax:  
vars(object)
The method returns the __dict__ attribute for a module, class, instance, or any other object if the same has a __dict__ attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable __dict__ attribute however, other objects may have written restrictions on their __dict__ attributes. vars() acts like locals() method when an empty argument is passed which implies that the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.  
Python3
# Python program to illustrate# working of vars() method in Python class Geeks:  def __init__(self, name1 = "Arun", num2 = 46, name3 = "Rishab"):    self.name1 = name1    self.num2 = num2    self.name3 = name3   GeeksforGeeks = Geeks()print(vars(GeeksforGeeks))
Output:  
{'num2': 46, 'name1': 'Arun', 'name3': 'Rishab'}
 
Python3
# Python program to illustrating# the use of vars() and locals# when no argument is passed and# how vars() act as locals().class Geeks(object):    def __init__(self):        self.num1 = 20        self.num2 = "this is returned"     def __repr__(self):        return "Geeks() is returned"     def loc(self):        ans = 21        return locals()         # Works same as locals()    def code(self):        ans = 10        return vars()     def prog(self):        ans = "this is not printed"        return vars(self)      if __name__ == "__main__":    obj = Geeks()    print (obj.loc())    print (obj.code())    print (obj.prog())
Output:  
{'ans': 21, 'self': Geeks() is returned}
{'ans': 10, 'self': Geeks() is returned}
{'num1': 20, 'num2': 'this is returned'}
 
adnanirshad158
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How To Convert Python Dictionary To JSON?
BufferedWriter flush() method in Java with Examples - GeeksforGeeks

28 May, 2020
The flush() method of BufferedWriter class in Java is used to flush the characters from the buffered writer stream.
Syntax:
public void flush()
            throws IOException

Specified By: This method is specified by the flush() method of Flushable interface.
Overrides: This method overrides the flush() method of Writer class.
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate flush() method in BufferedWriter class in IO package:
Program 1:
// Java program to illustrate// BufferedWriter flush() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws IOException    {          // Create the string Writer        StringWriter stringWriter            = new StringWriter();          // Convert stringWriter to        // bufferedWriter        BufferedWriter buffWriter            = new BufferedWriter(                stringWriter);          // Write "GEEKS" to buffer writer        buffWriter.write(            "GEEKSFORGEEKS", 0, 5);          // Flush the buffer writer        buffWriter.flush();          System.out.println(            stringWriter.getBuffer());    }}
GEEKS

Program 2:
// Java program to illustrate// BufferedWriter flush() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws IOException    {        // Create the string Writer        StringWriter stringWriter            = new StringWriter();          // Convert stringWriter to        // bufferedWriter        BufferedWriter buffWriter            = new BufferedWriter(                stringWriter);          // Write "GEEKS" to buffered writer        buffWriter.write(            "GEEKSFORGEEKS", 0, 5);          // Flush the buffered writer        buffWriter.flush();          System.out.println(            stringWriter.getBuffer());          // Write "GEEKSFORGEEKS"        // to buffered writer        buffWriter.write(            "GEEKSFORGEEKS", 5, 8);          // Flush the buffered writer        buffWriter.flush();          System.out.println(            stringWriter.getBuffer());    }}
GEEKS
GEEKSFORGEEKS

References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#flush()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java
Count no. of characters and words in a string in PL/SQL - GeeksforGeeks

05 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a string and the task is to count the number of characters and words in the given string.Examples:
Input: str = 'Geeks for geeks '
Output: Characters = 13 , Words = 3

Input: str = 'A Computer science portal'
Output: Characters = 22, Words = 4

Approach is to maintain two counter variables i.e. one for the characters and the other for words. Start traversing character one by one and increment the count and when there is a blank space then increment the count of words.Below is the required implementation:
DECLARE     -- Declare required variables     str       VARCHAR2(40) := 'Geeks for Geeks';     noofchars NUMBER(4) := 0;     noofwords NUMBER(4) := 1;     s         CHAR; BEGIN     FOR i IN 1..Length(str) LOOP         s := Substr(str, i, 1);           -- Count no. of characters         noofchars := noofchars + 1;           -- Count no. of words         IF s = ' ' THEN           noofwords := noofwords + 1;         END IF;     END LOOP;       dbms_output.Put_line('No. of characters:'                          ||noofchars);       dbms_output.Put_line('No. of words: '                          ||noofwords); END; -- Program End  
Output :
No. of characters:15
No. of words: 3

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DELETE, DROP and TRUNCATE
SQL | Views
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
How to Create a Table With Multiple Foreign Keys in SQL?
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
Aggregate functions in SQL - GeeksforGeeks

20 Aug, 2019
In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning.
 
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
 
Now let us understand each Aggregate function with a example:
Id     Name     Salary
-----------------------
1       A        80
2       B        40
3       C        60
4       D        70
5       E        60
6       F        Null

 
Count():
 
Count(*): Returns total number of records .i.e 6.Count(salary): Return number of Non Null values over the column salary. i.e 5.Count(Distinct Salary):  Return number of distinct Non Null values over the column salary .i.e 4
 
Sum():
 
sum(salary):  Sum all Non Null values of Column salary i.e., 310sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.
 
Avg():
 
Avg(salary) = Sum(salary) / count(salary) = 310/5Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
 
Min():
 
Min(salary): Minimum value in the salary column except NULL i.e., 40.Max(salary): Maximum value in the salary i.e., 80.
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
CTE in SQL
Introduction of B-Tree
Difference between Clustered and Non-clustered index
SQL Interview Questions
Introduction of ER Model
Data Preprocessing in Data Mining
Introduction of DBMS (Database Management System) | Set 1
SQL | Views
Difference between DELETE, DROP and TRUNCATE