code-rag-bench/online-tutorials huggingface dataset:
Difference between Storage Area Network (SAN) and Network Attached Storage (NAS) - GeeksforGeeks

22 Apr, 2022
Storage Area Network (SAN): Storage Area Network (SAN) is used for transferring the data between the servers and the storage devices fiber channel and switches. In SAN (Storage Area Network), Data is identified by disk block. Protocols that are used in SAN are: SCSI, SATA etc. Components of Storage Area Network (SAN):
1. Node ports
2. Cables
3. Interconnect device such as: Hubs, switches, directors
4. Storage arrays
5. SAN management Software 
Network Attached Storage (NAS): In Network Attached Storage (NAS), data is identified by file name as well as byte offset. In Network Attached Storage, File system is managed by Head unit such as CPU and Memory. In this for backup and recovery, files are used instead of block by block copying technique. Components of Network Attached Storage (NAS):
1. Head unit: CPU, Memory
2. Network Interface Card (NIC)
3. Optimized operating system
4. Protocols
5. Storage protocols: ATA, SCSI,FC 
Difference between Storage Area Network (SAN) and Network Attached Storage (NAS):
ashushrma378
manmeetjuneja5
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
C++ Ostream Library - write

It is used to inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process.
Following is the declaration for std::ostream::write.
ostream& write (const char* s, streamsize n);
s − Pointer to an array of at least n characters.
s − Pointer to an array of at least n characters.
n − Number of characters to insert.
n − Number of characters to insert.
It returns the ostream object (*this).
Basic guarantee − if an exception is thrown, the object is in a valid state.
Modifies the stream objectAccess up to n characters pointed by s./p>

In below example explains about std::ostream::write.
#include <fstream>

int main () {
   std::ifstream infile ("test.txt",std::ifstream::binary);
   std::ofstream outfile ("new.txt",std::ofstream::binary);

   infile.seekg (0,infile.end);
   long size = infile.tellg();
   infile.seekg (0);

   char* buffer = new char[size];

   infile.read (buffer,size);

   outfile.write (buffer,size);
 
   delete[] buffer;

   outfile.close();
   infile.close();
   return 0;
}
 Print
 Add Notes
 Bookmark this page
Select DataFrame rows between two index values in Python Pandas

We can slice a Pandas DataFrame to select rows between two index values. Let's take an example and see how it's done.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Initialize a variable for lower limit of the index.
Initialize another variable for upper limit of the index.
Use df[index_lower_limit: index_upper_limit] to print the DataFrame in range index.
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df

index_lower_limit = 1
index_upper_limit = 3

print("DataFrame between two index values:\n",
df[index_lower_limit: index_upper_limit])
Input DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1

DataFrame between two index values:
  x y z
1 2 7 3
2 7 5 5
Rename Files Using R - GeeksforGeeks

14 Sep, 2021
In this article, we are going to see how to rename files using R Programming Language.
To rename a file in R we use file.rename(). This function renames all the files mentioned as parameters. It returns normally TRUE for success, FALSE for failure. 
Note: File naming conventions depend on the platform.
Syntax: file.rename( to, from)
Parameters:
to: character vector that contains all the files to be renamed
from: character vector that contains new names for file
File for demonstration:
Directory
Below is the implementation:
Here we first list out the working directory and then use rename() function to rename the file name.
R
# Define working directoryworking_directory <- "working/dic/"  # get list of current file# names as character vector current_filescurrent_files <- list.files(working_directory)  # get file names after renaming# as character vector new_filesnew_files <- c("geeks1.txt","geeks2.txt")  # Use file.rename() function to rename filesfile.rename(paste0(working_directory, current_files),            paste0(working_directory, new_files))
Output:
TRUE TRUE
Final Directory
Picked
R-FileHandling
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
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
Blob conversion function in Cassandra - GeeksforGeeks

03 Dec, 2019
In Cassandra, Blob data type represents constant hexadecimal data type and the number is defined as 0[xX](hex)+ where hex means hexadecimal. It is useful to store a short string or small images.
In this article we will discuss Blob conversion function which converts the native types into binary data (blob):
typeAsBlob(value)
blobAsType(value) 
Let’s understand with an example.
To create table function_test1 used the following CQL query.
CREATE TABLE function_test1 ( 
Name varchar PRIMARY KEY, 
type_value blob
 ); 
