code-rag-bench/online-tutorials huggingface dataset:
How to Convert Pandas DataFrame columns to a Series? - GeeksforGeeks

01 Oct, 2020
It is possible in pandas to convert columns of the pandas Data frame to series. Sometimes there is a need to converting columns of the data frame to another type like series for analyzing the data set. 
Case 1: Converting the first column of the data frame to Series
Python3
# Importing pandas moduleimport pandas as pd  # Creating a dictionary dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],        'September': [4.8, 54, 68, 9.25, 58, 0.9],        'October': [78, 5.8, 8.52, 12, 1.6, 11],        'November': [100, 5.8, 50, 8.9, 77, 10] }  # Converting it to data framedf = pd.DataFrame(data=dit)  # Original DataFramedf
Output:
Converting the first column to series.
Python3
# Converting first column i.e 'August' to Seriesser1 = df.ix[:,0]  print("\n1st column as a Series:\n")print(ser1)  # Checking typeprint(type(ser1))
Output:
In the above example, we change the type of column ‘August‘ from the data frame to Series.
Case 2: Converting the last column of the data frame to Series
Python3
# Importing pandas moduleimport pandas as pd  # Creating a dictionary dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],        'September': [4.8, 54, 68, 9.25, 58, 0.9],        'October': [78, 5.8, 8.52, 12, 1.6, 11],        'November': [100, 5.8, 50, 8.9, 77, 10] }  # Converting it to data framedf = pd.DataFrame(data=dit)  # Original DataFramedf
Output:
Converting the last column to the series.
Python3
# Converting last column i.e 'November' to Seriesser1 = df.ix[:,3]  print("\nLast column as a Series:\n")print(ser1)  # Checking typeprint(type(ser1))
Output:
In the above example, we change the type of column ‘November‘ from the data frame to Series.
Case 3: Converting the multiple columns of the data frame to Series
Python3
# Importing pandas moduleimport pandas as pd  # Creating a dictionary dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],        'September': [4.8, 54, 68, 9.25, 58, 0.9],        'October': [78, 5.8, 8.52, 12, 1.6, 11],        'November': [100, 5.8, 50, 8.9, 77, 10] }  # Converting it to data framedf = pd.DataFrame(data=dit)  # Original DataFramedf
Output:
Converting multiple columns to series.
Python3
# Converting multiple columns # i.e 'September' and 'October' to Seriesser1 = df.ix[:,1]ser2 = df.ix[:,2]  print("\nMultiple columns as a Series:\n")print(ser1)print()print(ser2)  # Checking typeprint(type(ser1))print(type(ser2))
Output:
In the above example, we change the type of 2 columns i.e ‘September‘ and ‘October’ from the data frame to Series.
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
PyQt5 - QComboBox - GeeksforGeeks

22 Apr, 2020
QComboBox is a widget in PyQt5 which is used to choose from a list. It takes minimum space when we click on combo box, a drop down list came from which we can select the item. QComboBox class is used to add a combo box in a application. Below is the representation of how combo looks like –
Example :In this we will create a combo box in the window which allows us to choose in between “Geek”, “Super Geek” and “Ultra Geek”
Below is the code –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        combo_box = QComboBox(self)          # setting geometry of combo box        combo_box.setGeometry(200, 150, 120, 40)          # adding items to combo box        combo_box.addItem("Geek")        combo_box.addItem("Super Geek")        combo_box.addItem("Ultra Geek")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
GATE-CS-2000 - GeeksforGeeks

26 Feb, 2021
v[i, j] = i-j for all i, j, 1 <= i <= n, 1 <= j <= n
0    -1    -2    -3    -4    -5    -6    -7    ...    -n
1     0    -1    -2    -3    -4    -5    -6    ...  -(n-1)
2     1     0    -1    -2    -3    -4    -5    ...  -(n-2)
3     2     1     0    -1    -2    -3    -4    ...  -(n-3)
4     3     2     1     0    -1    -2    -3    ...  -(n-4)
5     4     3     2     1     0    -1    -2    ...  -(n-5)
6     5     4     3     2     1     0    -1    ...  -(n-6)
7     6     5     4     3     2     1     0    ...  -(n-6)
.     .     .     .     .     .     .     .     .   .   .
.     .     .     .     .     .     .     .     .   .   .
.     .     .     .     .     .     .     .     .   .   .
n    n-1   n-2   n-3   n-4   n-5   n-6    n-7  ...  2   1
The determinant of the matrix is  
 
