code-rag-bench/online-tutorials huggingface dataset:
Java Program to Create Set of Pairs Using HashSet - GeeksforGeeks

03 Feb, 2022
Problem statement: We need to find and print unique pairs among all given pairs.
Generally, if we have to find the unique numbers among all given numbers then we just put all numbers in HashSet and print them. Let us consider a sample illustration to interpret the problem statement better. Suppose we have three pairs be customly they are (3, 5), (4, 5), (3, 5). Now if we put it in the set then the output will be.
Output: (3, 5), (4, 5), (3, 5)
Note: But in the case of Pair, we can’t just write as shown below but if we try to put Pair in a set then it gives us the problem for illustration.
HashSet<Pair> set = new HashSet<>();
 From the example, we can clearly see that duplicate pairs are still present. This is because for the set, Pair is the same type of object and it can’t differentiate between them. So to overcome this problem we can just make a string of indexes and values of  Pairs and store it in Set in form of String and then print it and you can get all unique pairs.
Example
Java
// Java Program to Create Set of Pairs// using HashSet // Importing required classesimport java.io.*;import java.util.HashSet; // Class 1// Helper class for creating pairsclass Pair {     // Pair attributes    public int index;    public int value;     // Constructor to initialize pair    public Pair(int index, int value)    {        // This keyword refers to current instance        this.index = index;        this.value = value;    }} // Class 2// Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Initializing an array of Pair        // Custom input elements        Pair arr[] = new Pair[4];        arr[0] = new Pair(2, 3);        arr[1] = new Pair(3, 4);        arr[2] = new Pair(5, 10);        arr[3] = new Pair(3, 4);         // Creating a hashSet by        // declaring object of string type        HashSet<String> set = new HashSet<>();         // Adding pair in set in form of string        for (int i = 0; i < 4; i++) {            set.add(arr[i].index + ", " + arr[i].value);        }         // Lastly iterating using for each loop and        // printing the elements pairs        for (String e : set)            System.out.println("(" + e + ")");    }}
(5, 10)
(2, 3)
(3, 4)
Output explanation:
So from the code and output, you can clearly see that duplicate pairs are deleted and we can get all unique pairs without overriding the hashCode() method and equals() method.
sumitgumber28
java-set
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
String Formatting in C# to add padding

With C#, you can easily format content and add padding to it.
To add padding −
const string format = "{0,-5} {1,5}";
Now, add the padding to the strings −
string str1 = string.Format(format, "Rank","Student");
string str2 = string.Format(format, "2","Tom");
Let us see the complete code −
 Live Demo
using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {

      // set padding
      const string format = "{0,-5} {1,5}";
      string str1 = string.Format(format, "Rank","Student");
      string str2 = string.Format(format, "2","Tom");

      Console.WriteLine(str1);
      Console.WriteLine(str2);
   }
}
Rank Student
2 Tom
MySQL insert a value to specific row and column

