code-rag-bench/online-tutorials huggingface dataset:
How to fetch only a single result from a table in Java-MySQL?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.37 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.54 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(103,'Mike');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+------+-------+
| Id   | Name  |
+------+-------+
| 101  | Chris |
| 102  | David |
| 103  | Mike  |
+------+-------+
3 rows in set (0.00 sec)
Let us now see the Java-MySQL code. This will fetch only a single record from the top of the table −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class OneResultDemo {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      Statement st = null;
      ResultSet rs = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456");
         String query = "select *from DemoTable " + " limit 1";
         st = con.createStatement();
         rs = st.executeQuery(query);
         while (rs.next()) {
            System.out.println("Id=" + rs.getInt("Id"));
            System.out.println("Name=" + rs.getString("Name"));
         }
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}
This will produce the following output −
Id=101
Name=Chris
How to change the owner of a file using Python?

You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:
import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = 'my_folder'
os.chown(path, uid, gid)
How to find numbers in an array that are greater than, less than, or equal to a value in java?

You can find numbers in an array that are greater than, less than, or equal to a value as:
Live Demo
public class GreaterOrLess {
   public static void main(String args[]) {
      int value = 65;
      int[] myArray = {41, 52, 63, 74, 85, 96 };
      System.out.println("Elements of the array that are equal to the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value==myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
      System.out.println("Elements of the array that are greater than the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value<=myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
      System.out.println("Elements of the array that are less than the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value>myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
   }
}
Elements of the array that are equal to the given value are::
Elements of the array that are greater than the given value are::
Index ::3 Element::74
Index ::4 Element::85
Index ::5 Element::96
Elements of the array that are less than the given value are::
Index ::0 Element::41
Index ::1 Element::52
Index ::2 Element::63
HTML <option> selected Attribute

The selected attribute in the <option> element pre-selects an option when the page loads. The same option would be visible.
Following is the syntax −
<option selected>
Let us now see an example to implement the selected attribute of the <option> element −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Educational Qualification</h1>
<h2>Postgraduation</h2>
<select>
   <option value="mca">MCA</option>
   <option value="mcom">M.COM</option>
   <option value="mtech" selected>M.TECH</option>
   <option value="msc">M.Sc</option>
</select>
</body>
</html>
In the above example, we have a <select> to set a drop-down list:
<select>
<option value="mca">MCA</option>
<option value="mcom">M.COM</option>
<option value="mtech" selected>M.TECH</option>
<option value="msc">M.Sc</option>
</select>
In that, different options are set with <option> element −
<option value="mca">MCA</option>
<option value="mcom">M.COM</option>
<option value="mtech" selected>M.TECH</option>
<option value="msc">M.Sc</option>
We have set the default visible option when the page loads using the selected attribute −
<option value="mtech" selected>M.TECH</option>
Adding Tags Using Django-Taggit in Django Project

18 Apr, 2022
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project 
Installing django-taggit  
pip install django-taggit
ADD it to Main Project’s settings.py file  
Python3
INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'django.contrib.humanize',    'taggit']
Changes To models.py file  
Add TaggableManager in your post, blog, article modal
Python3
from django.db import modelsfrom django.utils.timezone import nowfrom taggit.managers import TaggableManager class Post(models.Model):    postid = models.AutoField(primary_key=True)    title = models.CharField(max_length=255)    content = models.TextField()    author = models.CharField(max_length=100)    postauthor = models.ForeignKey(User, on_delete=models.CASCADE)    slug = models.SlugField(unique=True)    category = models.CharField(max_length=200)    timestamp = models.DateTimeField(default=now, blank=True)    tags = TaggableManager()
After adding TaggableManager run following commands in terminal
python manage.py makemigrationspython manage.py migrate
The TaggableManager will show up automatically as a field in post modal  
 
The Taggit Modal will also appear automatically as a separate modal in admin panel 
 
Taggit Modal In Admin Panel
 
 
Adding tags 
1) If the tags input doesn’t contain any commas or double quotes, it will be taken as space-delimited list of tag names.  
geeks for geeks => "geeks", "for", "geeks"
2) If the tags input does contain commas or double quotes then :  
       
