code-rag-bench/online-tutorials huggingface dataset:
Python Pandas - Swap levels of a MultiIndex

To swap levels of a MultiIndex, use the swaplevel() method in Pandas. The levels to be swapped should be mentioned as arguments.
At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))
Swap levels of MultiIndex using swaplevel(). The 1st parameter is the first level of index to be swapped. The 2nd parameter is the second level of index to be swapped −
print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2))

Following is the code −
import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))

# display the MultiIndex
print("The MultiIndex...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# swap levels of MultiIndex using swaplevel()
# The 1st parameter is the first level of index to be swapped
# The 2nd parameter is the second level of index to be swapped
print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2))
This will produce the following output −
The MultiIndex...
MultiIndex([(2, 'Peter', 50),
            (4, 'Chris', 30),
            (3,  'Andy', 40),
            (1, 'Jacob', 70)],
            names=['rank', 'student', 'points'])

The levels in MultiIndex...
   [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]]

Swap levels in MultiIndex...
MultiIndex([(50, 'Peter', 2),
            (30, 'Chris', 4),
            (40, 'Andy', 3),
            (70, 'Jacob', 1)],
            names=['points', 'student', 'rank'])
Build a DIY Mini Radar Using Arduino, Python and Streamlit | by M Khorasani | Towards Data Science

For those of us in the business of robotics, specifically the competitive type the likes of sumo-wrestling and RoboCup bots, we know that detecting objects for avoidance or for collision rather cannot possibly be overstated. While more often than not you would inundate your robot with a slew of IR sensors to detect objects all around, it is in fact possible to build your own mini radar to achieve the same effect with far fewer resources. Here I will show you how to use an IR distance measuring sensor coupled with a servo motor to create a DIY mini radar and also how to visualize the results in real-time with a dazzling dashboard.
To begin with, we will use an Arduino Uno board to read distance values from the Sharp distance measuring sensor. Subsequently, we will mount the sensor onto the arm of a servo motor using double-sided tape and connect the wiring as shown below.
Once you have connected the sensor and servo, proceed with uploading the following program to the Arduino.
Please note that depending on which sensor you use and your supply voltage, you may need to recalibrate the sensor. The current sensor can read values between 20–150cm, if necessary recalibrate the motor experimentally by reading the sensor measurements for known distances and using that to derive a new equation.
To verify that the Arduino and sensor are working as expected, open the serial monitor (Tools > Serial monitor) to ensure that values are being recorded and sent over the serial port as shown below.
Now that the Arduino, sensor, and servo are working and sending values to the serial port, we need to acquire the readings in Python to produce our radar dashboard. To interface our Python script with the Arduino through a serial USB connection, we will need to download and install Pyserial. Go ahead and fire up Anaconda or any other Python IDE of your choice and type the following command:
pip install pyserial
To produce a graphical user interface where we can visualize and interact with our dashboard we will use Streamlit. This highly versatile web framework allows you to quickly develop and deploy applications to a web server or alternatively run them locally on your browser. And to display a radar plot of the sensor readings we will use Plotly. This is a Python binding for JavaScript’s highly interactive data visualization framework that allows you to render dazzling visuals at your fingertips.
Proceed by saving the following source code in your local directory:
The above code will initiate a connection to the Arduino and then will continuously read radar position and sensor values from the serial port until prompted to stop. It will also continuously render and update the radar plot.
To run the above script type the following commands in Anaconda prompt:
cd C:/Users/.../local_directorystreamlit run python_radar.py
And there you have it, a DIY mini radar in action!
If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses:
BreakIterator getText() method in Java with Examples - GeeksforGeeks

