code-rag-bench/online-tutorials huggingface dataset:
Handling EOFError Exception in Python

02 Sep, 2020
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except keywords in Python. This is called as Exception Handling.
Example: This code will generate an EOFError when there is no input given to the online IDE.
Python3
n = int(input())print(n * 10)
Output:
This exception can be handled as:
Python3
try:    n = int(input())    print(n * 10)    except EOFError as e:    print(e)
Output:
EOF when reading a line
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | os.path.join() method
Reading Text from the Image using Tesseract

30 Aug, 2020
Pytesseract or Python-tesseract is an Optical Character Recognition (OCR) tool for python. It will read and recognize the text in images, license plates, etc. Here, we will use the tesseract package to read the text from the given image.  
Mainly, 3 simple steps are involved here as shown below:-  
Loading an Image saved from the computer or download it using a browser and then loading the same. (Any Image with Text).
Binarizing the Image (Converting Image to Binary).
We will then Pass the Image through the OCR system.
The following python code represents the Localizing of the Text and correctly guessing the text written in the image.  
Python3
# We import the necessary packages#import the needed packagesimport cv2import os,argparseimport pytesseractfrom PIL import Image  #We then Construct an Argument Parserap=argparse.ArgumentParser()ap.add_argument("-i","--image",                required=True,                help="Path to the image folder")ap.add_argument("-p","--pre_processor",                default="thresh",                 help="the preprocessor usage")args=vars(ap.parse_args())  #We then read the image with textimages=cv2.imread(args["image"])  #convert to grayscale imagegray=cv2.cvtColor(images, cv2.COLOR_BGR2GRAY)  #checking whether thresh or blurif args["pre_processor"]=="thresh":    cv2.threshold(gray, 0,255,cv2.THRESH_BINARY| cv2.THRESH_OTSU)[1]if args["pre_processor"]=="blur":    cv2.medianBlur(gray, 3)      #memory usage with image i.e. adding image to memoryfilename = "{}.jpg".format(os.getpid())cv2.imwrite(filename, gray)text = pytesseract.image_to_string(Image.open(filename))os.remove(filename)print(text)  # show the output imagescv2.imshow("Image Input", images)cv2.imshow("Output In Grayscale", gray)cv2.waitKey(0)
Now, follow the below steps to successfully Read Text from an image: 
Save the code and the image from which you want to read the text in the same file.
Open Command Prompt.Go to the location where the code file and image is saved.
Execute the command below to view the Output.
Example 1:
Execute the command below to view the Output.
python  tesseract.py --image Images/title.png

We have The Original Image displayed.
title
We have the Grey Scale Image Displayed. (p.png)
p
Output:
Example 2:
Execute the command below to view the Output.
python  tesseract.py --image Images/OCR.png

We have The Original Image displayed.
OCR
We have the Grey Scale Image Displayed. (p.png)
p
Output:
OCR-Optical-Character-Recognition
Python-Pytesseract
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Place_forget() method using Tkinter in Python

01 Aug, 2020
To hide or forget a widget from the parent widget or screen in tkinter, the place_forget() method is used on that widget based on place geometry management.
Syntax: widget.place_forget() 
Parameter: NoneReturn: None
Below is the implementation : 
Python3
# Imports everything from tkinter# and ttk modulefrom tkinter import *from tkinter.ttk import *  # toplevel windowroot = Tk()  # setting window sizeroot.geometry("150x100")  # label widgetlabel = Label(root, text="LABEL")  # place in the windowlabel.place(relx=0.4, y=5)  # button widgets# In command attribute of Button,# place_forget() method is passed# in the lambda function to temporarily# hide the labelb1 = Button(root, text = "hide text",            command = lambda: label.place_forget())  b1.place(relx = 0.3, y = 30)  # the label is placed againb2 = Button(root, text = "retrieve text",            command = lambda: label.place(              relx = 0.4))  b2.place(relx = 0.3, y = 50)  # Start the GUIroot.mainloop()
Output: 
 
After hiding: 
 
After retrieving: 
 
Note: There are other methods pack_forget() and grid_forget() that work the same way as forget_pack() and forget_grid() .
Python-gui
Python-tkinter
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
XQuery - If Then Else

XQuery provides a very useful if-then-else construct to check the validity of the input values passed. Given below is the syntax of the if-then-else construct.
if (condition) then
 ... 
else
 ... 