a) geeks, geeks for geeks            =>   "geeks", "geeks for geeks" 
b) "geeks, forgeeks" geek geeksfor   =>   "geeks, forgeeks", "geek", "geeksfor"
c) "geeks, forgeeks", geek geeksfor  =>   "geeks, forgeeks", "geeks geeksfor"
d) geeks "for" geeks                 =>   "geeks", "for", "geeks"
 
After Adding Tags to the posts the taggit modal will look like :
 
All the tags which are associated with different posts will appear in tags modal under taggit
 
On clicking the particular tag, There will come a list of all the posts associated with that particular tag. Now this model can be used with the project like other models
 
sagar0719kumar
rkbhola5
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DIFFERENCE() Function in SQL Server

13 Oct, 2020
The DIFFERENCE() function compares two different SOUNDEX values, and return the value of the integer. This value measures the degree that the SOUNDEX values match, on a scale of 0 to 4. A value of 0 indicates a weak or no similarity between the SOUNDEX values; 4 indicates that the SOUNDEX values are extremely similar, or even identical.
Syntax :
DIFFERENCE(string, string)
Parameter : This method accepts two-parameters as mentioned above and described below –
string, string –It is an alphanumeric expression of character data. It can be a constant, variable, or column.
Returns : It returns an integer value measuring the difference between the SOUNDEX() values of two different string.
Example-1 :Using DIFFERENCE() function with similar SOUNDEX() values.
SELECT SOUNDEX('poor') soundex_poor, SOUNDEX('pour') soundex_pour, 
DIFFERENCE('poor', 'pour') similarity;
Output :
Example-2 :Returns a DIFFERENCE value of 3, the less possible difference.
SELECT SOUNDEX('GeeksForGeeks'), SOUNDEX('GeeksOfGeeks'),
DIFFERENCE('GeeksForGeeks', 'GeeksOfGeeks');
Output :
3
Example-3 :Returns a DIFFERENCE value of 2, the medium possible difference.
SELECT SOUNDEX('GeeksForGeeks') soundex_GeeksForGeeks, SOUNDEX('GFG') soundex_GFG,
DIFFERENCE('GeeksForGeeks', 'GFG') similarity;
Output :
Example-4 :Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('javascript') soundex_javascript, SOUNDEX('c#') soundex_c#,
DIFFERENCE('javascript', 'c#') similarity;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby Integer odd? function with example

07 Jan, 2020
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false.
Syntax: number.odd?
Parameter: The function takes the integer which is to be checked for odd or not.
Return Value: The function returns a boolean value which determines if the value is odd or not.
Example #1:
# Ruby program of integer odd? function  # Initializing the numbers num1 = 19num2 = 2num3 = 28num4 = 13   # Prints true if number is oddputs num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?
Output:
true
false
false
true

Example #2:
# Ruby program of integer odd? function  # Initializing the numbers num1 = 18num2 = 200num3 = 2987num4 = 13   # Prints true if number is odd puts num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?
Output:
false
false
true
true

Ruby Integer-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby on Rails Introduction
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Exception handling
Ruby | Types of Variables
Why is a C++ pure virtual function initialized by 0?

It’s just a syntax, nothing more than that for saying that “the function is pure virtual”.
A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in declaration.
Here is an example of pure virtual function in C++ program
 Live Demo
#include<iostream>
using namespace std;
class B {
   public: virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
   public: void s() {
      cout << " Virtual Function in Derived class\n";
   }
};

int main() {
   B *b;
   D dobj;
   b = &dobj;
   b->s();
}
Virtual Function in Derived class
C++ Program to Perform Finite State Automaton based Search