27 Jun, 2021
The getText() method of java.text.BreakIterator class is used to get the text previously set by the setText() method in breakiterator.Syntax:  
public abstract CharacterIterator getText()
Parameter: This method does not accept any parameter.Return Value: This method provides the text scanned previously.Below are the examples to illustrate the getText() method:Example 1:  
Java
// Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG {    public static void main(String[] argv)    {        // creating and initializing BreakIterator        BreakIterator wb            = BreakIterator.getWordInstance();         // setting text for BreakIterator        wb.setText("Code Geeks");         // getting the text being scanned by        // using getText() method        StringCharacterIterator text            = (StringCharacterIterator)wb.getText();         // display the result        System.out.print("Retrieved text is : "                         + text.first());        for (int i = text.getBeginIndex() - 1;             i < text.getEndIndex() - 2;             i++)            System.out.print(text.next());    }}
Retrieved text is : Code Geeks
Example 2:  
Java
// Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG {    public static void main(String[] argv)    {        // creating and initializing BreakIterator        BreakIterator wb            = BreakIterator.getWordInstance();         // setting text for BreakIterator        wb.setText("Geeks For GEeks");         // getting the text being scanned by        // using getText() method        StringCharacterIterator text            = (StringCharacterIterator)wb.getText();         // display the result        System.out.print("Retrieved text is : "                         + text.first());        for (int i = text.getBeginIndex() - 1;             i < text.getEndIndex() - 2;             i++)            System.out.print(text.next());    }}
Retrieved text is : Geeks For GEeks
Reference: https://docs.oracle.com/javase/9/docs/api/java/text/BreakIterator.html#getText– 
akshaysingh98088
Java-BreakIterator
Java-Functions
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples
Tryit Editor v3.7

CSS Attr Selectors
Tryit: The [attribute|="value"] selector
How to create a Dialog in JavaFX?

A Dialog is a graphical element, a window that shows information to the window and receives a response. You can create a dialog by instantiating the javafx.scene.control.Dialog class.
The following Example demonstrates the creation of a Dialog.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class DialogExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a dialog
      Dialog<String> dialog = new Dialog<String>();
      //Setting the title
      dialog.setTitle("Dialog");
      ButtonType type = new ButtonType("Ok", ButtonData.OK_DONE);
      //Setting the content of the dialog
      dialog.setContentText("This is a sample dialog");
      //Adding buttons to the dialog pane
      dialog.getDialogPane().getButtonTypes().add(type);
      //Setting the label
      Text txt = new Text("Click the button to show the dialog");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      txt.setFont(font);
      //Creating a button
      Button button = new Button("Show Dialog");
      //Showing the dialog on clicking the button
      button.setOnAction(e -> {
         dialog.showAndWait();
      });
      //Creating a vbox to hold the button and the label
      HBox pane = new HBox(15);
      //Setting the space between the nodes of a HBox pane
      pane.setPadding(new Insets(50, 150, 50, 60));
      pane.getChildren().addAll(txt, button);
      //Creating a scene object
      Scene scene = new Scene(new Group(pane), 595, 250, Color.BEIGE);
      stage.setTitle("Dialog");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Java - String equals() Method

This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Here is the syntax of this method −
public boolean equals(Object anObject)

Here is the detail of parameters −
anObject − the object to compare this String against.
anObject − the object to compare this String against.
This method returns true if the String are equal; false otherwise.
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("This is really not immutable!!");
      String Str2 = Str1;
      String Str3 = new String("This is really not immutable!!");
      boolean retVal;

      retVal = Str1.equals( Str2 );
      System.out.println("Returned Value = " + retVal );

      retVal = Str1.equals( Str3 );
      System.out.println("Returned Value = " + retVal );
   }
}
This will produce the following result −
Returned Value = true
Returned Value = true


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to force Matplotlib to show the values on X-axis as integers?

To force matplotlib to show the values on X-axis as integers, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create two lists, x and y, of data points.
Plot x and y using plot() method.
Make a new list for only integers tick on X-axis. Use math.floor() and math.ceil() to remove the decimals and include only integers in the list.
Set x and y labels.
Set the title of the figure.
To display the figure, use show() method.
import math
from matplotlib import pyplot as plt

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

y = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151]
x = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50]

plt.plot(x, y)

new_list = range(math.floor(min(x)), math.ceil(max(x))+1)
plt.xticks(new_list)

plt.xlabel("X-axis ")
plt.ylabel("Y-axis ")

plt.title("Only Integers on the X-axis")

plt.show()
TypeScript - String search()

This method executes the search for a match between a regular expression and this String object.
string.search(regexp);

regexp − A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
If successful, the search returns the index of the regular expression inside the string. Otherwise, it returns -1.
var re = /apples/gi; 
var str = "Apples are round, and apples are juicy.";
if (str.search(re) == -1 ) { 
   console.log("Does not contain Apples" ); 
} else { 
   console.log("Contains Apples" ); 
} 

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Contains Apples


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: A bordered list
A single MySQL query to search multiple words from different column values

For this, you can use WHERE clause with multiple LIKE. Let us first create a table −
mysql> create table DemoTable1536
   -> (
   -> Sentence text
   -> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1536 values('I like MySQL database.');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1536 values('Java is an Object Oriented Programming Language');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable1536 values('I only like data structure');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1536 values('MongoDB is NoSQL database');
Query OK, 1 row affected (0.46 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1536;
This will produce the following output −
+--------------------------------------------------+
| Sentence                                         |
+--------------------------------------------------+
| I like MySQL database.                           |
| Java is an Object Oriented Programming Language  |
| I only like data structure                       |
| MongoDB is NoSQL database                        |
+--------------------------------------------------+
4 rows in set (0.00 sec)
Following is the query to search multiple words −
mysql> select * from DemoTable1536
   -> where ( Sentence like '%like%') or (Sentence like '%database%') or (Sentence like '%data%');
This will produce the following output −
+----------------------------+
| Sentence                   |
+----------------------------+
| I like MySQL database.     |
| I only like data structure |
| MongoDB is NoSQL database  |
+----------------------------+
3 rows in set (0.00 sec)
PyQt5 QCalendarWidget - Getting Selected Date - GeeksforGeeks

06 Aug, 2021
In this article we will see how we can get the selected date of QCalendarWidget, selected date is the date that is currently highlighted user can change the selected date using mouse and cursor by default selected date is the real-time date although we can set the selected date any time with the help of setSelectedDate method.
Note : The selected date must be within the date range specified by the minimumDate and maximumDate properties. 
In order to do this we will use selectedDate method with the QCalendarWidget object.Syntax : calendar.selectedDate(date)Argument : It takes no argumentReturn : It returns QDate object  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QCalendarWidget object        calendar = QCalendarWidget(self)         # setting geometry to the calendar        calendar.setGeometry(10, 10, 400, 250)         # date        date = QDate(2021, 1, 1)         # setting selected date        calendar.setSelectedDate(date)         # creating label        label = QLabel(self)         # setting geometry to the label        label.setGeometry(100, 270, 250, 60)         # making label multi line        label.setWordWrap(True)         # getting the selected date        value = calendar.selectedDate()         # setting text to the label        label.setText("Selected Date: " + str(value))  # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output : 
 
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
C Program find nCr and nPr.

In C programming language, nCr is referred as the combination. nCr is the selection of r objects from a set of n objects, where the order of objects does not matter.
nPr is referred as the permutation. nPr is arrangement of 'r' objects from a set of 'n' objects, which should be in an order or sequence.
The formulas to find the permutation and combination of given numbers in C language are given below −
nCr = n!/(r!*(n-r)!)
nPr = n!/(n-r)!.
The logic used to find nCr is as follows −
result = factorial(n)/(factorial(r)*factorial(n-r));
The logic used to find nPr is as follows −
result = factorial(n)/factorial(n-r);
Following is the C program to find the permutation and combination of given numbers −
#include <stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
int main(){
   int n, r;
   long ncr, npr;
   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);
   return 0;
}
long find_ncr(int n, int r) {
   long result;
   result = factorial(n)/(factorial(r)*factorial(n-r));
   return result;
}
long find_npr(int n, int r) {
   long result;
   result = factorial(n)/factorial(n-r);
   return result;
}
long factorial(int n) {
   int c;
   long result = 1;
   for (c = 1; c <= n; c++)
   result = result*c;
   return result;
}
When the above program is executed, it produces the following output −
Enter the value of n and r
5 2
5C2 = 10
5P2 = 20
Special Operators in SQL

The different special operators in SQL are as follows −
ALL operator
ANY Operator
BETWEEN Operator
EXISTS Operator
IN Operator
LIKE Operator
Now let us create a table to understand the examples of special operators −
<Employee>
<Dependents>
Details of all the special operators using the above tables are −
The ALL operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for all the values. For example −
Select * from Employee
Where Emp_Salary > ALL (select Emp_Salary from Employee
where Emp_DeptID=30);
This query returns the details of all the employees whose salary is greater than the salary of all the employees in Department number 30 i.e. Angel in this case.
The ANY operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for any value in the set of values. For example −
Select * from Employee
Where Emp_salary > ANY (select Emp_Salary from Employee
where Emp_DeptID=30);
This query returns the details of all the employees whose salary is greater than the salary of even one employee in Department number 30 i.e. Aaron, Harry, Angel and Will in this case.
The BETWEEN operator returns the information within a given range of values, where the minimum and maximum of the range is specified. For example −
Select * from Employee
Where Emp_Salary BETWEEN 20000 AND 60000;
This query returns information about all the employees whose salary is between the range of 20000 and 60000 i.e. Angel and Will in this case.
The EXISTS operator only returns true if the subquery returns at least one record i.e if some data exists for the given subquery. For example −
Select * from Employee
Where EXISTS (select * from Dependents where
Employee.Emp_ID=dependents.Emp_ID);
This query will return results for only those employees who have any dependents i.e. Harry, Mary and Will.
The IN operator is true if the query results in values that are contained in the list of constant values for the IN operator. For example −
Select * from Employee
Where Emp_ID IN (1,2,5);
This query gives details about the employees whose Employee number is 1,2 or 5 i.e Aaron, Harry and Will.
The LIKE operator is used to select the values that match the patterns specified in the query. Two wildcard operators are used for this. For example −
Select * from Employee
Where Emp_Name LIKE “A%”
This query returns the data of all the employees whose name starts with A i.e. Aaron and Angel in our example.
How to Get the names of the table in SQL - GeeksforGeeks

14 Aug, 2020
The syntax provided in this article works only for SQL Server and MySQL. 
If you want to know how many tables are present in your database and the details of the table like TABLE_SCHEMA, TABLE_TYPE and all. 
Syntax (When we have only single database):  
Select * from schema_name.table_name
Syntax (When we have multiple databases): 
Select * from database_name.schema_name.table_name
Example: 
SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE 
1. INFORMATION_SCHEMA views allow you to retrieve metadata about the objects within a database. These views can be found in the master database under Views / System Views and be called from any database in your SQL Server instance. 
2. INFORMATION_SCHEMA.TABLES The INFORMATION_SCHEMA.TABLES view allows you to get information about all tables and views within a database. 
Output:  
 
khushboogoyal499
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Difference between SQL and NoSQL
SQL | Views
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
SQL | GROUP BY
What is Cursor in SQL ?
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | TRANSACTIONS
CTE in SQL
What is an array of structures in C language?

The most common use of structure in C programming language is an array of structures.
To declare an array of structures, first the structure must be defined and then, an array variable of that type can be defined.
For example, struct book b[10]; //10 elements in an array of structures of type ‘book’
Given below is the C program for accepting and printing details of 3 students with regards to an array of structures −
 Live Demo
#include <stdio.h>
#include <string.h>
struct student{
   int id;
   char name[30];
   float percentage;
};
int main(){
   int i;
   struct student record[2];
   // 1st student's record
   record[0].id=1;
   strcpy(record[0].name, "Bhanu");
   record[0].percentage = 86.5;
   // 2nd student's record
   record[1].id=2;
   strcpy(record[1].name, "Priya");
   record[1].percentage = 90.5;
   // 3rd student's record
   record[2].id=3;
   strcpy(record[2].name, "Hari");
   record[2].percentage = 81.5;
   for(i=0; i<3; i++){
      printf(" Records of STUDENT : %d \n", i+1);
      printf(" Id is: %d \n", record[i].id);
      printf(" Name is: %s \n", record[i].name);
      printf(" Percentage is: %f\n\n",record[i].percentage);
   }
   return 0;
}
When the above program is executed, it produces the following result −
Records of STUDENT : 1
Id is: 1
Name is: Bhanu
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Priya
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Hari
Percentage is: 81.500000
Convert Java Boolean Primitive to Boolean object

To convert Boolean Primitive to Boolean object, use the valueOf() method in Java.
Firstly, let us take a boolean primitive.
boolean val = false;
To convert it into an object, use the valueOf() method and set the argument as the boolean primitive.
Boolean res = Boolean.valueOf(val);
Let us see the complete example to learn how to convert Boolean Primitive to Boolean object.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      boolean val = false;
      // converting to object
      Boolean res = Boolean.valueOf(val);
      System.out.println(res);
   }
}
False
How to sort a nested Python dictionary?