20 
4 
0 
5 
It is a 4*4 matrix, in the first row all elements except 2 are zero so lets find the cofactor for a(0,0). The cofactor has all zeroes except 1 in its first column so lets find the cofactor of a(1,1). This turns out to be 2*1 – 6*0 = 2 a(0,0) * a(1,1) * cofactor(a(1,1)) = 2 * 1 *2 = 4 Hence the answer is 4. 
If ready pin is high the microprocessor will complete the operation and proceeds for the next operation.
If ready pin is low the microprocessor will wait until it goes high.
Thus, option (B) is the answer.
Please comment below if you find anything wrong in the above post.
Pipelined CPU : Total time (T1) = (K + (N - 1)) * T = KT
Non-Pipelined CPU : Total time (T2) = KNT = KT
Considering buffer delays in pipelined CPU, T1 >= T2
 Thus, option (B) is the answer.
Please comment below if you find anything wrong in the above post.
X: Indirect addressing            1 : Loops

Y: Immediate addressing           2 : Pointers

Z: Auto decrement addressing      3: Constants
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
How to read a local text file using JavaScript? - GeeksforGeeks

20 Jul, 2021
HTML 5 provides a standard way to interact with local files with the help of File API. The File API allows interaction with single, multiple as well as BLOB files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling. However, all the browsers do not have HTML 5 support so it is important to test the browser compatibility before using the File API. There are four inbuilt methods in the FileReader API to read local files:
FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.
In this case we are using FileReader.readAsText() method to read local .txt file.
<!DOCTYPE html><html>  <head>    <title>Read Text File</title></head>  <body>    <input type="file" name="inputfile"            id="inputfile">    <br>       <pre id="output"></pre>          <script type="text/javascript">        document.getElementById('inputfile')            .addEventListener('change', function() {                          var fr=new FileReader();            fr.onload=function(){                document.getElementById('output')                        .textContent=fr.result;            }                          fr.readAsText(this.files[0]);        })    </script></body>  </html>
This code prints the content of the input file exactly the same as is there in the input file.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Keep track of previous indexes after sorting a vector in C++ STL - GeeksforGeeks

06 Mar, 2019
Prerequisite: vector, vector pair sorting
Given a vector, keep track of the present indexes corresponding to each element and after sorting print element with its previous respective indexes.
Examples:
Input: Arr[] = {2, 5, 3, 7, 1}Output: {1, 4} {2, 0} {3, 2} {5, 1} {7, 3}Explanation:Before sorting [index(element)]: [0(2), 1(5), 2(3), 3(7), 4(1)]After sorting [previous_index(element)]: [4(1), 0(2), 2(3), 1(5), 3(7)]
Input: Arr[] = {4, 5, 10, 8, 3, 11}Output: {3, 4} {4, 0} {5, 1} {8, 3} {10, 2} {11, 5}
Approach: The idea is to store each element with its present index in a vector pair and then sort all the elements of the vector, Finally, print the elements with its index associated with it.
Below is the implementation of the above approach:
// C++ implementation to keep track// of previous indexes// after sorting a vector  #include <bits/stdc++.h>using namespace std;  void sortArr(int arr[], int n){      // Vector to store element    // with respective present index    vector<pair<int, int> > vp;      // Inserting element in pair vector    // to keep track of previous indexes    for (int i = 0; i < n; ++i) {        vp.push_back(make_pair(arr[i], i));    }      // Sorting pair vector    sort(vp.begin(), vp.end());      // Displaying sorted element    // with previous indexes    // corresponding to each element    cout << "Element\t"         << "index" << endl;    for (int i = 0; i < vp.size(); i++) {        cout << vp[i].first << "\t"             << vp[i].second << endl;    }}  // Driver codeint main(){    int arr[] = { 2, 5, 3, 7, 1 };    int n = sizeof(arr) / sizeof(arr[0]);    sortArr(arr, n);      return 0;}
Element    index
1    4
2    0
3    2
5    1
7    3

