code-rag-bench/online-tutorials huggingface dataset:
Add, subtract, multiple and divide two Pandas Series - GeeksforGeeks

28 Jul, 2020
Let us see how to perform basic arithmetic operations like addition, subtraction, multiplication, and division on 2 Pandas Series.
For all the 4 operations we will follow the basic algorithm :
Import the Pandas module.Create 2 Pandas Series objects.Perform the required arithmetic operation using the respective arithmetic operator between the 2 Series and assign the result to another Series.Display the resultant Series.
Import the Pandas module.
Create 2 Pandas Series objects.
Perform the required arithmetic operation using the respective arithmetic operator between the 2 Series and assign the result to another Series.
Display the resultant Series.
# importing the moduleimport pandas as pd  # creating 2 Pandas Seriesseries1 = pd.Series([1, 2, 3, 4, 5])series2 = pd.Series([6, 7, 8, 9, 10])  # adding the 2 Seriesseries3 = series1 + series2  # displaying the resultprint(series3)
Output :
# importing the moduleimport pandas as pd  # creating 2 Pandas Seriesseries1 = pd.Series([1, 2, 3, 4, 5])series2 = pd.Series([6, 7, 8, 9, 10])  # subtracting the 2 Seriesseries3 = series1 - series2  # displaying the resultprint(series3)
Output :
# importing the moduleimport pandas as pd  # creating 2 Pandas Seriesseries1 = pd.Series([1, 2, 3, 4, 5])series2 = pd.Series([6, 7, 8, 9, 10])  # multiplying the 2 Seriesseries3 = series1 * series2  # displaying the resultprint(series3)
Output :
# importing the moduleimport pandas as pd  # creating 2 Pandas Seriesseries1 = pd.Series([1, 2, 3, 4, 5])series2 = pd.Series([6, 7, 8, 9, 10])  # dividing the 2 Seriesseries3 = series1 / series2  # displaying the resultprint(series3)
Output :
pandas-dataframe-program
Python-pandas
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Area and Perimeter of Rectangle in PL/SQL - GeeksforGeeks

04 Oct, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given the value of the length, breadth, and the task is to calculate the area and perimeter of the Rectangle.
Examples:
Input: l = 2, b = 2
Output: Area = 4, Perimeter = 8

Input: l = 4, b = 8
Output: Area = 32, Perimeter=24

Mathematical Formula:Area of rectangle:
Perimeter of rectangle:
Below is the required implementation:
-- Declaration statement DECLARE  -- Declaration of length and assigning values   l NUMBER(4, 2) := 3;   --Declaration of breadth and assigning values   b NUMBER(4, 2) := 7;   --Declaration of a variable for Area of rectangle   a NUMBER(4, 2);     --Declaration of a variable for perimeter   p NUMBER(4, 2); BEGIN       -- calculate area and perimeter  a := l * b;   p := 2 * (l + b);     --Display result   dbms_output.Put_line('Area of the rectangle is  '   || a);   dbms_output.Put_line('Perimeter of the rectangle is '   || p); END; --ENd program
Output:
Area of the rectangle is 21
Perimeter of the rectangle is 20

SQL-PL/SQL
square-rectangle
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
How to Create a Table With Multiple Foreign Keys in SQL?
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
Spiral Matrix in C++

Suppose we have a matrix and we have to print the matrix elements in a spiral way. At first starting from the first row, print the whole content and then follow the last column to print, then the last row, and so on, thus it prints the elements in a spiral fashion. So if the matrix is like −
Then the output will be like [1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16]
To solve this, we will follow these steps −
currRow := 0 and currCol := 0
currRow := 0 and currCol := 0
while currRow and currCol are in the matrix rangefor i in range currCol and n-1,display mat[currRow, i]increase currRow by 1for i in range currRow and m-1, dodisplay mat[i, n-1]decrease n by 1if currRow < m, thenfor i := n-1 down to currCol, dodisplay mat[m-1, i]decrease m by 1if currCol < n, thenfor i := m-1 down to currRow, dodisplay mat[i, currCol]increase currCol by 1
while currRow and currCol are in the matrix range
for i in range currCol and n-1,display mat[currRow, i]
for i in range currCol and n-1,
display mat[currRow, i]
display mat[currRow, i]
increase currRow by 1
increase currRow by 1
for i in range currRow and m-1, dodisplay mat[i, n-1]
for i in range currRow and m-1, do
display mat[i, n-1]
display mat[i, n-1]
decrease n by 1
decrease n by 1
if currRow < m, thenfor i := n-1 down to currCol, dodisplay mat[m-1, i]decrease m by 1if currCol < n, thenfor i := m-1 down to currRow, dodisplay mat[i, currCol]increase currCol by 1
if currRow < m, then
for i := n-1 down to currCol, dodisplay mat[m-1, i]
for i := n-1 down to currCol, do
display mat[m-1, i]
display mat[m-1, i]
decrease m by 1
decrease m by 1
if currCol < n, thenfor i := m-1 down to currRow, dodisplay mat[i, currCol]increase currCol by 1
if currCol < n, then
for i := m-1 down to currRow, dodisplay mat[i, currCol]
for i := m-1 down to currRow, do
display mat[i, currCol]
display mat[i, currCol]
increase currCol by 1
increase currCol by 1
Let us see the following implementation to get a better understanding −
 Live Demo