Let us first create a table −
mysql> create table DemoTable1569
   -> (
   -> StudentId varchar(10),
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (3.05 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1569 values('John_12','John Smith');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1569 values('David_321','Carol Taylor');
Query OK, 1 row affected (0.50 sec)
mysql> insert into DemoTable1569 values('David_989','David Miller');
Query OK, 1 row affected (0.24 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1569;
This will produce the following output
+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
| John_12   | John Smith   |
| David_321 | Carol Taylor |
| David_989 | David Miller |
+-----------+--------------+
3 rows in set (0.00 sec)
Here is the query to insert a value to specific row and column.
mysql> update DemoTable1569 set StudentId='Carol_321' where StudentName='Carol Taylor';
Query OK, 1 row affected (0.26 sec)
Rows matched: 1  Changed: 1 Warnings: 0
Let us check the table records once again.
mysql> select * from DemoTable1569;
This will produce the following output
+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
| John_12   | John Smith   |
| Carol_321 | Carol Taylor |
| David_989 | David Miller |
+-----------+--------------+
3 rows in set (0.00 sec)
SQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.
Note: Be careful before dropping a table. Deleting a 
table will result in loss of complete information stored in the table!
The following SQL statement drops the existing table "Shippers":
The TRUNCATE TABLE statement is used to delete the data inside a table, but 
not the table itself.
Write the correct SQL statement to delete a table called Persons.
 Persons;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to get all the values from a Scala map - GeeksforGeeks

29 Jul, 2019
In order to get all the values from a Scala map, we need to use values method (to get all the values as an Iterable) and if we want to get the values as an iterator, we need to use valuesIterator method. Now, lets check some examples.Example #1:
// Scala program of values()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying values method        val result = m1.values                  // Displays output        println(result)          }}
MapLike(geeks, for, cs)

Here, values method is utilized.Example #2:
// Scala program of valuesIterator()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying valuesIterator method        val result = m1.valuesIterator                  // Displays output        println(result)          }}
non-empty iterator

Here, valuesIterator method is utilized.
Scala
Scala-Map
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hello World in Scala
Scala Map get() method with example
Scala ListBuffer
Scala List map() method with example
How to install Scala on Windows?
Scala | Case Class and Case Object
Scala | Traits
Inheritance in Scala
Scala List length() method with example
JSTL - fn:split() Function

The fn:split() function splits a string into an array of substrings based on a delimiter string.
The fn:split() function has the following syntax −
java.lang.String[] split(java.lang.String, java.lang.String)

Following is the example to explain the functionality of the fn:split() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<html>
   <head>
      <title>Using JSTL Functions</title>
   </head>

   <body>
      <c:set var = "string1" value = "This is first String."/>
      <c:set var = "string2" value = "${fn:split(string1, ' ')}" />
      <c:set var = "string3" value = "${fn:join(string2, '-')}" />

      <p>String (3) : ${string3}</p>

      <c:set var = "string4" value = "${fn:split(string3, '-')}" />
      <c:set var = "string5" value = "${fn:join(string4, ' ')}" />

      <p>String (5) : ${string5}</p>
   </body>
</html>
You will receive the following result −
String (3) : This-is-first-String.
String (5) : This is first String.


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to call Python module from command line?

If we are writing a Python script that is to be used as a module, we can test this module by adding this call of the function to the bottom:
def fubar():
    #does something useful
fubar()
and run it  at the command prompt like this:
~$ python fubar.py
Java - atan() Method

The method returns the arctangent of the specified double value.
double atan(double d)

Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns the arctangent of the specified double value.
public class Test { 

   public static void main(String args[]) {
      double degrees = 45.0;
      double radians = Math.toRadians(degrees);

      System.out.format("The value of pi is very very very approximately %.4f%n", Math.PI);
      System.out.format("The arctangent of %.4f is %.4f degrees %n", Math.cos(radians), 
         Math.toDegrees(Math.atan(Math.sin(radians))));
   }
}
This will produce the following result −
The value of pi is very very very approximately 3.1416
The arctangent of 0.7071 is 35.2644 degrees 


    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
Trigonometric Functions in C#

Trignometric Functions in C# include, ACos, ASin, Sin, Cos, Tan, etc. It comes under the Math type of the System namespace.
The following is an example showing how to implement trigonometric functions in C# −
 Live Demo
using System;

class Program {
   static void Main() {
      Console.WriteLine(Math.Acos(0));
      Console.WriteLine(Math.Cos(2));

      Console.WriteLine(Math.Asin(0.2));
      Console.WriteLine(Math.Sin(2));

      Console.WriteLine(Math.Atan(-5));
      Console.WriteLine(Math.Tan(1));
   }
}
1.5707963267949
-0.416146836547142
0.201357920790331
0.909297426825682
-1.37340076694502
1.5574077246549
Above we saw the Inverse Sine value using Asin −
Math.Asin(0.2)
With that, we also saw the Inverse Cosine value using Acos −
Math.Acos(0)
In the same way, we found out the value of Tan(1), Atab(-5), Sin(2) and Cos(2).
Combinational and Sequential Circuits - GeeksforGeeks

12 Apr, 2020
A Digital logic (or Switching) circuit has voltage levels to be switched from one value to another but has a finite number of distinct values (generally 0 for false and 1 for true). These circuits operate a definite set of logic rules so it is also known as Logic circuits. These are basic circuits which are used in mobile phones, calculators, computers, etc.
Types of Logic Circuits:There are two types of Digital circuits depends on their output and memory used:
(i) Combinational circuit, and
(ii) Sequential circuit 
A combinational circuit consists of logic gates whose outputs at any time are determined from only the present combination of inputs and they have no memory. A sequential circuit consists of logic gates whose outputs at any time are determined from both the present combination of inputs and previous output. That means sequential circuits use memory elements to store the value of previous output.
1. Combinational Circuits:These circuits developed using AND, OR, NOT, NAND and NOR logic gates. These logic gates are building blocks of combinational circuits. A combinational circuit consists of input variables and output variables. Since these circuits are not dependent upon previous input to generate any output, so are combinational logic circuits. A combinational circuit can have an n number of inputs and m number of outputs. In combinational circuits, the output at any time is a direct function of the applied external inputs.
2. Sequential circuits:A sequential circuit is specified by a time sequence of inputs, outputs, and internal states. The output of a sequential circuit depends not only the combination of present inputs but also on the previous outputs. Unlike combinational circuits, sequential circuits include memory elements with combinational circuits.
The memory elements are circuits capable of storing binary information.
The binary information stored in these memory elements at any given time defines the state of the sequential circuit at that time.
The external output of a sequential circuit depends both on the present input and previous output state.
The next state of the memory elements also depends on the external input and present state of external output.
Some sequential circuits may not contain combinational circuits, but only memory elements.
Generally, there are two types of storage elements used: Latches, and Flip-Flops. Storage elements that operate with signal levels (rather than signal transitions) are referred to as latches ; those controlled by a clock transition are flip-flops.
Digital Electronics & Logic Design
GATE CS
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
4-bit binary Adder-Subtractor
IEEE Standard 754 Floating Point Numbers
Full Subtractor in Digital Logic
Encoder in Digital Logic
Shift Registers in Digital Logic
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
CSS - Pseudo-class :focus

The :focus pseudo-class is used to add special effect to an element while the element has focus.
While defining pseudo-classes in a <style>...</style> block, following points should be taken care −
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
Pseudo-class names are not case-sensitive.
Pseudo-class names are not case-sensitive.
Pseudo-class are different from CSS classes but they can be combined.
Pseudo-class are different from CSS classes but they can be combined.
color − Any valid color value.
color − Any valid color value.
Anchor / Link element.
Following is the example which demonstrates how to use :focus class to change the color of focused links.
<html>
   <head>
      <style type = "text/css">
         a:focus {color: #0000FF}
      </style>
   </head>

   <body>
      <a href = "/html/index.htm">Click this Link</a>
   </body>
</html>
This will produce following link. This will change it color to orange when this link gets focused, then you focus on any other link to see that this color will change when it will lose focus.

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Scroll element to the middle of the screen with Selenium

We can scroll to the middle of the screen with Selenium webdriver using the JavaScript Executor. Selenium can execute JavaScript commands with the help of the executeScript method.
To scroll to the middle of the screen, we have to first identify the element upto which we want to scroll on the page. Then pass scrollIntoView and the web element as parameters to the executeScript method.
JavaScript command scrollIntoView can have multiple optional parameters. They are −
behavior – This can have the values - smooth or auto. It describes the animation of the transition. The default value is auto.
behavior – This can have the values - smooth or auto. It describes the animation of the transition. The default value is auto.
block – This can have the values - start, end, center, or nearest. It describes the vertical alignment. The default value is start.
block – This can have the values - start, end, center, or nearest. It describes the vertical alignment. The default value is start.
inline – This can have the values - start, end, center, or nearest. It describes the horizontal alignment. The default value is nearest.
inline – This can have the values - start, end, center, or nearest. It describes the horizontal alignment. The default value is nearest.
WebElement e = driver.findElement(By.name("txt"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'})", e);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollToMiddle{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement m = driver.findElement(By.linkText("Latest Courses"));
      //scroll to middle with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'})", m);
      System.out.println("Text is: " + m.getText());
   }
}
MoviePy – Playing video clip file for n times - GeeksforGeeks

01 Aug, 2020
In this article we will see how we can play the video file clip in loop i.e n times in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can display a video with the help of ipython_display method and we can preview a video with the help of preview method. But when we display a video there is no looping although we can add looping to it any time i.e when we display the video file it will start playing replaying itself n times.
In order to do this we will use ipython_display method with the VideoFileClip object
Syntax : clip.clip.ipython_display(loop = n)
Argument : It takes loop = integer as argument
Return : It returns None
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *     # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")     # getting only first 5 secondsclip = clip.subclip(0, 5)  # looping video 3 timesclip.ipython_display(loop = 3)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")    # getting only first 5 secondsclip = clip.subclip(0, 5)  # looping video 3 timesclip.ipython_display(loop = 3)
Output :
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

Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How to extract the digit part from the string in MySQL?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John19383');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Carol9999');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('David123456');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+
| StudentId   |
+-------------+
| John19383   |
| Carol9999   |
| David123456 |
+-------------+
3 rows in set (0.00 sec)
Following is the query to extract the digit part from the string −
mysql> SELECT replace(reverse(FORMAT(reverse(StudentId), 0)), ',', '') as OnlyDigit from DemoTable;
This will produce the following output −
+-----------+
| OnlyDigit |
+-----------+
| 19383     |
| 9999      |
| 123456    |
+-----------+
3 rows in set (0.05 sec)
Is there a way to convert Integer field into Varchar without losing data in MySQL?

You can use ALTER command to convert Integer into Varchar. Let us first create a table
mysql> create table DemoTable
(
   UserId int,
   UserFirstName varchar(20),
   UserLastName varchar(20),
   UserAge int
);
Query OK, 0 rows affected (0.73 sec)
Now check the description of table using DESC command:
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| UserId        | int(11)     | YES  |     | NULL    |       |
| UserFirstName | varchar(20) | YES  |     | NULL    |       |
| UserLastName  | varchar(20) | YES  |     | NULL    |       |
| UserAge       | int(11)     | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
4 rows in set (0.17 sec)
Now you can change the integer data type to varchar without losing data:
mysql> alter table DemoTable change UserId UserId varchar(20);
Query OK, 0 rows affected (1.35 sec)
Records: 0 Duplicates: 0 Warnings: 0
Check the table description:
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| UserId        | varchar(20) | YES  |     | NULL    |       |
| UserFirstName | varchar(20) | YES  |     | NULL    |       |
| UserLastName  | varchar(20) | YES  |     | NULL    |       |
| UserAge       | int(11)     | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
C++ Program to Solve any Linear Equation in One Variable

Any linear equation in one variable has the form aX + b = cX + d. Here the value of X is to be found, when the values of a, b, c, d are given.
A program to solve a linear equation in one variable is as follows −
 Live Demo
#include<iostream>
using namespace std;
int main() {
   float a, b, c, d, X;
   cout<<"The form of the linear equation in one variable is: aX + b = cX + d"<<endl;
   cout<<"Enter the values of a, b, c, d : "<<endl;
   cin>>a>>b>>c>>d;
   cout<<"The equation is "<<a<<"X + "<<b<<" = "<<c<<"X + "<<d<<endl;

   if(a==c && b==d)
   cout<<"There are infinite solutions possible for this equation"<<endl;
   else if(a==c)
   cout<<"This is a wrong equation"<<endl;
   else {
      X = (d-b)/(a-c);
      cout<<"The value of X = "<< X <<endl;
   }
}
The output of the above program is as follows
The form of the linear equation in one variable is: aX + b = cX + d
Enter the values of a, b, c, d :
The equation is 5X + 3 = 4X + 9
The value of X = 6
In the above program, first the values of a, b, c and d are input by the user. Then the equation is displayed. This is given below −
cout<<"The form of the linear equation in one variable is: aX + b = cX + d"<<endl;

cout<<"Enter the values of a, b, c, d : "<<endl;
cin>>a>>b>>c>>d;

cout<<"The equation is "<<a<<"X + "<<b<<" = "<<c<<"X + "<<d<<endl;
If a is equal to c and b is equal to d, then there are infinite solutions for the equation. If a is equal to c, then the equation is wrong. Otherwise, the value of X is calculated and printed. This is given below −
if(a==c && b==d)
cout<<"There are infinite solutions possible for this equation"<<endl;
else if(a==c)
cout<<"This is a wrong equation"<<endl;
else {
   X = (d-b)/(a-c);
   cout<<"The value of X = "<< X <<endl;
}
How to redirect from an HTML page?

Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value in the content is the number of seconds; you want the page to redirect after.
Set the content attribute to 0, if you want it to load immediately.
The following is an example of redirecting current page to another page after 0 seconds.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Meta Tag</title>
      <meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />
   </head>
   <body>
      <p>Hello HTML5!</p>
   </body>
</html>
Extract the user ID from the username only in MySQL?

To extract the User ID only from MySQL, you can use SUBSTRING_INDEX(), which extracts the part of a string from the Username to get the User ID. 
Let us first display the user −
mysql> SELECT USER();
This will produce the following output −
+----------------+
| USER()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
Let us now extract the UserID only −
mysql> SELECT SUBSTRING_INDEX(USER(),'@',1);
This will produce the following output −
+-------------------------------+
| SUBSTRING_INDEX(USER(),'@',1) |
+-------------------------------+
| root                          |
+-------------------------------+
1 row in set (0.00 sec)
Additionally, if you want the host name, you can use the below query −
mysql> SELECT SUBSTRING_INDEX(USER(),'@',-1);
This will produce the following output −
+--------------------------------+
| SUBSTRING_INDEX(USER(),'@',-1) |
+--------------------------------+
| localhost                      |
+--------------------------------+
1 row in set (0.00 sec)
Java import Keyword

❮ Java Keywords

Import the Scanner class from the Java API:
import java.util.Scanner;

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}


Run Example »

The import keyword is used to import a package, class or interface.
Read more about packages in our Java Packages Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Erosion and Dilation of images using OpenCV in Python

In this problem, we will see how Python can do some Morphological Operations like Erosion and Dilation using the OpenCV module. The OpenCV library is mainly designed for computer vision. It is open source. Originally it was designed by Intel. This is free to use under open-source BSD license.
To use the OpenCV functionality, we need to download them using pip.
sudo pip3 install opencv-python

In the Erosion, it erodes away the boundaries of foreground objects. It is used to remove small white noises from the images. Erosion can also be used to detach two connected images.
A kernel is formed from an image. The kernel is a matrix, where the order is odd, like 3, 5, 7.
A kernel is formed from an image. The kernel is a matrix, where the order is odd, like 3, 5, 7.
A pixel of image is chosen. This pixel will be chosen as 1 only if all the pixels under the kernel is 1. Otherwise it will be eroded.
A pixel of image is chosen. This pixel will be chosen as 1 only if all the pixels under the kernel is 1. Otherwise it will be eroded.
So all pixels near the boundary will be discarded.
So all pixels near the boundary will be discarded.
So the thickness of foreground object decreases.
So the thickness of foreground object decreases.
In the Dilation, it increases the object area. The Erosion can remove the white noises, but it also shrinks our image, so after Erosion, if Dilation is performed, we can get better noise removal results. The Dilation can also be used to joins some broken parts of an object.
A kernel is formed from an image. The kernel is a matrix, where the order is odd, like 3, 5, 7.
A kernel is formed from an image. The kernel is a matrix, where the order is odd, like 3, 5, 7.
A pixel of image is chosen. This pixel will be chosen as 1 only if all the pixels under the kernel is 1.
A pixel of image is chosen. This pixel will be chosen as 1 only if all the pixels under the kernel is 1.
Increases the white region or the size of foreground objects of the image.
Increases the white region or the size of foreground objects of the image.
import cv2 
import numpy as np
input_image = cv2.imread('TP_logo.jpg', cv2.IMREAD_COLOR)
 kernel = np.ones((3,3), np.uint8)       # set kernel as 3x3 matrix from numpy
#Create erosion and dilation image from the original image
erosion_image = cv2.erode(input_image, kernel, iterations=1)
dilation_image = cv2.dilate(input_image, kernel, iterations=1)
cv2.imshow('Input', input_image)
cv2.imshow('Erosion', erosion_image)
cv2.imshow('Dilation', dilation_image)
cv2.waitKey(0)       #wait for a key to exit
How to group array of objects by Id in JavaScript?

Following is the code to group array of objects by id in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>group the array of objects by Id in JavaScript</h1>
<div class="result">
{ name: 'Rohan', age: 18 }, { name: 'Mohan', age: 20 }, { name: 'Shawn',
age: 18 }, { name: 'Michael', age: 18 }, { name: 'David', age: 20 }
</div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to sort the above object based on peoples age
</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let BtnEle = document.querySelector(".Btn");
   const people = [
      { name: "Rohan", age: 18 },
      { name: "Mohan", age: 20 },
      { name: "Shawn", age: 18 },
      { name: "Michael", age: 18 },
      { name: "David", age: 20 },
   ];
   let groupBy = (array, key) => {
      return array.reduce((result, obj) => {
         (result[obj[key]] = result[obj[key]] || []).push(obj);
         return result;
      }, {});
   };
   let a = groupBy(people, "age");
   BtnEle.addEventListener("click", () => {
      console.log(a);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button and checking the output in console −
Python - Extract Upper Case Characters - GeeksforGeeks

30 Jan, 2020
Sometimes, while working with strings, we are concerned about the case-sensitivity of strings and might require to get just a specific case of character in a long string. Let’s discuss certain ways in which only uppercase letters can be extracted from a string.
Method #1 : Using list comprehension + isupper()List comprehension and isupper function can be used to perform this particular task. The list comprehension is primarily used to iterate over the list and isupper function checks for the uppercase characters.
# Python3 code to demonstrate working of# Extract Upper Case Characters # Using list comprehension + isupper()  # initializing string test_str = "GeeksForGeeKs"  # printing original string print("The original string is : " + str(test_str))  # Extract Upper Case Characters # Using list comprehension + isupper()res = [char for char in test_str if char.isupper()]  # printing result print("The uppercase characters in string are : " + str(res))
The original string is : GeeksForGeeKs
The uppercase characters in string are : ['G', 'F', 'G', 'K']

 
Method #2 : Using filter() + lambdaFilter function along with lambda functionality can be used to perform this particular task. The filter function performs the specific selection of case characters and lambda function is used for string traversal.
# Python3 code to demonstrate working of# Extract Upper Case Characters# Using filter() + lambda  # initializing string test_str = "GeeksForGeeKs"  # printing original string print("The original string is : " + str(test_str))  # Extract Upper Case Characters# Using filter() + lambdares = list(filter(lambda c: c.isupper(), test_str))  # printing result print("The uppercase characters in string are : " + str(res))
The original string is : GeeksForGeeKs
The uppercase characters in string are : ['G', 'F', 'G', 'K']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Exponential expressions in Arduino

The pow() function of Arduino can be used for evaluating exponential expressions. Any expression of the form ab can be expressed as pow(a,b). For example 23 becomes pow(2,3).
The type for both the base (a) and the exponent (b) is float. This function returns a double.
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   float base = 2;
   float exponent = 3;
   Serial.println(pow(base,exponent));
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor Output is shown below −
You are encouraged to try different values of base and exponent and check the working of this function.
Can we declare main() method as private or protected or with no access modifier in java?

Java provides various access specifiers namely private, public and protected etc...
The Private modifier restricts the access of members from outside the class. A class and interface cannot be public.
The Private modifier restricts the access of members from outside the class. A class and interface cannot be public.
The Public access modifier can be associated with class, method, constructor, interface, etc. public can be accessed from any other class.
The Public access modifier can be associated with class, method, constructor, interface, etc. public can be accessed from any other class.
The protected access modifier can be associated with variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier can be associated with variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The default access modifier does not have keyword a variable or method declared without any access control modifier is available to any other class in the same package.
The default access modifier does not have keyword a variable or method declared without any access control modifier is available to any other class in the same package.
Therefore, if you declare a method public it can be accessed from anywhere outside the class. As we know that JVM accesses/invokes the main method directly if the main method is public JVM can invoke it from anywhere.
You can define the main method in your program without private, protected or, default (none) modifier, the program gets compiled without compilation errors.
But, at the time of execution JVM does not consider this as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument.
public static int main(String[] args){
}
If such a method is not found, a run time error is generated.
In the following Java program, the class Sample contains the main method which is public.
 Live Demo
public class Sample{
   private static void main(String[] args){
      System.out.println("This is a sample program");
   }
}
On executing, this program generates the following error.
Error: Main method not found in class Sample, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Find minimum and maximum elements in singly Circular Linked List in C++

Here we will see how to get the minimum and maximum value from one singly circular linked linear list. The basic concept is very simple. The next part of the last node will be pointed to the first node, the first node will also be pointed using start pointer. When we insert some element into the list, after inserting the next part of the newly inserted node will be updated with the address of the start node.
Initially the min is assigned with positive infinity, and max is assigned with negative infinity. Now traverse the list from left to right. If the current element is less than the min element, then update min, if the current element is larger than the max element, then update the max. Thus we can get the min and max values.
#include<iostream>
using namespace std;
class Node{
   public:
   int data;
   Node *next;
};
Node* getNode(int key){
   Node *newNode = new Node();
   newNode->data = key;
   newNode->next = NULL;
   return newNode;
}
void insert(Node **start, int data){
   Node *current = *start;
   Node *newNode = getNode(data);
   if(*start == NULL){
      newNode->next = newNode;
      *start = newNode;
      return;
   }
   while (current->next != *start) {
      current = current->next;
   }
   newNode->next = *start;
   current->next = newNode;
}
void displayList(Node *start){
   Node* current = start;
   if (start == NULL) {
      cout << "Display List is empty";
      return;
   } else {
      do {
         cout << current->data << " ";
         current = current->next;
      }
       while (current != start);
   }
   cout << endl;
}
void getMinMax(Node **start){
   if(*start == NULL){
      return;
   }
   Node* current;
   current = *start;
   int min = INT_MAX, max = INT_MIN;
   while (current->next != *start) {
      if (current->data < min) {
         min = current->data;
      }
      if (current->data > max) {
         max = current->data;
      }
      current = current->next;
   }
   cout << "Minimum: " << min << ", Maximum: " << max;
}
int main() {
   int data[] = {99, 11, 22, 10, 44, 55, 66};
   int n = sizeof(data)/sizeof(data[0]);
   Node *start = NULL;
   for(int i = 0; i<n; i++){
      insert(&start, data[i]);
   }
   displayList(start);
   getMinMax(&start);
}
99 11 22 10 44 55 66
Minimum: 10, Maximum: 99
Find a new line character with JavaScript RegExp.

To find a new line character with JavaScript Regular Expression, use the following −
\n
You can try to run the following code to find a new line character. It returns the position where the new line (\n) is found −
<html>
   <head>
      <title>JavaScript Regular Expression</title>
   </head>
   <body>
      <script>
         var myStr = "UI \n Responsive!";
         var reg = /\n/;
         var match = myStr.search(reg);

         document.write(match);
      </script>
   </body>
</html>
Program to convert KiloBytes to Bytes and Bits in C++

Given with the input as KiloBytes and the task is to convert the given input into number of bytes and bits.
Bit − In computers, bit is the smallest unit represented with two integer value 0 and 1 and all the information in computer is processed as a sequence of these two digits.
N-bits = 2 ^ N patterns, where N can be any integer value starting from 1.
Byte − In computers, byte is represented with 8 bits. Byte is capable of holding one character to numbers ranging between 0 and 255.
1 byte = 8 bits
Which means 2 ^ 8 patterns which is equals to 256
There are multiple forms of bytes −
1 Kilobyte(KB) = 1024 bytes
1 Megabyte(MB) = 1048576 bytes
1 Gigabyte = 1073741824 bytes
Input 1-: kilobytes = 10
Output -: 10 Kilobytes = 10240 Bytes and 81920 Bits
Input 2-: kilobytes = 1
Output -: 1 Kilobytes = 1024 Bytes and 8192 Bits
Approach used below is as follows −
Input data in kilobytes
Apply the formula to convert the kilobytes into bytesBytes = kilobytes * 1024
Apply the formula to convert the kilobytes into bytes
Bytes = kilobytes * 1024
Apply the formula to convert the kilobytes into bitsBits = kilobytes * 8192
Apply the formula to convert the kilobytes into bits
Bits = kilobytes * 8192
Start
Step 1-> Declare function to convert into bits
   long Bits(int kilobytes)
      set long Bits = 0
      set Bits = kilobytes * 8192
      return Bits
step 2-> Declare function to convert into bytes
   long Bytes(int kilobytes)
      set long Bytes = 0
      set Bytes = kilobytes * 1024
      return Bytes
step 3-> In main()
   declare int kilobytes = 10
   call Bits(kilobytes)
   call Bytes(kilobytes)
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//convert into bits
long Bits(int kilobytes) {
   long Bits = 0;
   Bits = kilobytes * 8192;
   return Bits;
}
//convert into bytes
long Bytes(int kilobytes) {
   long Bytes = 0;
   Bytes = kilobytes * 1024;
   return Bytes;
}
int main() {
   int kilobytes = 10;
   cout << kilobytes << " Kilobytes = " << Bytes(kilobytes) << " Bytes and " << Bits(kilobytes) << "    Bits";
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
10 Kilobytes = 10240 Bytes and 81920 Bits
JavaScript Number - constructor()

It returns a reference to the Number function that created the instance's prototype.
Its syntax is as follows −
number.constructor()

Returns the function that created this object's instance.
<html>
   <head>
      <title>JavaScript constructor() Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var num = new Number( 177.1234 );
         document.write("num.constructor() is : " + num.constructor); 
      </script>   
   </body>
</html>
num.constructor() is : function Number() { [native code] }


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
What are the default values of instance variables whether primitive or reference type in Java?

When we haven’t initialized the instance variables compiler initializes them with default values.
For boolean type, the default value is false, for float and double types default values are 0.0 and for remaining primitive types default value is 0.
Live Demo
public class Sample {
   int varInt;
   float varFloat;
   boolean varBool;
   long varLong;
   byte varByte;
   short varShort;
   double varDouble;
   public static void main(String args[]){
      Sample obj = new Sample();
      System.out.println("Default int value ::"+obj.varInt);
      System.out.println("Default float value ::"+obj.varFloat);
      System.out.println("Default boolean value ::"+obj.varBool);
      System.out.println("Default long value ::"+obj.varLong);
      System.out.println("Default byte value ::"+obj.varByte);
      System.out.println("Default short value ::"+obj.varShort);
      System.out.println("Default double value ::"+obj.varDouble);
   }
}
Default int value ::0
Default float value ::0.0
Default boolean value ::false
Default long value ::0
Default byte value ::0
Default short value ::0
Default double value ::0.0
Python NLTK | nltk.TweetTokenizer() - GeeksforGeeks

07 Jun, 2019
With the help of NLTK nltk.TweetTokenizer() method, we are able to convert the stream of words into small small tokens so that we can analyse the audio stream with the help of nltk.TweetTokenizer() method.
Syntax : nltk.TweetTokenizer()Return : Return the stream of token
Example #1 :In this example when we pass audio stream in the form of string it will converted to small tokens from a long string with the help of nltk.TweetTokenizer() method.
# import TweetTokenizer() method from nltkfrom nltk.tokenize import TweetTokenizer  # Create a reference variable for Class TweetTokenizertk = TweetTokenizer()  # Create a string inputgfg = "Geeks for Geeks"  # Use tokenize methodgeek = tk.tokenize(gfg)  print(geek)
Output :
[‘Geeks’, ‘for’, ‘Geeks’]
Example #2 :
# import TweetTokenizer() method from nltkfrom nltk.tokenize import TweetTokenizer  # Create a reference variable for Class TweetTokenizertk = TweetTokenizer()  # Create a string inputgfg = ":-) <> () {} [] :-p"  # Use tokenize methodgeek = tk.tokenize(gfg)  print(geek)
Output :
[‘:-)’, ”, ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, ‘]’, ‘:-p’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Selecting rows in pandas DataFrame based on conditions