To insert data into the table using the following CQL query.
INSERT INTO function_test1 (Name, type_value) 
       VALUES ('Ashish', bigintAsBlob(5));
INSERT INTO function_test1 (Name, type_value) 
       VALUES ('Rana', bigintAsBlob(9));  
To read the data using the following CQL query.
SELECT * 
FROM function_test1; 
Output:
Now, to convert blobAsBigint then first update the table by using the following CQL query.
ALTER TABLE function_test1 ADD Id bigint; 
Now, again insert data into the updated table. So, let’s have a look.
INSERT INTO function_test1 (Name, Id) 
       VALUES ('Ashish', blobAsBigint(0x0000000000000005));
INSERT INTO function_test1 (Name, Id) 
       VALUES ('Rana', blobAsBigint(0x0000000000000009)); 
To see the final output used the following CQL query.
SELECT * 
FROM function_test1; 
Output:
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Introduction of ER Model
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL | Views
Difference between DDL and DML in DBMS
Third Normal Form (3NF)
Second Normal Form (2NF)
CTE in SQL
What's the best way to trim std::string in C++?

Here we will see how to trim the strings in C++. The trimming string means removing whitespaces from left and right part of the string.
To trim the C++ string, we will use the boost string library. In that library, there are two different methods called trim_left() and trim_right(). To trim string completely, we can use both of them.
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
main(){
   string myStr = " This is a string ";
   cout << "The string is: (" << myStr << ")" << endl;
   //trim the string
   boost::trim_right(myStr);
   cout << "The string is: (" << myStr << ")" << endl;
   boost::trim_left(myStr);
   cout << "The string is: (" << myStr << ")" << endl;
}
$ g++ test.cpp
$ ./a.out
The string is: (       This is a string         )
The string is: (       This is a string)
The string is: (This is a string)
$
Python Number round() Method

Python number method round() returns x rounded to n digits from the decimal point.
Following is the syntax for round() method −
round( x [, n]  )

x − This is a numeric expression.
x − This is a numeric expression.
n − This is also a numeric expression.
n − This is also a numeric expression.
This method returns x rounded to n digits from the decimal point.
The following example shows the usage of round() method.
#!/usr/bin/python

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)
When we run above program, it produces following result −
round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0
Node.js http.ClientRequest.setTimeout() Method

06 May, 2021
The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request.
Syntax:
request.setTimeout(timeout[, callback])
Parameters: This method takes the time out value as a parameter in milliseconds, and the second parameter is the callback function that executes after the given timeout value.
Return Value: This method returns nothing but a callback function for further operation.
Example 1: Filename-index.js
Javascript
// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverconst server = http.createServer((req, res) => {    res.writeHead(200, { 'Content-Type': 'text/plain' });    res.end('okay');}); // Now that server is runningserver.listen(3000, '127.0.0.1', () => {     // Make a request    const options = {        port: 3000,        host: '127.0.0.1',        headers: {            'Connection': 'Upgrade',            'Upgrade': 'websocket'        }    };     // Getting client request    const req = http.request(options);     // Setting the timeout for the client request    // by using host method    req.setTimeout(3000, () => {        console.log("timeout")        process.exit(0)    })});
 
 
Run the index.js file using the following command:
 
node index.js
Output:
 
timeout
Example 2: Filename-index.js
 
Javascript
// Node.js program to demonstrate the // request.setTimeout() method // Importing http moduleconst http = require('http'); // Create an HTTP serverhttp.createServer((req, res) => { }).listen(3000, '127.0.0.1', () => {     // Getting client request    const req = http.request({        port: 3000,        host: '127.0.0.1',    });     // Setting the timeout for the client request    // by using host method    req.setTimeout(5000, () => {        console.log("timeout")        process.exit(0)    })});
Run the index.js file using the following command:
node index.js
Output:
timeout
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_settimeout_timeout_callback
sweetyty
Node.js-Methods
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Get or set the number of elements that the ArrayList can contain

01 Feb, 2019
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Capacity property is used to get or set the number of elements that the ArrayList can contain.
Properties of ArrayList Class:
Elements can be added or removed from the Array List collection at any point in time.
The ArrayList is not guaranteed to be sorted.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
It also allows duplicate elements.
Using multidimensional arrays as elements in an ArrayList collection is not supported.
Syntax:
public virtual int Capacity { get; set; }