#include <iostream>
#define ROW 3
#define COL 6
using namespace std;
int array[ROW][COL] = {{1, 2, 3, 4, 5, 6},
   {7, 8, 9, 10, 11, 12},
   {13, 14, 15, 16, 17, 18}};
void dispSpiral(int m, int n){
   int i, currRow = 0, currCol = 0;
   while (currRow < ROW && currCol < COL){
      for (i = currCol; i < n; i++){ //print the first row normally
      cout << array[currRow][i]<<" ";
   }
   currRow++; //point to next row
   for (i = currRow; i < m; ++i){ //Print the last column
      cout << array[i][n-1]<<" ";
   }
   n--; //set the n-1th column is current last column
   if ( currRow < m){ //when currRow is in the range, print the last row
      for (i = n-1; i >= currCol; --i){
         cout << array[m-1][i]<<" ";
      }
      m--; //decrease the row range
   }
   if (currCol < n){ //when currCol is in the range, print the fist column
      for (i = m-1; i >= currRow; --i){
         cout << array[i][currCol]<<" ";
      }
      currCol++;
      }
   }
}
int main(){
   dispSpiral(ROW, COL);
}
[[1,2,3,4,5,6]
[7,8,9,10,11,12]
[13,14,15,16,17,18]]
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16
Different ways to print exception messages in Java

Following are the different ways to handle exception messages in Java.
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred.catch(Exception e) {
e.printStackTrace();
}
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred.
catch(Exception e) {
e.printStackTrace();
}
Using toString() method − It prints the name and description of the exception.catch(Exception e) {
System.out.println(e.toString());
}
Using toString() method − It prints the name and description of the exception.
catch(Exception e) {
System.out.println(e.toString());
}
Using getMessage() method − Mostly used. It prints the description of the exception.catch(Exception e) {
System.out.println(e.getMessage());
}
Using getMessage() method − Mostly used. It prints the description of the exception.
catch(Exception e) {
System.out.println(e.getMessage());
}
import java.io.Serializable;

public class Tester implements Serializable, Cloneable {
   public static void main(String args[]) {

      try {
         int a = 0;
         int b = 10;
         int result = b/a;
         System.out.println(result);

      } catch(Exception e) {
         System.out.println("toString(): " + e.toString());
         System.out.println("getMessage(): " + e.getMessage());
         System.out.println("StackTrace: ");
         e.printStackTrace();
      }
   }
}
toString(): java.lang.ArithmeticException: / by zero
getMessage(): / by zero
StackTrace:
java.lang.ArithmeticException: / by zero
at Tester.main(Tester.java:8)
Two essential Pandas add-ons. These two must-have UIs will help you... | by Josh Taylor | Towards Data Science