We will use the following books.xml file and apply to it XQuery expression containing an if-then-else construct to retrieve the titles of those books with a price value that is greater than 30.
<?xml version="1.0" encoding="UTF-8"?>
<books>
   <book category="JAVA">
      <title lang="en">Learn Java in 24 Hours</title>
      <author>Robert</author>
      <year>2005</year>
      <price>30.00</price>
   </book>
   
   <book category="DOTNET">
      <title lang="en">Learn .Net in 24 hours</title>
      <author>Peter</author>
      <year>2011</year>
      <price>40.50</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XQuery in 24 hours</title>
      <author>Robert</author>
      <author>Peter</author>
      <year>2013</year>
      <price>50.00</price>
   </book>
   
   <book category="XML">
      <title lang="en">Learn XPath in 24 hours</title>
      <author>Jay Ban</author>
      <year>2010</year>
      <price>16.50</price>
   </book>
</books>
The following XQuery expression is to be applied on the above XML document.
<result>
{
   if(not(doc("books.xml"))) then (
      <error>
         <message>books.xml does not exist</message>
      </error>
   )
   else ( 
      for $x in doc("books.xml")/books/book	
      where $x/price>30
      return $x/title
   )
}
</result>
<result>
   <title lang="en">Learn .Net in 24 hours</title>
   <title lang="en">Learn XQuery in 24 hours</title>
</result>

To verify the result, replace the contents of books.xqy (given in the Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program.
 Print
 Add Notes
 Bookmark this page
Perl | Use of STDIN for Input - GeeksforGeeks

24 Jun, 2019
Perl allows the programmer to accept input from the user to perform operations on. This makes it easier for the user to give input of its own and not only the one provided as Hardcoded input by the programmer. This Input can then be processed and printed with the use of print() function.
Input to a Perl program can be given by keyboard with the use of <STDIN>. Here, STDIN stands for Standard Input. Though there is no need to put STDIN in between the ‘diamond’ or ‘spaceship’ operator i.e, <>. It is standard practice to do so. <> operator can be used to write to files as well. <STDIN> can be also be used in Scalar and List context.
Syntax: $x = <STDIN>; or $x = <>;
Example:
#!/usr/bin/perl -w use strict;use warnings;  print"Enter some text:";my $string = <STDIN>;  print "You entered $string as a String";
Input:
GeeksForGeeks
Output:
Enter some text: GeeksForGeeks
You Entered GeeksForGeeks
as a String
In the above code, after giving Input, there is a need to press ENTER. This ENTER is used to tell the compiler to execute the next line of the code. But, <STDIN> takes this ENTER key pressed as a part of the Input given and hence when we print the line. A new line will automatically be printed after the Input string. To avoid this, a function chomp() is used. This function will remove the newline character added to the end of the Input provided by the user.
Example:
#!/usr/bin/perl -w use strict;use warnings;  print"Enter some text:";my $string = <STDIN>;chomp $string;  print "You entered $string as a String";
Input:
GeeksForGeeks
Output:
Enter some text: GeeksForGeeks
You Entered GeeksForGeeks as a String
Perl-Input-Output
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Polymorphism in OOPs
Perl | Regular Expressions
Perl Tutorial - Learn Perl With Examples
Perl | Subroutines or Functions
Perl | Boolean Values
Perl | length() Function
Introduction to Perl
Perl | sleep() Function
Perl | substitution Operator
Perl | Regex Cheat Sheet
Tryit Editor v3.6 - Show Python

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)
​
mycursor = mydb.cursor()
​
mycursor.execute("CREATE DATABASE mydatabase")
Set addAll() method in Java with Examples - GeeksforGeeks

31 Dec, 2018
The java.util.Set.addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
Syntax:
boolean addAll(Collection C)
Parameters: The parameter C is a collection of any type that is to be added to the set.
Return Value: The method returns true if it successfully appends the elements of the collection C to this Set otherwise it returns False.
Below programs illustrate the Java.util.Set.addAll() method:
Program 1 : Appending a tree set.
// Java code to illustrate addAll()import java.io.*;import java.util.*;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> st1 = new TreeSet<String>();          // Use add() method to add elements into the Set        st1.add("Welcome");        st1.add("To");        st1.add("Geeks");        st1.add("4");        st1.add("Geeks");        st1.add("TreeSet");          // Displaying the Set        System.out.println("Set: " + st1);          // Creating another Set        Set<String> st2 = new TreeSet<String>();          // Use add() method to add elements into the Set        st2.add("Hello");        st2.add("World");          // Using addAll() method to Append        st1.addAll(st2);          // Displaying the final Set        System.out.println("Set: " + st1);    }}
Set: [4, Geeks, To, TreeSet, Welcome]
Set: [4, Geeks, Hello, To, TreeSet, Welcome, World]