Return Value: The number of elements that the ArrayList can contain.
Exceptions:
ArgumentOutOfRangeException : If the Capacity is set to a value that is less than Count i.e, number of elements in the ArrayList.
OutOfMemoryException : If there is not enough memory available on the system.
Example:
// C# code to get or set the number // of elements that the ArrayList can containusing System; using System.Collections;  class GFG {      // Driver codepublic static void Main() {           // Creating an ArrayList    ArrayList myList = new ArrayList();          // Adding elements to ArrayList    myList.Add(1);    myList.Add(2);    myList.Add(3);    myList.Add(4);    myList.Add(5);          // Displaying count of elements of ArrayList    Console.WriteLine("Number of elements: " + myList.Count);           // Displaying Current capacity of ArrayList    Console.WriteLine("Current capacity: " + myList.Capacity); } }
Number of elements: 5
Current capacity: 8

Important Points:
Capacity is the number of elements that the ArrayList can store. The Count is the number of elements that are actually in the ArrayList.
Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.capacity?view=netframework-4.7.2
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
Scala | Nested Functions

06 Jun, 2021
A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions. Syntax:  
def FunctionName1( parameter1, parameter2, ..) = { def FunctionName2() = { // code } }
 Single Nested Function Here is an example of single nested function that takes two numbers as parameters and returns the Maximum and Minimum of them. Example  
Scala
// Scala program of Single Nested Functionobject MaxAndMin{    // Main method    def main(args: Array[String])    {        println("Min and Max from 5, 7")                maxAndMin(5, 7);    }         // Function    def maxAndMin(a: Int, b: Int) = {            // Nested Function       def maxValue() = {          if(a > b)          {              println("Max is: " + a)          }          else          {              println("Max is: " + b)          }       }            // Nested Function       def minValue() = {          if (a < b)          {              println("Min is: " + a)          }          else          {              println("Min is: " + b)          }       }       maxValue();       minValue();    }}
Output  
Min and Max from 5, 7
Max is: 7
Min is: 5
In above code maxAndMin is a function and maxValue is another inner function returns maximum value between a and b similarly minValue is another inner function which is also nested function this function returns minimum value between a and b. Multiple Nested Function Here is an implementation of multiple nested function. Example  
Scala
// Scala program of Multiple Nested Functionobject MaxAndMin{    // Main method    def main(args: Array[String])    {        fun();    }         // Function    def fun() = {                 geeks();                 // First Nested Function        def geeks() = {            println("geeks");                         gfg();                         // Second Nested Function            def gfg() = {                println("gfg");                 geeksforgeeks();                 // Third Nested Function                def geeksforgeeks() = {                    println("geeksforgeeks");                }            }        }    }}
Output  
geeks
gfg
geeksforgeeks
In above code fun is a function and geeks, gfg, geeksforgeeks are nested functions or local function . 
sumitgumber28
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Append to StringBuilder in C# with a new line on the end

The AppendLine() method appends the content and add a new line on the end.
Firstly, set the StringBuilder −
StringBuilder str = new StringBuilder();
Use AppendLine() −
str.AppendLine("Accessories");
str.AppendLine();
str.AppendLine("Electronics");
The following is the complete code −
 Live Demo
using System;
using System.Text;

class Demo {
   static void Main() {
      StringBuilder str = new StringBuilder();
      str.AppendLine("Accessories");
      str.AppendLine();
      str.AppendLine("Electronics");
      Console.Write(str);
   }
}
Accessories

Electronics
Convert datetime to get month name in MySQL?

To get only month name, the syntax is as follows −
select date_format(yourColumnName,'%M %Y') from yourTableName;
Let us first create a table −
mysql> create table DemoTable1619
    -> (
    -> ArrivalTime datetime
    -> );
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1619 values(now());
Query OK, 1 row affected (0.40 sec)
mysql> insert into DemoTable1619 values(curdate());
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1619 values('2019-12-31');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1619;
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-10-20 15:02:12 |
| 2019-10-20 00:00:00 |
| 2019-12-31 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
Following is the query to convert datetime to get month name in MySQL −
mysql> select date_format(ArrivalTime,'%M %Y') from DemoTable1619;
This will produce the following output −
+----------------------------------+
| date_format(ArrivalTime,'%M %Y') |
+----------------------------------+
| October 2019                     |
| October 2019                     |
| December 2019                    |
+----------------------------------+
3 rows in set (0.00 sec)
How to read multiple text files from folder in Python?

02 Feb, 2021
Prerequisite:
File Handling
os
Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python.
Approach:
Import modules
Add path of the folder
Change directory
Get the list of a file from a folder
Iterate through the file list and check whether the extension of the file is in .txt format or not.
If text-file exist, read the file using File Handling
Functions used:
os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path.
Syntax: os.chdir(path)
Parameters:
path: A complete path of directory to be changed to new directory path.
Returns: Doesn’t return any value
os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Syntax: os.listdir(path)
Parameters:
path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Below is the Implementation:
Program:
Python3
# Import Moduleimport os  # Folder Pathpath = "Enter Folder Path"  # Change the directoryos.chdir(path)  # Read text File    def read_text_file(file_path):    with open(file_path, 'r') as f:        print(f.read())    # iterate through all filefor file in os.listdir():    # Check whether file is in text format or not    if file.endswith(".txt"):        file_path = f"{path}\{file}"          # call read text file function        read_text_file(file_path)
Output:
Picked
Python file-handling-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | Namespace

04 Oct, 2021
Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts.
It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.
A namespace is a hierarchically labeled code block holding a regular PHP code.
A namespace can contain valid PHP code.
Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants.
Namespaces are declared using the namespace keyword.
A namespace must be declared the namespace at the top of the file before any other code – with one exception: the declare keyword.  
php
<?phpnamespace MyNamespaceName {      // Regular PHP code    function hello()    {        echo 'Hello I am Running from a namespace!';    }}?>
If namespace is declared globally, then declare it without any name.  
php
<?phpnamespace {      // Global space!}?>
Multiple namespaces can be declared within a single PHP code.  
php
<?phpnamespace MyNamespace1 {  }   namespace MyNamespace2 {  }   namespace {  }?>
A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.Example:  
php
<?phpnamespace MyNamespaceName;function hello()    {        echo 'Hello I am Running from a namespace!';    }   // Resolves to MyNamespaceName\hellohello(); // Explicitly resolves to MyNamespaceName\hellonamespace\hello();?>
Aliasing in Namespaces
Importing is achieved by using the ‘use’ keyword. Optionally, It can specify a custom alias with the ‘as’ keyword. Example:  
php
<?phpnamespace MyNamespaceName;   require 'project/database/connection.php';   use Project\Database\Connection as Connection;   $connection = new Connection();   use Project\Database as Database;   $connection = new Database\Connection();?>
It is possible to dynamically call namespaced code, dynamic importing is not supported.  
php
<?phpnamespace OtherProject;   $title = 'geeks';   // This is valid PHPrequire 'project/blog/title/' . $title . '.php';   // This is notuse Project\Blog\title\$title;?>
Reference : http://php.net/manual/en/language.namespaces.php 
saurabh1990aror
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Executing Shell Commands with Python

01 Oct, 2020
Prerequisite: Some basic shell commands
In programming, the shell is a software interface for accessing the functionality of the operating system. Shells in the operating system use either a CLI (Command Line Interface) or a GUI (Graphical User Interface) based on the functionality and basic operation of the device.
The os module in Python includes functionality to communicate with the operating system. The os module is one of the standard utility modules of Python. This Python module offers a convenient way to use operating system-dependent features, shell commands can be executed using the system() method in the os module.
Below are some examples to execute shell commands using Python:
Example 1:
Python3
# Importing required moduleimport os  # Using system() method to # execute shell commandsos.system('echo "Geeks 4 Geeks"')
Output:
Example 2: 
Python3
# Importing required moduleimport os  # Using system() method to execute# shell commandsos.system('pwd')
Output: 
Example 3: 
Python3
# Importing required moduleimport os  # Using system() method to execute# shell commandsos.system('ls')
Output: 
Example 4: 
Python3
# Importing required moduleimport os  # Using system() method to execute# shell commandsos.system('cat')
Output: 
Example 5: 
Python3
# Importing required moduleimport os  # Using system() method to execute# shell commandsos.system('telnet towel.blinkenlights.nl')
Output:  
 
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
numpy.expand_dims

This function expands the array by inserting a new axis at the specified position. Two parameters are required by this function.
numpy.expand_dims(arr, axis)

Where,
arr
Input array
axis
Position where new axis to be inserted
import numpy as np 
x = np.array(([1,2],[3,4])) 

print 'Array x:' 
print x 
print '\n'  
y = np.expand_dims(x, axis = 0) 

print 'Array y:' 
print y 
print '\n'

print 'The shape of X and Y array:' 
print x.shape, y.shape 
print '\n'  
# insert axis at position 1 
y = np.expand_dims(x, axis = 1) 

print 'Array Y after inserting axis at position 1:' 
print y 
print '\n'  

print 'x.ndim and y.ndim:' 
print x.ndim,y.ndim 
print '\n'  

print 'x.shape and y.shape:' 
print x.shape, y.shape
The output of the above program would be as follows −
Array x:
[[1 2]
 [3 4]]

Array y:
[[[1 2]
 [3 4]]]

The shape of X and Y array:
(2, 2) (1, 2, 2)

Array Y after inserting axis at position 1:
[[[1 2]]
 [[3 4]]]

x.ndim and y.ndim:
2 3

x.shape and y.shape:
(2, 2) (2, 1, 2)
Python | Pandas Series.dt.quarter

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.quarter attribute return the quarter of the date in the underlying datetime based data in the given series object.
Syntax: Series.dt.quarter
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object.
# return the quarter of the dateresult = sr.dt.quarter  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object. Example #2 : Use Series.dt.quarter attribute to return the quarter of the date in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                        periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.quarter attribute to return the quarter of the date in the datetime based data in the given series object.
# return the quarter of the dateresult = sr.dt.quarter  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.quarter attribute has successfully accessed and returned the quarter of the date in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Node.js Promise Chaining

08 Oct, 2021
Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task.
To demonstrate promise chaining, the following function will be used to simulate an asynchronous task. In reality, it’s just adding up a couple of numbers, waiting two seconds, and fulfilling the promise with the sum.
Filename: index.js
const add = (a, b) => {         return new Promise((resolve, reject) => {                setTimeout(() => {                        if (a < 0 || b < 0) {                                 return reject('Numbers must be non-negative')            }             resolve(a + b)                 }, 2000)     })}  add(1, 2).then((sum) => {         console.log(sum)  // Print 3       return add(sum, 4)}).then((sum2) => {         console.log(sum2) // Print 7 }).catch((e) => {     console.log(e) });
Step to run the program:
Run index.js file using below command:node index.js
node index.js
With the dummy asynchronous function defined, promise chaining can be used to call add twice. The code below adds up 1 and 2 for a total of 3. It then uses the sum value 3 as the input for another call to add. The second call to add adds up 3 and 4 for a total of 7.
Promise chaining occurs when the callback function returns a promise. It allows you to chain on another then call which will run when the second promise is fulfilled. Catch can still be called to handle any errors that might occur along the way.
Node.js-Basics
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Script | setTimeout() & setInterval() Method

10 Jun, 2022
SetTimeout and SetInterval are the only native function in javaScript that is used to run code asynchronously , it means allow the function to executed immediately , there is no need to wait for current execution completion , it will for further to execute.
setTimeout() method The setTimeout() method executes a function, after waiting a specified number of milliseconds. 
Syntax:
window.setTimeout(function, milliseconds);
Parameter: There are two parameter that accepted by this method
function : first parameter is a function to be executed
milliseconds : indicates the number of milliseconds before execution takes place.
For example, we want an alert box to pop up, 2 seconds after the user presses the click me button. 
Example: 
javascript
<!DOCTYPE html><html> <head>    <title>       HTML | DOM Window setTimeout() method    </title></head> <body>     <button onclick="setTimeout(gfg, 2000);">      Press me    </button>     <script>        function gfg() {            alert('Welcome to GeeksforGeeks');        }    </script> </body> </html>
Output: As soon as the user presses the “press me” button, then after a pause of 2 seconds this message alert box will pop up.
  
setInterval() Method The setInterval() method repeats a given function at every given time-interval. 
Syntax:
window.setInterval(function, milliseconds);
Parameter: There are two parameter that accepted by this method
function : first parameter is the function to be executed
milliseconds :indicates the length of the time-interval between each execution.
Example: 
javascript
<!DOCTYPE html><html> <head>    <title>        HTML | DOM Window setTimeout() method    </title></head> <body>     <p>I will say hi many times</p>     <p id="GFG"></p>     <script>        var myVar = setInterval(myTimer, 1000);         function myTimer() {            document.getElementById("GFG").innerHTML +=                                            "<p>Hi</p>";        }    </script> </body></html>
Output: After every second a new “hi” message will be displayed.
  
Then:
  
Supported Browser: The browser supported by setTimeout() & setInterval() Method are listed nelow:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
surbhikumaridav
javascript-functions
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
Python – sys.stdout.flush()

21 Apr, 2020
A data buffer is a region of physical memory storage used to temporarily store data while it is being moved from one place to another. The data is stored in a buffer as it is retrieved from an input device or just before it is sent to an output device or when moving data between processes within a computer. Python’s standard out is buffered. This means that it collects some data before it is written to standard out and when the buffer gets filled, then it is written on the terminal or any other output stream.
Let’s look at the code below :
# Python3 program demonstrating working # of flush during output    import sysimport time  for i in range(10):    print(i)    time.sleep(1)
Output:
0
1
2
3
4
5
6
7
8
9
When the above program is executed, then the numbers from 0 to 9 are printed after every second on a new line, i.e., the output is automatically flushed out. This is because, by default end parameter of print statement is set to ‘\n’ which flushes the output.
Now let’s look at the code below :
# Python3 program demonstrating working # of flush during output  import sysimport time  for i in range(10):    print(i, end =' ')    time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9
When the above program is executed, then there is no output for the first 9 seconds, then at the 10th, all the 10 numbers from 0 to 9 appear simultaneously in a line separated by spaces. This is because the output is buffered and it is not flushed by any means.
Now, look at the code below :
# Python3 program demonstrating working # of flush during output and usage of# sys.stdout.flush() function  import sysimport time  for i in range(10):    print(i, end =' ')    sys.stdout.flush()    time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9
When the above program is executed, the numbers from 0 to 9 are printed every second on the same line separated by spaces. This is because calling sys.stdout.flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. It lets us access system-specific parameters and functions.
Another way of achieving the same functionality as above is setting the flush parameter of the print statement to true.
# Python3 program demonstrating working # of flush during output and usage of# flush parameter of print statement  import sysimport time  for i in range(10):    print(i, end =' ', flush = True)    time.sleep(1)
Output:
0 1 2 3 4 5 6 7 8 9 
Python-sys
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is export default in JavaScript ?

20 Jun, 2022
The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports. Named Exports: Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object. 
javascript
// Exporting individual featuresexport var name1 = ..., name2 = ..., ..., nameN; // also let, const // Export listexport { name1, name2, ..., nameN }; //Exporting everything at onceexport { object, number, x, y, boolean, string } // Renaming exportsexport { variable1 as name1, variable2 as name2, ..., nameN }; // export features declared earlierexport { myFunction, myVariable };
Example: 
javascript
//file math.jsfunction square(x) {  return x * x;}function cube(x) {  return x * x * x;}export { square, cube };   //while importing square function in test.jsimport { square, cube } from './math;console.log(square(8)) //64console.log(cube(8)) //512
Output:
64
512
Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import. 
javascript
// file module.jsvar x=4;export default x; // test.js// while importing x in test.jsimport y from './module';// note that y is used import x instead of// import x, because x was default exportconsole.log(y);       // output will be 4
Output
4
Another example of Default Exports with function 
javascript
// file math.jsexport default function square(x) {  return x * x;} //while importing square function in test.jsimport square from './math;console.log(square(8)) //64
Output:
64
Using Named and Default Exports at the same time: It is possible to use Named and Default exports in the same file. It means both will be imported in the same file. Example: 
javascript
//module.jsvar x=2;const y=4;function fun() {   return "This a default export."}function square(x) {  return x * x;}export { fun as default, x, y, square };
While importing this module.js we can use any name for fun because it is a default export and curly braces for other named exports. 
javascript
//test.js fileimport anyname, { x, y, square} from './module.js';console.log(anyname()); //This is a default export.console.log(x); //2
Output
This is a default export.
2
dasjet
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
PostgreSQL – Difference between CHAR, VARCHAR and TEXT

30 Sep, 2021
Now that we are familiar with the concept of character data types CHAR, VARCHAR, and TEXT respectively in PostgreSQL, this article will focus on highlighting the key difference between them. 
What is CHAR data type? This data type is used to store characters of limited length. It is represented as char(n) or character(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to char(1) or character(1). 
What is VARCHAR data type? This data type is used to store characters of limited length. It is represented as varchar(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to varchar which has unlimited length. 
What is TEXT data type? This data type is used to store characters of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same. 
The below table provides with the major difference between CHAR, VARCHAR, and TEXT: 
Example: 
Let’s create a new table(say, character_tests) for the demonstration using the below commands:  
CREATE TABLE character_tests (
    id serial PRIMARY KEY,
    x CHAR (1),
    y VARCHAR (10),
    z TEXT
);
Now let’s insert a new row into the char_test table using the below command:  
INSERT INTO character_tests (x, y, z)
VALUES
    (
        'Geeks',
        'This is a test for varchar',
        'This is a very long text for the PostgreSQL text column'
    );
At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below:  
ERROR:  value too long for type character(1)
So, now let’s fix it.  
INSERT INTO character_tests (x, y, z)
VALUES
    (
        'G',
        'This is a test for varchar',
        'This is a very long text for the PostgreSQL text column'
    );
Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below:  
ERROR:  value too long for type character(10)
Let’s fix it too.  
INSERT INTO character_tests (x, y, z)
VALUES
    (
        'Y',
        'varchar(n)',
        'This is a very long text for the PostgreSQL text column'
    );
Now that we have managed to successfully assign the values to the character data type, check it by running the below command: 
SELECT * FROM character_tests;
Output:  
 
Akanksha_Rai
kashishsoda
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT
PostgreSQL - LEFT JOIN
How to find the subsequence in an input sequence that matches the pattern required in Java Regular Expressions?

The find() method finds the subsequence in an input sequence that matches the pattern required. This method is available in the Matcher class that is available in the java.util.regex package.
A program that demonstrates the method Matcher.find() in Java regular expressions is given as follows:
 Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("Sun");
      Matcher m = p.matcher("The Earth revolves around the Sun");
      System.out.println("Subsequence: Sun");
      System.out.println("Sequence: The Earth revolves around the Sun");
      if (m.find())
         System.out.println("\nSubsequence found");
      else
         System.out.println("\nSubsequence not found");
   }
}
Subsequence: Sun
Sequence: The Earth revolves around the Sun
Subsequence found
Now let us understand the above program.
The subsequence “Sun” is searched in the string sequence "The Earth revolves around the Sun". Then the find() method is used to find if the subsequence is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("Sun");
Matcher m = p.matcher("The Earth revolves around the Sun");
System.out.println("Subsequence: Sun" );
System.out.println("Sequence: The Earth revolves around the Sun" );
if (m.find())
   System.out.println("\nSubsequence found");
else
   System.out.println("\nSubsequence not found");
GATE | GATE-CS-2005 | Question 82

28 Jun, 2021
Consider the following C-function:
double foo (int n){    int i;    double sum;    if (n = = 0) return 1.0;    else    {        sum = 0.0;        for (i = 0; i < n; i++)            sum += foo (i);        return sum;    }}
Suppose we modify the above function foo() and store the values of foo (i), 0 < = i < n, as and when they are computed. With this modification, the time complexity for function foo() is significantly reduced. The space complexity of the modified function would be:(A) O(1)(B) O(n)(C) O(n!)(D) O(nn)Answer: (B)Explanation: Space complexity now is also O(n).
We would need an array of size O(n). The space required for recursive calls would be O(1) as the values would be taken from stored array rather than making function calls again and again.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
C# - Stack Class

It represents a last-in, first out collection of object.	It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
The following table lists some commonly used properties of the Stack class −
Count
Gets the number of elements contained in the Stack.
The following table lists some of the commonly used methods of the Stack class −
public virtual void Clear();
Removes all elements from the Stack.
public virtual bool Contains(object obj);
Determines whether an element is in the Stack.
public virtual object Peek();
Returns the object at the top of the Stack without removing it.
public virtual object Pop();
Removes and returns the object at the top of the Stack.
public virtual void Push(object obj);
Inserts an object at the top of the Stack.
public virtual object[] ToArray();
Copies the Stack to a new array.
The following example demonstrates use of Stack −
using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();
         
         st.Push('A');
         st.Push('M');
         st.Push('G');
         st.Push('W');
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         Console.WriteLine();
         
         st.Push('V');
         st.Push('H');
         Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
         Console.WriteLine("Current stack: ");
         
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         
         Console.WriteLine();
         
         Console.WriteLine("Removing values ");
         st.Pop();
         st.Pop();
         st.Pop();
         
         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Current stack: 
W G M A
The next poppable value in stack: H
Current stack: 
H V W G M A
Removing values
Current stack: 
G M A


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page