The Python Data Analysis Library (Pandas) is the de facto analysis tool for Python. It still amazes me that such a powerful analysis library can be open-source and free to use.
But it is not perfect...
There are a couple of frustrations that I have with the library especially when it comes to performing simple filtering and pivoting. There are certain situations where a user interface can really speed-up analysis. Nothing beats ‘drag-and-drop’ for an intuitive way of exploring and filtering data and this is not something that Pandas allows you to do. Thankfully there are two libraries which address these issues and work perfectly alongside Pandas.
The pivot table in Pandas is very powerful but it does not lend itself to quick and easy data exploration. In fact things can get very complex very quickly:
Thankfully there is a fantastic interactive pivot-table and plotting add-on, pivottablejs. It can be installed and run in 4 lines of code:
!pip install pivottablejsfrom pivottablejs import pivot_uipivot_ui(df,outfile_path=’pivottablejs.html’)HTML(‘pivottablejs.html’)
This gives you an interactive HTML pivot chart. This can be displayed within a notebook or opened in a browser as an HTML file (this allows it to be easily shared with others):
Fed-up of looking at the first and last 5 rows of a Pandas dataframe? How often have you wished that you could quickly filter and see what is happening with your data. Pandas does provide useful filtering functionality with loc and iloc however in the same way that pivot tables can become quite complex, so can statements using these indexing functions.
QGrid allows you to do this and much more. Some of the key features are:
Filter and sort dataframes
Scroll through large dataframes without loosing performance (>1million rows)
Edit cells in a dataframe directly through the UI
Return a new dataframe with the filters/sorts/edits applied
Compatible with Jupyter Notebooks and JupyterLab
Installation is simple via pip or Conda:
pip install qgridjupyter nbextension enable --py --sys-prefix qgridimport qgrid# only required if you have not enabled the ipywidgets nbextension yetjupyter nbextension enable --py --sys-prefix widgetsnbextension#to show a df simply use the below:qgrid.show_grid(df)
To get an idea of what is possible, see the below demo from the QGrid Github page:
That’s all. Hopefully these two tools will help speed up your data analysis in Python.
If you know of any other UI libraries for Pandas, please let people know in the comments below.
3D Surface Plots using Plotly in Python - GeeksforGeeks

05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
Surface plot is those plot which has three-dimensions data which is X, Y, and Z. Rather than showing individual data points, the surface plot has a functional relationship between dependent variable Y and have two independent variables X and Z. This plot is used to distinguish between dependent and independent variables.
Syntax: plotly.graph_objects.Surface(arg=None, hoverinfo=None, x=None, y=None, z=None, **kwargs)
Parameters:
arg:  dict of properties compatible with this constructor or an instance of plotly.graph_objects.Surface
x: Sets the x coordinates.
y: Sets the y coordinates.
z: Sets the z coordinates.
hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired.
Example:
Python3
import plotly.graph_objects as goimport numpy as np  x = np.outer(np.linspace(-2, 2, 30), np.ones(30))y = x.copy().Tz = np.cos(x ** 2 + y ** 2)  fig = go.Figure(data=[go.Surface(x=x, y=y, z=z)])  fig.show()
Output:
In plotly, contours attribute is used to Display and customize contour data for each axis.
Example:
Python3
import plotly.graph_objects as goimport numpy as np  x = np.outer(np.linspace(-2, 2, 30), np.ones(30))  # transposey = x.copy().Tz = np.cos(x ** 2 + y ** 2)  fig = go.Figure(data=[go.Surface(x=x, y=y, z=z)])  fig.update_traces(contours_z=dict(    show=True, usecolormap=True,    highlightcolor="limegreen",    project_z=True))  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
How to Get Current time in Golang? - GeeksforGeeks

21 Apr, 2020
With the help of time.Now() function, we can get the current time in Golang by importing time module.
Syntax: time.Now()Return: Return current date and time.
Example #1: In this example, we can see that by using time.Now() function, we are able to get the current date and time.
// Golang program to get the current timepackage main  // Here "fmt" is formatted IO which// is same as C’s printf and scanf.import "fmt"  // importing time moduleimport "time"  // Main functionfunc main() {      // Using time.Now() function.    dt := time.Now()    fmt.Println("Current date and time is: ", dt.String())}
Output :
Current date and time is:  2009-11-10 23:00:00 +0000 UTC m=+0.000000001

Example #2:
// Golang program to get the current timepackage main  // Here "fmt" is formatted IO which// is same as C’s printf and scanf.import "fmt"  // importing time moduleimport "time"  // Main functionfunc main() {      // Using time.Now() function.    dt := time.Now()    fmt.Println(dt.Format("01-02-2006 15:04:05"))  }
Output:
11-10-2009 23:00:00

GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Arrays in Go
Slices in Golang
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Default Value in MongoDB using Node.js - GeeksforGeeks

