code-rag-bench/online-tutorials huggingface dataset:
Binary Search Trees in Data Structures

The binary search trees are binary tree which has some properties. These properties are like below −
Every Binary Search Tree is a binary tree
Every left child will hold lesser value than root
Every right child will hold greater value than root
Ideal binary search tree will not hold same value twice.
Suppose we have one tree like this −
This tree is one binary search tree. It follows all of the mentioned properties. If we traverse elements into inorder traversal mode, we can get 5, 8, 10, 15, 16, 20, 23. Let us see one code to understand how we can implement this in C++ code.
 Live Demo
#include<iostream>
using namespace std;
class node{
   public:
      int h_left, h_right, bf, value;
      node *left, *right;
};
class tree{
   private:
      node *get_node(int key);
   public:
      node *root;
      tree(){
         root = NULL; //set root as NULL at the beginning
      }
      void inorder_traversal(node *r);
      node *insert_node(node *root, int key);
};
node *tree::get_node(int key){
   node *new_node;
   new_node = new node; //create a new node dynamically
   new_node->h_left = 0; new_node->h_right = 0;
   new_node->bf = 0;
   new_node->value = key; //store the value from given key
   new_node->left = NULL; new_node->right = NULL;
   return new_node;
}
void tree::inorder_traversal(node *r){
   if(r != NULL){ //When root is present, visit left - root - right
      inorder_traversal(r->left);
      cout << r->value << " ";
      inorder_traversal(r->right);
   }
}
node *tree::insert_node(node *root, int key){
   if(root == NULL){
      return (get_node(key)); //when tree is empty, create a node as root
   }
   if(key < root->value){ //when key is smaller than root value, go to the left
      root->left = insert_node(root->left, key);
   }else if(key > root->value){ //when key is greater than root value, go to the right
      root->right = insert_node(root->right, key);
   }
   return root; //when key is already present, do not insert it again
}
main(){
   node *root;
   tree my_tree;
   //Insert some keys into the tree.
   my_tree.root = my_tree.insert_node(my_tree.root, 10);
   my_tree.root = my_tree.insert_node(my_tree.root, 5);
   my_tree.root = my_tree.insert_node(my_tree.root, 16);
   my_tree.root = my_tree.insert_node(my_tree.root, 20);
   my_tree.root = my_tree.insert_node(my_tree.root, 15);
   my_tree.root = my_tree.insert_node(my_tree.root, 8);
   my_tree.root = my_tree.insert_node(my_tree.root, 23);
   cout << "In-Order Traversal: ";
   my_tree.inorder_traversal(my_tree.root);
}
In-Order Traversal: 5 8 10 15 16 20 23
How to set default text for a Tkinter Entry widget?

Tkinter Entry widget is used to print and display a single line of text taken from the user Input. It is used for many applications such as creating login forms, signup forms, and other user interaction forms.
We can set the default text for the Entry Widget using insert() function by passing the default text as the argument.
In this example, we have created an Entry widget that has a default text.
#Import the tkinter library
from tkinter import *

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

#Set the geometry
win.geometry("650x250")

#Create an Entry Widget
entry= Entry(win)
entry.insert(END, 'Enter any Text')
entry.pack()

win.mainloop()
Running the above code will set the default text for entry widget.
Multiply values of two columns and display it a new column in MySQL?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> NumberOfItems int,
   -> Amount int
   -> );
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(4,902);
Query OK, 1 row affected (0.45 sec)

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

mysql> insert into DemoTable values(3,80);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+---------------+--------+
| NumberOfItems | Amount |
+---------------+--------+
|             4 | 902    |
|             5 | 1000   |
|             3 | 80     |
+---------------+--------+
3 rows in set (0.00 sec)
Following is the query for database manipulation −
mysql> select NumberOfItems,Amount,(NumberOfItems*Amount) AS PayableAmount from DemoTable;
+---------------+--------+---------------+
| NumberOfItems | Amount | PayableAmount |
+---------------+--------+---------------+
|             4 | 902    |         3608  |
|             5 | 1000   |         5000  |
|             3 | 80     |         240   |
+---------------+--------+---------------+
3 rows in set (0.00 sec)
Using Multiple Table Updates

In the previous chapter, we have discussed about how to use multiple tables. So we proceed a step further and learn multiple table updates in this chapter.
Using SQLAlchemy’s table object, more than one table can be specified in WHERE clause of update() method. The PostgreSQL and Microsoft SQL Server support UPDATE statements that refer to multiple tables. This implements “UPDATE FROM” syntax, which updates one table at a time. However, additional tables can be referenced in an additional “FROM” clause in the WHERE clause directly. The following lines of codes explain the concept of multiple table updates clearly.
stmt = students.update().\
values({
   students.c.name:'xyz',
   addresses.c.email_add:'abc@xyz.com'
}).\
where(students.c.id == addresses.c.id)
The update object is equivalent to the following UPDATE query −
UPDATE students 
SET email_add = :addresses_email_add, name = :name 
FROM addresses 
WHERE students.id = addresses.id
As far as MySQL dialect is concerned, multiple tables can be embedded into a single UPDATE statement separated by a comma as given below −
stmt = students.update().\
   values(name = 'xyz').\
   where(students.c.id == addresses.c.id)