cpp-pair
cpp-vector
STL
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
How to Read CSV Files with NumPy? - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to read CSV files with Numpy in Python.
Dataset in use:
To import data from a text file, we will use the NumPy loadtxt() method. To use this function we need to make sure that the count of entries in each line of the text document should be equal. In Python, numpy.load() is used to load data from a text file, with the goal of being a quick read for basic text files.
Syntax: 
numpy.loadtxt('data.csv')
Example: Loading csv from loadtxt method
Python3
import numpy as np  # using loadtxt()arr = np.loadtxt("sample_data.csv",                 delimiter=",", dtype=str)display(arr)
Output:
The genfromtxt() method is used to import the data from a text document. We can specify how to handle the missing values in our dataset in case if there are.
Syntax:
numpy.genfromtxt('data.csv')
Example: Loading CSV from genfromtxt method
Python3
import numpy as np  # using genfromtxt()arr = np.genfromtxt("sample_data.csv",                    delimiter=",", dtype=str)display(arr)
Output:
csv.reader() reads each line of the CSV file. We read data line by line and then convert each line to a list of items.
Syntax:
csv.reader(x)
Here x denotes each line of the CSV file.
Example: Loading CSV using csv reader
Python3
import numpy as np  # Importing csv moduleimport csv    with open("sample_data.csv", 'r') as x:    sample_data = list(csv.reader(x, delimiter=","))  sample_data = np.array(sample_data)display(sample_data)
Output:
Picked
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Python calendar module : prmonth() method

04 Dec, 2020
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
class calendar.TextCalendar(firstweekday=0) can be used to generate plain text calendars. prmonth() method is one of the methods of TextCalendar instance.
prmonth() method in Python is used to print a month’s calendar as returned by formatmonth().
Syntax: prmonth(year, month, width=0, lines=0)
Parameter:year: year of the calendarmonth: month of the calendarwidth: [optional] Specifies the width of the date columns, which are centeredline: [optional] Specifies the number of lines that each week will use.
Returns: Return a month’s calendar.
Code #1:
# Python program to demonstrate working of prmonth() method  # importing calendar moduleimport calendar  text_cal = calendar.TextCalendar(firstweekday = 0)  year = 2018month = 9  # default value of width is 0  # printing prmonthprint(text_cal.prmonth(year, month))
Output:
   September 2018
Mo Tu We Th Fr Sa Su
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
 None

 
Code #2: With parameter width
# Python program to demonstrate working of prmonth() method  # importing calendar moduleimport calendar  text_cal = calendar.TextCalendar(firstweekday = 0)    # default value of width is 0  # printing prmonthprint(text_cal.prmonth(2018, 10, w = 5))
Output:
               October 2018
 Mon   Tue   Wed   Thu   Fri   Sat   Sun
   1     2     3     4     5     6     7
   8     9    10    11    12    13    14
  15    16    17    18    19    20    21
  22    23    24    25    26    27    28
  29    30    31
 None
 Code #3:
# Python program to demonstrate working of prmonth() method  # importing calendar moduleimport calendar  text_cal = calendar.TextCalendar(firstweekday = 0)    # giving value of width = 6, line = 2  # printing prmonthprint(text_cal.prmonth(2018, 10, 6, 2))
Output:
                  October 2018

 Mon    Tue    Wed    Thu    Fri    Sat    Sun

   1      2      3      4      5      6      7

   8      9     10     11     12     13     14

  15     16     17     18     19     20     21

  22     23     24     25     26     27     28

  29     30     31

 None
Python Calander-module
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pandas – Filling NaN in Categorical data