28 Mar, 2022
Mongoose.module is one of the most powerful external module of the NodeJS. Mongoose is a MongoDB ODM i.e. (Object database Modeling) that is used to translate the code and its representation from MongoDB to the NodeJS server. Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database.(Refer this Link).
Default Value: This value is entered when no value is entered as a value of the field in the collection.
Installing Module:
npm install mongoose
Project Structure:
Running the server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
Filename- index.js:
Javascript
// Importing mongoose moduleconst mongoose = require("mongoose"); // Database Addressconst url = "mongodb://localhost:27017/GFG"; // Connecting to databasemongoose  .connect(url)  .then((ans) => {    console.log("Connected Successful");  })  .catch((err) => {    console.log("Error in the Connection");  }); // Schema classconst Schema = mongoose.Schema; // Creating Structure of the collectionconst collection_structure = new Schema({  name: {    type: String, // String type    required: true,  },  marks: {    type: Number, // Number type    default: 100,  },});// Creating collectionconst collections = mongoose.model("GFG2", collection_structure); // Inserting one documentcollections  .create({     // Inserting value of only one key    name: "aayush",  })  .then((ans) => {    console.log(ans);  })  .catch((err) => {    console.log(err.message);  });
Run index.js file using below command:
node index.s
Output: Console output- Default Value is inserted.
sagar0719kumar
NodeJS-Questions
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
MongoDB - Check the existence of the fields in the specified collection
Aggregation in MongoDB
MongoDB - db.collection.Find() Method
Mongoose Populate() Method
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
Python Pandas - Create a datetime with DateTimeIndex

To create a datetime, we will use the date_range(). The periods and the time zone will also be set with the frequency. At first, import the required libraries −
import pandas as pd
DatetimeIndex with period 8 and frequency as M i.e. months. The timezone is Australia/Sydney −
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

Display the datetime −
print("DateTime...\n", datetime)
Following is the code −
import pandas as pd

# DatetimeIndex with period 8 and frequency as M i.e. months
# timezone is Australia/Sydney
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

# display
print("DateTime...\n", datetime)

# get the day name
print("\nGetting the day name..\n",datetime.day_name())

# get the month name
print("\nGetting the month name..\n",datetime.month_name())

# get the year
print("\nGetting the year name..\n",datetime.year)

# get the hour
print("\nGetting the hour..\n",datetime.hour)

# get the minutes
print("\nGetting the minutes..\n",datetime.minute)

# get the seconds
print("\nGetting the seconds..\n",datetime.second)
This will produce the following output −
DateTime...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00',
               '2022-03-31 02:35:55+11:00', '2022-04-30 02:35:55+10:00'],
               dtype='datetime64[ns, Australia/Sydney]', freq='M')

Getting the day name..
Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday','Thursday', 'Saturday'],
dtype='object')

Getting the month name..
Index(['September', 'October', 'November', 'December', 'January', 'February','March', 'April'], dtype='object')

Getting the year name..
   Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')

Getting the hour..
   Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')

Getting the minutes..
   Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')

Getting the seconds..
   Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')
How to use Tkinter in python to edit the title bar?

Tkinter creates a window or frame that appears after executing the program. Since
all the functions and modules in Tkinter are independent, we can specifically use
a particular function to customize the window attributes.
Tkinter creates a default root window for every application. To customize or edit
the default title of Tkinter window, we can use the following method,
title(text= “your title”)
Let us create a window by initiating an object of Tkinter frame and edit the title of
the window or frame.
#Import the library
from tkinter import *

#Create an instance of window
win= Tk()

#Set the geometry of the window
win.geometry("700x400")

#Set the title of the window
win.title("tutorialspoint.com")

#Create a label if needed
Label(win, text= "The Title is tutorialspoint.com", font=('Helvetica bold',20), fg= "green").pack(pady=20)

#Keep running the window or frame
win.mainloop()
The above Python code will set the title as tutorialspoint.com.
Calendar toString() Method in Java with Examples - GeeksforGeeks

13 Feb, 2019
The toString() method in Calendar class is used to get the string representation of the Calendar object. This method in Calendar Class is just for debug process and not to be used as an operation.
Syntax:
public String toString()
Parameters: The method does not take any parameters.
Return Value: The method returns the String representation of the Calendar object. It can return an empty object but not null.
Below programs illustrate the working of toString() Method of Calendar class:
Example 1:
// Java Code to illustrate toString() Method  import java.util.*;  public class CalendarClassDemo {    public static void main(String args[])    {        // Creating a calendar object        Calendar calndr1            = Calendar.getInstance();          // Returning the string representation        System.out.println("The string form: "                           + calndr1.getTime()                                 .toString());    }}
The string form: Wed Feb 13 09:46:36 UTC 2019

Example 2:
// Java Code to illustrate toString() Method  import java.util.*;  public class CalendarClassDemo {    public static void main(String args[])    {        // Creating a calendar object        Calendar calndr1            = new GregorianCalendar(2018, 12, 2);          // Returning the string representation        System.out.println("The string form: "                           + calndr1.getTime()                                 .toString());    }}
The string form: Wed Jan 02 00:00:00 UTC 2019

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#toString()
Java - util package
Java-Calendar
Java-Functions
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
How to convert a List to a Map in Kotlin?