This is a C++ program to perform finite state automaton based search. An automaton with a finite number of states is called a Finite Automaton. Here, a text is given text[0 ... t-1] and a pattern p[0 ... p-1] is also given. We have to find the pattern in the text and print its all occurrences at the respective indices.
Begin
   Function void transitiontable():
   1) put the entries in first row and filled it up. All entries in first row are always 0 except the entry for p[0] character. Always we need to go to state 1.
   for p[0].
   2) Initialize longestprefixsuffix as 0.
   3) for i = 1 to P. (Here P is the length of the pattern)
      a) Copy the entries from the row at index equal to longestprefixsuffix.
      b) Update the entry for p[i] character to i+1.
      c) Update longestprefixsuffix = TF[lps][pat[i]]
      where TT is the 2D array.
End
#include<iostream>
#include<cstring>
#define NO_OF_CHARS 512
using namespace std;
// builds the TF table which represents Finite Automata for a given pattern
void transitiontable(char *p, int P, int TT[][NO_OF_CHARS]) {
   int i, longestprefixsuffix = 0, y;
   // put entries in first row
   for (y =0; y < NO_OF_CHARS; y++)
   TT[0][y] = 0;
   TT[0][p[0]] = 1;
   // put entries in other rows
   for (i = 1; i<= P; i++) { // Copy values from row at index longestprefixsuffix
      for (y = 0; y < NO_OF_CHARS; y++)
      TT[i][y] = TT[longestprefixsuffix][y];
      // Update the entry
      TT[i][p[i]] = i + 1;
      // Update lps for next row to be filled
      if (i < P)
         longestprefixsuffix = TT[longestprefixsuffix][p[i]]; // TT is the 2D array which is being constructed.
   }
}
//Prints all occurrences of pattern in text
void patternsearch(char *p, char *t) {
   int P = strlen(p);
   int T = strlen(t);
   int TT[P+1][NO_OF_CHARS];
   transitiontable(p, P, TT);
   // process text over FA.
   int i, j=0;
   for (i = 0; i < T; i++) {
      j = TT[j][t[i]];
      if (j == P) {
         cout<<"\n pattern is found at index: "<< i-P+1;
      }
   }
}
int main() {
   char *text = "AABAA ABBAACCDD CCDDAABAA"; //take the text as input
   char *pattern = "AABAA"; //take the pattern as input
   patternsearch(pattern, text);
   getchar();
   return 0;
}
pattern is found at index: 0
pattern is found at index: 20
ggplot2 - Scatter Plots & Jitter Plots

Scatter Plots are similar to line graphs which are usually used for plotting. The scatter plots show how much one variable is related to another. The relationship between variables is called as correlation which is usually used in statistical methods. We will use the same dataset called “Iris” which includes a lot of variation between each variable. This is famous dataset which gives measurements in centimeters of the variables sepal length and width with petal length and width for 50 flowers from each of 3 species of iris. The species are called Iris setosa, versicolor and virginica.
Following steps are involved for creating scatter plots with “ggplot2” package −
For creating a basic scatter plot following command is executed −
> # Basic Scatter Plot
> ggplot(iris, aes(Sepal.Length, Petal.Length)) +
+    geom_point()

We can change the shape of points with a property called shape in geom_point() function.
> # Change the shape of points
> ggplot(iris, aes(Sepal.Length, Petal.Length)) +
+    geom_point(shape=1)

We can add color to the points which is added in the required scatter plots.
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+    geom_point(shape=1)

In this example, we have created colors as per species which are mentioned in legends. The three species are uniquely distinguished in the mentioned plot.
Now we will focus on establishing relationship between the variables.
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+    geom_point(shape=1) +
+    geom_smooth(method=lm)

geom_smooth function aids the pattern of overlapping and creating the pattern of required variables.
The attribute method “lm” mentions the regression line which needs to be developed.
> # Add a regression line
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+    geom_point(shape=1) +
+    geom_smooth(method=lm)

We can also add a regression line with no shaded confidence region with below mentioned syntax −
># Add a regression line but no shaded confidence region
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+    geom_point(shape=1) +
+    geom_smooth(method=lm, se=FALSE)