21 Aug, 2021
Real-world data is full of missing values. In order to work on them, we need to impute these missing values and draw meaningful conclusions from them. In this article, we will discuss how to fill NaN values in Categorical Data. In the case of categorical features, we cannot use statistical imputation methods. 
Let’s first create a sample dataset to understand methods of filling missing values:
Python3
# import modulesimport numpy as npimport pandas as pd # create datasetdata = {'Id': [1, 2, 3, 4, 5, 6, 7, 8],                 'Gender': ['M', 'M', 'F', np.nan,                   np.nan, 'F', 'M', 'F'],                 'Color': [np.nan, "Red", "Blue",                  "Red", np.nan, "Red",                  "Green", np.nan]} # convert to data framedf = pd.DataFrame(data)display(df)
Output:
To fill missing values in Categorical features, we can follow either of the approaches mentioned below –
Method 1: Filling with most occurring class
One approach to fill these missing values can be to replace them with the most common or occurring class. We can do this by taking the index of the most common class which can be determined by using value_counts() method. Let’s see the example of how it works:
Python3
# filling with most common classdf_clean = df.apply(lambda x: x.fillna(x.value_counts().index[0]))df_clean
Output:
Method 2: Filling with unknown class
At times, the missing information is valuable itself, and to impute it with the most common class won’t be appropriate. In such a case, we can replace them with a value like “Unknown” or “Missing” using the fillna() method. Let’s look at an example of this –
Python3
# filling with Unknown classdf_clean = df.fillna("Unknown")df_clean
Output:
Method 3: Using Categorical Imputer of sklearn-pandas library 
We have scikit learn imputer, but it works only for numerical data. So we have sklearn_pandas with the transformer equivalent to that, which can work with string data. It replaces missing values with the most frequent ones in that column. Let’s see an example of replacing NaN values of “Color” column – 
Python3
# using sklearn-pandas packagefrom sklearn_pandas import CategoricalImputer # handling NaN valuesimputer = CategoricalImputer()data = np.array(df['Color'], dtype=object)imputer.fit_transform(data)
Output:
surindertarika1234
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SimpleDateFormat format() Method in Java with Examples

01 Dec, 2021
The format() Method of SimpleDateFormat class is used to format a given date into Date/Time string. Basically the method is used to convert this date and time into a particular format for say mm/dd/yyyy.Syntax:  
public final String format(Date date)
Parameters: The method takes one parameter date of Date object type and refers to the date whose string output is to be produced.Return Value: The method returns Date or time in string format of mm/dd/yyyy.Below programs illustrate the working of format() Method of SimpleDateFormat:Example 1:  
Java
// Java code to illustrate format() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat("MM/dd/yyyy");         // Initializing the calendar Object        Calendar cal = Calendar.getInstance();         // Displaying the actual date        System.out.println("The original Date: "                           + cal.getTime());         // Using format() method for conversion        String curr_date            = SDFormat.format(cal.getTime());        System.out.println("Formatted Date: "                           + curr_date);    }}
The original Date: Tue Jan 29 12:23:40 UTC 2019
Formatted Date: 01/29/2019
 
Example 2:  
Java
// Java code to illustrate format() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat();         // Initializing the calendar Object        Calendar cal = Calendar.getInstance();         // Displaying the actual date        System.out.println("The original Date: "                           + cal.getTime());         // Using format() method for conversion        String curr_date = SDFormat.format(cal.getTime());        System.out.println("Formatted Date: "                           + curr_date);    }}
The original Date: Tue Jan 29 12:29:32 UTC 2019
Formatted Date: 1/29/19 12:29 PM
 
abhishek0719kadiyan
Java-Functions
Java-SimpleDateFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Python – Test substring order

05 Sep, 2020
Given two strings, check if substring characters occur in correct order in string.
Input : test_str = ‘geeksforgeeks’, K = ‘sees’Output : TrueExplanation : “s” after that “ee” and then “s” is present in order in string 1.
Input : test_str = ‘geeksforgeeks’, K = ‘seef’Output : FalseExplanation : Unordered String.
Method #1 : Using join() + generator expression + in operator
In this, we check we join all the characters which occur in substring using join(), post that check if substring is present using in operator.
Python3
# Python3 code to demonstrate working of # Test substring order# Using join() + in operator + generator expression  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringK = 'seek'  # concatenating required characters temp = lambda sub: ''.join(chr for chr in sub if chr in set(K))  # checking in orderres = K in temp(test_str)  # printing result print("Is substring in order : " + str(res)) 
The original string is : geeksforgeeks
Is substring in order : True

Method #2 : Using all() + next() + generator expression
In this, we get the string with just substring characters using next() and generator expression, to check for order, all() operation is used for each character in substring.
Python3
# Python3 code to demonstrate working of # Test substring order# Using all() + next() + generator expression  # initializing stringtest_str = 'geeksforgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringK = 'seek'  # concatenating required characters using next()# all() used to test ordertest_str = iter(test_str)res = all(next((ele for ele in test_str if ele == chr), None) is not None for chr in K)  # printing result print("Is substring in order : " + str(res)) 
The original string is : geeksforgeeks
Is substring in order : True

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to read data from scanner to an array in java?