In this article, we will see how we can convert a List to a Map using various options provided by the Kotlin Library.
The most standard way of converting a list into a map is by using the associate() function. This function takes a list of items as an argument and it returns a map containing key-value pairs. In the following example, we will see how it works.
data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of values in it.
   val myMap: Map<String, String> = mySubjectList.associate {
      Pair(it.priority, it.name)
   }

   println(myMap)
}
Once we run the above piece of code, it will generate the following output
which is a map and we get the output in a key-value format.
{1=Java, 2=Kotlin, 3=C}
AssociateBy() is another function that can be used in order to transform a list into a Map. In the following example, we will see how we can implement the same.
data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of the values in it
   val myMap: Map<String, String> = mySubjectList.associateBy(
      {it.priority}, {it.name}
   )

   println(myMap)
}
It will generate the following output which is a map and we get the output in a key-value format.
{1=Java, 2=Kotlin, 3=C}
Kotlin library provides another function to convert a list of items into a Map. Kotlin Map class contains a function called toMap() which returns a new map containing all the key-value pairs from a given collection. Let's see how it works.
data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of the values in it .
   val myMap: Map<String, String> = mySubjectList.map{
      it.priority to it.name
   }.toMap()

   println(myMap)
}
Once we run the above piece of code, it will generate the following output which is a map and we get the output in a key-value format.
{1=Java, 2=Kotlin, 3=C}
PHP | range() Function

08 Mar, 2018
The range() function is an inbuilt function in PHP which is used to create an array of elements of any kind such as integer, alphabets within a given range(from low to high) i.e, list’s first element is considered as low and last one is considered as high.
Syntax:
array range(low, high, step)
Parameters: This function accepts three parameters as described below:
low: It will be the first value in the array generated by range() function.high: It will be the last value in the array generated by range() function.step: It is used when the increment used in the range and it’s default value is 1.
low: It will be the first value in the array generated by range() function.
high: It will be the last value in the array generated by range() function.
step: It is used when the increment used in the range and it’s default value is 1.
Return Value: It returns an array of elements from low to high.
Examples:
Input : range(0, 6)
Output : 0, 1, 2, 3, 4, 5, 6
Explanation: Here range() function print 0 to 
6 because the parameter of range function is 0 
as low and 6 as high. As the parameter step is 
not passed, values in the array are incremented 
by 1.

Input : range(0, 100, 10)
Output : 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Explanation: Here range() function accepts 
parameters as 0, 100, 10 which are values of low, 
high, step respectively so it returns an array with 
elements starting from 0 to 100 incremented by 10.

Below programs illustrate range() function in PHP:Program 1:
<?php  // creating array with elements from 0 to 6// using range function$arr = range(0,6);  // printing elements of arrayforeach ($arr as $a) {          echo "$a ";}  ?>
Output:
0 1 2 3 4 5 6
Program 2:
<?php  // creating array with elements from 0 to 100// with difference of 20 between consecutive // elements using range function$arr = range(0,100,20);  // printing elements of arrayforeach ($arr as $a) {          echo "$a ";}  ?>
Output:
0 20 40 60 80 100
Program 3:
<?php  // creating array with elements from a to j// using range function$arr = range('a','j');  // printing elements of arrayforeach ($arr as $a) {          echo "$a ";}  ?>
Output:
a b c d e f g h i j
Program 4:
<?php  // creating array with elements from p to a// in reverse order using range function$arr = range('p','a');  // printing elements of arrayforeach ($arr as $a) {          echo "$a ";}  ?>
Output:
p o n m l k j i h g f e d c b a
Reference:http://php.net/manual/en/function.range.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to take integer input in Python?

20 Jun, 2022
In this post, We will see how to take integer input in Python. As we know that Python’s built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.
Let us see the examples:
Example 1:
Python3
# take input from userinput_a = input() # print data typeprint(type(input_a)) # type cast into integerinput_a = int(input_a) # print data typeprint(type(input_a))
Output:
100
<class 'str'>
<class 'int'>
Example 2:
Python3
# string inputinput_a = input() # print typeprint(type(input_a)) # integer inputinput_b = int(input()) # print typeprint(type(input_b))
Output:
10
<class 'str'>
20
<class 'int'>
Example 3:
Python3
# take multiple inputs in arrayinput_str_array = input().split() print("array:", input_str_array) # take multiple inputs in arrayinput_int_array = [int(x) for x in input().split()] print("array:", input_int_array)
Output:
10 20 30 40 50 60 70
array: ['10', '20', '30', '40', '50', '60', '70']
10 20 30 40 50 60 70
array: [10, 20, 30, 40, 50, 60, 70]
Example 4:
Python3
# Python program to take integer input  in Python # input size of the listn = int(input("Enter the size of list : "))# store integrs in a list using map, split and strip functionslst = list(map(int, input(    "Enter the integer elements of list(Space-Separated): ").strip().split()))[:n]print('The list is:', lst)   # printing the list
Output:
Enter the size of list : 4
Enter the integer elements of list(Space-Separated): 6 3 9 10
The list is: [6, 3, 9, 10]
susobhanakhuli
python-basics
python-input-output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Difference between URL and URI