If you have a dictionary of the following format:
{
   'KEY1':{'name':'foo','data':1351,'completed':100},
   'KEY2':{'name':'bar','data':1541,'completed':12},
   'KEY3':{'name':'baz','data':58413,'completed':18}
}
And you want to sort by the key, completed within each entry, in a ascending order, you can use the sorted function with a lambda that specifies which key to use to sort the data. For example,
my_collection = {
   'KEY1':{'name':'foo','data':1351,'completed':100},
   'KEY2':{'name':'bar','data':1541,'completed':12},
   'KEY3':{'name':'baz','data':58413,'completed':18}
}
sorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed']))
print(sorted_keys)
This will give the output:
['KEY2', 'KEY3', 'KEY1']
Async & await keyword in C#

The async and await keyword is used in C# for asynchronous programming.
An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected.
Let us see what is discussed above −
private void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req = HttpWebRequest.Create(_requestedUri);
   var res = req.GetResponse();
}
To solve the above issue, use the async and await keywords −
private async void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req= HttpWebRequest.Create(_requestedUri);
   var res = await req.GetResponseAsync();
}
Changing year in MySQL date?

To change the year in MySQL date, you need to use DATE_FORMAT() function with UPDATE
command. The syntax is as follows.
UPDATE yourTableName
SET yourDateColumnName = DATE_FORMAT(yourDateColumnName ,'yourYearValue-%m-%d');
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ChangeYear
   -> (
   -> id int not null auto_increment,
   -> ArrivalTime date,
   -> PRIMARY KEY(id)
   -> );
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into ChangeYear(ArrivalTime) values(date_add(now(),interval -2 year));
Query OK, 1 row affected, 1 warning (0.20 sec)