The following code depicts the resulting UPDATE query −
'UPDATE students SET name = :name 
FROM addresses 
WHERE students.id = addresses.id'
SQLite dialect however doesn’t support multiple-table criteria within UPDATE and shows following error −
NotImplementedError: This backend does not support multiple-table criteria within UPDATE


    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Convert string to integer/ float in Arduino

In order to convert a string to an integer or a float, the .toInt() and .toFloat() functions can be used. Of course, the string should actually correspond to the integer or floating-point value. For instance, "1.87" can be converted to float. But it doesn't make sense to convert "Hello" to float. The below example code illustrates the conversions −
void setup() {
   Serial.begin(9600);
   Serial.println();
   // put your setup code here, to run once:
   String s1 = "235";
   String s2 = "1.56";
   String s3 = "Hello";
   int i1 = s1.toInt();
   int i2 = s2.toInt();
   int i3 = s3.toInt();
   float f1 = s2.toFloat();
   float f2 = s3.toFloat();
   Serial.println(i1);
   Serial.println(i2);
   Serial.println(i3);
   Serial.println(f1);
   Serial.println(f2);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, the integer and float conversions for "Hello" are 0. The conversion of floating point to integer happens through chopping, as can be seen. The integer value of 1.56 was printed as 1.
Static Block and main() method in Java

20 Dec, 2018
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading.
This is illustrated well in the following example:
// Java program to demonstrate that static // block is executed before main()  class staticExample {      // static block    static    {        System.out.println("Inside Static Block.");    }      // main method    public static void main(String args[])    {        System.out.println("Inside main method.");    }}
One question arises from the above example:
Question: Can we execute a Java class without declaring main() method?Answer: No since JDK 1.7 it is not possible to execute any java class without main() method. But it was one of the ways till JDK 1.6.Example:
// The below code would not work in JDK 1.7class staticExample {      // static block execution without main method in JDK 1.6.    static    {        System.out.println("Inside Static Block.");        System.exit(0);    }}
Output:(In JDK 1.6)
Inside Static Block.

But from JDK 1.7 onwards the above code gives an error in output.
Output:
Error: Main method not found in class staticExample, please define the main method as:
       public static void main(String args[])
       or a JavaFX application class must extend javafx.application.Application


java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
MakeFile in C++ and its applications

In this tutorial, we will be discussing a program to understand MakeFile in C++ and its applications.
The task is to break the entire program with MakeFile. It is usually done by making .cpp files and .h files with all the classes/functionalities and link them together.
main.cpp
#include <bits/stdc++.h>
#include "function.h"
using namespace std;
//main execution program
int main(){
   int num1 = 1;
   int num2 = 2;
   cout << multiply(num1, num2) << endl;
   int num3 = 5;
   cout << factorial(num3) << endl;
   print();
}
print.cpp
#include <bits/stdc++.h>
#include "function.h"
using namespace std;
void print()
{
   cout < "makefile" << endl;
}
factorial.cpp
#include <bits/stdc++.h>
#include "function.h"
using namespace std;
//factorial program
int factorial(int n){
   if (n == 1)
      return 1;
   return n * factorial(n - 1);
}
multiply.cpp
#include <bits/stdc++.h>
#include "function.h"
using namespace std;
int multiply(int a, int b){
   return a * b;
}
functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
void print();
int factorial(int);
int multiply(int, int);
#endif
2
120
makefile
How to get the Azure VM available sizes using PowerShell?

To get the Azure VM sizes using PowerShell, we can use the Get-AzVmSize command.
To get all the supported Azure VM sizes as per location, use the below command.
PS C:\> Get-AzVMSize -Location Eastus
To get available and supported size for the existing virtual machine, use the below command.
Get-AzVMSize -ResourceGroupName ResourceGroup1 -VMName TestVM
Add a character in the end to column values with MySQL SELECT?

For this, you need to perform concatenation using CONCAT().
Let us first create a table −
mysql> create table DemoTable766 (Name varchar(100));
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable766 values('John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable766 values('Sam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable766 values('Carol');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable766 values('David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable766 values('Bob');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable766;
This will produce the following output -
+-------+
| Name  |
+-------+
| John  |
| Sam   |
| Carol |
| David |
| Bob   |
+-------+
5 rows in set (0.00 sec)
Following is the query to add a character in the end to column values −
mysql> select concat(Name,' S') from DemoTable766;
This will produce the following output -
+-------------------+
| concat(Name,' S') |
+-------------------+
| John S            |
| Sam S             |
| Carol S           |
| David S           |
| Bob S             |  
+-------------------+
5 rows in set (0.00 sec)
How do we return multiple values in Python?

It is possible to return multiple values from a function in the form of tuple, list, dictionary or an object of a user defined class
Return as tuple
>>> def function():
      a=10; b=10
      return a,b

>>> x=function()
>>> type(x)
<class 'tuple'>
>>> x
(10, 10)
>>> x,y=function()
>>> x,y
(10, 10)
Return as list
>>> def function():
      a=10; b=10
      return [a,b]

>>> x=function()
>>> x
[10, 10]
>>> type(x)
<class 'list'>
Return as dictionary
>>> def function():
      d=dict()
      a=10; b=10
      d['a']=a; d['b']=b
      return d

>>> x=function()
>>> x
{'a': 10, 'b': 10}
>>> type(x)
<class 'dict'>
Return as object of user defined class
>>> class tmp:
def __init__(self, a,b):
self.a=a
self.b=b


>>> def function():
      a=10; b=10
      t=tmp(a,b)
      return t

>>> x=function()
>>> type(x)
<class '__main__.tmp'>
>>> x.a
10
>>> x.b
10
How to select month and year from dates in MySQL?

To select month and year in MySQL, you can use MONTH() and YEAR() method. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> DueDate datetime
   -> );
Query OK, 0 rows affected (0.90 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-21');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('2019-06-15');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2018-12-01');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2015-04-01');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2016-08-14');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql− select *from DemoTable;
This will produce the following output −
+---------------------+
| DueDate             |
+---------------------+
| 2019-01-21 00:00:00 |
| 2019-06-15 00:00:00 |
| 2018-12-01 00:00:00 |
| 2015-04-01 00:00:00 |
| 2016-08-14 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)
Following is the query to select month and year from MySQL −
mysql> select MONTH(DueDate) AS MONTH, YEAR(DueDate) AS YEAR from DemoTable;
This will produce the following output −
+-------+------+
| MONTH | YEAR |
+-------+------+
| 1     | 2019 |
| 6     | 2019 |
| 12    | 2018 |
| 4     | 2015 |
| 8     | 2016 |
+-------+------+
5 rows in set (0.00 sec)
Tryit Editor v3.7