04 Jul, 2022
URL (Uniform Resource Locator): 
URL (Uniform Resource Locator) is often defined as a string of characters that is directed to an address. It is a very commonly used way to locate resources on the web. It provides a way to retrieve the presentation of the physical location by describing its network location or primary access mechanism. 
The protocol is described within the URL which is employed to retrieve the resource and resource name. The URL contains http/https at the start if the resource may be a web type resource. Similarly, it begins with ftp if the resource may be a file and mailto if the resource is an email address. The syntax of an URL is shown below where the primary part is employed for protocol and the remainder of the part is employed for the resource which consists of a website name or program name.
https://www.geeksforgeeks.org/minimum-cost-graph
Here, the domain name describes the server (web service) and program name (path to the directory and file on the server). 
URI (Uniform Resource Identifier): 
Similar to URL, URI (Uniform Resource Identifier) is also a string of characters that identifies a resource on the web either by using location, name or both. It allows uniform identification of the resources. A URI is additionally grouped as a locator, a name or both which suggests it can describe a URL, URN or both. The term identifier within the URI refers to the prominence of the resources, despite the technique used. 
The former category in URI is URL, during which a protocol is employed to specify the accessing method of the resource and resource name is additionally laid out in the URL. A URL may be a non-persistent sort of the URI. A URN is required to exist globally unique and features a global scope.
  
Difference between URL and URI:
sayanc170
Technical Scripter 2019
Web technologies
Computer Networks
Difference Between
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python | cmp() function

24 Apr, 2020
cmp() method in Python 2.x compares two integers and returns -1, 0, 1 according to comparison.cmp() does not work in python 3.x. You might want to see list comparison in Python.
Syntax:
cmp(a, b)
Parameters:
a and b are the two numbers in which the comparison is being done. 
Returns:
-1 if a<b

0 if a=b

1 if a>b

# Python program to demonstrate the # use of cmp() method  # when a<ba = 1 b = 2 print(cmp(a, b))    # when a = b a = 2b = 2 print(cmp(a, b))    # when a>b a = 3b = 2 print(cmp(a, b))
Output:
-1
0 
1

Practical Application: Program to check if a number is even or odd using cmp function.
Approach: Compare 0 and n%2, if it returns 0, then it is even, else its odd.
Below is the Python implementation of the above program:
# Python program to check if a number is  # odd or even using cmp function      # check 12  n = 12 if cmp(0, n % 2):      print"odd"else:     print"even"         # check 13     n = 13 if cmp(0, n % 2):      print"odd"else:     print"even" 
Output:
even
odd

PK 1
ShubhamVm
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL - SAVEPOINT Statement

A save point is a logical rollback point within a transaction. When you set a save point, whenever an error occurs past a save point, you can undo the events you have done up to the save point using the rollback.
MySQL InnoDB provides support for the statements SAVEPOINT, ROLLBACK TO SAVEPOINT, RELEASE SAVEPOINT.
The SAVEPOINT statement is used to set a save point for the transaction with the specified name. If a save point with the given name already exists the old one will be deleted.
Following is the syntax of the MySQL SAVEPOINT statement −
SAVEPOINT identifier

MySQL saves the changes done after the execution of each statement. To save changes automatically, set the autocommit option as shown below −
SET autocommit=0;

Assume we have created a table in MySQL with name EMPLOYEES as shown below −
mysql> CREATE TABLE EMP(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT);
Query OK, 0 rows affected (0.36 sec)
Let us insert 4 records in to it using INSERT statements as −
mysql> INSERT INTO EMP VALUES
   ('Krishna', 'Sharma', 19, 'M', 2000),
   ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'F', 5000);
Query OK, 3 rows affected (0.49 sec)
Records: 3 Duplicates: 0 Warnings: 0
Following transaction updates, the age values of all the employees in the emp table −
START TRANSACTION;

SELECT * FROM EMP;
UPDATE EMP SET AGE = AGE + 1;