Shaded regions represent things other than confidence regions.
Jitter plots include special effects with which scattered plots can be depicted. Jitter is nothing but a random value that is assigned to dots to separate them as mentioned below −
> ggplot(mpg, aes(cyl, hwy)) +
+    geom_point() +
+    geom_jitter(aes(colour = class))
Python NLTK | nltk.tokenize.mwe()

07 Jun, 2019
With the help of NLTK nltk.tokenize.mwe() method, we can tokenize the audio stream into multi_word expression token which helps to bind the tokens with underscore by using nltk.tokenize.mwe() method. Remember it is case sensitive.
Syntax : MWETokenizer.tokenize()Return : Return bind tokens as one if declared before.
Example #1 :In this example we are using MWETokenizer.tokenize() method, which used to bind the tokens which is defined before. We can also add the predefined tokens by using tokenizer.add_mwe() method.
# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer   # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')])   # Create a string inputgfg = "geeks for geeks g f g"   # Use tokenize methodgeek = tk.tokenize(gfg.split())   print(geek)
Output :
[‘geeks_for_geeks’, ‘g_f_g’]
Example #2 :
# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer   # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')])tk.add_mwe(('who', 'are', 'you'))   # Create a string inputgfg = "who are you at geeks for geeks"   # Use tokenize methodgeek = tk.tokenize(gfg.split())   print(geek)
Output :
[‘who_are_you’, ‘at’, ‘geeks_for_geeks’]
Python-nltk
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Properties keySet() method in Java with Examples

23 May, 2019
The keySet() method of Properties class is used to create a set out of the key elements contained in the Properties. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
Syntax:
public Set keySet()
Parameters: This method accepts no parameters
Returns: This method returns a Set view of the keys contained in this Properties object.
Below programs show the implementation of int keySet() method.
Program 1:
// Java code to show the implementation of// keySet() method  import java.util.*;public class GfG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();        properties.put("Pen", 10);        properties.put("Book", 500);        properties.put("Clothes", 400);        properties.put("Mobile", 5000);          // Print Properties details        System.out.println("Properties: "                           + properties.toString());          System.out.println("keySet: "                           + properties.keySet());    }}
Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
keySet: [Book, Mobile, Pen, Clothes]

Program 2:
// Java program to demonstrate// keySet() method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();          // Inserting elements into the properties        properties.put("Geeks", 10);        properties.put("4", 15);        properties.put("Geeks", 20);        properties.put("Welcomes", 25);        properties.put("You", 30);          // Print Properties details        System.out.println("Current Properties: "                           + properties.toString());          System.out.println("keySet: "                           + properties.keySet());    }}
Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20}
keySet: [You, Welcomes, 4, Geeks]

References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keySet–
nidhi_biet
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
How to get a substring between two strings in PHP?

21 Feb, 2022
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples:  
Input:$string="hey, How are you?"
If we need to extract the substring between 
"How" and "you" then the output should be are
 
Output:"Are"

Input:Hey, Welcome to GeeksforGeeks
If we need to get the substring between Welcome and 
for then it should be to geeks as for lies within GeeksforGeeks.