CSS Style Images
Tryit: Flip an image
How to validate an email id using regular expression in Python?

The following code validates any given email id using regex in Python
import re
s = 'manogna.neelam@tutorialspoint.com'
match = re.search(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', s, re.I)
print match.group()
This gives the output
manogna.neelam@tutorialspoint.com
Arduino - doâ¦while loop

The do...while loop is similar to the while loop. In the while loop, the loop-continuation condition is tested at the beginning of the loop before performed the body of the loop. The do...while statement tests the loop-continuation condition after performed the loop body. Therefore, the loop body will be executed at least once.
When a do...while terminates, execution continues with the statement after the while clause. It is not necessary to use braces in the do...while statement if there is only one statement in the body. However, the braces are usually included to avoid confusion between the while and do...while statements.
do { 
   Block of statements; 
} 
while (expression);


    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Julia break Keyword | Exiting from a loop in Julia - GeeksforGeeks

26 Mar, 2020
Keywords in Julia are predefined words that have a definite meaning to the compiler. These keywords can’t be used to name variables.
'break' keyword in Julia is used to exit from a loop immediately. Whenever the break keyword is executed, the compiler immediately stops iterating over further values and sends the execution pointer out of the loop.Syntax:
loop condition
    statement
    statement
    break
    statement
end

Example 1:
# Julia program to illustrate# the use of 'break' keyword  # Defining for-loopfor i in 1:10    if i == 6          # Using 'break' keyword        break    else        println(i)    endend
Output:
1
2
3
4
5


Example 2:
# Julia program to illustrate# the use of 'break' keyword  i = 0  # Defining while-loopwhile true    global i = i + 1    if i == 6        # Using 'break' keyword        break    else        println(i)    endend
Output:
1
2
3
4
5


Julia-keywords
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Formatting of Strings in Julia
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Working with CSV Files in Julia
Map keySet() Method in Java with Examples

08 Sep, 2020
This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
Syntax:
Set keySet()
Parameters: This method has no argument.
Returns: This method returns a set containing keys of the specified map.
Below programs show the implementation of int keySet() method.
Program 1:
// Java code to show the implementation of// isEmpty method in Map interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a Map of type HashMap        Map<String, String> map = new HashMap<>();          System.out.println(map);          System.out.println(map.isEmpty());    }}
Output:
{}
true

Program 2: Below is the code to show implementation of hashCode().
// Java code to show the implementation of// keySet method in Map interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a Map of type HashMap        Map<Integer, String> map = new HashMap<>();        Set<Integer> s = new HashSet<>();        map.put(1, "One");        map.put(3, "Three");        map.put(5, "Five");        map.put(7, "Seven");        map.put(9, "Ninde");        System.out.println(map);        s = map.keySet();        System.out.println(s);    }}
Output:
{1=One, 3=Three, 5=Five, 7=Seven, 9=Ninde}
[1, 3, 5, 7, 9]

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initialize an ArrayList in Java
Redis - Hash Hgetall Command

Redis HGETALL command is used to get all the fields and values of the hash stored at the key. In the returned value, every field name is followed by its value, so the length of the reply is twice the size of the hash.
Array reply, list of fields and their values stored in the hash, or an empty list when the key does not exist.
Following is the basic syntax of Redis HGETALL command.
redis 127.0.0.1:6379> HGETALL KEY_NAME 

redis 127.0.0.1:6379> HSET myhash field1 "foo" 
(integer) 1 
redis 127.0.0.1:6379> HSET myhash field2 "bar" 
(integer) 1 
redis 127.0.0.1:6379> HGETALL myhash
Why use Question mark in TypeScript variable ?

30 Jan, 2020
Question marks on TypeScript variable are used to mark that variable as an optional variable. If we put the question mark when declaring a variable that variable becomes optional. The optional parameters will have value as undefined when unused.
syntax:
function A(x?: number) {
    // Function_body
}

Below examples illustrate the above approach:
Example 1:<script>function point(x?: number, y?: number){    if(x)         console.log('X : ' + x);    else         console.log('Value of X coordinate not given');    if(y)         console.log('Y : ' + y);    else         console.log('Value of Y coordinate not given');}</script>
<script>function point(x?: number, y?: number){    if(x)         console.log('X : ' + x);    else         console.log('Value of X coordinate not given');    if(y)         console.log('Y : ' + y);    else         console.log('Value of Y coordinate not given');}</script>
Output:Function Call: point();
Value of X coordinate not given
Value of Y coordinate not given

Function Call : point(10);
X : 10
Value of Y coordinate not given

Function Call : point(10, 20);
X : 10
Y : 20

Function Call: point();
Value of X coordinate not given
Value of Y coordinate not given

Function Call : point(10);
X : 10
Value of Y coordinate not given

Function Call : point(10, 20);
X : 10
Y : 20

Example 2:<script>class Hello{      constructor(private firstName: string, private lastName?: string)    {        this.firstName = firstName;        this.lastName = lastName;        if (lastName)            console.log('Hello ' + this.firstName + ' ' + this.lastName);        else            console.log('Hello ' + this.firstName);    }}  // Creating an object h1let h1 = new Hello('Shivam');   // Creating an object h2let h2 = new Hello('Shivam', 'Gupta'); </script>
<script>class Hello{      constructor(private firstName: string, private lastName?: string)    {        this.firstName = firstName;        this.lastName = lastName;        if (lastName)            console.log('Hello ' + this.firstName + ' ' + this.lastName);        else            console.log('Hello ' + this.firstName);    }}  // Creating an object h1let h1 = new Hello('Shivam');   // Creating an object h2let h2 = new Hello('Shivam', 'Gupta'); </script>
Output:Hello Shivam
Hello Shivam Gupta

Hello Shivam
Hello Shivam Gupta

Note: A required parameter cannot follow an optional parameter. If we declare any variable as optional, all the variables on the right side of that must also be optional, otherwise, it will give an error.
Picked
Technical Scripter 2019
TypeScript
JavaScript
Technical Scripter
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript | fetch() Method
JavaScript String includes() Method
Async/Await Function in JavaScript
Python | Conversion to N*N tuple matrix

30 Dec, 2020
Sometimes, while working with data, we can have a problem in which we have data in form of tuple Matrix with uneven length rows. In this case there’s a requirement to complete the N*N matrix with a default value. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + * operatorThis problem can be solved using loop. This is brute force method to perform this task. We just append the default value as many times, as the data is missing in a row than N.
# Python3 code to demonstrate working of# Conversion to N * N tuple matrix # using loop + * operator  # initialize tupletest_tup = ((5, 4), (3, ), (1, 5, 6, 7), (2, 4, 5))  # printing original tupleprint("The original tuple is : " + str(test_tup))  # initializing dimensionN = 4  # Conversion to N * N tuple matrix # using loop + * operatorres = []for tup in test_tup :    res.append( tup +(0, ) * (N - len(tup)))  # printing resultprint("Tuple after filling values : " + str(res))
The original tuple is : ((5, 4), (3, ), (1, 5, 6, 7), (2, 4, 5))
Tuple after filling values : [(5, 4, 0, 0), (3, 0, 0, 0), (1, 5, 6, 7), (2, 4, 5, 0)]

 
Method #2 : Using tuple() + generator expressionSimilar task can be performed in one line using generator expression. In this, similar logic is applied as above just zipped as one-liner. The tuple(), changes result to tuple.
# Python3 code to demonstrate working of# Conversion to N * N tuple matrix # using tuple() + generator expression  # initialize tupletest_tup = ((5, 4), (3, ), (1, 5, 6, 7), (2, 4, 5))  # printing original tupleprint("The original tuple is : " + str(test_tup))  # initializing dimensionN = 4  # Conversion to N * N tuple matrix # using tuple() + generator expressionres = tuple(sub + (0, ) * (N-len(sub)) for sub in test_tup)  # printing resultprint("Tuple after filling values : " + str(res))
The original tuple is : ((5, 4), (3, ), (1, 5, 6, 7), (2, 4, 5))
Tuple after filling values : ((5, 4, 0, 0), (3, 0, 0, 0), (1, 5, 6, 7), (2, 4, 5, 0))

Python matrix-program
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.figure.Figure.add_axes() in Python

30 Apr, 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 add_axes() method figure module of matplotlib library is used to add an axes to the figure.
Syntax: add_axes(self, *args, **kwargs)
Parameters: This accept the following parameters that are described below:
rect : This parameter is the dimensions [left, bottom, width, height] of the new axes.
projection : This parameter is the projection type of the Axes.
sharex, sharey : These parameters share the x or y axis with sharex and/or sharey.
label : This parameter is the label for the returned axes.
Returns: This method return the axes class depends on the projection used.
Below examples illustrate the matplotlib.figure.Figure.add_axes() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt    fig = plt.figure()fig.subplots_adjust(top = 0.8)ax1 = fig.add_subplot(211)  t = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)line, = ax1.plot(t, s, color ='green', lw = 2)  np.random.seed(19680801)  ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])n, bins, patches = ax2.hist(np.random.randn(1000), 50,                            facecolor ='yellow',                            edgecolor ='yellow')   fig.suptitle('matplotlib.figure.Figure.add_axes() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  fig = plt.figure()rect = fig.patchrect.set_facecolor('lightslategray')  ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])rect = ax1.patchrect.set_facecolor('lightgoldenrodyellow')    for label in ax1.xaxis.get_ticklabels():    label.set_color('green')    label.set_rotation(25)    label.set_fontsize(16)  for line in ax1.yaxis.get_ticklines():    line.set_color('yellow')    line.set_markersize(5)    line.set_markeredgewidth(3)  fig.suptitle('matplotlib.figure.Figure.add_axes() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
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
Bash shell script to find sum of digits

18 Aug, 2021
Given a number Num, find the sum of digits of the number.Examples:  
Input : 
444
Output :
sum of digits of 444 is : 12

Input :
34
Output :
sum of digits of 34 is : 7
Approach:
1. Divide the number into single digits
2. Find the sum of digits .
Bash
# !/bin/bash # Program to find sum# of digits # Static input of the# numberNum=123g=$Num # store the sum of# digitss=0 # use while loop to# calculate the sum# of all digitswhile [ $Num -gt 0 ]do    # get Remainder    k=$(( $Num % 10 ))     # get next digit    Num=$(( $Num / 10 ))     # calculate sum of    # digit     s=$(( $s + $k ))doneecho  "sum of digits of $g is : $s"
Output:
sum of digits of 123 is : 6 
gulshankumarar231
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert current date/ time using now() in a field with MySQL?

In MySQL, now() can be used to insert current date/time. The syntax is as follows −
insert into yourTableName values(now());
To understand the above concept of inserting current date/time in the table, let us first create a table −
mysql> create table CurrentDateTimeDemo
   −> (
   −> YourTime datetime
   −> );
Query OK, 0 rows affected (0.58 sec)
Inserting current date/time using now(). The query is as follows −
mysql> insert into CurrentDateTimeDemo values(now());
Query OK, 1 row affected (0.20 sec)
Now you can check the current date/time has been inserted or not −
mysql> select *from CurrentDateTimeDemo;
The following output displays that the current date is successfully inserted using now():
+---------------------+
| YourTime            |
+---------------------+
| 2018-12-08 19:08:41 |
+---------------------+
1 row in set (0.00 sec)
Lodash _.countBy() Method - GeeksforGeeks

01 Sep, 2020
The _.countBy method creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
Syntax:
_.countBy(collection, [iteratee=_.identity])

Parameters: This method accepts two parameters as mentioned above and described below:
collection (Array|Object): This parameter holds the collection to iterate over.
[iteratee=_.identity] (Function): This parameter holds the iteratee to transform keys.
Return Value: This method is used to returns the composed aggregate object.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array   var obj1 = ([6.1, 4.2, 6.3, 5, 7.9, 5.3, 5.1, 7.3 ]);  // Use of _.countBy() methodlet y = _.countBy(obj1, Math.floor);        // Printing the output console.log(y);
Output:
{ '4': 1, '5': 3, '6': 2, '7':2 }
Example 2:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array   var obj1 = (['one', 'two', 'three', 'five', 'eleven', 'twelve'] );  // Use of _.countBy() // method   // The `_.property` iteratee shorthand.let y = _.countBy(obj1, 'length');      // Printing the output console.log(y);
Output:
{ '3': 2, '4': 1, '5': 1, '6':2 }
Example 3:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array   var obj1 = (['tee', 'cee', 'dee', 'bee', 'eee' ]);var obj2 = (['q', 'r', 's', 'p' ]);  // Use of _.countBy() method   // The `_.property` iteratee shorthand.let x = _.countBy(obj1, 'length');    let y = _.countBy(obj2, 'length');  // Printing the output console.log(x);console.log(y);
Output:
{ '3': 5 }
{ '1': 4 }

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to animate 3D plot_surface in Matplotlib?

To animate 3D plot_surface in Matplotlib, we can take the following steps−
Initialize variables for number of mesh grids (N), frequency per second (fps) to call a function, and frame numbers (frn).
Create x, y and z array for a curve.
Make a function to make a z-array using lambda function.
To pass a function into animation class, make a user-defined function that removes the previous plot and plot a surface using x, y and z-array.
Create a new figure or activate an existing figure.
Add a subplot arrangement using subplots() method.
Set the Z-axis limit using set_zlim() method.
Call the animation class to animate the surface plot.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 50
fps = 250
frn = 75

x = np.linspace(-4, 4, N + 1)
x, y = np.meshgrid(x, x)
zarray = np.zeros((N + 1, N + 1, frn))

f = lambda x, y, sig: 1 / np.sqrt(sig) * np.exp(-(x ** 2 + y ** 2) / sig ** 2)

for i in range(frn):
   zarray[:, :, i] = f(x, y, 1.5 + np.sin(i * 2 * np.pi / frn))

def change_plot(frame_number, zarray, plot):
   plot[0].remove()
   plot[0] = ax.plot_surface(x, y, zarray[:, :, frame_number], cmap="afmhot_r")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

plot = [ax.plot_surface(x, y, zarray[:, :, 0], color='0.75', rstride=1, cstride=1)]

ax.set_zlim(0, 1.1)
ani = animation.FuncAnimation(fig, change_plot, frn, fargs=(zarray, plot), interval=1000 / fps)

ax.axis('off')

plt.show()
Int 64 Struct in C#

The Int 64 struct represents a 64-bit signed integer. It is an immutable value type representing signed integers with values: negative 9,223,372,036,854,775,808 through positive 9,223,372,036,854,775,807.
Following are the fields of Int 64 −
Following are some of the methods −
Let us now see some examples of the methods −
The Int64.CompareTo() method in C# is used to compare this instance to a specified object or Int64 and returns an indication of their relative values.
Following is the syntax −
public int CompareTo (long val);
public int CompareTo (object val);
Above, in the 1st syntax, the value val is an integer to compare. The val in the 2nd syntax is an object to compare.
Let us now see an example to implement the Int64.CompareTo() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      long val1 = 20;
      long val2 = 18;
      Console.WriteLine("Value 1 = "+val1);
      Console.WriteLine("Value 2 = "+val2);
      Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2));
   }
}
This will produce the following output −
Value 1 = 20
Value 2 = 18
Return value (comparison) = 1
Let us now see another example to implement the Int64.CompareTo() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      long val1 = 20;
      object val2 = (long)20;
      Console.WriteLine("Value 1 = "+val1);
      Console.WriteLine("Value 2 = "+val2);
      Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2));
   }
}
This will produce the following output −
Value 1 = 20
Value 2 = 20
Return value (comparison) = 0
The Int64.Equals() method in C# is used to return a value indicating whether this instance is equal to a specified object or Int64.
Following is the syntax −
public bool Equals (long ob);
public override bool Equals (object ob);
Above, the parameter ob is an Int64 value to compare to this instance, whereas the parameter ob is an object to compare with this instance.
Let us now see an example to implement the Int64.Equals() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      long val1 = 150;
      long val2 = 240;
      Console.WriteLine("Value1 = "+val1);
      Console.WriteLine("Value2 = "+val2);
      Console.WriteLine("Are they equal? = "+val1.Equals(val2));
   }
}
This will produce the following output −
Value1 = 150
Value2 = 240
Are they equal? = False
Let us now see another example to implement the Int64.Equals() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      long val1 = 8768768768;
      long val2 = 8768768768;
      Console.WriteLine("Value1 = "+val1);
      Console.WriteLine("Value2 = "+val2);
      Console.WriteLine("Are they equal? = "+val1.Equals(val2));
   }
}
This will produce the following output −
Value1 = 8768768768
Value2 = 8768768768
Are they equal? = True
java.time.Month.getDisplayName() Method Example