Program 2 : Appending an ArrayList.
// Java code to illustrate addAll()import java.io.*;import java.util.*;  public class SetDemo {    public static void main(String args[])    {        // Creating an empty Set        Set<String> st1 = new TreeSet<String>();          // Use add() method to add elements into the Set        st1.add("Welcome");        st1.add("To");        st1.add("Geeks");        st1.add("4");        st1.add("Geeks");        st1.add("Set");          // Displaying the Set        System.out.println("Initial Set: " + st1);          // An array collection is created        ArrayList<String> collect = new ArrayList<String>();        collect.add("A");        collect.add("Computer");        collect.add("Portal");          // Using addAll() method to Append        st1.addAll(collect);          // Displaying the final Set        System.out.println("Final Set: " + st1);    }}
Initial Set: [4, Geeks, Set, To, Welcome]
Final Set: [4, A, Computer, Geeks, Portal, Set, To, Welcome]

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#addAll(java.util.Collection)
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Multithreading in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
Stack Class in Java
How to Remove Duplicate Values From an Array in C#? - GeeksforGeeks

23 Nov, 2021
An array is a group of homogeneous elements that are referred to by a common name and can contain duplicate values. In C#, we cannot remove elements from the specified array but we can create a new array that contains the distinct elements. So to do this we use the Distinct() function. This function gives distinct values from the given sequence. This method will throw ArgumentNullException if the given array is null.  
Syntax:
array_name.Distinct()
where array_name is an input array.
Example:
Input  : data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 }
Output :
10
20
230
34
56
12
Input  : data = { "java", "java", "c", "python", "cpp", "c" }
Output :
java
c
python
cpp
Approach
1. Create an array with elements of any type like int, string, float, etc.
2. Apply distinct function and convert to array
data.Distinct().ToArray();
3. Here, ToArray() method converts the values in an array.
4. Display the unique elements by iterating through the array
Array.ForEach(unique, i => Console.WriteLine(i));
Example 1: 
C#
// C# program to remove duplicate elements from the arrayusing System;using System.Linq;  class GFG{  public static void Main(){          // Declare an array of integer type    int[] data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 };    Console.WriteLine("Array before removing duplicate values: ");    Array.ForEach(data, i => Console.WriteLine(i));          // Use distinct() function    // To create an array that contain distinct values    int[] unique = data.Distinct().ToArray();          // Display the final result    Console.WriteLine("Array after removing duplicate values: ");    Array.ForEach(unique, j => Console.WriteLine(j));}}
Output:
Array before removing duplicate values:
10
20
230
34
56
10
12
34
56
56
Array after removing duplicate values:
10
20
230
34
56
12
Example 2:
C#
// C# program to remove duplicate elements from the arrayusing System;using System.Linq;  class GFG{  public static void Main(){          // Declare an array of string type    string[] data1 = { "Java", "Java", "C", "Python", "CPP", "C" };    Console.WriteLine("Array before removing duplicate values: ");    Array.ForEach(data1, i => Console.WriteLine(i));          // Use distinct() function    // To create an array that contain distinct values    string[] unique = data1.Distinct().ToArray();          // Display the final result    Console.WriteLine("Array after removing duplicate values: ");    Array.ForEach(unique, j => Console.WriteLine(j));}}
Output:
Array before removing duplicate values: 
Java
Java
C
Python
CPP
C
Array after removing duplicate values: 
Java
C
Python
CPP
CSharp-Arrays-Programs
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
Convert String to Character Array in C#
Socket Programming in C#
Getting a Month Name Using Month Number in C#
Program to Print a New Line in C#
Program to find absolute value of a given number
What are the differences between switch_to_default_content() and switch_to.parent_frame() methods in Selenium with python?

There are differences between switch_to.parent_frame() and switch_to_default_content() in frames. They are listed below −
switch_to_parent_frame()This method is used to come out of the present frame, then we can access the elements outside that frame and not inside of that frame. Thus the control is switched; the outer part may be another frame or part of the web page. So we are able to come out of the current frame.
switch_to_parent_frame()
This method is used to come out of the present frame, then we can access the elements outside that frame and not inside of that frame. Thus the control is switched; the outer part may be another frame or part of the web page. So we are able to come out of the current frame.
Syntax −
driver.switch_to.parent_frame();
switch_to_default_content()This method is used to come out of all the frames and switch the focus at the page. Once we move out, it loses the access to the elements inside the frames in the page.
switch_to_default_content()
Syntax −
driver.switch_to_default_content();
Code Implementation with switch_to_default_content() method.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# to switch to frame with frame name
driver.switch_to.frame("frame-bottom")
# to get the text inside the frame and print on console
print(driver.find_element_by_xpath ("//*[text()='BOTTOM']").text)
# to move out the current frame to the page level
driver.switch_to.default_content()
#to close the browser
driver.quit()
Code Implementation with switch_to_parent_frame() method.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://the-internet.herokuapp.com")
#to refresh the browser
driver.refresh()
driver.find_element_by_link_text("Frames").click()
driver.find_element_by_link_text("Nested Frames").click()
# to switch to frame with parent frame name
driver.switch_to.frame("frame-top")
# to switch to frame with frame inside parent frame with name
driver.switch_to.frame("frame-left")
# to get the text inside the frame and print on console
print(driver.find_element_by_xpath ("//*[text()='LEFT']").text)
# to move out the current frame to the parent frame
driver. switch_to_parent_frame()
#to close the browser
driver.quit()
Method Chaining in JavaScript

Chaining Methods, also known as Cascading, means repeatedly calling one method after another on an object, in one continuous line of code. Let us look at an example where method chaining can help us avoid repetition.
Take the following class car for example -
class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w
   }
   setDoors(d) {
      this.doors = d
   }
   setTopSpeed(t) {
      this.topSpeed = t
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}
let sportsCar = new Car();
sportsCar.setDoors(2)
sportsCar.setTopSpeed(250)
sportsCar.setFeulCapacity("600 Litres")
sportsCar.displayCarProps()
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 
See how many times sportsCar is unnecessarily repeated? We can get rid of it by using method chaining. To do so, instead of letting the setters just setting the value, return this at the end. This will allow us to perform operations on the object. After making this change, our code looks like −
class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w;
      return this;
   }
   setDoors(d) {
      this.doors = d;
      return this;
   }
   setTopSpeed(t) {
      this.topSpeed = t;
      return this;
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc;
      return this;
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}
Now we can change the part where we create the car object with the more readable and less repeating code −
let sportsCar = new Car()
   .setDoors(2)
   .setTopSpeed(250)
   .setFeulCapacity("600 Litres")
   .displayCarProps()
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 
Method chaining is also called fluent interface as it allows to operate on the object through methods without breaking the flow again and again by repeating the object.
C# Currency ("C") Format Specifier

The "C" (or currency) format specifier is used to convert a number to a string representing a currency amount.
Let us see an example.
double value = 139.87;
Now to display the above number until three decimal places, use (“C3”) currency format specifier.
value.ToString("C3", CultureInfo.CurrentCulture)
Let us see another example.
 Live Demo
using System;
using System.Globalization;
class Demo {
   static void Main() {
      double value = 234.66;
      // displays $
      Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
      Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
   }
}
$234.66
$234.660
How to add 24 hours to a unix timestamp in php?

17 May, 2020
The Unix timestamp is designed to track time as a running total of seconds from the Unix Epoch on January 1st, 1970 at UTC. To add 24 hours to a Unix timestamp we can use any of these methods:
Method 1: Convert 24 hours to seconds and add the result to current Unix time.
Program:<?php   echo time() + (24*60*60);   ?>
<?php   echo time() + (24*60*60);   ?>
Output:1588671070
1588671070
Method 2: Since hours in a day vary in systems such as Daylight saving time (DST) from exactly 24 hours in a day. It’s better to use PHP strtotime() Function to properly account for these anomalies. Using strtotime to parse current DateTime and one day to timestamp
Program:<?php   echo strtotime("now"), "\n";echo strtotime('+1 day');   ?>
<?php   echo strtotime("now"), "\n";echo strtotime('+1 day');   ?>
Output:1588584696
1588671096
1588584696
1588671096
Method 3: Using DateTime class we can achieve same result. First create a DateTime object with current timestamp and add interval of one day. P1D represents a Period of 1 Day interval to be added.
Program:<?php   // Get current time stamp$now = new DateTime();$now->format('Y-m-d H:i:s');    echo $now->getTimestamp(), "\n";     // Add interval of P1D or Period of 1 Day$now->add(new DateInterval('P1D'));echo $now->getTimestamp();  ?>
<?php   // Get current time stamp$now = new DateTime();$now->format('Y-m-d H:i:s');    echo $now->getTimestamp(), "\n";     // Add interval of P1D or Period of 1 Day$now->add(new DateInterval('P1D'));echo $now->getTimestamp();  ?>
Output:1588584729
1588671129
1588584729
1588671129
PHP-date-time
Picked
PHP
Web Technologies
Web technologies Questions
Write From Home
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to delete an array element based on key in PHP?
PHP in_array() Function
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Cypress - Fixtures