Output:" to geeks"
Method 1: Firstly you have to find the ending position of the start word. Then find the starting position of the ending word after that return the substring between those indexes. Below program illustrate the approach:Program:  
PHP
<?php    function string_between_two_string($str, $starting_word, $ending_word){    $subtring_start = strpos($str, $starting_word);    //Adding the starting index of the starting word to    //its length would give its ending index    $subtring_start += strlen($starting_word);     //Length of our required sub string    $size = strpos($str, $ending_word, $subtring_start) - $subtring_start;     // Return the substring from the index substring_start of length size    return substr($str, $subtring_start, $size); } $str = 'Hey, Welcome to geeksforgeeks';$substring = string_between_two_string($str, 'Welcome', 'for'); echo $substring;     ?>
Output:  
 to geeks
Method 2: Using the explode() function. The explode function splits the given string on the basis of the parameter provided i.e. the separator. Syntax:  
 $arr=explode(separator, string).
This will return an array which will contain the string split on the basis of the separator.  
Split the list on the basis of the starting word.
In the returned array the 2nd index will contain the words after the start word.
In the string provided by step 2 if we again split it on the basis of the ending word then the value at first index will be the string between the starting and the ending word.
Below program illustrate the approach Program:  
PHP
<?php  function string_between_two_string($str, $starting_word, $ending_word){    $arr = explode($starting_word, $str);    if (isset($arr[1])){        $arr = explode($ending_word, $arr[1]);        return $arr[0];    }    return '';  }   $str = "Hey, how are you?";  $start = "Hey";  $end = "you";  $substring = string_between_two_string($str, $start, $end);  echo $substring;?>
Output:  
, how are 
 
nidhi_biet
varshagumber28
PHP-string
Picked
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to create a register form with CSS?

Following is the code to create a register form with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
   font-family: Arial, Helvetica, sans-serif;
}
h1{
   text-align: center;
}
* {
   box-sizing: border-box;
}
form {
   padding: 16px;
   max-width: 800px;
   margin-left: 20%;
   background-color: rgb(255, 254, 195);
}
input[type=text], input[type=password] {
   width: 100%;
   padding: 15px;
   margin: 5px 0 22px 0;
   display: inline-block;
   border: none;
   background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
   background-color: #ddd;
   outline: none;
}
hr {
   border: 1px solid #f1f1f1;
   margin-bottom: 25px;
}
.registerbtn {
   background-color: #4CAF50;
   color: white;
   padding: 16px 20px;
   margin: 8px 0;
   border: none;
   cursor: pointer;
   width: 100%;
   opacity: 0.9;
}
.registerbtn:hover {
   opacity: 1;
}
a {
   color: dodgerblue;
   text-decoration: none;
}
.signin {
   background-color: #f1f1f1;
   text-align: center;
}
@media (max-width: 800px) {
   form {
      width: 100%;
      margin-left: 0px;
   }
}
</style>
</head>
<body>
<h1>Registeration Form Example</h1>
<form>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="signin">
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</body>
</html>
This will produce the following output −
AtomicInteger accumulateAndGet() method in Java with Examples - GeeksforGeeks

04 Feb, 2021
The Java.AtomicInteger.accumulateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the updated value.
Syntax: 
public final int accumulateAndGet(int y, 
             IntBinaryOperator function)
Parameters: This method accepts as parameter an integer value y and an IntBinaryOperator function. It applies the given function to the current value of the object and the value y.
Return Value: The function returns the updated value of the current object.
Example to demonstrate the function. 
Java
// Java program to demonstrate// AtomicInteger accumulateAndGet() method import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntBinaryOperator; public class Demo {    public static void main(String[] args)    {        new UserThread("Thread A");        new UserThread("Thread B");    }} class Shared {    static AtomicInteger ai = new AtomicInteger(0);} class UserThread implements Runnable {    String name;    UserThread(String name)    {        this.name = name;        new Thread(this).start();    }    IntBinaryOperator ibo = (x, y) -> (x + y);    int value = 5;    @Override    public void run()    {        for (int i = 0; i < 3; i++) {            int ans = Shared.ai                          .accumulateAndGet(value, ibo);            System.out.println(name + " " + ans);        }    }}
Thread A 5
Thread A 10
Thread A 15
Thread B 20
Thread B 25
Thread B 30
 
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html 
arorakashish0911
Java-AtomicInteger
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
C# | Clone() Method - GeeksforGeeks

31 Jan, 2019
In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data.In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance. This method will not take any parameters.
Syntax:
public object Clone()