The Scanner class of the java.util package gives you methods like nextInt(), nextByte(), nextFloat() etc. to read data from keyboard. To read an element of an array uses these methods in a for loop:
 Live Demo
import java.util.Arrays;
import java.util.Scanner;

public class ReadingWithScanner {
   public static void main(String args[]) {
      Scanner s = new Scanner(System.in);
      System.out.println("Enter the length of the array:");
      int length = s.nextInt();
      int [] myArray = new int[length];
      System.out.println("Enter the elements of the array:");

      for(int i=0; i<length; i++ ) {
         myArray[i] = s.nextInt();
      }

      System.out.println(Arrays.toString(myArray));
   }
}
Enter the length of the array:
5
Enter the elements of the array:
25
56
48
45
44
[25, 56, 48, 45, 44]
Change Font of Plot in R

06 Jun, 2021
In this article, we will be looking at the two different approaches to change the font of the plot in R programming language.
In this approach to change the font of the given plot, the user needs to call the windowsFont() which is one of the in-build function of the R programming language, with the name of the font as its parameter, this function is used to specify the font family as per requirement and with this, the user also need to use the family argument of the plot() function to change the font family of the texts of the plot in the R programming language.
 windowsFont() function is used to handle the translation of a device-independent R graphics font family name to a Windows font description and is available only on Windows.
Syntax:
windowsFont(family)
Parameter:
family: a character vector containing the font family name (“TT” as the first two characters indicate a TrueType font).
Example:
R
sample1_x <- c(1, 8, 5, 3, 8, 7)                sample1_y <- c(4, 6, 3, 8, 2, 7)  windowsFonts(A = windowsFont("Rockwell"))    plot(sample1_x, sample1_y, family = "A", cex=.8, pch=1,      col="red", main="Plot to show font Change")  sample2_x<-c(4, 5, 8, 6, 4)sample2_y<-c(9, 8, 2, 3, 1)sample3_x<-c(2, 1, 6, 7, 4)sample3_y<-c(7, 9, 1, 5, 2)  points(sample2_x, sample2_y, cex=.8, pch=2, col="blue")points(sample3_x, sample3_y, cex=.8, pch=3, col="green")  legend("topright", c("gfg1", "gfg2", "gfg3"),       cex=1, col=c("red", "blue", "green"), pch=c(1, 2, 3))
Output:
In this method to change the font of the given plot user firstly needs to install and import the ggplot2 package and then call the windowsFont() function to specify the required parameter as its parameter and secondly need to call the theme() function from the ggplot2 package to change the font of the given ggplot2 plot.
theme() function used to modify theme settings.
Syntax:
theme(..., complete = FALSE, validate = TRUE)
Parameters:
...: a list of element names, element pairings that modify the existing theme.
complete: set this to TRUE if this is a complete theme, such as the one returned by theme_grey().
validate: TRUE to run validate_element, FALSE to bypass checks.
Example:
R
library("ggplot2")     gfg_data<-data.frame(x_values=c(1, 2, 3, 4, 5), y_values=c(5, 4, 3, 2, 1))  windowsFonts(A = windowsFont("Times New Roman"))    gfg_plot<-ggplot(data=gfg_data, aes(x_values, y_values)) +  geom_bar(stat="identity")+ ggtitle("Plot to show font change")+  theme(text = element_text(family = "A"))  gfg_plot
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
How to iterate over rows in Pandas Dataframe

14 Jan, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Let’s see the how to iterate over rows in Pandas Dataframe using iterrows() and itertuples() :Method #1: Using the DataFrame.iterrows() methodThis method iterated over the rows as (index, series) pairs. 
Python3
# importing pandasimport pandas as pd # list of dictsinput_df = [{'name':'Sujeet', 'age':10},            {'name':'Sameer', 'age':11},            {'name':'Sumit', 'age':12}] df = pd.DataFrame(input_df)print('Original DataFrame: \n', df)  print('\nRows iterated using iterrows() : ')for index, row in df.iterrows():    print(row['name'], row['age'])
Original DataFrame: 
    age    name