mysql> insert into ChangeYear(ArrivalTime) values('2012-10-24');
Query OK, 1 row affected (0.18 sec)

mysql> insert into ChangeYear(ArrivalTime) values('2016-3-21');
Query OK, 1 row affected (0.19 sec)

mysql> insert into ChangeYear(ArrivalTime) values('2015-4-24');
Query OK, 1 row affected (0.20 sec)

mysql> insert into ChangeYear(ArrivalTime) values(curdate());
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from ChangeYear;
The following is the output.
+----+-------------+
| id | ArrivalTime |
+----+-------------+
| 1 | 2017-01-07 |
| 2 | 2012-10-24 |
| 3 | 2016-03-21 |
| 4 | 2015-04-24 |
| 5 | 2019-01-07 |
+----+-------------+
5 rows in set (0.00 sec)
Here is the query to update only the year in the date column. For our example, let us change the
year to 2019 −
mysql> update ChangeYear
   -> set ArrivalTime = DATE_FORMAT(ArrivalTime,'2019-%m-%d');
Query OK, 4 rows affected (0.12 sec)
Rows matched − 5 Changed − 4 Warnings − 0
Check all the updated records from the table using select statement. The query is as follows −
mysql> select *from ChangeYear;
The following is the output displaying the updated year 2019, but rest of the date remains the same −
+----+-------------+
| id | ArrivalTime |
+----+-------------+
|  1 | 2019-01-07  |
|  2 | 2019-10-24  |
|  3 | 2019-03-21  |
|  4 | 2019-04-24  |
|  5 | 2019-01-07  |
+----+-------------+
5 rows in set (0.00 sec)
RTTI (Run-time type Information) in C++ program