Return Value Type: System.Object or we can say this instance of String.
Below program illustrate the use of Clone() Method:
// C# program to illustrate // Clone() methodusing System;class Geeks {      // Main Method    public static void Main(string[] args)    {        string s1 = "GeeksForgeeks";          // Cannot implicitly convert         // type object to the string.        // So explicit conversion         // using Clone() method        string s2 = (String)s1.Clone();                 // Displaying both the string        Console.WriteLine("String : {0}", s1);        Console.WriteLine("Clone String : {0}", s2);    }}
String : GeeksForgeeks
Clone String : GeeksForgeeks

Reference: https://msdn.microsoft.com/en-us/library/system.string.clone
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
Destructors in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Partial Classes in C#
Lambda Expressions in C#
Convert String to Character Array in C#
How to append two DataFrames in Pandas?

To append the rows of one dataframe with the rows of another, we can use the Pandas append() function. With the help of append(), we can append columns too. Let's take an example and see how to use this method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1.
Print the input DataFrame, df1.
Create another DataFrame, df2, with the same column names and print it.
Use the append method, df1.append(df2, ignore_index=True), to append the rows of df2 with df2.
Print the resultatnt DataFrame.
import pandas as pd

df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"x": [1, 3], "y": [1, 9], "z": [29, 30]})

print "Input DataFrame 1 is:\n", df1
print "Input DataFrame 2 is:\n", df2

df3 = df1.append(df2, ignore_index=True)

print "After appending, DataFrame is: \n", df3
Input DataFrame 1 is:
  x y z
0 5 4 9
1 2 7 3

Input DataFrame 2 is:
  x y  z
0 1 1 29
1 3 9 30

After appending, DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 1 1 29
3 3 9 30
Now, let's use different column names for the dataframes and use the append() function without ignore_index parameter. The default value of ignore_index is False.
import pandas as pd

df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"a": [1, 3], "b": [1, 9], "c": [29, 30]})


print "Input DataFrame 1 is:\n", df1 
print "Input DataFrame 2 is:\n", df2 


df3 = df1.append(df2)


print "After appending, DataFrame is: \n", df3 
Now, it will produce the following output
Input DataFrame 1 is:
  x y z
0 5 4 9
1 2 7 3

Input DataFrame 2 is:
  a b  c
0 1 1 29
1 3 9 30

After appending, DataFrame is:
  x     y    z    a    b    c
0 5.0  4.0  9.0  NaN  NaN  NaN
1 2.0  7.0  3.0  NaN  NaN  NaN
0 NaN  NaN  NaN  1.0  1.0  29.0
1 NaN  NaN  NaN  3.0  9.0  30.0
SQL Tryit Editor v1.6

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Python time altzone() Method

Python time method altzone() is the attribute of the time module. This returns the offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.
Following is the syntax for altzone() method −
time.altzone

NA
NA
This method returns the offset of the local DST timezone, in seconds west of UTC, if one is defined.
The following example shows the usage of altzone() method.
#!/usr/bin/python
import time

print "time.altzone %d " % time.altzone
When we run above program, it produces following result −
time.altzone() 25200


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
MySQL Stored Procedure to create a table?

Following is the query to create a stored procedure that creates a table. Here, we are creating a table with three columns, one of them is Id −
mysql> DELIMITER //
   mysql> CREATE PROCEDURE Stored_Procedure_CreatingTable()
   BEGIN
      create table DemoTable
      (
      Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
      UserFirstName varchar(20),
      UserLastName varchar(20)
      );
   END;
   //
   Query OK, 0 rows affected (0.16 sec)
mysql> DELIMITER ;
Now you can call stored procedure with the help of CALL command −
mysql> call Stored_Procedure_CreatingTable();
Query OK, 0 rows affected (0.18 sec)
Let us check the description of table using DESC command −
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| Id            | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserFirstName | varchar(20) | YES  |     | NULL    |                |
| UserLastName  | varchar(20) | YES  |     | NULL    |                |
+---------------+-------------+------+-----+---------+----------------+
3 rows in set (0.04 sec)
How to handle ESC keydown on JavaScript popup window?

As we know the ESC has the keycode 27. If you will use the keycode 27, then you can handle the condition.
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
</body>
<script>
   $(document).keydown(function (eventValue) {
      if (eventValue.keyCode == 27) {
         console.log("ESC key is pressed....");
      }
      else {
         console.log("Some other is key pressed....")
      }
   });
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now I am going to press another button except the ESC key.
This will produce the following output on console −
Now, I am going to press the ESC key. The console output will change −
How can I append a tuple into another tuple in Python?

You can directly add a tuple to another tuple using a + operator. For example,
x = (1, 2, 3)
y = (4, 5)
x = x + y
print(x)
This will give the output
x = (1, 2, 3)
y = (4, 5)
x = x + y
Perl send Function

This function sends a message on SOCKET (the opposite of recv). If the socket is unconnected, you must supply a destination to communicate to with the TO parameter. In this case, the sendto system function is used in place of the system send function.
The FLAGS parameter is formed from the bitwise or of 0 and one or more of the MSG_OOB and MSG_DONTROUTE options. MSG_OOB allows you to send out-of-band data on sockets that support this notion.
The underlying protocol must also support out-of-band data. Only SOCK_STREAM sockets created in the AF_INET address family support out-of-band data. The MSG_DONTROUTE option is turned on for the duration of the operation. Only diagnostic or routing programs use it.
Following is the simple syntax for this function −
send SOCKET, MSG, FLAGS, TO

send SOCKET, MSG, FLAGS

This function returns undef on failure else Integer, number of bytes sent.

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Jenkins - Setup Build Jobs

For this exercise, we will create a job in Jenkins which picks up a simple HelloWorld application, builds and runs the java program.
Step 1 − Go to the Jenkins dashboard and Click on New Item
Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’
Step 3 − The following screen will come up in which you can specify the details of the job.
Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git repository(E:\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of the local git repository.
Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository.
Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command
Step 6 − In the command window, enter the following commands and then click on the Save button.
Javac HelloWorld.java
Java HelloWorld

Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job.
Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress.
Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has been executed successfully. Click on the #1 in the Build history to bring up the details of the build.
Step 10 − Click on the Console Output link to see the details of the build
Apart from the steps shown above there are just so many ways to create a build job, the options available are many, which what makes Jenkins such a fantastic continuous deployment tool.

    38 Lectures 
     5 hours 

 Eduonix Learning Solutions

    41 Lectures 
     5 hours 

 AR Shankar

    42 Lectures 
     2 hours 

 Chaitanya Allidona

    37 Lectures 
     2.5 hours 

 Spotle Learn
 Print
 Add Notes
 Bookmark this page
Data Structures | Binary Search Trees | Question 7

28 Jun, 2021
The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)(A) 2(B) 3(C) 4(D) 6Answer: (B)Explanation: Constructed binary search tree will be..
                    10
                  /     \
                 1       15
                 \      /  \
                  3    12   16
                    \
                     5
Quiz of this Question
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Data Structures | Hash | Question 5
Amazon Interview Experience for SDE-II
Data Structures | Linked List | Question 4
Data Structures | Linked List | Question 16
Data Structures | Linked List | Question 11
Data Structures | Linked List | Question 15
Data Structures | Queue | Question 11
Data Structures | Linked List | Question 8
What are valid identifiers in Java?

A valid identifier in java –
Must begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
Can have any combination of characters after the first character.
Cannot be a keyword.
Following example shows various possible identifiers used to declare a variable in Java.
 Live Demo
public class VariableTest {
   public static void main(String args[]) {
      // Declaring a variable named num
      int num = 1;
      int _num = 10;
      int $num = 100;
      int num123 = 1000;
      int NUM = 10000;     
      //Printing the value of the variable num
      System.out.println("value if the variable num: "+num);
      System.out.println("value if the variable _num: "+_num);
      System.out.println("value if the variable $num: "+$num);
      System.out.println("value if the variable num123: "+num123);
      System.out.println("value if the variable NUM: "+NUM);
   }
}
value if the variable num: 1
value if the variable _num: 10
value if the variable $num: 100
value if the variable num123: 1000
value if the variable NUM: 10000
ISRO CS 2018 - GeeksforGeeks

02 Jun, 2021
#include 
main()
{
    int i, j , x ;
    scanf("%d", &x);
    i = 1 ; j = 1;
    while ( i< 10 ) {
          j = j * i;
          i = i + 1;
          if (i == x) break ;
          }
 }
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Matplotlib.pyplot.rc_context() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The rc_context() function in pyplot module of matplotlib library is used to return a context manager for managing rc settings.
Syntax: matplotlib.pyplot.rc_context(rc=None, fname=None)
Parameters:
rc: This parameter is a dictionary can also be passed to the context manager.
fname: This parameter contains the name of file which is to be called.
Returns: This method return a context manager for managing rc settings.
Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot:
Example 1:
# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np    np.random.seed(19680801)  dots = np.arange(20)x, y = np.meshgrid(dots, dots)data = [x.ravel(), y.ravel()]  with plt.rc_context({'axes.xmargin': .2,                      'axes.ymargin': .4}):    plt.scatter(*data, c = data[1])      plt.grid(True)  plt.title('matplotlib.pyplot.rc_context()\Example')plt.show()
Output:
Example 2:
# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np    np.random.seed(19680801)  fig, ax = plt.subplots()dots = np.arange(100)x, y = np.meshgrid(dots, dots)  data = [x.ravel(), y.ravel()]ax.scatter(*data, c = data[1])  with plt.rc_context({'axes.autolimit_mode': 'round_numbers',                     'axes.xmargin': .8,                     'axes.ymargin': .8}):          fig, ax = plt.subplots()    ax.scatter(*data, c = data[1])      plt.grid(True)  plt.title('matplotlib.pyplot.rc_context() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Lodash _.unset() Method - GeeksforGeeks

09 Sep, 2020
The Lodash _.unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.
Syntax:
_.unset(object, path)

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the object to modify.
path: This parameter holds the path of the property to unset. It can be an array or string.
Return Value: This method returns true if the property is deleted, else false. 
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] };  // Use of _.unset() methodconsole.log(_.unset(obj, 'cpp[0].java.python'));  // Object is modifiedconsole.log(obj);
Output:
true
{ cpp: [ { java: {} } ] }

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] };  // Use of _.unset() methodconsole.log(_.unset(obj, ['html', 'css', 'javascript']));  // Objectconsole.log(obj);
Output:
true
{ cpp: [ { java: [Object] } ] }

Note: This will not work in normal JavaScript because it requires the library lodash to be installed and can be installed using npm install lodash..
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
PostgreSQL - ARRAY_AGG() Function - GeeksforGeeks

01 Jun, 2020
PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array.
Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...])
The ORDER BY clause is an voluntary clause. It specifies the order of rows that are processed in the collection, which establishes the order of the elements in the result array. It is often used with the GROUP BY clause.Now let’s look into some examples.Example 1:We will be using the film, film_actor and actor tables in the dvdrental sample database for demonstration. In this example we will query for the list of film title and a list of actors for each film using the ARRAY_AVG() function as follows:
SELECT
    title,
    ARRAY_AGG (first_name || ' ' || last_name) actors
FROM
    film
INNER JOIN film_actor USING (film_id)
INNER JOIN actor USING (actor_id)
GROUP BY
    title
ORDER BY
    title;
Output:
Example 2:here we will use the ARRAY_AGG() function to return a list of films and a list of actors for each film sorted by the actor’s first name using the commands below:
SELECT
    title,
    ARRAY_AGG (
        first_name || ' ' || last_name
        ORDER BY
            first_name
    ) actors
FROM
    film
INNER JOIN film_actor USING (film_id)
INNER JOIN actor USING (actor_id)
GROUP BY
    title
ORDER BY
    title;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
PostgreSQL - SELECT