0   10  Sujeet
1   11  Sameer
2   12   Sumit

Rows iterated using iterrows() : 
Sujeet 10
Sameer 11
Sumit 12
 
  Method #2: Using the DataFrame.itertuples() methodThis method returns a named tuple for every row. getattr() function can be used to get the row attribute in the returned tuple. This method is faster than Method #1.  
Python3
# importing pandasimport pandas as pd # list of dictsinput_df = [{'name':'Sujeet', 'age':10},            {'name':'Sameer', 'age':110},            {'name':'Sumit', 'age':120}] df = pd.DataFrame(input_df)print('Original DataFrame: \n', df) print('\nRows iterated using itertuples() : ')for row in df.itertuples():    print(getattr(row, 'name'), getattr(row, 'age'))
Original DataFrame: 
    age    name
0   10  Sujeet
1  110  Sameer
2  120   Sumit

Rows iterated using itertuples() : 
Sujeet 10
Sameer 110
Sumit 120
 
There are few other ways we can iterate over rows in Pandas Dataframe. See Different ways to iterate over rows in Pandas Dataframe. 
adnanirshad158
pandas-dataframe-program
Picked
Python pandas-dataFrame
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – API.get_direct_message() in Tweepy

12 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The get_direct_message() method of the API class in Tweepy module is used to fetch a direct message as the authenticated user.
Syntax : API.get_direct_message(id, full_text)
Parameters :
id : ID of the direct message.
full_text : boolean indicating whether or not the full text of a message should be returned or not.
Returns : an object of class DirectMessage
Example 1 :
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # ID of the direct messageid =   # fetching the direct messagedirect_message = api.get_direct_message(id)  print(direct_message.message_create['message_data']['text'])
Output :
This is a Direct Message.

Example 2 : Exception is raised when the ID is invalid.
# invalid ID of the direct messageid = 12345  # fetching the direct messagedirect_message = api.get_direct_message(id)
Output :
    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{'code': 34, 'message': 'Sorry, that page does not exist.'}]

Python-Tweepy
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Pattern Searching using C++ library

12 Dec, 2021
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n > m.Examples:  
Input : txt[] = "geeks for geeks"
        pat[] = "geeks"
Output : Pattern found at index 0
         Pattern found at index 10

Input : txt[] = "aaaa"
        pat[] = "aa"
Output : Pattern found at index 0
         Pattern found at index 1
         Pattern found at index 2
The idea is to use find() in C++ string class.
CPP
// CPP program to print all occurrences of a pattern// in a text#include <bits/stdc++.h>using namespace std; void printOccurrences(string txt, string pat){    int found = txt.find(pat);    while (found != string::npos) {        cout << "Pattern found at index " << found << endl;        found = txt.find(pat, found + 1);    }} int main(){    string txt = "aaaa", pat = "aa";    printOccurrences(txt, pat);    return 0;}
Pattern found at index 0
Pattern found at index 1
Pattern found at index 2
 
kk773572498
cpp-string
STL
C++
C++ Programs
Pattern Searching
Pattern Searching
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PyOpenGL on Windows?

30 Sep, 2021
PyOpenGL is the most common cross-platform Python binding to OpenGL. In this, article, we will look into the process of installing the PyopenGL Library on Windows.
The only thing that you need for installing the Scrapy module on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:
conda install -c anaconda pyopengl
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if PyopenGL Library  has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list pyopengl
You’ll get the below message if the installation is complete:
If you want the installation to be done through PIP,  open up the Command Prompt and use the below command:
pip install pyopengl
You will get a similar message once the installation is complete:
To verify if the PyopenGL Library  has been successfully installed in your system run the below command in Command Prompt:
python -m pip show pyopengl
You’ll get the below message if the installation is complete:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Pygame on Windows ?
Node.js fs.symlink() Function