SAVEPOINT samplesavepoint;

INSERT INTO EMP ('Mac', 'Mohan', 26, 'M', 2000);

ROLLBACK TO SAVEPOINT samplesavepoint;
COMMIT;
If you retrieve the contents of the table, you can see the updated values as −
mysql> SELECT * FROM EMP;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE  | SEX  | INCOME |
+------------+-----------+------+------+--------+
| Krishna    | Sharma    | 20   | M    | 2000   |
| Raj        | Kandukuri | 21   | M    | 7000   |
| Ramya      | Ramapriya | 26   | F    | 5000   |
+------------+-----------+------+------+--------+
3 rows in set (0.07 sec)
CSS - Pseudo-class :hover

The :hover pseudo-class is used to add special effect to an element when you mouse over it.
While defining pseudo-classes in a <style>...</style> block, following points should be taken care −
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
Pseudo-class names are not case-sensitive.
Pseudo-class names are not case-sensitive.
Pseudo-class are different from CSS classes but they can be combined.
Pseudo-class are different from CSS classes but they can be combined.
color − Any valid color value.
color − Any valid color value.
Anchor / Link element.
Following is the example which demonstrates how use :hover class to change the color of links when we bring a mouse pointer over that link.
<html>
   <head>
      <style type = "text/css">
         a:hover {color: #FFCC00}
      </style>
   </head>

   <body>
      <a href = "/html/index.htm">Bring Mouse Here</a>
   </body>
</html> 
This will produce following link. Now you bring your mouse over this link and you will see that it changes its color to yellow.

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Memcached - Connection

To connect to a Memcached server, you need to use the telnet command on HOST and PORT names.
The basic syntax of Memcached telnet command is as shown below −
$telnet HOST PORT

Here, HOST and PORT are machine IP and port number respectively, on which the Memcached server is executing.
The following example shows how to connect to a Memcached server and execute a simple set and get command. Assume that the Memcached server is running on host 127.0.0.1 and port 11211.
$telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
// now store some data and get it from memcached server
set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END

To connect the Memcached server from your java program, you need to add the Memcached jar into your classpath as shown in the previous chapter. Assume that the Memcached server is running on host 127.0.0.1 and port 11211. −
import net.spy.memcached.MemcachedClient;
public class MemcachedJava {
   public static void main(String[] args) {
      
      // Connecting to Memcached server on localhost
      MemcachedClient mcc = new MemcachedClient(new
      InetSocketAddress("127.0.0.1", 11211));
      System.out.println("Connection to server sucessfully");
      
      //not set data into memcached server
      System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").done);
      
      //Get value from cache
      System.out.println("Get from Cache:"+mcc.get("tutorialspoint"));
   }
}
On compiling and executing the program, you get to see the following output −
Connection to server successfully
set status:true
Get from Cache:memcached.

The terminal may show few informational messages too, those can be ignored.
 Print
 Add Notes
 Bookmark this page
Python - Plotting scatter charts in excel sheet using XlsxWriter module

A scatter plot is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. If the points are coded, one additional variable can be displayed.
# import xlsxwriter module
import xlsxwriter
# Workbook() takes one, non-optional, argument which is the filename #that we want to create.
workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
# The workbook object is then used to add new worksheet via the #add_worksheet() method.  
worksheet = workbook.add_worksheet()      
# Create a new Format object to formats cells in worksheets using #add_format() method .    
# here we create bold format object .
bold = workbook.add_format({'bold': 1})    
# create a data list .
headings = ['Number', 'Batch 1', 'Batch 2']    
data = [
   [2, 3, 4, 5, 6, 7],
   [80, 80, 100, 60, 50, 100],
   [60, 50, 60, 20, 10, 20],
]      
# Write a row of data starting from 'A1' with bold format .
worksheet.write_row('A1', headings, bold)    
# Write a column of data starting from 'A2', 'B2', 'C2' respectively
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])    
# Create a chart object that can be added to a worksheet using #add_chart() method.    
# here we create a scatter chart object .
chart1 = workbook.add_chart({'type': 'scatter'})    
# Add a data series to a chart using add_series method.    
# Configure the first series.
# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].  
# note : spaces is not inserted in b / w
# = and Sheet1, Sheet1 and !
# if space is inserted it throws warning.
chart1.add_series({
   'name':       '= Sheet1 !$B$1',
   'categories': '= Sheet1 !$A$2:$A$7',
   'values':     '= Sheet1 !$B$2:$B$7',
})    
# Configure a second series.
# Note use of alternative syntax to define ranges.
# [sheetname, first_row, first_col, last_row, last_col].
chart1.add_series({
   'name':       ['Sheet1', 0, 2],
   'categories': ['Sheet1', 1, 0, 6, 0],
   'values':     ['Sheet1', 1, 2, 6, 2],
})      
# Add a chart title  
chart1.set_title ({'name': 'Results of data analysis'})
# Add x-axis label
chart1.set_x_axis({'name': 'Test number'})
# Add y-axis label
chart1.set_y_axis({'name': 'Data length (mm)'})
# Set an Excel chart style.
chart1.set_style(11)
# add chart to the worksheet the top-left corner of a chart  
# is anchored to cell E2 .  
worksheet.insert_chart('E2', chart1)
# Finally, close the Excel file via the close() method.  
workbook.close()
MySQL Select IN range?