In this section, we will see what is the RTTI (Runtime Type Information) in C++. In C++ the RTTI is a mechanism, that exposes information about an object’s datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing.
In the following example, the first code will not work. It will generate an error like “cannot dynamic_cast base_ptr (of type Base*) to type ‘class Derived*’ (Source type is not polymorphic)”. This error comes because there is no virtual function in this example.
#include<iostream>
using namespace std;
class Base { };
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}
Now after adding a virtual method, it will work.
#include<iostream>
using namespace std;
class Base {
   virtual void function() {
      //empty function
   }
};
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}
It is working
Find all substrings that are anagrams of another substring of the string S - GeeksforGeeks

25 Aug, 2021
Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at the different index.
Examples:
Input: S = “aba”Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S:
“a”: Substring “a” is anagram of the substring “a”(= {S[0]}).“a”: Substring “a” is anagram of the substring “a”(= {S[2]}).“ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).“ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}).
“a”: Substring “a” is anagram of the substring “a”(= {S[0]}).
“a”: Substring “a” is anagram of the substring “a”(= {S[2]}).
“ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).
“ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}).
Input: S = “abcd”Output: []
Approach: The given problem can be solved by using Hashing by storing the anagrams of each substring of the string S and print the resultant substring. Follow the below steps to solve the given problem:
Initialize a HashMap that stores all the anagrams of each substring of the string S.
Generate all the possible substrings of S and for each substring, say str store the substring in the HashMap mapped with the key as the sorted string str.
Traverse the HashMap and print all the strings associated with each key whose number of strings associated with each string is at least 1.
Below is the implementation of the above approach:
Python3
# Python program for the above approach import collections # Function to find all the substrings# whose anagram exist as a different# substring in Sdef findAnagrams(S):       # Stores the lists of anagrams of    # each substring of S    Map = collections.defaultdict(list)         # Stores the length of S    N = len(S)         # Generate all substrings of S    for i in range(N):        for j in range(i, N):                         # Store the current substring            # of the string S            curr = S[i: j + 1]                         # Key is the sorted substring            key = "".join(sorted(curr))                         # Add the sorted substring            # to the dictionary            Map[key].append(curr)         # Store the final result    result = []         # Iterate over values of dictionary    for vals in Map.values():                 # If length of list > 1        if len(vals) > 1:                        # Print all the strings            for v in vals:                  print(v, end =" ")    # Driver Code S = "aba"findAnagrams(S)
ab ba a a
 
Time Complexity: O(N3)Auxiliary Space: O(N2)
clintra
anagram
substring
Hash
Sorting
Strings
Hash
Strings
Sorting
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Most frequent element in an array
Counting frequencies of array elements
Double Hashing
Quadratic Probing in Hashing
Implementing our Own Hash Table with Separate Chaining in Java
Factorial recursion in JavaScript

