code-rag-bench/online-tutorials huggingface dataset:
Boxplots in R Language - GeeksforGeeks

10 Dec, 2021
A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. This distribution of data based on five sets (minimum, first quartile, median, third quartile, maximum).
Boxplots are created in R by using the boxplot() function.
Syntax: boxplot(x, data, notch, varwidth, names, main)
Parameters: 
x: This parameter sets as a vector or a formula.
data: This parameter sets the data frame.
notch: This parameter is the label for horizontal axis.
varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size.
main: This parameter is the title of the chart.
names: This parameter are the group labels that will be showed under each boxplot.
To understand how we can create a boxplot: 
We use the data set “mtcars”.
Let’s look at the columns “mpg” and “cyl” in mtcars.
R
input <- mtcars[, c('mpg', 'cyl')]print(head(input))
Output:
Creating the Boxplot graph.
Take the parameters which are required to make boxplot.
Now we draw a graph for the relation between “mpg” and “cyl”.
R
# Plot the chart.boxplot(mpg ~ cyl, data = mtcars,        xlab = "Number of Cylinders",        ylab = "Miles Per Gallon",        main = "Mileage Data")
Output:  
Here we are creating multiple boxplots. The individual data for which a boxplot representation is required is based on the function.
R
set.seed(20000)                                       data <- data.frame( A = rpois(900, 3),                    B = rnorm(900),                    C = runif(900)                                          ) # Applying boxplot functionboxplot(data)
Output:
To draw a boxplot using a notch: 
With the help of notch, we can find out how the medians of different data groups match with each other.
We are using xlab as “Quantity of Cylinders” and ylab as “Miles Per Gallon”.
Python3
# Plot the chart.boxplot(mpg ~ cyl, data = mtcars,        xlab = "Number of Cylinders",        ylab = "Miles Per Gallon",        main = "Mileage Data",        notch = TRUE,        varwidth = TRUE,        col = c("green", "red", "blue"),        names = c("High", "Medium", "Low")        )
Output:
Akanksha_Rai
kumar_satyam
Picked
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Python program to create a dictionary from a string

21 Jun, 2020
Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary.So, let us discuss how we can tackle this problem.Method # 1: Using eval()If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily convert it to dictionary usingeval() in Python.
# Python3 code to convert # a string to a dictionary  # Initializing String string = "{'A':13, 'B':14, 'C':15}"  # eval() convert string to dictionaryDict = eval(string)print(Dict)print(Dict['A'])print(Dict['C'])
{'C': 15, 'B': 14, 'A': 13}
13
15

Method # 2: Using generator expressions in pythonIf we get a string input does not completely resemble a dictionary object then we can use generator expressions to convert it to a dictionary.
# Python3 code to convert # a string to a dictionary  # Initializing String string = "A - 13, B - 14, C - 15"  # Converting string to dictionaryDict = dict((x.strip(), y.strip())             for x, y in (element.split('-')              for element in string.split(', ')))  print(Dict)print(Dict['A'])print(Dict['C'])
{'C': '15', 'A': '13', 'B': '14'}
13
15

The code given above does not convert integers to an int type,
if integers keys are there then just line 8 would work
string = "11 - 13, 12 - 14, 13 - 15"  Dict = dict((x.strip(), int(y.strip()))              for x, y in (element.split('-')              for element in string.split(', ')))  print(Dict)
{'13': 15, '12': 14, '11': 13}

Picked
Python dictionary-programs
Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time command in Linux with examples

13 Aug, 2021
time command in Linux is used to execute a command and prints a summary of real-time, user CPU time and system CPU time spent by executing a command when it terminates. ‘real‘ time is the time elapsed wall clock time taken by a command to get executed, while ‘user‘ and ‘sys‘ time are the number of CPU seconds that command uses in user and kernel mode respectively. 
Syntax: 
time [option] [COMMAND]
Example:  
In the above example, sleep 3 is used to create a dummy job which lasts 3 seconds. 
Options: 
time -p : This option is used to print time in POSIX format.  
 
help time : it displays help information.  
kapoorsagar226
linux-command
Linux-system-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Python3 Program for Left Rotation and Right Rotation of a String

27 May, 2022
Given a string of size n, write functions to perform the following operations on a string-
Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n).
Left (Or anticlockwise) rotate the given string by d elements (where d <= n)
Right (Or clockwise) rotate the given string by d elements (where d <= n).
Examples: 
Input : s = "GeeksforGeeks"
        d = 2