Cypress fixtures are added to maintain and hold the test data for automation. The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project. Basically, it helps us to get the data input from external files.
Cypress fixtures folder can have files in JSON or other formats and the data is maintained in "key:value" pairs.
All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.
The syntax for Cypress data driven testing is as follows −
cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)

Here,
path of test data is the path of test data file within fixtures folder.
path of test data is the path of test data file within fixtures folder.
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
Opts − Modifies the timeout for response. The default value is 30000ms. The wait
time for cy.fixture(), prior throws an exception.
Opts − Modifies the timeout for response. The default value is 30000ms. The wait
time for cy.fixture(), prior throws an exception.
Given below is the implementation of data driven testing with example.json in Cypress −
{
   "fullName": "Robert",
   "number": "789456123"
}

The implementation of actual data driven testing in Cypress is as follows −
describe('Tutorialspoint Test', function () {
   //part of before hook
   before(function(){
      //access fixture data
      cy.fixture('example').then(function(regdata){
         this.regdata=regdata
      })
   })
   // test case
   it('Test Case1', function (){
      // launch URL
      cy.visit("https://register.rediff.com/register/register.php")
      //data driven from fixture
      cy.get(':nth-child(3) > [width="185"] > input')
      .type(this.regdata.fullName)
      cy.get('#mobno').type(this.regdata.number)
   });
});
Execution Results
The output is as follows −
The output logs show the values Robert and 789456123 being fed to the Full Name and Mobile No. fields respectively. This data has been passed to the test from the fixtures.
How to write backslash in Golang string?

04 May, 2020
In most of the programming languages, Backslash (\) works as an escape sequence character and the same is the case with Golang. Thus, if a user needs to write backslash in a string, he can make use of the two common methods.
1. A user can use another backslash just before the backslash (\) he/she wants to display.
Example:
// Printing backslash in Golang stringpackage main  import "fmt"  func main() {      // using another backslash    fmt.Println("\\Hello, Welcome to GeeksforGeeks")}
Output:
\Hello, Welcome to GeeksforGeeks
Explanation: Suppose, the user wants to write backslash at the starting of the string. This is done by using an escape operator “\” just before the desired backslash as shown in the above example. In this manner, the user can insert the backslash at any desired position in the string.
2. Another approach is to use a raw string literal (`).
// Printing backslash in Golang stringpackage main  import "fmt"  func main() {      // using raw string lateral (`)    fmt.Println(`\Happy Learning\`)}
Output:
\Happy Learning\
Explanation: In this example, we used a raw string lateral (`) to write a backslash in the string. If a user wants to write a string in between the backslashes, he can do so by writing the desired string within raw string literals (`) as shown in this example.
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Time Durations in Golang
Loops in Go Language
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
Convert output of MySQL query to UTF8?

You need to use CAST() or CONVERT() function to convert output of MySQL query to UTF8. Here, I am using MySQL version 8.0.12. Let us first check the version:
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.00 sec)
In this if you use utf8 then you will get warning of aliases because it has utf8mb4. Therefore, you can avoid the warning by placing utf8mb4.
Note: Never use UTF8. For current versions, use UTF8MB4
Here is the syntax to convert output of MySQL query to UTF8:
SELECT yourColumnName1,convert(yourColumnName2 USING utf8) as anyVariableName FROM yourTableName;
You can use another syntax which is as follows:
SELECT yourColumnName1,CONVERT(CAST(yourColumnName2 as BINARY) USING utf8) as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table ConvertOutputtoUtf8Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into ConvertOutputtoUtf8Demo(Name,Age) values('John',24);
Query OK, 1 row affected (0.78 sec)
mysql> insert into ConvertOutputtoUtf8Demo(Name,Age) values('Larry',21);
Query OK, 1 row affected (0.15 sec)
mysql> insert into ConvertOutputtoUtf8Demo(Name,Age) values('Carol',26);
Query OK, 1 row affected (0.12 sec)
mysql> insert into ConvertOutputtoUtf8Demo(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.18 sec)
mysql> insert into ConvertOutputtoUtf8Demo(Name,Age) values('Sam',22);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from ConvertOutputtoUtf8Demo;
The following is the output:
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | John  | 24   |
|  2 | Larry | 21   |
|  3 | Carol | 26   |
|  4 | Mike  | 27   |
|  5 | Sam   | 22   |
+----+-------+------+
5 rows in set (0.00 sec)
Here is the query to convert output of MySQL query to UTF8:
mysql> select Id,convert(Name using utf8) as ConvertToUtf8 from ConvertOutputtoUtf8Demo;
The following is the output:
+----+---------------+
| Id | ConvertToUtf8 |
+----+---------------+
| 1 | John           |
| 2 | Larry          |
| 3 | Carol          |
| 4 | Mike           |
| 5 | Sam            |
+----+---------------+
5 rows in set, 1 warning (0.00 sec)
You can use another query which is as follows:
mysql> SELECT Id,CONVERT(CAST(Name as BINARY) USING utf8) as ConvertToUtf8 FROM ConvertOutputtoUtf8Demo;
The following is the output:
+----+---------------+
| Id | ConvertToUtf8 |
+----+---------------+
| 1 | John           |
| 2 | Larry          |
| 3 | Carol          |
| 4 | Mike           |
| 5 | Sam            |
+----+---------------+
5 rows in set, 1 warning (0.00 sec)
Python Program to Find Sum of First and Last Digit

23 Aug, 2021
Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digit of the given number N.
Examples:
Input: N = 1247
Output: 8
Explanation: First digit is 1 and Last digit is 7. So, addition of these two (1 + 7) is equal to 8.
Input: N = 73
Output: 10
Take input in the form of String or typecast given input in String.
Now pick the 0th index of the String and typecast it into Integer and store it in a variable.
The same thing with the -1st index and also store in another variable.
Now add these two variables and
print them as an Output.
Note:  We can access the first element of String using string[0] and the last element of String using string[-1].
String Representation
Python3
# We have a numbernumber = 1247  # We are type casting it in stringnumber = str(number)  # Storing first and last digit in a variable# after type casting into Integer.first_digit = int(number[0])last_digit = int(number[-1])  # Adding these two variablesaddition = first_digit + last_digit  # Display our outputprint('Addition of first and last digit of the number is',       addition)
Output:
Addition of first and last digit of the number is 8
We have given a positive Integer.
After dividing by 10, store the remainder in a result variable.
Continue the loop until the number becomes less than 9.
Each time in the loop, divide the number by 10(integer division).
After the end of the loop.
Add the number in the result variable.
Display the result variable as the output.
Note: Whenever we divide any number with 10, we get the last digit as the remainder. If we divide any number with 100, we get the last two-digit as the remainder.
Python3
# We have a number.number = 1247  # Assigning last digit of the number in res# variable.res = number % 10  # Now, continue a loop until# the number becomes less than 9.while number > 9:      # integer division of the number and reassigning    # it.    number = number // 10  # Here, our number only contain one digit.# So, add this number in res variable.res += number  # Now, display our outputprint('Addition of first and last digit of number is', res)
Output:
Addition of first and last digit of the number is 8
Time Complexity: O(n), where n is how many digits are there in the given number.
number-digits
Picked
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
HTML | DOM Form submit() Method

12 Feb, 2019
The form submit() Method in HTML DOM is used to send the form data to the web-server. It works as same as submit button. It does not contain any parameters.
Syntax:
formObject.submit()
Example:
<!DOCTYPE html> <html>   <head>    <title>        HTML DOM Form submit() Method    </title></head>  <body style="text-align:center;">       <h1 style="color:green;">        GeeksForGeeks    </h1>          <!-- HTML code to create form -->    <h2>DOM Form submit() Method</h2>          <form id="GFG" action="https://ide.geeksforgeeks.org/tryit.php">          <label for="username">Username:</label>         <input type="text" name="username" id="Username">                  <br>                  <label for="password">Password:</label>         <input type="password" name="password" id ="password">                  <br><br>          <input type="button" onclick="myGeeks()" value="Submit form">    </form>      <!-- script to use submit() method -->    <script>        function myGeeks() {              document.getElementById("GFG").submit();        }    </script></body>  </html>
Output:
Supported Browsers: The browser supported by DOM Form submit() method are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-DOM
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding nullptr in C++

22 Jul, 2021
Consider the following C++ program that shows problem with NULL (need of nullptr) 
CPP
// C++ program to demonstrate problem with NULL#include <bits/stdc++.h>using namespace std; // function with integer argumentvoid fun(int N)   { cout << "fun(int)"; return;} // Overloaded function with char pointer argumentvoid fun(char* s)  { cout << "fun(char *)"; return;} int main(){    // Ideally, it should have called fun(char *),    // but it causes compiler error.    fun(NULL); }
Output: 
16:13: error: call of overloaded 'fun(NULL)' is ambiguous
     fun(NULL);
 What is the problem with above program? NULL is typically defined as (void *)0 and conversion of NULL to integral types is allowed. So the function call fun(NULL) becomes ambiguous.  
CPP
// This program compiles (may produce warning)#include<stdio.h>int main(){   int x = NULL;}
 How does nullptr solve the problem? In the above program, if we replace NULL with nullptr, we get the output as “fun(char *)”.nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types. 
CPP
// This program does NOT compile#include<stdio.h>int main(){   int x = nullptr;}
Output: 
Compiler Error
As a side note, nullptr is convertible to bool.  
CPP
// This program compiles#include<iostream>using namespace std; int main(){   int *ptr = nullptr;    // Below line compiles   if (ptr) { cout << "true"; }      else { cout << "false"; }   }
Output: 
false
        There are some unspecified things when we compare two simple pointers but comparison between two values of type nullptr_t is specified as, comparison by <= and >= return true and comparison by < and > returns false and comparing any pointer type with nullptr by == and != returns true or false if it is null or non-null respectively.  
C
// C++ program to show comparisons with nullptr#include <bits/stdc++.h>using namespace std; // Driver program to test behavior of nullptrint main(){    // creating two variables of nullptr_t type    // i.e., with value equal to nullptr    nullptr_t np1, np2;     // <= and >= comparison always return true    if (np1 >= np2)        cout << "can compare" << endl;    else        cout << "can not compare" << endl;     // Initialize a pointer with value equal to np1    char *x = np1;  // same as x = nullptr (or x = NULL                    // will also work)    if (x == nullptr)        cout << "x is null" << endl;    else        cout << "x is not null" << endl;     return 0;}
Output : 
can compare
x is null
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
shubham_singh
vineetkumar7677
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect If textbox content has changed using JavaScript ?

27 Apr, 2020
The task is to detect the changes in the textbox content with JavaScript. There are two approaches that are discussed below.
Approach 1: We will use the onchange event in the input element and call a function to see the effect.
Example:<!DOCTYPE html><html>  <head>    <title>        Detect If Textbox content has        changed using pure JavaScript    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">       GeeksforGeeks     </h1>    <p>      Change the text of input text      and click outside of it to see.    </p>    <input id="input" name="input"           onchange="GFG_Fun()" />    <br>    <br>    <script>        function GFG_Fun() {            alert('Changed');        }    </script></body>  </html>
<!DOCTYPE html><html>  <head>    <title>        Detect If Textbox content has        changed using pure JavaScript    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">       GeeksforGeeks     </h1>    <p>      Change the text of input text      and click outside of it to see.    </p>    <input id="input" name="input"           onchange="GFG_Fun()" />    <br>    <br>    <script>        function GFG_Fun() {            alert('Changed');        }    </script></body>  </html>
Output:
Approach 2: There are few other events that can be used to detect the change in content of textbox. Use any or all of them onchange event, onpropertychange event, onkeyup event, onpaste event and oninput event in the input element and call a function to see the effect.
Example:<!DOCTYPE html><html>  <head>    <title>        Detect If Textbox content has         changed using pure JavaScript    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksforGeeks      </h1>    <p>       Change the text of input text and      click outside of it to see.    </p>    <input id="input" name="input"           onchange            onpropertychange            onkeyuponpaste oninput="GFG_Fun()" />    <br>    <br>    <script>        function GFG_Fun() {            alert('Changed');        }    </script></body>  </html>
<!DOCTYPE html><html>  <head>    <title>        Detect If Textbox content has         changed using pure JavaScript    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">        GeeksforGeeks      </h1>    <p>       Change the text of input text and      click outside of it to see.    </p>    <input id="input" name="input"           onchange            onpropertychange            onkeyuponpaste oninput="GFG_Fun()" />    <br>    <br>    <script>        function GFG_Fun() {            alert('Changed');        }    </script></body>  </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy matrix.resize()

18 Apr, 2019
With the help of Numpy matrix.resize() method, we are able to resize the shape of the given matrix. Remember all elements should be covered after resizing the given matrix.
Syntax : matrix.resize(shape)
Return: new resized matrix
Example #1 :In the given example we are able to resize the given matrix by using matrix.resize() method.
# import the important module in pythonimport numpy as np           # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]')           # applying matrix.resize() methodgeeks = gfg.resize((1, 4))     print(geeks)
[[64  1 12  3]]

Example #2 :
# import the important module in pythonimport numpy as np           # make a matrix with numpygfg = np.matrix('[1, 2; 4, 5; 7, 8]')           # applying matrix.resize() methodgeeks = gfg.resize((2, 3))     print(geeks)
[[1 2 4]
 [5 7 8]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
PostgreSQL – ORDER BY clause

28 Aug, 2020
The PostgreSQL ORDER BY clause is used to sort the result query set returned by the SELECT statement. As the query set returned by the SELECT statement has no specific order, one can use the ORDER BY clause in the SELECT statement to sort the results in the desired manner.
Syntax:SELECTcolumn_1,column_2FROMtable_nameORDER BYcolumn_1 [ASC | DESC],column_2 [ASC | DESC];
Let’s analyze the above syntax:
Firstly we specify the column or the expression that we want to be sorted. If multiple columns or expressions are to be used in the SELECT statement, we separate them with commas.
Secondly, The ASC expression is used to sort the result set in ascending order, and DESC expression is used to sort the result set in descending order. By default the ORDER BY clause uses ASC.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Using PostgreSQL ORDER BY clause to sort rows by one column in the “customer” table of the sample database
SELECT
    first_name,
    last_name
FROM
    customer
ORDER BY
    first_name DESC;
Output:
Example 2:Using PostgreSQL ORDER BY clause to sort rows by multiple columns in the “customer” table. Here we will be sorting the customers by the first name in the ascending order first, and then sort the sorted result set by the last name in descending order.
SELECT
    first_name,
    last_name
FROM
    customer
ORDER BY
    first_name ASC,
    last_name DESC;
Output:
The output of the code gets more clear if the first name of the customer is the same as shown below:
Example 3:Using PostgreSQL ORDER BY clause to sort rows by expressions. In the below example we will be using the ORDER BY clause with the LENGTH() function to sort the rows by the lengths of the first names of customers. The LENGTH() function accepts a string and returns its length.
SELECT 
    first_name,
    LENGTH(first_name) len
FROM
    customer
ORDER BY 
    LENGTH(first_name) DESC;
Output:
postgreSQL-clauses
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get coordinates or dimensions of element with Selenium Python?

We can get coordinates or dimensions of elements with Selenium
webdriver. Each of the elements have .size and .location properties which give the x, y coordinates and height, width of the element in the form of a dictionary.
Syntax −
loc = element.location
s = element.size
Let us consider an element for which we shall find coordinates and dimensions−
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element
l= driver.find_element_by_xpath("//img[@class='tp-logo']")
#get x, y coordinates
loc = l.location
#get height, width
s = l.size
print(loc)
print(s)
driver.close()
Python program to find runner-up score

Suppose we have a list of scores for different number of participants. We have to find the runner-up score.
So, if the input is like scores = [5,8,2,6,8,5,8,7], then the output will be 7 because the winner score is 8 and second largest score is 7.
To solve this, we will follow these steps −
winner := -99999
runner_up := -99999
for each i in scores, doif i > winner, thenwinner := irunner_up := winnerotherwise when i < winner and i > runner_up, thenrunner_up := i
if i > winner, thenwinner := irunner_up := winner
winner := i
runner_up := winner
otherwise when i < winner and i > runner_up, thenrunner_up := i
runner_up := i
return runner_up
Let us see the following implementation to get better understanding
def solve(scores):
   winner = -99999
   runner_up = -99999
   for i in scores:
      if (i > winner):
         winner, runner_up = i, winner
      elif (i < winner and i > runner_up):
         runner_up = i
   return runner_up

scores = [5,8,2,6,8,5,8,7]
print(solve(scores))
[5,8,2,6,8,5,8,7]
7