08 Oct, 2021
The fs.symlink() method is used to create a symlink to the specified path. This creates a link making the path point to the target. The relative targets are relative to the link’s parent directory.
Syntax:
fs.symlink( target, path, type, callback )
Parameters: This method accept four parameters as mentioned above and described below:
target: It is a string, buffer or URL which represents the path to which the symlink has to be created.
path: It is a string, buffer or URL which represents the path where the symlink will be created.
type: It is a string which represents the type of symlink to be created. It can be specified with ‘file’, ‘dir’ or ‘junction’. If the target does not exist, ‘file’ will be used.
callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails.
err: It is an error that would be thrown if the operation fails.
Below examples illustrate the fs.symlink() method in Node.js:
Example 1: This example creates a symlink to a file.
// Node.js program to demonstrate the// fs.symlink() method  // Import the filesystem moduleconst fs = require('fs');  console.log("Contents of the text file:");console.log(fs.readFileSync('example_file.txt', 'utf8'));  fs.symlink(__dirname + "\\example_file.txt",        "symlinkToFile", 'file', (err) => {  if (err)    console.log(err);  else {    console.log("\nSymlink created\n");    console.log("Contents of the symlink created:");    console.log(fs.readFileSync('symlinkToFile', 'utf8'));  }})
Output:
Contents of the text file:
Hello Geeks

Symlink created

Contents of the symlink created:
Hello Geeks
Example 2: This example creates a symlink to a directory.
// Node.js program to demonstrate the// fs.symlink() method  // Import the filesystem moduleconst fs = require('fs');  fs.symlink(__dirname + "\\example_directory",           "symlinkToDir", 'dir', (err) => {  if (err)    console.log(err);  else {    console.log("Symlink created");    console.log("Symlink is a directory:",       fs.statSync("symlinkToDir").isDirectory()    );  }});
Output:
Symlink created
Symlink is a directory: true
Reference: https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tetrahedral Numbers

21 Jun, 2022
A number is termed as a tetrahedral number if it can be represented as a pyramid with a triangular base and three sides, called a tetrahedron. The nth tetrahedral number is the sum of the first n triangular numbers.The first ten tetrahedral numbers are: 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, ... 
 
Formula for nth tetrahedral number:  
Tn = (n * (n + 1) * (n + 2)) / 6
Proof:  
The proof uses the fact that the nth tetrahedral 
number is given by,

Trin = (n * (n + 1)) / 2

It proceeds by induction.

Base Case
T1 = 1 = 1 * 2 * 3 / 6

Inductive Step
Tn+1 = Tn + Trin+1