Output : Left Rotation  : "eksforGeeksGe" 
         Right Rotation : "ksGeeksforGee"  


Input : s = "qwertyu" 
        d = 2
Output : Left rotation : "ertyuqw"
         Right rotation : "yuqwert"
A Simple Solution is to use a temporary string to do rotations. For left rotation, first, copy last n-d characters, then copy first d characters in order to the temporary string. For right rotation, first, copy last d characters, then copy n-d characters. 
Can we do both rotations in-place and O(n) time? The idea is based on a reversal algorithm for rotation.
// Left rotate string s by d (Assuming d <= n)
leftRotate(s, d)
  reverse(s, 0, d-1); // Reverse substring s[0..d-1]
  reverse(s, d, n-1); // Reverse substring s[d..n-1]
  reverse(s, 0, n-1); // Reverse whole string.  

// Right rotate string s by d (Assuming d <= n)
rightRotate(s, d)

  // We can also call above reverse steps
  // with d = n-d.
  leftRotate(s, n-d)  
Below is the implementation of the above steps : 
Python3
# Python3 program for Left# Rotation and Right# Rotation of a String # In-place rotates s towards left by ddef leftrotate(s, d):    tmp = s[d : ] + s[0 : d]    return tmp   # In-place rotates s# towards right by ddef rightrotate(s, d):      return leftrotate(s, len(s) - d) # Driver codeif __name__=="__main__":         str1 = "GeeksforGeeks"    print(leftrotate(str1, 2))      str2 = "GeeksforGeeks"    print(rightrotate(str2, 2)) # This code is contributed by Rutvik_56
Output: 
Left rotation:  eksforGeeksGe
Right rotation:  ksGeeksforGee                 
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(1), as we are not using any extra space.
Please refer complete article on Left Rotation and Right Rotation of a String for more details!
rohitsingh57
rohan07
rotation
Python
Strings
Strings
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
Python | os.path.join() method
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python | Reverse a numpy array

21 Feb, 2019
As we know Numpy is a general-purpose array-processing package which provides a high-performance multidimensional array object, and tools for working with these arrays. Let’s discuss how can we reverse a numpy array.Method #1: Using shortcut Method
# Python code to demonstrate# how to reverse numpy array# using shortcut method  import numpy as np  # initialising numpy arrayini_array = np.array([1, 2, 3, 6, 4, 5])  # printing initial ini_arrayprint("initial array", str(ini_array))  # printing type of ini_arrayprint("type of ini_array", type(ini_array))  # using shortcut method to reverseres = ini_array[::-1]  # printing resultprint("final array", str(res))
Output:
initial array [1 2 3 6 4 5]
type of ini_array <class 'numpy.ndarray'>
final array [5 4 6 3 2 1]

 Method #2: Using flipud function
# Python code to demonstrate# how to reverse numpy array# using flipud method  import numpy as np  # initialising numpy arrayini_array = np.array([1, 2, 3, 6, 4, 5])  # printing initial ini_arrayprint("initial array", str(ini_array))  # printing type of ini_arrayprint("type of ini_array", type(ini_array))  # using flipud method to reverseres = np.flipud(ini_array)  # printing resultprint("final array", str(res))
Output:
initial array [1 2 3 6 4 5]
type of ini_array <class 'numpy.ndarray'>
final array [5 4 6 3 2 1]

Python numpy-arrayManipulation
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Python | Sympy Line.perpendicular_line method

22 Jul, 2021
In Sympy, the function perpendicular_line() is used to create a new Line perpendicular to the given linear entity which passes through the given point p.  
Syntax: Line.perpendicular_line(p)

Parameters:
p: Point

Returns:line 
Example #1:  
Python3
# import sympy and Point, Linefrom sympy import Point, Line  p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)  l1 = Line(p1, p2)  # using perpendicular_line() methodl2 = l1.perpendicular_line(p3)  # checking l2 is perpendicular to l1 using is_perpendicular() methodisPerpendicular = l1.is_perpendicular(l2)  print(isPerpendicular)
Output:  
True
Example #2:  
Python3
# import sympy and Point3D, Line3Dfrom sympy import Point3D, Line3D  p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)  l1 = Line3D(p1, p2)  # using perpendicular_line() methodl2 = l1.perpendicular_line(p3)  # checking l2 is perpendicular to l1 using is_perpendicular() methodisPerpendicular = l2 = l1.is_perpendicular(p3)  print(isPerpendicular)
Output:  
True
 
kalrap615
Python SymPy-Geometry
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Docker - Containers