The java.time.Month.getDisplayName(TextStyle style, Locale locale) method gets the textual representation, such as 'Jan' or 'December'.
Following is the declaration for java.time.Month.getDisplayName(TextStyle style, Locale locale) method.
public String getDisplayName(TextStyle style, Locale locale)

style − the length of the text required, not null.
style − the length of the text required, not null.
locale − the locale to use, not null.
locale − the locale to use, not null.
the text value of the month-of-year, not null.
The following example shows the usage of java.time.Month.getDisplayName(TextStyle style, Locale locale) method.
package com.tutorialspoint;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;

public class MonthDemo {
   public static void main(String[] args) {
 
      Month day = Month.of(3);
      System.out.println(day.getDisplayName(TextStyle.SHORT,Locale.ENGLISH));  
   }
}
Let us compile and run the above program, this will produce the following result −
Mar

 Print
 Add Notes
 Bookmark this page
How Seaborn library used to display a kernel density estimation plot (joinplot) in Python?

Seaborn is a library that helps in visualizing data. It comes with customized themes and a high level interface.
Kernel Density Estimation, also known as KDE is a method in which the probability density function of a continuous random variable can be estimated. This method is used for the analysis of the non-parametric values. While using ‘jointplot’, if the argument ‘kind’ is set to ‘kde’, it plots the kernel density estimation plot.
Let us understand how the ‘jointplot’ function works to plot a kernel density estimation in python.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
my_df = sb.load_dataset('iris')
sb.jointplot(x = 'petal_length',y = 'petal_width',data = my_df,kind = 'kde')
plt.show()
The required packages are imported.
The required packages are imported.
The input data is ‘iris_data’ which is loaded from the scikit learn library.
The input data is ‘iris_data’ which is loaded from the scikit learn library.
This data is stored in a dataframe.
This data is stored in a dataframe.
The ‘load_dataset’ function is used to load the iris data.
The ‘load_dataset’ function is used to load the iris data.
This data is visualized using the ‘jointplot’ function.
This data is visualized using the ‘jointplot’ function.
Here, the ‘x’ and ‘y’ axis values are supplied as parameters.
Here, the ‘x’ and ‘y’ axis values are supplied as parameters.
Here, the ‘kind’ parameter is specified as ‘kde’ so that the plot understands to print kernel density estimation.
Here, the ‘kind’ parameter is specified as ‘kde’ so that the plot understands to print kernel density estimation.
This kernel density estimation data is displayed on the console.
This kernel density estimation data is displayed on the console.
C++ Program to Find the Frequency of a Character in a String

A string is a one-dimensional character array that is terminated by a null character. Frequency of characters in a string is the number of times they occur in a string. For example −
String: Football is a sport
The frequency of alphabet o in the above string is 3
A program to find the frequency of a particular alphabet is given as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   char str[100] = "this string contains many alphabets";
   char c = 'a';
   int count = 0;
   for(int i = 0; str[i] != '\0'; i++) {
      if(str[i] == c)
      count++;
   }
   cout<<"Frequency of alphabet "<<c<<" in the string is "<<count;
   return 0;
}
Frequency of alphabet a in the string is 4
In the above program, for loop is used to find the frequency of alphabet a for the string given. In the for loop, if str[i] is equal to the alphabet, then count is incremented by 1. This value of count is displayed as the frequency of the alphabet. The code snippet for this is given as follows.
for(int i = 0; str[i] != '\0'; i++) {
   if(str[i] == c)
   count++;
}
cout<<"Frequency of alphabet "<<c<<" in the string is "<<count;
The program to find the frequency of all the alphabets in the string is given as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   char str[100] = "this string contains many alphabets";
   int i = 0, alphabet[26] = {0}, j;
   while (str[i] != '\0') {
      if (str[i] >= 'a' && str[i] <= 'z') {
         j = str[i] - 'a';
         ++alphabet[j];
      }
      ++i;
   }
   cout<<"Frequency of all alphabets in the string is:"<<endl;
   for (i = 0; i < 26; i++)
   cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
   return 0;
}
Frequency of all alphabets in the string is:
a : 4
b : 1
c : 1
d : 0
e : 1
f : 0
g : 1
h : 2
i : 3
j : 0
k : 0
l : 1
m : 1
n : 4
o : 1
p : 1
q : 0
r : 1
s : 4
t : 4
u : 0
v : 0
w : 0
x : 0
y : 1
z : 0
In the above program, a while loop is used to find the frequency of all the alphabets in the string. An array alphabet[] stores the frequency of all the alphabets. The variable j stores the numerical value of the alphabet i.e a is 0, b is 1 and so on. Then the jth index of the array alphabet is incremented by 1. This is demonstrated by the following code snippet −
while (str[i] != '\0') {
   if (str[i] >= 'a' && str[i] <= 'z') {
      j = str[i] - 'a';
      ++alphabet[j];
   }
   ++i;
}
After the whole string is evaluated, the frequency of the alphabets is printed. This is shown as follows.
cout<<"Frequency of all alphabets in the string is:"<<endl;
for (i = 0; i < 26; i++)
cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
How to Rename a View in SQL Server?