You cannot do select IN range. For the same result, use BETWEEN. Let us see an example −
IN(start,end): It means that the intermediate value between start and end won’t get displayed. For the above logic, you can use BETWEEN.
BETWEEN clause is inclusive, for example, suppose there are 1,2,3,4,5,6 numbers. If you want to display numbers from 2 to 6 inclusively, then using BETWEEN the numbers 2 and 6 will also get displayed.
Let us create a table −
mysql> create table SelectInWithBetweenDemo
   -> (
   -> PortalId int
   -> );
Query OK, 0 rows affected (0.77 sec)
Insert some records with the help of batch insert. The query is as follows −
mysql> insert into SelectInWithBetweenDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15);
Query OK, 15 rows affected (0.19 sec)
Records: 15 Duplicates: 0 Warnings: 0
Display all records with the help of select statement. The query is as follows −
mysql> select *from SelectInWithBetweenDemo;
Here is the output −
+----------+
| PortalId |
+----------+
|        1 |
|        2 |
|        3 |
|        4 |
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
|       10 |
|       11 |
|       12 |
|       13 |
|       14 |
|       15 |
+----------+
15 rows in set (0.00 sec)
Let us now check the select IN range. The query is as follows −
mysql> select PortalId from SelectInWithBetweenDemo where PortalId IN(4,10);
The following is the output −
+----------+
| PortalId |
+----------+
|        4 |
|       10 |
+----------+
2 rows in set (0.00 sec)
Look at the above output, we are getting only 4 and 10, whereas we want the value 4,5,6,7,8,9,10.
Now we will use BETWEEN clause. It will give the result as we want with inclusion.
The query is as follows −
mysql> select PortalId from SelectInWithBetweenDemo where PortalId Between 4 and 10;
The following is the output −
+----------+
| PortalId |
+----------+
|        4 |
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
|       10 |
+----------+
7 rows in set (0.09 sec)
Suppose if you want exclusive property then you can use > and <. The query is as follows −
mysql> select PortalId from SelectInWithBetweenDemo where PortalId > 4 and PortalId < 10;
Here is the output −
+----------+
| PortalId |
+----------+
|        5 |
|        6 |
|        7 |
|        8 |
|        9 |
+----------+
5 rows in set (0.00 sec)
C library function - fgets()

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
Following is the declaration for fgets() function.
char *fgets(char *str, int n, FILE *stream)
str − This is the pointer to an array of chars where the string read is stored.
str − This is the pointer to an array of chars where the string read is stored.
n − This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.
n − This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.
stream − This is the pointer to a FILE object that identifies the stream where characters are read from.
stream − This is the pointer to a FILE object that identifies the stream where characters are read from.
On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.
If an error occurs, a null pointer is returned.
The following example shows the usage of fgets() function.
#include <stdio.h>

int main () {
   FILE *fp;
   char str[60];

   /* opening file for reading */
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* writing content to stdout */
      puts(str);
   }
   fclose(fp);
   
   return(0);
}
Let us assume, we have a text file file.txt, which has the following content. This file will be used as an input for our example program −
We are in 2012
Now, let us compile and run the above program that will produce the following result −
We are in 2012


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Example of embedded CSS

Place your CSS rules into an HTML document using the <style> element that is called embedded CSS. This tag is placed inside <head>...</head> tags. Rules defined using this syntax will be applied to all the elements available in the document.
Following is the example of embed CSS based on the above syntax:
<!DOCTYPE html>
<html>
   <head>
      <style media = "all">
         body {
            background-color: orange;
         }
         h1 {
            color: yellow;
            margin-left: 30px;
         }
      </style>
   </head>
   <body>
      <h1>This is a heading</h1>
      <p>This is a paragraph.</p>
   </body>
</html>
The following is the attribute: