code-rag-bench/online-tutorials huggingface dataset:
Objective-C Categories

Sometimes, you may find that you wish to extend an existing class by adding behavior that is useful only in certain situations. In order add such extension to existing classes, Objective-C provides categories and extensions.
If you need to add a method to an existing class, perhaps, to add functionality to make it easier to do something in your own application, the easiest way is to use a category.
The syntax to declare a category uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it specifies the name of the category in parentheses, like this −
@interface ClassName (CategoryName)

@end
A category can be declared for any class, even if you don't have the original implementation source code.
A category can be declared for any class, even if you don't have the original implementation source code.
Any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class.
Any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class.
At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
Now, let's look at a sample category implementation. Let's add a category to the Cocoa class NSString. This category will make it possible for us to add a new method getCopyRightString which helps us in returning the copyright string. It is shown below.
#import <Foundation/Foundation.h>

@interface NSString(MyAdditions)
+(NSString *)getCopyRightString;
@end

@implementation NSString(MyAdditions)

+(NSString *)getCopyRightString {
   return @"Copyright TutorialsPoint.com 2013";
}

@end

int main(int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSString *copyrightString = [NSString getCopyRightString];
   NSLog(@"Accessing Category: %@",copyrightString);
   
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-22 21:19:12.125 Categories[340:303] Accessing Category: Copyright TutorialsPoint.com 2013

Even though any methods added by a category are available to all instances of the class and its subclasses, you'll need to import the category header file in any source code file where you wish to use the additional methods, otherwise you'll run into compiler warnings and errors.
In our example, since we just have a single class, we have not included any header files, in such a case we should include the header files as said above.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
C Program to convert first character uppercase in a sentence

Given a string and with mixed case, i.e with both uppercase and lower case, the task is to covert the first character to uppercase rest in lowercase if it’s in upper case.
Let’s understand it in depth with the help of a simple example.
Like we are given a string “hElLo world”, we have to convert the first character ‘h’ which is in lowercase to uppercase ‘H’ and rest all letters before the space or end of the string to lowercase.
Moreover when we encounter first character after a space we have to convert it to uppercase.
Input: str[] = {“heLlO wORLD”}
Output: Hello World
Input: str[] = {"sUNIDHi bAnSAL"}
Output: Sunidhi Bansal
Approach used below is as follows −
To solve this problem we will use the ASCII values of characters.
ASCII stands for American Standards Code for Information Interchange, implies that every character has some code associated to it. Like uppercase letters A-Z are given numerical values from 65-90 and lowercase a-z are given numbers ranging 97-122. So we will be using these values to solve our problem.
We will traverse the whole string and,
Check if the first character or the immediate character after a space ‘’ is in range a-z then we will subtract the ASCII values of 'A' and 'a' then add the result to the character.
If it is not the first character or the character immediate after the space then we have to check whether the character is in uppercase then convert to lowercase add the character’s value to the result of subtraction of 'a' - 'A'.
Start
In Function int firstupper(char str[], int n)
   Step 1-> Initialize int i
   Step 2-> Loop For i = 0 And i<n And i++
      If i == 0 && str[i] != ' ' || str[i] != ' ' && str[i-1] == ' ' then,
         If str[i] >= 'a' && str[i]<='z' then,
            str[i] = (char)(('A'-'a') + str[i] )
         End If
         Else If str[i] >= 'A' && str[i] <= 'Z' then,
            str[i] = (char)(str[i] + ('a' - 'A'))
         End If
      End Function
In Function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize char str[] = {"sUNIDHi bAnSAL"}
   Step 2-> Declare n set as sizeof(str)/sizeof(str[0])
   Step 3-> firstupper(str, n)
   Step 4-> Print "%s\n", str
End main
 Live Demo
#include <stdio.h>
int firstupper(char str[], int n) {
   int i;
   for(i = 0; i<n; i++) {
      if (i == 0 && str[i] != ' ' || str[i] != ' ' && str[i-1] == ' ') {
         if(str[i] >= 'a' && str[i]<='z') {
            str[i] = (char)(('A'-'a') + str[i] );
         }
      } else if (str[i] >= 'A' && str[i] <= 'Z') {
         str[i] = (char)(str[i] + ('a' - 'A'));
      }
   }
   return 0;
}
int main(int argc, char const *argv[]) {
   char str[] = {"sUNIDHi bAnSAL"};
   int n = sizeof(str)/sizeof(str[0]);
   firstupper(str, n);
   printf("%s\n", str);
   return 0;
}
Sunidhi Bansal
Sum of even numbers from n to m regardless if n<m or n>m JavaScript

We are required to write a function that takes two numbers as arguments m and n, and it returns
the sum of all even numbers that falls between m and n (both inclusive)
For example −
If m = 10 and n = -4
The output should be 10+8+6+4+2+0+(-2)+(-4) = 24
We will first calculate the sum of all even numbers up to n and the sum of all even numbers up to m.
Then we will check for the bigger of the two m and n. Subtract the sum of smaller from the sum
of bigger which will eventually give us the sum between m and n.
Sum of all even number from 0 to N is given by −
N×(N+2)4
Therefore, let’s put all this into code −
const sumEven = n => (n*(n+2))/4;
const evenSumBetween = (a, b) => {
   return a > b ? sumEven(a) - sumEven(b) + b : sumEven(b) - sumEven(a) + a;
};
console.log(evenSumBetween(-4, 10));
console.log(evenSumBetween(4, 16));
console.log(evenSumBetween(0, 10));
console.log(evenSumBetween(8, 8));
console.log(evenSumBetween(-4, 4));
The output in the console will be −
24
70
30
8
0
Multiple Goroutines

05 Jun, 2022
Prerequisite: Multiple Goroutines A Goroutine is a function or method which executes independently and simultaneously in connection with any other Goroutines present in your program. Or in other words, every concurrently executing activity in Go language is known as a Goroutines. In Go language, you are allowed to create multiple goroutines in a single program. You can create a goroutine simply by using go keyword as a prefixing to the function or method call as shown in the below syntax:
func name(){

// statements
}

// using go keyword as the 
// prefix of your function call
go name()
Now we discuss how to create and work on multiple goroutines with the help of an example: 
C
// Go program to illustrate Multiple Goroutinespackage main import (    "fmt"    "time") // For goroutine 1func Aname() {     arr1 := [4]string{"Rohit", "Suman", "Aman", "Ria"}     for t1 := 0; t1 <= 3; t1++ {             time.Sleep(150 * time.Millisecond)        fmt.Printf("%s\n", arr1[t1])    }} // For goroutine 2func Aid() {     arr2 := [4]int{300, 301, 302, 303}         for t2 := 0; t2 <= 3; t2++ {             time.Sleep(500 * time.Millisecond)        fmt.Printf("%d\n", arr2[t2])    }} // Main functionfunc main() {     fmt.Println("!...Main Go-routine Start...!")     // calling Goroutine 1    go Aname()     // calling Goroutine 2    go Aid()     time.Sleep(3500 * time.Millisecond)    fmt.Println("\n!...Main Go-routine End...!")}
Output:
!...Main Go-routine Start...!
Rohit
Suman
Aman
300
Ria
301
302
303

!...Main Go-routine End...!
Creation: In the above example, we have two goroutines other than main goroutine, i.e, Aname, and Aid. Here, Aname prints the name of the authors and Aid prints the id of the authors. Working: Here, we have two goroutines, i.e, Aname, and Aid and one main goroutine. When we run this program first the main goroutine start and print “!...Main Go-routine Start...!”, here the main goroutine is like a parent and other goroutines are its children so first main goroutine run after that those other goroutines start and if the main goroutine terminates, then other goroutines are also terminated. So, after the main goroutine, Aname and Aid goroutines start their working concurrently. The Aname goroutine starts it working from 150ms and Aid start its working from 500ms as shown in the below image: 
vinayedula
Golang
Golang-Concurrency
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Server Mathematical functions (SQRT, PI, SQUARE, ROUND, CEILING & FLOOR)

21 Mar, 2018
Mathematical functions are present in SQL server which can be used to perform mathematical calculations. Some commonly used mathematical functions are given below:1. SQRT():SQRT() function is the most commonly used function. It takes any numeric values and returns the square root value of that number.
Syntax:
SELECT SQRT(..value..)
Example:
2. PI(): There are calculations which require use of pi. Using pi() function, value of PI can be used anywhere in the query.
Syntax:
SELECT PI()
Example:
3. SQUARE(): SQUARE() function is used to find the square of any number.
Syntax:
SELECT SQUARE(..value..)
Example:
4. ROUND(): ROUND() function is used to round a value to the nearest specified decimal place.
Syntax:
SELECT ROUND(..value.., number_of_decimal_places)
Example:
5. CEILING() and FLOOR()CEILING(): CEILING() function is used to find the next highest value (integer).
Syntax:
SELECT CEILING(..value..)
FLOOR(): FLOOR() function returns the next lowest value (integer).Syntax:
SELECT FLOOR(..value..)
Example:
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
Window functions in SQL
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
ReactJS componentDidUpdate() Method

31 Dec, 2020
The componentDidUpdate() method allows us to execute the React code when the component is updated. All the network requests that are to be made when the props passed to the component changes are coded here.
The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes.
Syntax:
componentDidUpdate(prevProps, prevState, snapshot)
Parameters: Following are the parameter used in this function:
prevProps: Previous props passed to the component
prevState: Previous state of the component
snapshot: Value returned by getSnapshotBeforeUpdate() method
Tip: To avoid an infinite loop, all the network requests are needed to be inside a conditional statement as:
componentDidUpdate(prevProps, prevState) {
  if (prevState.data !== this.state.data) {
    // Now fetch the new data here.
  }
}
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a React application that changes the text in the heading when the state of the component is updated.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';  class App extends React.Component {  // Defining the state  state = {    company: 'GFG'  };    componentDidMount() {    // Changing the state after 600ms    setTimeout(() => {      this.setState({ company: 'GeeksForGeeks' });    }, 600);  }    componentDidUpdate() {    document.getElementById('disclaimer').innerHTML =      'P.s:  GFG is also known as ' + this.state.company;  }    render() {    return (      <div>        <h1 style={{          margin: 'auto',          width: '50%',          padding: 20,          marginTop: '10%',          border: 'solid 1px black',          textAlign: 'center',          fontSize: 18,        }}>          Greatest Science Portal For Geeks :          {this.state.company}          <div id="disclaimer"></div>        </h1>      </div>    );  }}  export default App;
Note: You can apply your own styling to the application.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
Output
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
How to float three div side by side using CSS?
ReactJS | Router
How to get character array from string in JavaScript?
Matplotlib.figure.Figure.set_dpi() in Python

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_dpi() method figure module of matplotlib library is used to set the resolution of the figure in dots-per-inch.
Syntax: set_dpi(self, val)
Parameters: This method accept the following parameters that are discussed below:
val : This parameter is the float value.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_dpi() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np         fig = plt.figure(figsize =(5, 4))       ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])    xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))    fig.set_dpi(150.0)    fig.suptitle("""matplotlib.figure.Figure.set_dpi()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np        fig = plt.figure(facecolor ="lightgreen")       ax = Subplot(fig, 111) fig.add_subplot(ax)       ax.axis["left"].set_visible(False) ax.axis["top"].set_visible(False)   fig.set_dpi(90.0)    fig.suptitle("""matplotlib.figure.Figure.set_dpi()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
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
turtle.Screen().bgcolor() function in Python

17 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set or return background color of the Turtle Screen.
Syntax:
turtle.bgcolor(*args)

Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle  # set the background color# of the turtle screenturtle.Screen().bgcolor("orange")  # move turtleturtle.forward(100)
Output :
Example 2 :
Python3
# importing packageimport turtle  # set the background color# of the turtle screenturtle.Screen().bgcolor(0,0,255)  # move turtleturtle.forward(100)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python – Extract dictionary items with List elements

31 Jan, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let’s discuss certain ways in which this task can be performed. 
Input : test_dict = {‘gfg’ : [4, 6, 10], ‘is’ : [12]} Output : {‘gfg’: [4, 6, 10]}Input : test_dict = {‘gfg’ : [4, 6, 10]} Output : {‘gfg’: [4, 6, 10]}  
Method #1 : Using set() + dictionary comprehension + items() The combination of above functionalities can be used to solve this problem. In this, we first reduce the list elements to remove duplicate, extract dictionary items using items() and construction of required dictionary happens using dictionary comprehension. 
Python3
# Python3 code to demonstrate working of# Extract dictionary items with List elements# Using set() + dictionary comprehension + items() # helpr_fncdef hlper_fnc(req_list, test_dict):    temp = set(req_list)    temp2 = { key: set(val) for key, val in test_dict.items() }    return { key: val for key, val in test_dict.items() if temp2[key].issubset(temp)} # initializing dictionarytest_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing req_listreq_list = [4, 6, 10] # Extract dictionary items with List elements# Using set() + dictionary comprehension + items()res = hlper_fnc(req_list, test_dict)     # printing resultprint("The extracted dictionary: " + str(res))
The original dictionary : {‘is’: [10], ‘best’: [4, 5, 7], ‘gfg’: [4, 6]} The extracted dictionary: {‘is’: [10], ‘gfg’: [4, 6]} 
 
 Method #2 : Using all() + dictionary comprehension The combination of above functions can be used to solve this problem. This is one-liner solution and uses all() to check for elements membership to decide for filtration. The dictionary comprehension performs task of construction of dictionary. 
Python3
# Python3 code to demonstrate working of# Extract dictionary items with List elements# Using all() + dictionary comprehension # initializing dictionarytest_dict = {'gfg' : [4, 6], 'is' : [10], 'best' : [4, 5, 7]} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing req_listreq_list = [4, 6, 10] # Extract dictionary items with List elements# Using all() + dictionary comprehensionres = {key: val for key, val in test_dict.items() if all(vals in req_list for vals in val)}     # printing resultprint("The extracted dictionary: " + str(res))
The original dictionary : {'is': [10], 'best': [4, 5, 7], 'gfg': [4, 6]}
The extracted dictionary: {'is': [10], 'gfg': [4, 6]}
 
adnanirshad158
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optional orElse() method in Java with examples

30 Jul, 2019
The orElse() method of java.util.Optional class in Java is used to get the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value.
Syntax:
public T orElse(T value)

Parameters: This method accepts value as a parameter of type T to return if there is no value present in this Optional instance.
Return value: This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value.
Below programs illustrate orElse() method:Program 1:
// Java program to demonstrate// Optional.orElse() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);          // orElse value        System.out.println("Value by orElse"                           + "(100) method: "                           + op.orElse(100));    }}
Optional: Optional[9455]
Value by orElse(100) method: 9455

Program 2:
// Java program to demonstrate// Optional.orElse() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // orElse value            System.out.println("Value by orElse"                               + "(100) method: "                               + op.orElse(100));        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
Value by orElse(100) method: 100

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElse-T-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Shuffle dictionary Values

24 Jan, 2021
Given a dictionary, the task is to write a python program to shuffle its values to different keys.
Examples:
Input: test_dict = {“gfg” : 1, “is” : 7, “best” : 8, “for” : 3, “geeks” : 9}
Output : {“gfg” : 9, “is” : 8, “best” : 7, “for” : 3, “geeks” : 1}
Explanation : Keys are at same position but values are shuffled.
Input : test_dict = {“gfg” : 7, “is” : 1, “best” : 8, “for” : 3, “geeks” : 9}
Output : {“gfg” : 9, “is” : 8, “best” : 7, “for” : 3, “geeks” : 1}
Explanation : Keys are at same position but values are shuffled.
Method #1 : Using shuffle() + zip() + dict()
In this, we perform the task of shuffling elements using shuffle(), and zip() is used to map the shuffled values to keys. In the end, dict() is used to convert the result to a dictionary.
Python3
# Python3 code to demonstrate working of# Shuffle dictionary Values# Using shuffle() + zip() + dict()import random  # initializing dictionarytest_dict = {"gfg": 1, "is": 7, "best": 8,              "for": 3, "geeks": 9}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # shuffling valuestemp = list(test_dict.values())random.shuffle(temp)  # reassigning to keysres = dict(zip(test_dict, temp))  # printing resultprint("The shuffled dictionary : " + str(res))
Output:
The original dictionary is : {‘gfg’: 1, ‘is’: 7, ‘best’: 8, ‘for’: 3, ‘geeks’: 9}
The shuffled dictionary : {‘gfg’: 1, ‘is’: 7, ‘best’: 3, ‘for’: 9, ‘geeks’: 8}
Method #2 : Using sample() + zip()
In this, the task of shuffling values is done using sample() of random library.
Python3
# Python3 code to demonstrate working of# Shuffle dictionary Values# Using sample() + zip()from random import sample  # initializing dictionarytest_dict = {"gfg": 1, "is": 7, "best": 8,              "for": 3, "geeks": 9}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # reassigning to keysres = dict(zip(test_dict, sample(list(test_dict.values()),                                  len(test_dict))))  # printing resultprint("The shuffled dictionary : " + str(res))
Output:
The original dictionary is : {‘gfg’: 1, ‘is’: 7, ‘best’: 8, ‘for’: 3, ‘geeks’: 9}
The shuffled dictionary : {‘gfg’: 8, ‘is’: 9, ‘best’: 1, ‘for’: 3, ‘geeks’: 7}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Methods With Same Name in Golang

26 Aug, 2019
In Go language, it is allowed to create two or more methods with the same name in the same package, but the receiver of these methods must be of different types. This feature does not available in Go function, means you are not allowed to create same name methods in the same package, if you try to do, then the compiler will throw an error.
Syntax:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){// Code}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){// Code}
Let us discuss this concept with the help of the examples:
Example 1:
// Go program to illustrate how to// create methods of the same namepackage main  import "fmt"  // Creating structurestype student struct {    name   string    branch string}  type teacher struct {    language string    marks    int}  // Same name methods, but with// different type of receiversfunc (s student) show() {      fmt.Println("Name of the Student:", s.name)    fmt.Println("Branch: ", s.branch)}  func (t teacher) show() {      fmt.Println("Language:", t.language)    fmt.Println("Student Marks: ", t.marks)}  // Main functionfunc main() {      // Initializing values    // of the structures    val1 := student{"Rohit", "EEE"}      val2 := teacher{"Java", 50}      // Calling the methods    val1.show()    val2.show()}
Output:
Name of the Student: Rohit
Branch:  EEE
Language: Java
Student Marks:  50

Explanation: In the above example, we have two same name methods, i.e, show() but with different type of receivers. Here first show() method contain s receiver which is of the student type and the second show() method contains t receiver which is of the teacher type. And in the main() function, we call both the methods with the help of their respective structure variables. If you try to create this show() methods with the same type of receiver, then the compiler throws an error.
Example 2:
// Go program to illustrate how to// create the same name methods// with non-struct type receiverspackage main  import "fmt"  type value_1 stringtype value_2 int  // Creating same name function with// different types of non-struct receiversfunc (a value_1) display() value_1 {      return a + "forGeeks"}  func (p value_2) display() value_2 {      return p + 298}  // Main functionfunc main() {      // Initializing the values    res1 := value_1("Geeks")    res2 := value_2(234)      // Display the results    fmt.Println("Result 1: ", res1.display())    fmt.Println("Result 2: ", res2.display())}
Output:
Result 1:  GeeksforGeeks
Result 2: 532

Go-Functions
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Physical and Logical Tags in HTML

25 Feb, 2021
Physical and Logical tags are used in HTML for better visibility and understanding of the text by the user on the web page. However, both tags differ from each other as suggested by their names.
Logical Tags  :Logical Tags are used in HTML to display the text according to the logical styles. Following are the Logical tags commonly used in HTML.
Logical Tags
Sample Code using Logical Tags:
HTML
<!DOCTYPE html><html><head><title>Page Title</title></head><body>  <h1> Logical Tags </h1>   Welcome to <abbr title="GeeksforGeeks"> GFG</abbr> <br>    This is <acronym title="GeeksforGeeks">GFG</acronym> <br>    <address> GeeksforGeeks, 5th & 6th Floor, Royal Kapsons, A- 118, Sector- 136, Noida, Uttar Pradesh (201305) </address> <br>    <cite> GeeksforGeeks </cite> is my favourite website. <br>    <code> Sample code: system.out.println(); </code>    <blockquote cite="https://www.geeksforgeeks.org/">A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes.</blockquote>    <del> This contains deleted content.</del>    <ins> Newly inserted content.</ins>      <p><dfn> GeeksforGeeks </dfn> is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, and quizzes.</p>      <kbd> GeeksforGeeks - This is a Keyboard input </kbd>    <pre>    Dear User,      Congratulations !!        We are delighted to inform you that you are going to be part of GfG journey.          Thanks,    GfG Team    This is a predefine formatted text </pre>      </body></html>
Output:
Physical Tags 
Physical Tags are used in HTML to provide actual physical formatting to the text. Following are the Physical tags commonly used in HTML.
Physical Tags
Sample Code using Physical Tags:
HTML
<!DOCTYPE html><html><head><title>Physical Tags</title></head><body>    <h1> Physical Tags </h1>Text without any formatting <br><b> GeeksforGeeks- This is Bold text </b> <br><big> GeeksforGeeks- This is BIG text </big> <br><i> GeeksforGeeks- This is Italic text </i> <br><small> GeeksforGeeks- This is Small text </small> <br>1<sup>st </sup> <br>H<sub>2</sub>O <br><tt> GeeksforGeeks- This is teletype text </tt> <br><u> GeeksforGeeks- This is underlined text</u> <br>    </body></html>
Output:
HTML-Tags
Picked
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Form validation using HTML and JavaScript
Python – Test if a list is completely True

29 Dec, 2019
Sometimes, we need to check if a list is completely True, these occurrences come more often in testing purposes after the development phase. Hence, having a knowledge of all this is necessary and useful. Lets discuss certain ways in which this can be performed.
Method #1 : Naive MethodIn the naive method, we just run a loop from beg to end of list and check manually for each value. This is the most basic way to perform this particular task.
# Python3 code to demonstrate # Pure List Test# using naive method  # initializing list test_list = [True, True, True, True]  # printing original listprint ("The original list is : " + str(test_list))  flag = 0  # using naive method # Pure List Testfor i in test_list :    if not i :        flag = 1        break  # printing resultprint ("Is List completely True ? : " + str(bool(not flag)))
The original list is : [True, True, True, True]
Is List completely True ? : True

 
Method #2 : Using all()This function tests each value to be True and if yes, returns boolean True, else returns false. The list iteration is done using list comprehension.
# Python3 code to demonstrate # Pure List Test# using all()  # initializing list test_list = [True, True, True, True]  # printing original listprint ("The original list is : " + str(test_list))  flag = 0  # using all()# Pure List Test res = all(i for i in test_list)  # printing resultprint ("Is List completely True ? : " + str(res))
The original list is : [True, True, True, True]
Is List completely True ? : True

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

Python object oriented programming allows variables to be used at the class level or the instance level where variables are simply the symbols denoting value you’re using in the program. 
At the class level, variables are referred to as class variables whereas variables at the instance level are referred to as instance variables. Let’s understand the class variable and instance variable through a simple example −
# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
obj1.animal_type = "BigFish"

print ("\nPrinting class variable after making changes to one instance")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)
In above program, we have created a Shark class and then we are trying to change the class variable using object, this will create a new instance variable for that particular object and this variable shadows the class variable.
Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish

Printing class variable after making changes to one instance
obj1.animal_type= BigFish
obj2.animal_type = fish
Let’s modify our above program so as to get the correct output −
# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
#obj1.animal_type = "BigFish"

Shark.animal_type = "BigFish"
print("New class variable value is %s, changed through class itself" %(Shark.animal_type))

print ("\nPrinting class variable after making changes through instances")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)
Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish
New class variable value is BigFish, changed through class itself

Printing class variable after making changes through instances
obj1.animal_type= BigFish
obj2.animal_type = BigFish
MySQL query to update all records to capitalize only the first letter and set all others in lowercase

Let us first create a table −
mysql> create table DemoTable2017
   -> (
   -> Name text
   -> );
Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2017 values('JOHN SMITH,MYSQL');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable2017 values('DAVID MILLER,MONGODB');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2017 values('CHRIS BROWN,JAVA');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2017;
This will produce the following output −
+----------------------+
| Name                 |
+----------------------+
| JOHN SMITH,MYSQL     |
| DAVID MILLER,MONGODB |
| CHRIS BROWN,JAVA     |
+----------------------+
3 rows in set (0.00 sec)
Here is the query to set only the first letter in capital and rest in lower case −
mysql> update DemoTable2017
   -> set Name=REPLACE(CONCAT(UPPER(LEFT(Name, 1)), 
LOWER(SUBSTRING(Name, 2))),' , ', ', ');
Query OK, 3 rows affected (0.16 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2017;
This will produce the following output −
+----------------------+
| Name                 |
+----------------------+
| John smith,mysql     |
| David miller,mongodb |
| Chris brown,java     |
+----------------------+
3 rows in set (0.00 sec)
Primality Test in C++

In this problem, we are given a number N and our task is to check whether it is a prime number or not.
Primality test s the algorithm that is used to check whether the given number is prime or not.
Prime number is a number which can be divided by itself only. Example : 2, 3, 5, 7.
Let’s take an example to understand our problem,
Input: 11
Output: Yes
There are multiple methods to check for primality test of a number.
One simple method to check for primality is by checking the division of the number by all numbers less than N. If any number divides N, then it is not a prime number.
Check for all i = 2 - n-1. If n/i == 0, its not a prime number.
This method can be made more efficient by making these small changes in the algorithm.
First, we should check for values till √n instead of n. This will save a lot of loop values. √n include values of all probable factors of n.
Other change could be checking division by 2 and 3. Then checking of loop values from 5 to √n.
Program to show the implementation of this algorithm
 Live Demo
#include <iostream>
using namespace std;
bool isPrimeNumber(int n){
   if (n <= 1)
      return false;
   if (n <= 3)
   return true;
   if (n % 2 == 0 || n % 3 == 0)
      return false;
   for (int i = 5; i * i <= n; i = i + 6)
   if (n % i == 0 || n % (i + 2) == 0)
   return false;
   return true;
}
int main() {
   int n = 341;
   if (isPrimeNumber(n))
      cout<<n<<" is prime Number.";
   else
      cout<<n<<" is not prime Number.";
   return 0;
}
341 is not prime Number.
Other more effective method to check from the primality of a number is using Fermat’s method which is based on Fermat’s Little Theorem.
Fermat’s Little Theorem  For a prime number N, Every value of x belonging to (1, n-1). The below is true,
a n-1 ≡ 1 (mod n)
or
a n-1 % n = 1
Program to show implementation of this theorem,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
int power(int a, unsigned int n, int p) {
   int res = 1;
   a = a % p;
   while (n > 0){
      if (n & 1)
      res = (res*a) % p;
      n = n/2;
      a = (a*a) % p;
   }
   return res;
}
int gcd(int a, int b) {
   if(a < b)
      return gcd(b, a);
   else if(a%b == 0)
      return b;
   else return gcd(b, a%b);
}
bool isPrime(unsigned int n, int k) {
   if (n <= 1 || n == 4) return false;
   if (n <= 3) return true;
   while (k>0){
      int a = 2 + rand()%(n-4);
      if (gcd(n, a) != 1)
         return false;
      if (power(a, n-1, n) != 1)
         return false;
      k--;
   }
   return true;
}
int main() {
   int k = 3, n = 23;
   if(isPrime(n, k)){
      cout<<n<<" is a prime number";
   }
   else
      cout<<n<<" is not a prime number";
   return 0;
}
23 is a prime number
How to Use the IN Operator with a SubQuery in SQL? - GeeksforGeeks

19 Oct, 2021
In this article, we will see the use of IN Operator with a SubQuery in SQL. IN operator is used to compare the column values with the list of values. The list of values is defined after IN query in SQL. 
If we don’t know the exact list of values to be compared, we can generate the list of values using the query. 
Syntax:
Without subquery:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
with subquery
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT statement);
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geek’s database. The demo_table has the student’s data with their age and the grades obtained by them.
Query:
CREATE TABLE demo_table(
NAME VARCHAR(20),
AGE int,
GRADE VARCHAR(5));
Step 4: Insert data into a table
Query:
INSERT INTO demo_table
VALUES ('Romy',22, 'A'),
('Roshini', 20, 'A'),
('Akanksha', 22, 'A'),
('Shalini',23,'B'),
('Sambhavi',21,'A'),
('Meenakshi',22,'C'),
('Nikhil',24,'B'),
('Manu',25,'B'),
('Rohit',24,'C'),
('Astha',23,'A'),
('Samiksha',23,'A');
Step 5: View the content
Execute the below query to see the content of the table
SELECT * FROM demo_table;
Output:
Step 6: Use of In operator with a subquery
To get the data of students whose name starts with R.
Query:
SELECT * FROM demo_table
WHERE NAME IN  
(SELECT NAME FROM demo_table WHERE NAME LIKE 'R%') ;
Output:
To get the data of students whose age is more than 22.
Query:
SELECT * FROM demo_table
WHERE AGE IN  
(SELECT AGE FROM demo_table WHERE AGE>22) ;
Output:
Picked
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Types of Internet Protocols
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Loading and Saving Images in Python | by Renu Khandelwal | Towards Data Science

Install PIL, OpenCV, and matplotlib libraries.
Show() loads the image in a new window
from PIL import Imageimg_PIL = Image.open(r'\dogs-v-cats\dog.1.jpg')img_PIL.show()
display() loads the image inline
from IPython.display import displayfrom PIL import Imageimg_PIL = Image.open(r'\dogs-v-cats\dog.1.jpg')display(img_PIL)
You can save the JPEG image in a different format like PNG using save() of the PIL
img_PIL.save(r'\dogs-v-cats\dog.1.png')
import cv2image_cv2= cv2.imread(r'\dogs-v-cats\dog.1.png')cv2.imshow("Dog Image using OpenCV", image_cv2)cv2.waitKey(0)cv2.destroyAllWindows()
imread() reads the image.
The first parameter is the path that contains the image. The second parameter is a flag that tells us how the image should be read. Options for the flag parameter is
cv2.IMREAD_COLOR or 1: This is the default value and will load the color image
cv2.IMREAD_GRAYSCALE or 0: will load the image in grayscale
cv2.IMREAD_UNCHANGED or -1: Loads image as such, including the alpha channel.
imshow() display the image in a window
The first parameter is the window name, and the second parameter is the image.
waitKey() is a keyboard binding function.
If you specify a numeric value other than 0, then it will wait for specified milliseconds for any keyboard event. If you press any key, then the program will continue. If you specify 0 as the value, then it will wait indefinitely
destroyAllWindows() will destroy all windows created.
To destroy specific windows, you can use destroyWindow() to which you will pass the window name
import cv2image_cv2= cv2.imread(r'\dogs-v-cats\dog.1.png')cv2.imshow("Dog Image using OpenCV", image_cv2)cv2.waitKey(6000)cv2.destroyWindow("Dog Image using OpenCV")
result=cv2.imwrite(r'\dogs-v-cats\dog.100.png’, image_cv2)if result==True:  print(“File saved successfully”)else:  print(“Error in saving file”)
imwrite() saves the image file to the specified path. The first parameter is the path where you want to save the file, and the second parameter is the image to be saved.
import matplotlib.pyplot as pltimport matplotlib.image as mpimg%matplotlib inlineimage_mp= mpimg.imread(r'\dogs-v-cats\dog.1.jpg')imgplot=plt.imshow(image_mp)plt.plot()
imread() of matplotlib reads an image file from the specified path into an array. The second parameter is optional and specifies the format of the file like ‘JPEG’ or “PNG’. Default value is ‘PNG.’
imshow() of matplotlib display the data array as an image
you can also use plt.show() to display the image
import matplotlib.pyplot as pltimport matplotlib.image as mpimg%matplotlib inlineimage_mp= mpimg.imread(r'\dogs-v-cats\dog.1.jpg’, “JPG”)imgplot=plt.imshow(image_mp)plt.show()
plt.savefig(r'\dogs-v-cats\dog.2.png')
savefig() saves the current figure to the specified file
Python has several libraries like OpenCV, PIL, and matplotlib that can be used to load and save the image. In the next article, you will learn different image processing techniques like rotating the images, de-noising the images, cropping the images, converting the RGB image to the grayscale image, increasing the sharpness of the image.
How to clear items from a ttk.Treeview widget?

Generally, Tkinter treeview widget is used to draft or construct tables for the given data points in the input. We can even add items in the treeview widget to maintain a nested list in an application. If we want to remove or clear all the items in a given treeview widget, then we have to first select all the items present in the treeview widget using get_children() method.
Once we have selected all the treeview items programmatically, then we can delete the items using delete(item) method. In order to get all the children, we can use the delete() method inside a loop.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window
win.geometry("700x350")
s = ttk.Style()
s.theme_use('clam')

# Define a function to clear all the items present in Treeview
def clear_all():
   for item in tree.get_children():
      tree.delete(item)

# Add a Treeview widget
tree= ttk.Treeview(win, column=("c1", "c2"), show= 'headings', height= 6)
tree.column("# 1",anchor=CENTER)
tree.heading("# 1", text= "ID")
tree.column("# 2", anchor= CENTER)
tree.heading("# 2", text= "FName")

# Insert the data in Treeview widget
tree.insert('', 'end',text= "1",values=('1','Honda'))
tree.insert('', 'end',text= "2",values=('2', 'Hyundai'))
tree.insert('', 'end',text= "3",values=('3', 'Tesla'))
tree.insert('', 'end',text= "4",values=('4', 'Volkswagen'))
tree.insert('', 'end',text= "5",values=('5', 'Tata'))
tree.insert('', 'end',text= "6",values=('6', 'Renault'))

tree.pack()

# Create a Button for clearing the Treeview Item
ttk.Button(win, text= "Clear", command= clear_all).pack(pady=10)

win.mainloop()
When we run the above code, it will display a window that contains a table and a Button widget.
Once we click the button, it will clear all the content of the treeview widget.
How to calculate a directory size using Python?

To get the size of a directory, you'll have to walk the whole directory tree and add size of each file. To do this you can use the os.walk() and os.path.getsize() functions.
import os
total_size = 0
start_path = '.'  # To get size of current directory
for path, dirs, files in os.walk(start_path):
    for f in files:
        fp = os.path.join(path, f)
        total_size += os.path.getsize(fp)
print("Directory size: " + str(total_size))
If you're on *NIX OSes then you could simply call the du command using subprocess module as it is much easier than the way above.
import subprocess
path = '.'
size = subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
print("Directory size: " + size)
Running either program will give the output:
Directory size: 1524664