Containers are instances of Docker images that can be run using the Docker run command. The basic purpose of Docker is to run containers. Let’s discuss how to work with containers.
Running of containers is managed with the Docker run command. To run a container in an interactive mode, first launch the Docker container.
sudo docker run –it centos /bin/bash 

Then hit Crtl+p and you will return to your OS shell.
You will then be running in the instance of the CentOS system on the Ubuntu server.
One can list all of the containers on the machine via the docker ps command. This command is used to return the currently running containers.
docker ps

docker ps 

None
The output will show the currently running containers.
sudo docker ps
When we run the above command, it will produce the following result −
Let’s see some more variations of the docker ps command.
This command is used to list all of the containers on the system
docker ps -a 

─a − It tells the docker ps command to list all of the containers on the system.
─a − It tells the docker ps command to list all of the containers on the system.
The output will show all containers.
sudo docker ps -a 
When we run the above command, it will produce the following result −
With this command, you can see all the commands that were run with an image via a container.
docker history ImageID 

ImageID − This is the Image ID for which you want to see all the commands that were run against it.
ImageID − This is the Image ID for which you want to see all the commands that were run against it.
The output will show all the commands run against that image.
sudo docker history centos
The above command will show all the commands that were run against the centos image.
When we run the above command, it will produce the following result −

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page
\dfrac - Tex Command

\dfrac - Used to draw fractions.
{ \dfrac #1 #2 }
\dfrac command draws fractions.

\dfrac a b

ab


\frac a b

ab


\dfrac{a-1}b-1

a−1b−1


\dfrac{a-1}{b-1}

a−1b−1



\dfrac a b

ab


\dfrac a b
\frac a b

ab


\frac a b
\dfrac{a-1}b-1

a−1b−1


\dfrac{a-1}b-1
\dfrac{a-1}{b-1}

a−1b−1


\dfrac{a-1}{b-1}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
What is the difference between deleteOne() and findOneAndDelete() operation in MongoDB?

The findOneAndDelete() deletes single documents from the collection on the basis of a filter and sort criteria as well as it returns the deleted document.
The deleteOne() removes single document from the collection.
Let us see an example and create a collection with documents −
> db.demo448.insertOne({"Name":"Chris","Age":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a291cbbc41e36cc3caeca")
}
> db.demo448.insertOne({"Name":"David","Age":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a2926bbc41e36cc3caecb")
}
> db.demo448.insertOne({"Name":"Bob","Age":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a2930bbc41e36cc3caecc")
}
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2926bbc41e36cc3caecb"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Following is the query to implement deleteOne() −
> db.demo448.deleteOne({_id:ObjectId("5e7a2926bbc41e36cc3caecb")});
This will produce the following output −
{ "acknowledged" : true, "deletedCount" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Following is the query to implement findOneAndDelete() −
> db.demo448.findOneAndDelete({"_id":ObjectId("5e7a2930bbc41e36cc3caecc")});
This will produce the following output −
{ "_id" : ObjectId("5e7a2930bbc41e36cc3caecc"), "Name" : "Bob", "Age" : 22 }
Display all documents from a collection with the help of find() method −
> db.demo448.find();
This will produce the following output −
{ "_id" : ObjectId("5e7a291cbbc41e36cc3caeca"), "Name" : "Chris", "Age" : 21 }
How to use get parameter in Express.js ? - GeeksforGeeks

10 Oct, 2021
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UPDATE, etc). 
We can create an API endpoint receiving a GET request with the help of app.get() method. 
Syntax: 
app.get(route, (req, res) => {
    // Code logic
});
Route parameters are the name URL segments that capture the value provided at their position. We can access these route parameters on our req.params object using the syntax shown below.
app.get(/:id, (req, res) => {
    const id = req.params.id;
});
 
Project Setup:
Step 1: Install Node.js if you haven’t already.
Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.
npm init -y
Step 3: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like the following.
app.js
const express = require('express');const app = express();  app.get('/', (req, res) => {  res.send('<h1>Home page</h1>');});  app.get('/:id', (req, res) => {  res.send(`<h1>${req.params.id}</h1>`);});  app.listen(3000, () => {  console.log('Server is up on port 3000');});
Step to run the application: You can run your express server by using the following command on the command line.
node app.js
Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_id and you will view the following output.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need 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?
Difference between var, let and const keywords in JavaScript
Dictionary to list of tuple conversion in Python

ging the collection type from one type to another is a very frequent need in python. In this article we will see how we create a tuple from the key value pairs that are present in a dictionary. Each of the key value pair becomes a tuple. So the final list is a list whose elements are tuples.
We sue the items method of the dictionary which allows us to iterate through each of the key value pairs. Then we use a for loop to pack those values in to a tuple. We put all these tuples to a final list.
 Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}

# Using items()
res = [(k, v) for k, v in dictA.items()]

# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')]
Another approach is to use the zip function. The zip function will pair the keys and values as tuples and then we convert the entire result to a list by applying list function.
 Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}

# Using items()
res = list(zip(dictA.keys(), dictA.values()))

# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')]
The append() can append the result into a list after fetching the pair of values to create a tuple. We iterate through a for loop to get the final result.
 Live Demo
dictA = {'Mon': '2 pm', 'Tue': '1 pm', 'Fri': '3 pm'}

# Initialize empty list
res=[]

# Append to res
for i in dictA:
tpl = (i, dictA[i])
res.append(tpl)

# Result
print(res)
Running the above code gives us the following result −
[('Mon', '2 pm'), ('Tue', '1 pm'), ('Fri', '3 pm')]
R – if-else statement

18 Oct, 2021
The if-statement in Programming Language alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the R else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.
if (condition)
{
    // Executes this block if
    // condition is true
} else
{
    // Executes this block if
    // condition is false
}
Control falls into the if block.
The flow jumps to Condition.
Condition is tested. If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
The else block or the body inside the else is executed.
Flow exits the if-else block.
Example 1: 
R
x <- 5  # Check value is less than or greater than 10if(x > 10){    print(paste(x, "is greater than 10"))} else{    print(paste(x, "is less than 10"))}
Output: 
[1] "5 is less than 10"
Here in the above code, Firstly, x is initialized to 5, then if-condition is checked(x > 10), and it yields false. Flow enters the else block and prints the statement “5 is less than 10”.
Example 2: 
R
x <- 5 # Check if value is equal to 10if(x == 10){    print(paste(x, "is equal to 10"))} else{    print(paste(x, "is not equal to 10"))}
Output: 
[1] "5 is not equal to 10" 
The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively. An if-else statement within another if-else statement better justifies the definition.
if(condition1){
# execute only if condition 1 satisfies
if(condition 2){ 
# execute if both condition 1 and 2 satisfy
}
}else{
}
Example:
R
# creating valuesvar1 <- 6var2 <- 5var3 <- -4 # checking if-else if ladderif(var1 > 10 || var2 < 5){print("condition1")}else{if(var1 <4 ){    print("condition2")}else{    if(var2>10){    print("condition3")    }    else{    print("condition4")    }}}
Output:
[1] "condition4"
kumar_satyam
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – datetime.toordinal() Method with Example

06 Sep, 2021
datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object.
If January 1 of year 1 has ordinal number 1 then, January 2 year 1 will have ordinal number 2, and so on.
Syntax: 
datetimeObj.toordinal()
Parameters: None
Returns: Ordinal Value
Given below are some implementations for the same.
Example 1: Use datetime.toordinal() function to return the Gregorian ordinal for the given datetime object using date.today() class of datetime module.
Python3
# Python3 code to demonstrate# Getting Ordinal value using# toordinal(). # importing datetime module for today()import datetime # using date.today() to get todays datedateToday = datetime.date.today() # Using toordinal() to generate ordinal value.toOrdinal = dateToday.toordinal() # Prints Ordinal Value of Todays Date.print(f"Ordinal of date {dateToday} is {toOrdinal}")
Ordinal of date 2021-08-03 is 738005
Note: Attributes of DateTime class should be in given range otherwise it will show a ValueError
Example 2: Example to show the parameters needs to be in the range
Python3
# importing datetime classfrom datetime import datetime # Creating an instance of datetime.dateIs = datetime(189, 0, 0) # Using toordinal() methodtoOrdinal = dateIs.toordinal()print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")
Output:
Traceback (most recent call last):
  File “/home/2ecd5f27fbc894dc8eeab3aa6559c7ab.py”, line 5, in <module>
    dateIs = datetime(189,0,0)
ValueError: month must be in 1..12
Example 3: Use datetime.toordinal() function to return the Gregorian ordinal for the given DateTime object.
Python3
# importing datetime classfrom datetime import datetime # Creating an instance of datetime.dateIs = datetime(1, 1, 1, 0, 0, 0, 0) # Using toordinal() methodtoOrdinal = dateIs.toordinal()print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}") print() dateIs = datetime(9999, 12, 31, 23, 59, 59)toOrdinal = dateIs.toordinal()print(f"Ordinal value of Latemost Datetime {dateIs} is {toOrdinal}")
Output:
Ordinal value of Earliest Datetime 0001-01-01 00:00:00 is 1
Ordinal value of Latemost Datetime 9999-12-31 23:59:59 is 3652059
sagar0719kumar
Picked
Python-datetime
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Large Fibonacci Numbers in Java

20 Oct, 2020
Given a number n, find n-th Fibonacci Number. Note that n may be large.
Examples:
Input : 100
Output : 354224848179261915075

Input : 500
Output : 139423224561697880139724382870
         407283950070256587697307264108962948325571622
         863290691557658876222521294125 

Prerequisite: BigInteger Class in Java, Fibonacci numbersFibonacci of large number may contain more than 100 digits, it can be easily handled by BigInteger in Java. BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.
JAVA
// Java program to compute n-th Fibonacci// number where n may be large.import java.io.*;import java.util.*;import java.math.*;  public class Fibonacci{    // Returns n-th Fibonacci number    static BigInteger fib(int n)    {        BigInteger a = BigInteger.valueOf(0);        BigInteger b = BigInteger.valueOf(1);        BigInteger c = BigInteger.valueOf(1);        for (int j=2 ; j<=n ; j++)        {            c =  a.add(b);            a = b;            b = c;        }          return (b);    }      public static void main(String[] args)    {        int n = 100;        System.out.println("Fibonacci of " + n +            "th term" + " " +"is" +" " + fib(n));    }}
Fibonacci of 100th term is 354224848179261915075

Note that the above solution takes O(n) time, we can find the n-th Fibonacci number in O(log n) time. As an exercise, find the n-th Fibonacci number for large n in O(log n) time.This article is contriBigInteger.valueOf (1);but by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks’ main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nutan1510
Fibonacci
large-numbers
Java
Mathematical
Mathematical
Java
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to send email with Nodemailer using Gmail account in Node.js ?

13 Jun, 2022
Nodemailer is the Node.js npm module that allows to send email easily. In this article, we will cover each steps to send email using Gmail account with the help of nodemailer. 
Installations: Go to the project folder and use the following command.
Create a package.json file.
npm init -y
Install nodemailer
npm install nodemailer -S
Create server.js file directly or use command
touch server.js
Approach:
Include the nodemailer module in the code using require(‘nodemailer’).
Use nodemailer.createTransport() function to create a transporter who will send mail. It contains the service name and authentication details (user ans password).
Declare a variable mailDetails that contains the sender and receiver email id, subject and content of the mail.
Use mailTransporter.sendMail() function to send email from sender to receiver. If message sending failed or contains error then it will display error message otherwise message send successfully.
Example: 
javascript
const nodemailer = require('nodemailer');  let mailTransporter = nodemailer.createTransport({    service: 'gmail',    auth: {        user: 'xyz@gmail.com',        pass: '*************'    }}); let mailDetails = {    from: 'xyz@gmail.com',    to: 'abc@gmail.com',    subject: 'Test mail',    text: 'Node.js testing mail for GeeksforGeeks'}; mailTransporter.sendMail(mailDetails, function(err, data) {    if(err) {        console.log('Error Occurs');    } else {        console.log('Email sent successfully');    }});
Now open the link https://myaccount.google.com/lesssecureapps to Allow less secure apps: ON. Then use node server.js command to run the above code. It will send the email using gmail account. 
Output:
Terminal to run code: 
Sent mail:
 
Note 1: To use this code in any file we just have to import this file and call send() function.
var mail = require('./config/mailer')();
mail.send();
Note 2: To send HTML formatted text in your email, use the “html” property instead of the “text” property in sendMail function.
{ from:'"admin" ',
  to: "user@gmail.com",
  subject:'GeeksforGeeks Promotion',
  html:' <p> html code </p>'
}
Note 3: To send an email to more than one receiver, add them to the “to” property in sendMail function, separated by commas.
{ from:'”admin” ‘, 
to: ” user1@gmail.com, user2@gmail.com, user3@yahoo.in “, 
subject:’GeeksforGeeks Promotion’, 
text:’Check out GeeksforGeeks’+’best site to prepare for interviews and competitive exams.’ 
}
alphaenlightner
Node.js-Basics
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Naming a thread and fetching name of current thread in C#

24 Jan, 2019
A thread is a light-weight process within a process. In C#, a user is allowed to assign a name to the thread and also find the name of the current working thread by using the Thread.Name property of the Thread class.
Syntax :
public string Name { get; set; }
Here, the string contains the name of the thread or null if no name was assigned or set.
Important Points:
The by default value of the Name property is null.
The string given to the name property can include any Unicode Character.
The name property of Thread class is write-once.
If a set operation was requested, but the Name property has already set, then it will give InvalidOperationException.
Example 1:
// C# program to illustrate the // concept of assigning names // to the thread and fetching// name of the current working threadusing System;using System.Threading;  class Geek {      // Method of Geek class    public void value()    {        // Fetching the name of         // the current thread        // Using Name property        Thread thr = Thread.CurrentThread;        Console.WriteLine("The name of the current "+                           "thread is: " + thr.Name);    }}  // Driver classpublic class GFG {      // Main Method    static public void Main()    {          // Creating object of Geek class        Geek obj = new Geek();          // Creating and initializing threads        Thread thr1 = new Thread(obj.value);        Thread thr2 = new Thread(obj.value);        Thread thr3 = new Thread(obj.value);        Thread thr4 = new Thread(obj.value);          // Assigning the names of the threads        // Using Name property        thr1.Name = "Geeks1";        thr2.Name = "Geeks2";        thr3.Name = "Geeks3";        thr4.Name = "Geeks4";          thr1.Start();        thr2.Start();        thr3.Start();        thr4.Start();    }}
Output:
The name of the current thread is: Geeks2
The name of the current thread is: Geeks3
The name of the current thread is: Geeks4
The name of the current thread is: Geeks1

Example 2:
// C# program to illustrate the // concept of giving a name to threadusing System;using System.Threading;  class Name {    static void Main()    {          // Check whether the thread        // has already been named        // to avoid InvalidOperationException        if (Thread.CurrentThread.Name == null) {              Thread.CurrentThread.Name = "MyThread";            Console.WriteLine("The name of the thread is MyThread");        }        else {            Console.WriteLine("Unable to name the given thread");        }    }}
Output:
The name of the thread is MyThread

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.name?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
C# Dictionary with examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors
Pandas read_table() function

19 Jun, 2020
Pandas is one of the most used packages for analyzing data, data exploration, and manipulation. While analyzing the real-world data, we often use the URLs to perform different operations and pandas provide multiple methods to do so. One of those methods is read_table().
Parameters:read_table(filepath_or_buffer, sep=False, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)
Returns: A comma(‘,’) separated values file(csv) is returned as two dimensional data with labelled axes.
To get the link to csv file used in the article, click here. Code #1: Display the whole content of the file with columns separated by ‘,’
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',')
Output:
Code #2: Skipping rows without indexing
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',',skiprows=4,index_col=0)
Output:
In the above code, four rows are skipped and the last skipped row is displayed.
 Code #3: Skipping rows with indexing
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',',skiprows=4)
Output:
Code #4: In case of large file, if you want to read only few lines then give required number of lines to nrows.
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',',index_col=0,nrows=4)
Output:
Code #5: If you want to skip lines from bottom of file then give required number of lines to skipfooter.
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',',index_col=0,                     engine='python',skipfooter=5)
Output:
Code #6: Row number(s) to use as the column names, and the start of the data occurs after the last row number given in header.
# importing pandasimport pandas as pd  pd.read_table('nba.csv',delimiter=',',index_col=0,header=[1,3,5])
Output:
nidhi_biet
Pandas Panel-functions
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to combine two lists in R? - GeeksforGeeks

30 May, 2021
In this article, we are going to combine two lists in R Language using inbuilt functions. R provided two inbuilt functions named c() and append() to combine two or more lists.
Method 1: Using c() function
c() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.
Syntax:
c(list1, list2)
Example 1:
R
# R Program to combine two lists  # Creating Lists using the list() functionList1 <- list(1:5)List2 <- list(6:10)  print(List1)print(List2)  # Combining lists using c() functionList3 = c(List1, List2)print(List3)
Output:
Here, you can see that the second list has 2 elements, which shows that there are two lists combined as one.
Example 2: 
R
# R Program to combine two lists  # Creating Lists using the list() functionList1 <- list(1, 2, 3)List2 <- list('a', 'b', 'c')  # Combining lists using c() functionList3 = c(List1, List2)print(List3)
Output:
Method 2: Using append() function
append() function in R language accepts two or more lists as parameters and returns another list with the elements of both the lists.
Syntax:
append(list1, list2)
Example 1:
R
# R Program to combine two lists  # Creating Lists using the list() functionList1 <- list(1:5)List2 <- list(6:10)  print(List1)print(List2)  # Combining lists using append() functionList3 = append(List1, List2)print(List3)
Output:
Example 2: 
R
# R Program to combine two lists  # Creating Lists using the list() functionList1 <- list(1, 2, 3)List2 <- list('a', 'b', 'c')  # Combining lists using append() functionList3 = append(List1, List2)print(List3)
Output:
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
Python - Concatenate string rows in Matrix - GeeksforGeeks

30 Dec, 2020
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using join() + list comprehensionThe combination of above functions can help to get the solution to this particular problem in just a one line and hence quite useful. The join function computes the concatenation of sublists and all this bound together using list comprehension.
# Python3 code to demonstrate# Row String Concatenation Matrix# using join() + list comprehension  # initializing listtest_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]  # printing original listprint("The original list : " + str(test_list))  # using join() + list comprehension# Row String Concatenation Matrixres = [''.join(idx for idx in sub) for sub in test_list ]  # print resultprint("The row concatenation in matrix : " + str(res))
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']

 
Method #2 : Using loopThis task can also be performed in brute force manner in which we just iterate the sublists and perform join in brute manner creating new string for each sublist and appending in list.
# Python3 code to demonstrate# Row String Concatenation Matrix# using loop  # initializing listtest_list = [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]  # printing original listprint("The original list : " + str(test_list))  # using loop# Row String Concatenation Matrixres = []for sub in test_list:    res_sub = ""    for idx in sub:        res_sub = res_sub + idx    res.append(res_sub)  # print resultprint("The row concatenation in matrix : " + str(res))
The original list : [['gfg', ' is', ' best'], ['Computer', ' Science'], ['GeeksforGeeks']]
The row concatenation in matrix : ['gfg is best', 'Computer Science', 'GeeksforGeeks']

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Array element with minimum sum of absolute differences?