We are required to write a JavaScript function that computes the Factorial of a number n by making use of recursive approach.
Here, we are finding the factorial recursion and creating a custom function recursiceFactorial() −
const num = 9;
const recursiceFactorial = (num, res = 1) => {
   if(num){
      return recursiceFactorial(num-1, res * num);
   };
   return res;
};
Now, we will call the function and pass the value to find recursion −
console.log(recursiceFactorial(num));
console.log(recursiceFactorial(6));
console.log(recursiceFactorial(10));
Let’s write the code for this function −
const num = 9;
const recursiceFactorial = (num, res = 1) => {
   if(num){
      return recursiceFactorial(num-1, res * num);
   };
   return res;
};
console.log(recursiceFactorial(num));
console.log(recursiceFactorial(6));
console.log(recursiceFactorial(10));
console.log(recursiceFactorial(5));
console.log(recursiceFactorial(13));
Following is the output in the console −
362880
720
3628800
120
6227020800
How to count the number of rows in a table in Selenium with python?

We can count the total number of rows in a table in Selenium. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned. Next we need to compute the size of the list with the help of len method.
The html code snippet of a table row count is as described below −
driver.find_elements_by_xpath("//table/tbody/tr")
Code Implementation for getting row count.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm")
#to refresh the browser
driver.refresh()
# identifying the number of rows having <tr> tag
rows = driver.find_elements_by_xpath("//table/tbody/tr")
# len method is used to get the size of that list
print(len(rows))
#to close the browser
driver.close()
How to set the line breakpoint in the PowerShell?

To set the line breakpoint in the script, we can use the Set-PSBreakpoint command with -Line parameter and need to give the path of the script on which the Line breakpoint needs to set.
Consider we have the script below which retrieves the value up to 99, starting from 1,
We will set the Line Breakpoint at line number 3 so we will use the below command. Here the script name is WhieScript.ps1 and stored at C:\temp.
Set-PSBreakpoint C:\temp\WhileScript.ps1 -Line 3
Once you run the above command, you will get the output with the details as shown below.
ID Script    Line Command Variable Action
 -- ------   ---- ------- -------- ------
6 WhileScript.ps1 3
To check all the applied breakpoints, you can use the Get-PSBreakPoint command.
Now to enter the debug mode, you need to run the script.
You can see in the above image that the console has entered debug mode. To continue till the next breakpoint, press ‘C’.
There are other keywords for step in, step out, exit, etc. You can check them below at the MS site.
 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_debuggers?view=powershell-7.1
MySQL - CREATE TABLESPACE Statement

A logical group of datafiles in a database is known as a table space each database contains at least one tablespace.
You can create a tablespace in MySQL using the CREATE TABLESPACE Statement.
Following is the syntax to create a table space in MySQL −
CREATE [UNDO] TABLESPACE tablespace_name

Where, tablespace_name is the name of the table space you need to create.
Following query creates a table with name Employee −
mysql> CREATE TABLESPACE sample_tablespace;

Following query creates another tablespace with name test −
mysql> CREATE TABLESPACE sample ADD DATAFILE 'sample.ibd' ENGINE = INNODB;
Query OK, 0 rows affected (0.59 sec)

You can verify the creation of the above tablespace using the following query −
mysql> select * from INFORMATION_SCHEMA.FILES where TABLESPACE_NAME ='sample'\G
*************************** 1. row ***************************
             FILE_ID: 73
           FILE_NAME: ./sample.ibd
           FILE_TYPE: TABLESPACE
     TABLESPACE_NAME: sample
       TABLE_CATALOG:
        TABLE_SCHEMA: NULL
          TABLE_NAME: NULL
  LOGFILE_GROUP_NAME: NULL
LOGFILE_GROUP_NUMBER: NULL
              ENGINE: InnoDB
       FULLTEXT_KEYS: NULL
        DELETED_ROWS: NULL 
        UPDATE_COUNT: NUL
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 row in set (0.00 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Inheritance in Java

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance, the information is made manageable in a hierarchical order. 
The class which inherits the properties of other is known as a subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
 Live Demo 
class Calculation {
   int z;
   public void addition(int x, int y) {
      z = x + y;
      System.out.println("The sum of the given numbers:"+z);
   }
   public void Subtraction(int x, int y) {
      z = x - y;
      System.out.println("The difference between the given numbers:"+z);
   }
}
public class My_Calculation extends Calculation {
   public void multiplication(int x, int y) {
      z = x * y;
      System.out.println("The product of the given numbers:"+z);
   }
   public static void main(String args[]) {
      int a = 20, b = 10;
      My_Calculation demo = new My_Calculation();
      demo.addition(a, b);
      demo.Subtraction(a, b);
      demo.multiplication(a, b);
   }
}
Compile and execute the above code as shown below.
javac My_Calculation.java
java My_Calculation 
After executing the program, it will produce the following result − 
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
PL/SQL - Relational Operators

Relational operators compare two expressions or values and return a Boolean result. Following table shows all the relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable B holds 20, then −
!=
<>
~=
DECLARE 
   a number (2) := 21; 
   b number (2) := 10; 
BEGIN 
   IF (a = b) then 
      dbms_output.put_line('Line 1 - a is equal to b'); 
   ELSE 
      dbms_output.put_line('Line 1 - a is not equal to b'); 
   END IF;  
   IF (a < b) then 
      dbms_output.put_line('Line 2 - a is less than b'); 
   ELSE 
      dbms_output.put_line('Line 2 - a is not less than b'); 
   END IF; 
    
   IF ( a > b ) THEN 
      dbms_output.put_line('Line 3 - a is greater than b'); 
   ELSE 
      dbms_output.put_line('Line 3 - a is not greater than b'); 
   END IF;  
   -- Lets change value of a and b 
   a := 5; 
   b := 20; 
   IF ( a <= b ) THEN 
      dbms_output.put_line('Line 4 - a is either equal or less than b'); 
   END IF; 
   IF ( b >= a ) THEN 
      dbms_output.put_line('Line 5 - b is either equal or greater than a'); 
   END IF;
   IF ( a <> b ) THEN 
      dbms_output.put_line('Line 6 - a is not equal to b'); 
   ELSE 
      dbms_output.put_line('Line 6 - a is equal to b'); 
   END IF;  
END; 
/ 
When the above code is executed at the SQL prompt, it produces the following result −
Line 1 - a is not equal to b 
Line 2 - a is not less than b 
Line 3 - a is greater than b 
Line 4 - a is either equal or less than b 
Line 5 - b is either equal or greater than a 
Line 6 - a is not equal to b  

PL/SQL procedure successfully completed 

 Print
 Add Notes
 Bookmark this page
Express.js | app.set() Function - GeeksforGeeks

10 Jun, 2020
The app.set() function is used to assigns the setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server.
Syntax:
app.set(name, value)
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
var express = require('express');var app = express();var PORT = 3000;  app.set('title', 'GeeksforGeeks');  app.get('/', (req, res) => {  res.send(app.get('title'));})  app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);}); 
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks
GeeksforGeeks
So this is how you can use the express app.set() function which assigns setting name to value.
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Express.js express.Router() Function
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
How does 'void*' differ in C and C++? - GeeksforGeeks

28 Nov, 2021
C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++
For example, the following is valid in C but not C++: 
void* ptr;
int *i = ptr; // Implicit conversion from void* to int*
Similarly,
int *j = malloc(sizeof(int) * 5);  // Implicit conversion from void* to int* 
In order to make the above code compile in C++ as well, we have to use explicit casting, as shown below,
void* ptr;
int *i = (int *) ptr;
int *j = (int *) malloc(sizeof(int) * 5);
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects