code-rag-bench/online-tutorials huggingface dataset:
Node.js URL.hostname API

14 Oct, 2021
The url.hostname is an inbuilt application programming interface of class URL with in url module which is used to get and set the hostname portion of the URL. The key difference between url.host and url.hostname is that url.hostname does not include the port. 
Syntax:  
const url.hostname
Return value: It gets and sets the hostname portion of the URL.Below programs illustrate the use of url.hostname Method:Example 1:  
javascript
// node program to demonstrate the // url.hostname API as Setter    //importing the module 'url'const http = require('url');   // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram');   // Display href value of myURL before changeconsole.log("Before Change");console.log(myURL.href);   // assigning hostname portion// using hostnameconsole.log();myURL.hostname = 'example.org';   // Display href value of myURL after changeconsole.log("After Change");console.log(myURL.href);
Output:  
Example 2: 
javascript
// node program to demonstrate the // url.hostname API as Getter   //importing the module 'url'const http = require('url');  // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');  // getting the hostname portion// using hostnameconst hostname = myURL.hostname;  // Display hostname value console.log(hostname);
Output:  
NOTE: The above program will compile and run by using the node myapp.js command. Reference: https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_url_host
mridulmanochagfg
sweetyty
Node-URL
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
multiset begin() and end() function in C++ STL

17 Jun, 2022
The multiset::begin() is a built-in function in C++ STL that returns an iterator pointing to the first element in the multiset container. Since multiset always contains elements in an ordered way, begin() always points to the first element according to the sorting criterion. 
Syntax:
iterator multiset_name.begin()
Parameters: The function does not accept any parameters.
Return value: The function returns an iterator pointing to the first element in the container.
Below program illustrate the above-mentioned function: 
CPP
// CPP program to demonstrate the// multiset::begin() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 14, 10, 15, 11, 10 };     // initializes the set from an array    multiset<int> s(arr, arr + 5);     // Print the first element    cout << "The first element is: " << *(s.begin()) << endl;     // prints all elements in set    for (auto it = s.begin(); it != s.end(); it++)        cout << *it << " ";     return 0;}
The first element is: 10
10 10 11 14 15
The multiset::end() is a built-in function in C++ STL that returns an iterator pointing to the position past the last element in the container.
Syntax:
iterator multiset_name.end()
Parameters: The function does not accept any parameters.
Return value: The function returns an iterator pointing to the position past the last element in the container in the multiset container.
Below program illustrate the above-mentioned function: 
CPP
// CPP program to demonstrate the// multiset::end() function#include <bits/stdc++.h>using namespace std;int main(){     int arr[] = { 14, 10, 15, 11, 10, 12, 17, 12 };     // initializes the set from an array    multiset<int> s(arr, arr + 8);     // prints all elements in set    for (auto it = s.begin(); it != s.end(); it++)        cout << *it << " ";     return 0;}
10 10 11 12 12 14 15 17
Let  us see the differences in a tabular form as shown below as follows:
Its syntax is -:
iterator begin();
Its syntax is -:
iterator end();
mayank007rawa
CPP-Functions
cpp-multiset
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dart Programming - Abs Method

This property is used to return an integer representing the absolute value of a number.
Number.abs()

void main() {  
   var a = -2; 
   print(a.abs()); 
}  
It will produce the following output −.
2


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How can scikit-learn be used to convert an image from RGB to grayscale in Python?

Scikit-learn, commonly known as sklearn is a library in Python that is used for the purpose of implementing machine learning algorithms.
Conversion of an image from one color space to another is usually used so that the newly achieved color space can prove as a better input to perform other operations on it. This includes separating hues, luminosity, saturation levels, and so on. When an image is represented using RGB representation, the hue and luminosity attributes are shown as a linear combination of channels R, G and B.
When an image with RGB color space is tried to be converted to grayscale, the pixel values are calculated as the weighted sum of the red, green and blue pixels. The equation has been shown below −
Y = 0.2125 R + 0.7154 G + 0.0721 B
These weights are specifically provided, since they are used by CRT phosphors that represent human perception of the colors red, green and blue better, in comparison to providing equal weights for all the three values.
Let us see how an RGB image can be converted into a grayscale image −
from skimage import io
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2gray
from skimage import data
path = "path to puppy_1.JPG"
orig_img = io.imread(path)
grayscale_img = rgb2gray(orig_img)
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
ax[0].imshow(orig_img)
ax[0].set_title("Original image")
ax[1].imshow(grayscale_img, cmap=plt.cm.gray)
ax[1].set_title("Grayscale image")
fig.tight_layout()
plt.show()
The required libraries are imported.
The path where the image is stored is defined.
The ‘imread’ function is used to visit the path and read the image.
The ‘imshow’ function is used to display the image on the console.
The function ‘rgb2gray’ is used to convert the image from RGB color space to grayscale color space.
The matplotlib library is used to plot this data, and show the original image and the image after being converted to grayscale.
This is displayed on the console.
How to pass argument to an Exception in Python?

An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary from exception to exception. You capture an exception's argument by supplying a variable in the except clause as follows
try:
b=float(56+78/0)
except Exception, Argument:
print 'This is the Argument\n', Argument
The output obtained is as follows
This is the Argument
integer division or modulo by zero
If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
Python | Ways to remove numeric digits from given string - GeeksforGeeks

21 Feb, 2019
Given a string (may contain both characters and digits), write a Python program to remove the numeric digits from string.
Let’s discuss the different ways we can achieve this task.
Method #1: Using join and isdigit()
# Python code to demonstrate# how to remove numeric digits from string# using join and isdigit  # initialising stringini_string = "Geeks123for127geeks"  # printing initial ini_stringprint("initial string : ", ini_string)  # using join and isdigit # to remove numeric digits from stringres = ''.join([i for i in ini_string if not i.isdigit()])  # printing resultprint("final string : ", res)
initial string :  Geeks123for127geeks
final string :  Geeksforgeeks

 Method #2: Using translate and digits
# Python code to demonstrate# how to remove numeric digits from string# using translatefrom string import digits  # initialising stringini_string = "Geeks123for127geeks"  # printing initial ini_stringprint("initial string : ", ini_string)  # using translate and digits# to remove numeric digits from stringremove_digits = str.maketrans('', '', digits)res = ini_string.translate(remove_digits)  # printing resultprint("final string : ", res)
initial string :  Geeks123for127geeks
final string :  Geeksforgeeks

 Method #3: Using filter and lambda
# Python code to demonstrate# how to remove numeric digits from string# using filter and lambda  # initialising stringini_string = "akshat123garg"  # printing initial ini_stringprint("initial string : ", ini_string)  # using filter and lambda# to remove numeric digits from stringres = "".join(filter(lambda x: not x.isdigit(), ini_string))  # res = ini_string# printing resultprint("final string : ", str(res))
initial string :  akshat123garg
final string :  akshatgarg

Python string-programs
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Spring Boot - Tomcat Port Number

Spring Boot lets you to run the same application more than once on a different port number. In this chapter, you will learn about this in detail. Note that the default port number 8080.
In the application.properties file, we can set custom port number for the property server.port
server.port = 9090

In the application.yml file, you can find as follows −
server: 
   port: 9090

In the application.properties file, we can set random port number for the property server.port
server.port = 0

In the application.yml file, you can find as follows −
server: 
   port: 0

Note − If the server.port number is 0 while starting the Spring Boot application, Tomcat uses the random port number.
Deloitte USI Interview Experience for Analyst | On-Campus 2021

17 Aug, 2021
Hi Geeks, I am sharing my complete interview experience for Deloitte USI (Deloitte India – Offices of the  US). The company visited our campus in August 2021. Hiring was for roles of Analyst – Deloitte USI Consulting and Technology Analyst- Deloitte USI Risk & Financial Advisory.
Complete Process consists of 2 rounds for Analyst Deloitte USI Consulting role. 
Round 1(Aptitude Test): This round was conducted on the AMCAT platform and was a completely aptitude-based round consisting of questions from Logical reasoning, Quantitative/Qualitative reasoning, and Verbal ability.   
Test duration was 75 mins.
Logical Reasoning (25 questions) – 25 mins.
Quantitative reasoning (25 questions) – 35 mins.
Verbal Reasoning (25 questions) – 25 mins
It was easy round. After this round selected student got a link for the Pre-Placement talk. In Pre Placement talk organizers informed us about upcoming rounds and company and answered questions. 
Round 2(Technical + HR round): We got a link for this round after about a week from the aptitude round. It was easy as compared to other technical rounds. 
The interviewer introduced himself and then asked about me, my academic journey.
Then he asked about my interesting subjects in engineering apart from those mentioned in my CV.
Some questions about my hobbies and interests.
After that, we discussed 10 to 15 mins on the projects mentioned in the resume.
After the discussion, he asked me to code some of questions and share the screen.
Questions were pretty easy.
https://www.geeksforgeeks.org/program-cube-sum-first-n-natural-numbers/
printing slice of list as per given size.
After interview, we got list of selected students and a link to zoom call where all selected students are asked to join immediately where host informed us all candidates who joined this call are selected. 
Verdict – Selected
Deloitte
Marketing
On-Campus
Interview Experiences
Deloitte
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Removing an array element from a MongoDB collection

To remove an array element, simply use $pull along with update(). Let us create a collection with documents −
> db.demo146.insertOne({"ListOfEmployeeNames":["Chris","David","Bob","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32f54ffdf09dd6d08539bd")
}
Display all documents from a collection with the help of find() method −
> db.demo146.find();
This will produce the following output −
{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Bob", "Mike" ] }
Following is the query to remove an array element from MongoDB −
> db.demo146.update({}, { "$pull": { "ListOfEmployeeNames": "Bob" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo146.find();
This will produce the following output −
{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Mike" ] }
How to get memory usage under Linux in C++

Here we will see how to get the memory usage statistics under Linux environment using C++.
We can get all of the details from “/proc/self/stat” folder. Here we are taking the virtual memory status, and the resident set size.
#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void mem_usage(double& vm_usage, double& resident_set) {
   vm_usage = 0.0;
   resident_set = 0.0;
   ifstream stat_stream("/proc/self/stat",ios_base::in); //get info from proc
   directory
   //create some variables to get info
   string pid, comm, state, ppid, pgrp, session, tty_nr;
   string tpgid, flags, minflt, cminflt, majflt, cmajflt;
   string utime, stime, cutime, cstime, priority, nice;
   string O, itrealvalue, starttime;
   unsigned long vsize;
   long rss;
   stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
   >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
   >> utime >> stime >> cutime >> cstime >> priority >> nice
   >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care
   about the rest
   stat_stream.close();
   long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // for x86-64 is configured
   to use 2MB pages
   vm_usage = vsize / 1024.0;
   resident_set = rss * page_size_kb;
}
int main() {
   double vm, rss;
   mem_usage(vm, rss);
   cout >> "Virtual Memory: " >> vm >> "\nResident set size: " >> rss >> endl;
}
Virtual Memory: 13272
Resident set size: 1548
Count number of occurrences of records in a MySQL table and display the result in a new column?

For this, use COUNT(*) along with GROUP BY clause. Let us first create a table −
mysql> create table DemoTable1942
   (
   Value int
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(2);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(3);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1942 values(1);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1942;
This will produce the following output −
+-------+
| Value |
+-------+
|     1 |
|     2 |
|     3 |
|     2 |
|     3 |
|     3 |
|     1 |
+-------+
7 rows in set (0.00 sec)
Here is the query to count number of occurrences:
mysql> select Value, count(*) from DemoTable1942
   group by Value;
This will produce the following output −
+-------+----------+
| Value | count(*) |
+-------+----------+
|     1 |        2 |
|     2 |        2 |
|     3 |        3 |
+-------+----------+
3 rows in set (0.00 sec)
How to Install pyperclip in Python on MacOS? - GeeksforGeeks

26 Oct, 2021
In this article, we will learn how to install pyperclip in Python on MacOS. 
Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with both Python 2 and 3. This module was created to enable cross-platform copy-pasting in Python which was earlier absent. The pyperclip module has copy() and paste() functions that can send a text to and receive a text from your computer’s clipboard.
Follow the below steps to install the pyperclip package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install pyperclip using pip3.
pip3 install pyperclip
Follow the below steps to install the pyperclip pyperclip on macOS using the setup.py file:
Step 1: Download the latest source package of pyperclip for python3 from here.
curl https://files.pythonhosted.org/packages/a7/2c/4c64579f847bd5d539803c8b909e54ba087a79d01bb3aba433a95879a6c5/pyperclip-1.8.2.tar.gz > pyperclip.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf pyperclip.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd pyperclip-1.8.2
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import pyperclip
If there is any error while importing the module then is not installed properly.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Python os.utime() Method

Python method utime() sets the access and modified times of the file specified by path.
Following is the syntax for utime() method −
os.utime(path, times)

path − This is the path of the file.
path − This is the path of the file.
times − This is the file access and modified time. If times is none, then the file access and modified times are set to the current time. The parameter times consists of row in the form of (atime, mtime) i.e (accesstime, modifiedtime).
times − This is the file access and modified time. If times is none, then the file access and modified times are set to the current time. The parameter times consists of row in the form of (atime, mtime) i.e (accesstime, modifiedtime).
This method does not return any value.
The following example shows the usage of utime() method.
# !/usr/bin/python

import os, sys

# Showing stat information of file
stinfo = os.stat('a2.py')
print stinfo

# Using os.stat to recieve atime and mtime of file
print "access time of a2.py: %s" %stinfo.st_atime
print "modified time of a2.py: %s" %stinfo.st_mtime

# Modifying atime and mtime
os.utime("a2.py",(1330712280, 1330712292))
print "done!!"
When we run above program, it produces following result −
posix.stat_result(st_mode=33188, st_ino=3940649674337682L, st_dev=277923425L, st
_nlink=1, st_uid=400, st_gid=401, st_size=335L, st_atime=1330498070, st_mtime=13
30498074, st_ctime=1330498065)
access time of a2.py: 1330498070
modified time of a2.py: 1330498074
done!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Check if substring present in string in Python

In python data analysis we may come across a scenario to check if a given substring is part of a bigger string. We will achieve this through the following programs.
The find function finds the first occurrence of the specified value. If the value is not found then it returns -1. We will apply this function to the given string and design a if clause to find out is substring is part of a string.
 Live Demo
Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")
Running the above code gives us the following result −
Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string
The method count() returns the number of elements with the specified value in a string or data collection in python. In the below program we will calculate the count of the substring and if it is greater than 0 we conclude that the substring is present in the bigger string.
 Live Demo
Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is part of the string")
else:
   print("Substring is not a part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is a part of the string")
else:
   print("Substring is not a part of the string")
Running the above code gives us the following result −
Given string: In cloud 9
Given substring: cloud
Substring is not a part of the string
Given substring: 19
Substring is not a part of the string
What is slotted ALOHA in computer networks?

Aloha is a packet switching system. The time interval required to transmit one packet is called a slot. Aloha is a random access technique.
There are two ALOHA protocols as follows −
Pure ALOHA
Slotted ALOHA
Now let us see what Slotted ALOHA is −
The slotted ALOHA is explained below in stepwise manner −
Step 1 − Slotted ALOHA was introduced to improve the efficiency of pure ALOHA, because in pure ALOHA there is a high chance of collision.
Step 2 − In this protocol, the time of the shared channel is divided into discrete intervals called as slots.
Step 3 − The stations can send a frame only at the beginning of the slot and only one frame is sent in each slot.
Step 4 − In slotted ALOHA, if any station is not able to place the frame onto the channel at the beginning of the slot i.e. it misses the time slot then the station has to wait until the beginning of the next time slot.
Step 5 − In slotted ALOHA, there is still a possibility of collision if two stations try to send at the beginning of the same time slot.
Step 6 − The users are restricted to transmit only from the instant corresponding to the slot boundary.
The vulnerable period is only one time slot. It is shown below −
The throughput of slotted ALOHA is given by,
The Vulnerable time period is ‘1’.
Smax = 1/e
    = 0.368
Therefore, in slotted ALOHA, the channel utilization is 36 percent.
Final Arrays in Java

A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference. As an array is also an object and it is referred by a reference variable which if set as final then cannot be reassigned. Let's see the examples for further explanation.
public class Tester {
   public static void main(String []args) {
   
      final int[] arr = {1,2,3};

      //We can modify the final object's properties
      arr[1] = 4;
      for(int i = 0;i < arr.length ; i++) {
         System.out.println(arr[i]);
      }
   }
}
1
4
3
Now try to change the reference variable. Compiler will throw an error during compilation.
public class Tester {
   public static void main(String []args) {

      final int[] arr = {1,2,3};
      int[] arr2 = {4,5,6};
      //We cannot modify the final refernce
      arr = arr2;

      for(int i = 0;i < arr.length ; i++) {
         System.out.println(arr[i]);
      }
   }
}
Tester.java:6: error: cannot assign a value to final variable arr
arr = arr2;
^
1 error
GATE | GATE-CS-2016 (Set 2) | Question 52 - GeeksforGeeks

01 Oct, 2021
Consider the following two statements:
I. If all states of an NFA are accepting 
   states then the language accepted by 
   the NFA is Σ∗ .
II. There exists a regular language A such 
    that for all languages B, A ∩ B is regular. 
Which one of the following is CORRECT?
(A) Only I is true(B) Only II is true(C) Both I and II are true(D) Both I and II are falseAnswer: (B)Explanation: Statement I : False, Since there is no mention of transition between states. There may be a case, where between two states there is no transition defined.Statement II: True, Since any empty language (i.e., A = Φ ) is regular and its intersection with any other language is Φ. Thus A ∩ B is regular.
This explanation has been contributed by Shikhar Goel.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ's on Grammars (continued) with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0028:59 / 50:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h3ydTwg3fXM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to find common rows and columns between two dataframe in R? - GeeksforGeeks

26 Mar, 2021
Two data frames can have similar rows, and they can be determined. In this article, we will find the common rows and common columns between two data frames, in the R programming language.
Approach
Create a first data frame
Create a second data frame
Compare using required functions
Copy same rows to another data frame
Display data frame so generated.
Data frames in use:
data1:
data 2:
Method 1: Using Intersect() Function:
Syntax: intersect(data , data2)
Parameters:
data/data2 : It is the data frames on which we have to apply the function.
Example:
R
data1 <- data.frame(x1 = 1:7,                                          x2 = letters[1:7],                    x3 = "y")data1 data2 <- data.frame(x1 = 2:7,                                        x2 = letters[2:7],                   x3 = c("x", "x", "y", "y" , "x", "y"))data2  common_rows <- generics::intersect(data1, data2)  common_rows
Output:
Method 2: Using inner_join() function.
To find the common data using this method first install the “dplyr” package in the R environment.
install.packages(“dplyr”)                         
This module has an inner_join() which finds inner join between two data sets.
Syntax: inner_join(data1,data2)
Parameter:
data1/data2: two datasets to be compared
Example:
R
library("dplyr")  data1 <- data.frame(x1 = 1:7,                                          x2 = letters[1:7],                    x3 = "y")data1 data2 <- data.frame(x1 = 2:7,                                        x2 = letters[2:7],                   x3 = c("x", "x", "y", "y" , "x", "y"))data2   common_rows2 <- inner_join(data1, data2)          common_rows2
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
Java Program to Find the Sum of First N Odd & Even Numbers - GeeksforGeeks

16 Nov, 2020
When any number which ends with 0,2,4,6,8 is divided by 2 that is an even number. And when any number ends with 1,3,5,7,9 is not divided by two is an odd number.
Example:
Input : 8
Output: Sum of First 8 Even numbers = 72
        Sum of First 8 Odd numbers = 64

Approach #1: Iterative
Create two variables evenSum and oddSum and initialize them by 0.Start For loop from 1 to 2*n.If i is even Add i with evenSum.Else add i with oddSum.Print evenSum and oddSum at the end of loop.
Create two variables evenSum and oddSum and initialize them by 0.
Start For loop from 1 to 2*n.
If i is even Add i with evenSum.
Else add i with oddSum.
Print evenSum and oddSum at the end of loop.
Below is the implementation of the Java program:
Java
// Calculate the Sum of First N Odd & Even Numbers in Javaimport java.io.*;  public class GFG {      // Driver function    public static void main(String[] args)    {        int n = 8;        int evenSum = 0;        int oddSum = 0;          for (int i = 1; i <= 2 * n; i++) {            // check even & odd using Bitwise AND operator            if ((i & 1) == 0)                evenSum += i;            else                oddSum += i;        }        // Sum of even numbers less then 17        System.out.println("Sum of First " + n                           + " Even numbers = " + evenSum);          // sum of odd numbers less then 17        System.out.println("Sum of First " + n                           + " Odd numbers = " + oddSum);    }}
Sum of First 8 Even numbers = 72
Sum of First 8 Odd numbers = 64


Time Complexity: O(N), where N is the number of First N even/odd numbers.
Method 2: Using AP Formulas.
Sum of First N Even Numbers = n * (n+1)
Sum of First N Odd Numbers = n * n
Below is the implementation of the above approach:
Java
// Calculate the Sum of First N Odd & Even Numbers in Javaimport java.io.*;  public class GFG {      // Function to find the sum of even numbers    static int sumOfEvenNums(int n) { return n * (n + 1); }      // Function to find the sum of odd numbers.    static int sumOfOddNums(int n) { return n * n; }      // Driver function    public static void main(String[] args)    {        int n = 10;        int evenSum = sumOfEvenNums(n);        int oddSum = sumOfOddNums(n);          // Sum of even numbers        System.out.println("Sum of First " + n                           + " Even numbers = " + evenSum);          // sum of odd numbers        System.out.println("Sum of First " + n                           + " Odd numbers = " + oddSum);    }}
Sum of First 10 Even numbers = 110
Sum of First 10 Odd numbers = 100


Time Complexity: O(1)
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
A program to check if a binary tree is BST or not in C ?

A binary tree is a tree data structure in which there are two child nodes for each node. The child nodes being two are referred as, left and right child.
A BST is a tree structure in which left subtree contains nodes with values lesser than root and right subtree contains nodes with values greater that root.
Here, we will check if a binary tree is a BST or not −
To check for this we have to check for the BST condition on the binary tree. For a root node check for left child should be less that root, right child should be greater that root for all nodes of the tree in which the child's exist.
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class node {
   public:
      int data;
   node* left;
   node* right;
   node(int data) {
      this->data = data;
      this->left = NULL;
      this->right = NULL;
   }
};
int isBSTUtil(node* node, int min, int max);
int isBST(node* node) {
   return(isBSTUtil(node, INT_MIN, INT_MAX));
}
int isBSTUtil(node* node, int min, int max) {
   if (node==NULL)
      return 1;
   if (node->data < min || node->data > max)
      return 0;
   return
      isBSTUtil(node->left, min, node->data-1) && isBSTUtil(node->right, node->data+1, max);
}
int main() {
   node *root = new node(8);
   root->left = new node(3);
   root->right = new node(10);
   root->left->left = new node(1);
   root->left->right = new node(6);
   if(isBST(root))
      cout<<"The given tree is a BST";
   else
      cout<<"The given tree is Not a BST";
   return 0;
}
The given tree is a BST
Code Explained
The above code check for a BST. The main method, creates a tree and call the isBST() method. This method checks if the left and right child follow the BST rule also that the subtrees formed are BST’s too by using the isBSTuntil()
method.
Tryit Editor v3.7

Tryit: Center with flexbox
Python | Pandas Series.ge() - GeeksforGeeks

03 Jan, 2020
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.
Pandas series.ge() is used to compare every element of Caller series with passed series. It returns True for every element which is Greater than or Equal to the element in passed series.
Note: The results are returned on the basis of comparison caller series >= other series.
Syntax: Series.ge(other, level=None, fill_value=None, axis=0)
Parameters:other: other series to be compared withlevel: int or name of level in case of multi levelfill_value: Value to be replaced instead of NaNaxis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns.
Return type: Boolean series
Example #1: NaN handling
In this example, two series are created using pd.Series(). The series contains some Null values and some equal values at same indices too. The series are compared using .ge() method and 7 is passed to fill_value parameter to replace NaN values by 7.
# importing pandas module  import pandas as pd      # importing numpy module import numpy as np     # creating series 1 series1 = pd.Series([70, 0, 2, 225, 1, 16, np.nan, 10, np.nan])     # creating series 2 series2 = pd.Series([27, np.nan, 2, 23, 5, 95, 4, 3, 19])   # NaN replacementreplace_nan = 7  # calling and returning to result variableresult = series1.ge(series2, fill_value = replace_nan)  # display result 
Output:As shown in output, True was returned wherever value in caller series was Greater than or Equal value in passed series. Also it can be seen Null values were replaced by 7 and the comparison was made using that value.
 Example #2: Calling on Series with str objects
In this example, two series are created using pd.Series(). The series contains some string values too. In case of strings, the comparison is made with their ASCII values.
# importing pandas module  import pandas as pd      # importing numpy module import numpy as np     # creating series 1 series1 = pd.Series(['A', 0, 'c', 43, 9, 'e', np.nan, 'x', np.nan])     # creating series 2 series2 = pd.Series(['v', np.nan, 'c', 23, 5, 'D', 54, 'p', 19])   # NaN replacementreplace_nan = 14  # calling and returning to result variableresult = series1.ge(series2, fill_value = replace_nan)  # display result 
Output:As it can be seen in output, in case of strings, the comparison was made using their ASCII values.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
Python PIL | ImagePath.Path.tolist() method - GeeksforGeeks

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImagePath module is used to store and manipulate 2-dimensional vector data. Path objects can be passed to the methods on the ImageDraw module.
ImagePath.Path.tolist() Converts the path to a Python list [(x, y), ...].
Syntax: PIL.ImagePath.Path.tolist(flat=0)
Parameters:
flat – By default, this function returns a list of 2-tuples [(x, y), ...]. If this argument is True, it returns a flat list [x, y, ...] instead.
Returns: A list of coordinates.
     # from PIL importing ImagePathfrom PIL import ImagePath  # creating a list to mapgetbox = list(zip(range(3, 41, 1), range(11, 22, 2)))result = ImagePath.Path(getbox)  # using tolist functiona = result.tolist()print(getbox)print(a)
Output:
[(3, 11), (4, 13), (5, 15), (6, 17), (7, 19), (8, 21)][(3.0, 11.0), (4.0, 13.0), (5.0, 15.0), (6.0, 17.0), (7.0, 19.0), (8.0, 21.0)]
Another Example: changing parameters.
     # from PIL importing ImagePathfrom PIL import ImagePath  # creating a list to mapgetbox = list(zip(range(5, 51, 16), range(15, 22, 4)))result = ImagePath.Path(getbox)  # using tolist functiona = result.tolist()print(getbox)print(a)
Output:
[(5, 15), (21, 19)][(5.0, 15.0), (21.0, 19.0)]
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Series AP | Practice | GeeksforGeeks

Given the first 2 terms A1 and A2 of an Arithmetic Series.Find the Nth term of the series. 
Example 1:
Input:
A1=2
A2=3
N=4
Output:
5
Explanation:
The series is 2,3,4,5,6....
Thus,4th term is 5.
Example 2:
Input:
A1=1
A2=2
N=10
Output:
10
Explanation:
The series is1,2,3,4,5,6,7,8,9,10,11..
Thus,10th term is 10.

Your Task:
You don't need to read input or print anything.Your Task is to complete the function nthTermOfAP() which takes three integers A1,A2 and N as input parameters and returns the nth term of the AP that has A1 and A2 as the first and second terms respectively.

Expected Time Complexity:O(1)
Expected Auxillary Space:O(1)

Constraints:
-104<=A1,A2<=104
1<=N<=103
 
0
sumittripathi12 days ago
class Solution {   int nthTermOfAP(int A1, int A2, int N) {       // code here       int d=A2-A1;       int res=A1+(N-1)*d;       return res;   }}
0
rsbly7300951 week ago
class Solution{
    nthTermOfAP(A1, A2, N){
        return A1 + (( N - 1 )* (A2 - A1));
    }
}
0
mohdraza1 week ago
  return A1+((N-1)*(A2-A1));
0
avijit1126be203 weeks ago
class Solution {   int nthTermOfAP(int A1, int A2, int N) {       // code here       int count = N;       int val = A1;       while(N!=1)       {           val += A2-A1;           N--;       }       return val;   }}
0
samnerad4 weeks ago
C++ solution:
int nthTermOfAP(int A1, int A2, int N) {   return A1+(N-1)*(A2-A1);
}
0
agrawalshriyadiya1 month ago
c++ code solution -
 
int nthTermOfAP(int A1, int A2, int N) {       // code here       int d=A2-A1;       int res=A1+(N-1)*d;       return res;   }
+1
asifsaba5811 month ago
class Solution {
  public:
    int nthTermOfAP(int A1, int A2, int N) {
        
        
        return A1+(N-1)*(A2-A1);
    }
};
0
gayatri80771 month ago
c++ solution 
 
class Solution { public:   int nthTermOfAP(int A1, int A2, int N) {       // code here       int d = A2-A1;       int nth = A1+(N-1)*d;        return nth;          }};
0
0niharika22 months ago
return A1 + (N-1)*(A2 - A1);
-1
shreyanshikunda3 months ago
PYTHON SOLUTION
 def nthTermOfAP(self,A1,A2,N):       D=A2-A1       AP= A1+(N-1)*D       return AP
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Flat a JavaScript array of objects into an object

To flat a JavaScript array of objects into an object, we created a function that takes array of object as
only argument. It returns a flattened object with key append by its index. The time complexity is O(mn)
where n is the size of array and m is the number of properties in each object. However, its space
complexity is O(n) where n is the size of actual array.
//code to flatten array of objects into an object
//example array of objects
const notes = [{
   title: 'Hello world',
   id: 1
}, {
   title: 'Grab a coffee',
   id: 2
}, {
   title: 'Start coding',
   id: 3
}, {
   title: 'Have lunch',
   id: 4
}, {
   title: 'Have dinner',
   id: 5
}, {
   title: 'Go to bed',
   id: 6
}, ];
const returnFlattenObject = (arr) => {
   const flatObject = {};
   for(let i=0; i<arr.length; i++){
      for(const property in arr[i]){
         flatObject[`${property}_${i}`] = arr[i][property];
      }
   };
   return flatObject;
}
console.log(returnFlattenObject(notes));
Following is the output in console −
[object Object] {
   id_0: 1,
   id_1: 2,
   id_2: 3,
   id_3: 4,
   id_4: 5,
   id_5: 6,
   title_0: "Hello world",
   title_1: "Grab a coffee",
   title_2: "Start coding",
   title_3: "Have lunch",
   title_4: "Have dinner",
   title_5: "Go to bed"
}
Product of all the elements in an array divisible by a given number K in C++

Given an array arr[n] with n number of integers and another integer k, the task is to find the product all the elements of arr[] which are divisible by k.
To solve the problem we have to iterate every element of the array and find whether it is completely divisible by the number k and then product all the elements and store it into a variable. Like we have an array arr[] = {1, 2, 3, 4, 5, 6 } and assuming we have k = 2 so the numbers in the array which are divisible by 2 are 2, 4, 6 and their product will be equal to 48.
So, let's see the example how we want our answers as per the input
Input 
arr[] = {10, 11, 55, 2, 6, 7}
K = 11
Output 
605
Explanation − the numbers divisible by 11 are 11 and 55 only their product is 605
Input 
arr[] = {9, 8, 7, 6, 3}
K = 3
Output 
162
Iterate the whole array till the very end of an array.
Iterate the whole array till the very end of an array.
Look for every integer which is divisible by K.
Look for every integer which is divisible by K.
Product every element divisible by K.
Product every element divisible by K.
Return the product.
Return the product.
Print the result.
Print the result.
Start
Step 1→ declare function to find all the numbers divisible by number K
   int product(int arr[], int size, int k)
      declare int prod = 1
      Loop For int i = 0 and i < size and i++
      IF (arr[i] % k == 0)
         Set prod *= arr[i]
      End
      End
      return prod
Step 2→ In main()
   Declare int arr[] = {2, 3, 4, 5, 6 }
   Declare int size = sizeof(arr) / sizeof(arr[0])
   Set int k = 2
   Call product(arr, size, k)
Stop
 Live Demo
#include <iostream>
using namespace std;
//function to find elements in an array divisible by k
int product(int arr[], int size, int k){
   int prod = 1;
   for (int i = 0; i < size; i++){
      if (arr[i] % k == 0){
         prod *= arr[i];
      }
   }
   return prod;
}
int main(){
   int arr[] = {2, 3, 4, 5, 6 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int k = 2;
   cout<<"product of elements are : "<<product(arr, size, k);
   return 0;
}
If run the above code it will generate the following output −
product of elements are : 48
SQL Tryit Editor v1.6

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.