Here we will see one interesting problem. We are taking one array ‘a’ with N elements. We have to find an element x such that |a[0] - x| + |a[1] - x|+ ... + |a[n-1] - x| is minimized. Then we have to find the minimized sum.
Let the array is: {1, 3, 9, 6, 3} now the x is 3. So the sum is |1 - 3| + |3 - 3| + |9 - 3| + |6 - 3| + |3 - 3| = 11.
To solve this problem, we have to choose the median of the array as x. If the array size is even, then two median values will be there. Both of them will be an optimal choice of x.
begin
   sort array arr
   sum := 0
   med := median of arr
   for each element e in arr, do
      sum := sum + |e - med|
   done
   return sum
end
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int minSum(int arr[], int n){
   sort(arr, arr + n);
   int sum = 0;
   int med = arr[n/2];
   for(int i = 0; i<n; i++){
      sum += abs(arr[i] - med);
   }
   return sum;
}
int main() {
   int arr[5] = {1, 3, 9, 6, 3};
   int n = 5;
   cout << "Sum : " << minSum(arr, n);
}
Sum : 11
How to change the color of bars in base R barplot?

To change the color of bars in base R barplot, we can use col argument inside the barplot function.
For example, if we have a vector called V for which we want to create the barplot then we can use the command given below to get the bars in blue color −
barplot(V,col="blue")
Check out the below example to understand how it can be done.
To change the color of bars in base R barplot, use the code given below −
x<-rpois(10,5)
x
If you execute the above given code, it generates the following output −
[1] 4 3 2 8 2 8 4 2 3 5
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x)
If you execute all the above given snippets as a single program, it generates the following output −
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x,col="red")
If you execute all the above given snippets as a single program, it generates the following output −
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x,col="blue")
If you execute all the above given snippets as a single program, it generates the following output −
Linux Admin - head Command

head is a basic opposite of tail in relation to what part of the file operations are performed on. By default, head will read the first 10 lines of a file.
head offers similar options as tail −
Note − Head offers no -f option, since the files are appended from the bottom.
head is useful for reading descriptions of configuration files. When making such a file, it is a good idea to use the first 10 lines effectively.
[root@centosLocal centos]# head /etc/sudoers 
## Sudoers allows particular users to run various commands as 
## the root user, without needing the root password. 
## 
## Examples are provided at the bottom of the file for collections 
## of related commands, which can then be delegated out to particular 
## users or groups. 
##  
## This file must be edited with the 'visudo' command.

## Host Aliases 
[root@centosLocal centos]#


    57 Lectures 
     7.5 hours 

 Mamta Tripathi

    25 Lectures 
     3 hours 

 Lets Kode It

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    58 Lectures 
     2.5 hours 

 Frahaan Hussain

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    23 Lectures 
     5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
How to convert an OutputStream to a Writer in Java?

An OutputStream class is a byte-oriented whereas Writer class is a character-oriented. We can convert an OutputStream class to a Writer class using an OutputStreamWriter class and pass an argument of ByteArrayOutputStream object to OutputStreamWriter constructor. An OutputStreamWriter is a bridge from a character stream to a byte stream, the characters written to it are encoded into bytes using a specified charset.
public class OutputStreamWriter extends Writer
import java.io.*;
public class OutputStreamToWriterTest {
   public static void main(String[] args) throws Exception {
      String str = "TUTORIALSPOINT";
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(baos);
      for (int i=0; i < str.length(); i++) {
         osw.write((int) str.charAt(i));
      }
      osw.close();
      byte[] b = baos.toByteArray();
      for (int j=0; j < b.length; j++) {
         System.out.println(b[j]);
      }
   }
}
84
85
84
79
82
73
65
76
83
80
79
73
78
84
How to extract the first digit from a character column in an R data frame?

If we have a character column in the data frame that contains string as well as numeric values and the first digit of the numeric values has some meaning that can help in data analysis then we can extract those first digits. For this purpose, we can use stri_extract_first function from stringi package.
Consider the below data frame −
Live Demo
> x1<-1:20
> y1<-sample(c("HT23L","HT14L","HT32L"),20,replace=TRUE)
> df1<-data.frame(x1,y1)
> df1
   x1  y1
1  1  HT14L
2  2  HT14L
3  3  HT23L
4  4  HT14L
5  5  HT32L
6  6  HT32L
7  7  HT14L
8  8  HT32L
9  9  HT32L
10 10 HT32L
11 11 HT23L
12 12 HT32L
13 13 HT14L
14 14 HT23L
15 15 HT14L
16 16 HT23L
17 17 HT23L
18 18 HT23L
19 19 HT23L
20 20 HT23L
Loading stringi package and extracting first digit in column y1 −
> library(stringi)
> stri_extract_first(df1$y1,regex="\\d")
[1] "1" "1" "2" "1" "3" "3" "1" "3" "3" "3" "2" "3" "1" "2" "1" "2" "2" "2" "2"
[20] "2"
Live Demo
> x2<-sample(c("India1RT1","UK5RT1","Egypt2PT4"),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(x2,y2)
> df2
     x2      y2
1  India1RT1 2
2  India1RT1 8
3  India1RT1 7
4  India1RT1 6
5  UK5RT1    6
6  India1RT1 5
7  UK5RT1    6
8  India1RT1 6
9  India1RT1 7
10 UK5RT1    10
11 Egypt2PT4 8
12 Egypt2PT4 5
13 Egypt2PT4 7
14 India1RT1 2
15 UK5RT1    3
16 Egypt2PT4 5
17 UK5RT1    3
18 Egypt2PT4 6
19 Egypt2PT4 3
20 UK5RT1    5
Extracting first digit in column x2 −
> stri_extract_first(df2$x2,regex="\\d")
[1] "1" "1" "1" "1" "5" "1" "5" "1" "1" "5" "2" "2" "2" "1" "5" "2" "5" "2" "2"
[20] "5"
Live Demo
> x3<-sample(c("abc123","dfe456"),20,replace=TRUE)
> y3<-rnorm(20)
> df3<-data.frame(x3,y3)
> df3
     x3      y3
1  abc123  0.1027005
2  dfe456  0.2297002
3  dfe456 -0.1441151
4  dfe456  1.0510760
5  abc123  0.8182656
6  dfe456 -0.5018968
7  dfe456  0.2957634
8  abc123 -0.4240910
9  dfe456 -1.0700713
10 dfe456 -0.3374661
11 dfe456 -0.4654241
12 dfe456 -0.4542710
13 abc123  0.6969808
14 dfe456 -0.6514574
15 abc123  0.2258769
16 dfe456 -0.5348958
17 abc123  0.6629195
18 dfe456  1.0998636
19 dfe456 -1.3147809
20 dfe456 -2.3015384
Extracting first digit in column x3 −
> stri_extract_first(df3$x3,regex="\\d")
[1] "1" "4" "4" "4" "1" "4" "4" "1" "4" "4" "4" "4" "1" "4" "1" "4" "1" "4" "4"
[20] "4"