23 Sep, 2021
View is a virtual table based on the result-set of an SQL statement. It is like the subset of the table and basically created to optimize the database experience.
Like real table, this also contains rows and column. The data in a view are the data extracted from one or more real tables in the database.
We can perform all the functions to the view as we do with the tables.
CREATE VIEW view_name AS SELECT
column_1, column_2, ...
FROM table_name WHERE condition;
Step 1: Create database
Use the following command to create database.
Query:
CREATE TABLE geeks;
Step 2: Use database
Query:
USE geeks;
Step 3: Table definition
We have the following geeksforgeeks table in the database.
Query:
CREATE TABLE geeksforgeeks
(FIRSTNAME varchar(20), 
LASTNAME varchar(20),
GENDER varchar(10), AGE int);
Step 4: Insert values
Following command is used to insert values into the table.
Query:
INSERT INTO geeksforgeeks VALUES
('ROMY','KUMARI','FEMALE', 22),
 ('PUSHKAR', 'JHA', 'MALE', 23),
('SOUMYA', 'SHRIYA', 'FEMALE', 22), 
('NIKHIL', 'KALRA', 'MALE', 23),
('ROHIT', 'KUMAR', 'MALE', 23), 
('ASTHA', 'GUPTA', 'FEMALE',22),
('SAMIKSHA', 'MISHRA', 'FEMALE', 22), 
('MANU', 'PILLAI', 'MALE', 24);
Step 5: View data of the table
Query:
SELECT * FROM geeksforgeeks;
Output:
Step 6: Create View 
Query:
CREATE VIEW FEMALE AS SELECT fIRSTNAME, LASTNAME,AGE
FROM geeksforgeeks WHERE GENDER='FEMALE';
This will have the values whose gender is female.
Step 7: See the content of the view
Content can be viewed with the same query as we use for table.
Query:
SELECT * FROM female;
Output:
Step 8 : Rename view from object explorer
Steps to rename view:
Select View from menu bar.
Select Object explorer option. Object explorer will be appeared on left side of the screen.
Select Database folder and select your database (geeks we have used in this article).
Inside the database, select View option.
Right click on you viewname and select RENAME option.
Give new name as per your choice.
Object explorer:
View that we have created:
Rename by right clicking on it:
We have changed the name of view to ‘Changed_name’
Step 8: See the content of view using new view name
Query:
SELECT * FROM Changed_name;
Output:
Blogathon-2021
Picked
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
Python MySQL – Where Clause

23 Jan, 2022
Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.Syntax 
SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION];  
The above syntax is used for displaying a certain set of data following the condition.Example: Consider the following database named college and having a table name as a student.Schema of the database: 
  Database: 
   
Steps to use where clause in Python is:  
First form a connection between MySQL and Python program. It is done by importing mysql.connector package and using mysql.connector.connect() method, for passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.Now, create a cursor object on the connection object created above by using cursor() method. A database cursor is a control structure that enables traversal over the records in a database.Then, execute the where clause statement by passing it through execute() method.
First form a connection between MySQL and Python program. It is done by importing mysql.connector package and using mysql.connector.connect() method, for passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Now, create a cursor object on the connection object created above by using cursor() method. A database cursor is a control structure that enables traversal over the records in a database.
Then, execute the where clause statement by passing it through execute() method.
 
Python3
import mysql.connector  #Establishing connectionconn = mysql.connector.connect(user='your_username',                               host='localhost',                               password ='your_password',                               database='College')  # Creating a cursor object using# the cursor() methodmycursor = conn.cursor();  # SQL Querysql = "select * from Student where Roll_no >= 3;"  # Executing querymycursor.execute(sql)  myresult = mycursor.fetchall()  for x in myresult:    print(x) # Closing the connectionconn.close()
OUTPUT:  
 
Akanksha_Rai
adnanirshad158
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python