Tn+1 = [((n * (n + 1) * (n + 2)) / 6] + [((n + 1) * (n + 2)) / 2]

Tn+1 = (n * (n + 1) * (n + 2)) / 6
Below is the implementation of above idea :  
C++
Java
Python
C#
PHP
Javascript
// CPP Program to find the// nth tetrahedral number#include <iostream>using namespace std; int tetrahedralNumber(int n){    return (n * (n + 1) * (n + 2)) / 6;} // Driver Codeint main(){    int n = 5;         cout << tetrahedralNumber(n) << endl;     return 0;}
// Java Program to find the// nth tetrahedral numberclass GFG {     // Function to find Tetrahedral Numberstatic int tetrahedralNumber(int n){    return (n * (n + 1) * (n + 2)) / 6;} // Driver Codepublic static void main(String[] args){    int n = 5;         System.out.println(tetrahedralNumber(n));}} // This code is contributed by Manish Kumar Rai.
# Python3 Program to find the# nth tetrahedral number def tetrahedralNumber(n):         return (n * (n + 1) * (n + 2)) / 6 # Driver Coden = 5print (tetrahedralNumber(n))
// C# Program to find the// nth tetrahedral numberusing System; public class GFG{         // Function to find Tetrahedral Number    static int tetrahedralNumber(int n)    {        return (n * (n + 1) * (n + 2)) / 6;    }         // Driver code    static public void Main ()    {        int n = 5;             Console.WriteLine(tetrahedralNumber(n));    }} // This code is contributed by Ajit.
<?php// PHP Program to find the// nth tetrahedral number function tetrahedralNumber($n){    return ($n * ($n + 1) * ($n + 2)) / 6;} // Driver Code    $n = 5;     echo tetrahedralNumber($n);     // This code is contributed by mits?>
<script> // JavaScript Program to find the// nth tetrahedral number // Function to find Tetrahedral Numberfunction tetrahedralNumber(n){    return (n * (n + 1) * (n + 2)) / 6;}  // Driver code     let n = 5;    document.write(tetrahedralNumber(n));         // This code is contributed by code_hunt.</script>
Output:  
35
Time Complexity: O(1).
Space complexity: O(1) since using constant variables 
Manish_100
jit_t
Mithun Kumar
code_hunt
polymatir3j
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Convert emoji into text in Python

06 Apr, 2021
Converting emoticons or emojis into text in Python can be done using the demoji module. It is used to accurately remove and replace emojis in text strings. To install the demoji module the below command can be used:  
pip install demoji
The demoji module also requires an initial download of data from the Unicode Consortium’s emoji code repository as the emoji list itself is frequently updated and changed. The below code block should be used for the above-mentioned download:  
Python3
import demoji demoji.download_codes()
Output:  
Now that we are all set to use the demoji module we can jump into a few examples.Example 1: 
Output:  
Example 2: 
Output:  
Example 3:  
Output:  
Example 4:  
Output:  
 
yuvraj_chandra
Picked
Python-projects
python-utility
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
SASS variable for images path

27 Jun, 2020
Whenever we want to add an image to our webpage, we need not always write the full path of our images when using SASS. We can rather store the path to the images folder in a variable. It is always good to add the path of a folder to a variable.
Declaring a variableSyntax :
$assetPath :"path";
Adding a variable in image pathSyntax :
background: url(#{$assetPath}/gfg.gif);
Example 1: SASS file
$assetPath :"/assets/images";
body {
  margin: 0 auto;
  background: url(#{$assetPath}/gfg.gif);
  width: 100%; 
}
Output: Compiled CSS file
body {
  margin: 0 auto;
  background: url(/assets/images/gfg.gif);
  width: 100%; 
}
We can also use multiple variables in a single path to an image.
Syntax :
background: url(#{$variable1}/#{$variable2}/#{$variable3});
Example 2: SASS file
$assetsPath :"/assets/images";
$project :"project2";
body {
  margin: 0 auto;
  background: url(#{$assetsPath}/#{$project}/gfg.gif);
  width: 100%; 
}
Output: Compiled CSS file
body {
  margin: 0 auto;
  background: url(/assets/images/project/gfg.gif);
  width: 100%; 
}
Picked
SASS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.close() method

18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.close() method in Python is used to close the given file descriptor, so that it no longer refers to any file or other resource and may be reused.A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. A File descriptor is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc.For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2.Further files opened by the current process will get the value 3, 4, 5 an so on.
Syntax: os.close(fd)
Parameter:fd: A file descriptor, which is to be closed.
Return Type: This method does not return any value
# Python program to explain os.close() method     # importing os module import os  # Pathpath = "/home/ihritik/Desktop/file2.txt"    # open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_WRONLY)    # Perform some operation# Lets write a strings = "GeeksForGeeks: A computer science portal for geeks"  # Convert string to bytes objectline = str.encode(s)  # Write string to file referred by# by the file descriptoros.write(fd, line)    # close the file descriptoros.close(fd)print("File descriptor closed successfully")
File descriptor closed successfully

python-os-module
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to resize image in PHP?

Images can be resized using ImageMagick or GD functions. If GD’s functions are used, the size of the image file is also reduced when raw digital camera images are sampled. We will see how GD can be used to resize an image in the below code.
function image_resize($file_name, $width, $height, $crop=FALSE) {
   list($wid, $ht) = getimagesize($file_name);
   $r = $wid / $ht;
   if ($crop) {
      if ($wid > $ht) {
         $wid = ceil($wid-($width*abs($r-$width/$height)));
      } else {
         $ht = ceil($ht-($ht*abs($r-$w/$h)));
      }
      $new_width = $width;
      $new_height = $height;
   } else {
      if ($width/$height > $r) {
         $new_width = $height*$r;
         $new_height = $height;
      } else {
         $new_height = $width/$r;
         $new_width = $width;
      }
   }
   $source = imagecreatefromjpeg($file_name);
   $dst = imagecreatetruecolor($new_width, $new_height);
   image_copy_resampled($dst, $source, 0, 0, 0, 0, $new_width, $new_height, $wid, $ht);
   return $dst;
}
$img_to_resize = image_resize(‘path-to-jpg-image’, 250, 250);