code-rag-bench/online-tutorials huggingface dataset:
Comparing two data sets in R

13 Jan, 2022
There may be a situation where we have to compare datasets to do data analysis, with having the same structure but differences in the data. So to identify what is changed in the dataset and to get a summary to which extent it is changed. We can use the compare package in R. We can easily use this package to compare two data frames and check out the summary of what extent it is changed.
The function comparedf() is used to compare two dataframes in R. The function takes two dataframes and then check them for comparison. 
Syntax: comparedf(dataset1,dataset2)
Parameters:
dataset1, dataset2: These are the two datasets to be compared.
Also, we can see the summary of the difference as:
Syntax:
summary(comparedf(dat,dat2)
Approach:
Import library
We have to simply create datasets.
Pass the dataset as a parameter in the comparedf() function.
It will detect the difference if any.
Use the summary method to check the complete summary.
Example1 :
R
library(arsenal)  dat <- data.frame(SSN = c(23,434,565,878,231), Name=c("hamburgers","butter","cheeze","coffee","teacher"), Age = c(7,8,6,43,56), Gender = c(0,1,0,1,0)) dat2 <- data.frame(SSN = c(210,345,456,745,245), Name=c("fruits","cupcakes","mangoes","toffee","student"), Number= c(3,5,5,6,77), Different = c(0,0,1,1,0)) summary(comparedf(dat,dat2))
Output: 
Example 2:
R
library(arsenal)  dat <- data.frame(Rollnumber = c(1,2,3,4,5), Name=c("Akash","John","Tina","Kakashi","Brad"), Age = c(7,8,6,5,7), Marks = c(78,98,76,67,89)) dat2 <- data.frame(Rollnumber = c(1,2,3,4,5), Name=c("Akash","John","Tina","Kakashi","Brad"), Age = c(7,9,6,7,8), Marks= c(78,98,56,87,67)) comparedf(dat,dat2)
Output:
rkbhola5
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Joining of Dataframes in R Programming
Control Statements in R Programming
How to import an Excel File into R ?
How to change Colors in ggplot2 Line Plot in R ?
Normal Distribution in R
HTML <label> Tag

16 May, 2022
The <label> tag in HTML is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the <label> element, it toggles the control. The <label> tag defines the label for <button>, <input>, <meter>, <output>, <progress>, <select>, or <textarea> element.
The <label> tag can be used in two ways: 
Firstly, use <label> tag by providing the <input> and id attribute. The <label> tag needs a for attribute whose value is the same as input id.
Alternatively, <input> tag use directly inside the <label> tag. In this case, the for and id attributes are not needed because the association is implicit.
Syntax:  
<label> form content... </label>
Attribute Value: 
for: It refers to the input control that this label is for. Its value must be the same as the value of the input control’s “id” attribute.
form: It refers to the form to which the label belongs to.
Example 1: Here we will use the input tag outside the label tag. 
html
<!DOCTYPE html><html>  <body>      <h1>GeeksforGeeks</h1>    <strong>HTML label Tag</strong>      <form>          <!-- Starts label tags from here -->        <label for="student">                Student        </label>        <input type="radio" name="Occupation"               id="student" value="student"><br>          <label for="business">                Business        </label>        <input type="radio" name="Occupation"               id="business" value="business"><br>          <label for="other">                Other        </label>        <!-- Ends label tags here -->          <input type="radio" name="Occupation"                id="other" value="other">    </form></body>  </html>
Output: 
Example 2: Here we will use the input tag inside the level tag.
html
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>      <strong>HTML label Tag </strong>      <form>      <!-- label tag starts from here -->      <label>        Male        <input type="radio" name="gender"                id="male" value="male" />      </label><br/>        <label>        Female        <input type="radio" name="gender"                id="female" value="female" />       </label><br/>        <label>        Other        <input type="radio" name="gender"                id="other" value="other" />      </label>      <!-- label tag ends from here -->    </form>  </body></html>
Output: 
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ghoshsuman0129
satviksingh600
HTML-Tags
Picked
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to change the font-color of disabled input using CSS ?

08 Aug, 2021
In this article, we are going to learn how to change the font-color of disabled input. There is a method to solve this problem, which is discussed below:
Approach: With adding basic CSS property we are able to change the font-color of a disabled input. The disabled input element is unusable and un-clickable. This is a boolean attribute. Here using the color property of input we can change the font-color of this disabled input element.Below is the Syntax and implementation of the above approach:
Syntax:HTML:
<input disabled>
CSS:
input:disabled {
    color: black;
}

Example:
<!DOCTYPE html><html>  <head>    <title>        How to change font-color for        disabled input using CSS?    </title>      <style>        input {              /*it makes grey background and             white font-color of a input*/            background: grey;            color: white;        }              input:disabled {            /*css declaration to make             font-color of disable input            black*/            color: black;        }    </style></head>  <body>    <form>        Enable Input : <input value="Enabled"><br>          <!-- Disabled this input using            attribute: disable -->        Disable Input: <input value="Disabled"                    disabled><br>    </form></body>  </html>
Output:
Explanations: First input element is enabled and the second input element is disabled. Using CSS properties we have an initialized background of all input elements as grey and font-color as white. We have to change white font-color of the disabled input to any color.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
How to select all child elements recursively using CSS?
CSS | :not(:last-child):after Selector
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Shell Script to Display Name & Size of a File Whose Size is Greater than 1000 Bytes

20 Apr, 2021
We must have in situations at least once where we need to list files for their particular size maybe in bytes, kilobytes and so on, there comes a need to minimize tedious task to save time and focus on the required things. So we need certain tools or scripts to do this for us, here’s where Linux and shell scripting really shines. It’s very easy to make portable shell scripts in Linux. We can make use of some command-line utilities and tools to make it very efficient and easy.  
Here, we need to list out files with sizes greater than 1000 bytes. Tools and utilities like find, stat, etc can be used to locate and filter files and file systems with much control and functionality. We need to surely embed this tools in a shell script along with some basic conditional  and loop statements to make it more programmatic and efficient.
The approach of this script is quite important because that’s the real logic part that goes in the build is quite syntactical and theoretical. So we need to print files with a size limit. For that we need to iterate or loop over the path or directory specified to look for files, We can make use of command called find to traverse through the input path. Now for checking file sizes we need to make use of a command called stat to store the size of files in the required format(in this case bytes). After that a conditional statement (if block) to check whether the file matches the required conditions, in this case, it should exceed 1000.
Below is the implementation:
#!/bin/bash
read -p "Enter path : " -r filep
echo " file path   -   size "
for i in $(find "$filep" -depth);
do
        size=$(stat -c%s "$i")
        if [ $size -gt 1000 ]
        then
                echo $i " - " $size
        fi
done  
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
Python | Remove elements of list that are repeated less than k times

15 Apr, 2019
Given a list of integers (elements may be repeated), write a Python program to remove the elements that are repeated less than k times.
Examples:
Input : lst = ['a', 'a', 'a', 'b', 'b', 'c'], k = 2
Output : ['a', 'a', 'a', 'b', 'b']

Input : lst = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4], k = 3
Output : [1, 1, 1, 1, 3, 3, 3]

Approach #1 : Pythonic naive
Counter() from collections module construct a dictionary mapping values to counts and save them in ‘counted’. Then we make use of ‘temp_lst’ to store the elements that need to be removed. Finally, we traverse through the given list and append all elements that are not in ‘temp_lst’ to ‘res_lst’ containing the required output.
# Python3 program to Remove elements of # list that repeated less than k timesfrom collections import Counter  def removeElements(lst, k):    counted = Counter(lst)          temp_lst = []    for el in counted:        if counted[el] < k:            temp_lst.append(el)                  res_lst = []    for el in lst:        if el not in temp_lst:            res_lst.append(el)                  return(res_lst)      # Driver codelst = ['a', 'a', 'a', 'b', 'b', 'c']k = 2print(removeElements(lst, k))
['a', 'a', 'a', 'b', 'b']

Approach #2 : Efficient Approach
The efficient approach to use Counter method is to construct a dictionary mapping value to counts and then use a list comprehension to filter for counts larger than a specified value. This approach is both time and space efficient.
# Python3 program to Remove elements of # list that repeated less than k timesfrom collections import Counter  def removeElements(lst, k):    counted = Counter(lst)    return [el for el in lst if counted[el] >= k]      # Driver codelst = ['a', 'a', 'a', 'b', 'b', 'c']k = 2print(removeElements(lst, k))
['a', 'a', 'a', 'b', 'b']

Marketing
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – Cursor

01 May, 2021
A Cursor in PostgreSQL is used to process large tables. Suppose if a table has 10 million or billion rows. While performing a SELECT operation on the table it will take some time to process the result and most likely give an “out of memory” error and the program will be terminated.
A Cursor can only be declared inside a transaction. The cursor does not calculate the data but only prepares the query so that your data can be created when FETCH is called. In the end, simply commit the transaction.
Syntax:
DECLARE 
    [cursor_name] CURSOR FOR [query]
Let’s analyze the above syntax:
Use DECLARE to declare a cursor
[cursor_name] – Give any name to the cursor
[query] – Give a query to the cursor
After declaring a cursor, we can get the data using FETCH. The FETCH gets the next row(s) from the cursor. If no row found, then it returns NULL.
Syntax:
FETCH [direction (rows)] FROM [cursor_name];

where direction can be empty,
number of rows you want or one of the following:

NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count
ALL
FORWARD
FORWARD count
FORWARD ALL
BACKWARD
BACKWARD count
BACKWARD ALL
Lets, create a sample table using the below commands for examples:
CREATE TABLE students (
   student_id serial PRIMARY KEY,
   full_name VARCHAR NOT NULL,
   branch_id INT
);
Insert data into students table as follows:
INSERT INTO students (
    student_id,
    full_name,
    branch_id
)
VALUES
    (1, 'M.S Dhoni', NULL),
    (2, 'Sachin Tendulkar', 1),
    (3, 'R. Sharma', 1),
    (4, 'S. Raina', 1),
    (5, 'B. Kumar', 1),
    (6, 'Y. Singh', 2),
    (7, 'Virender Sehwag ', 2),
    (8, 'Ajinkya Rahane', 2),
    (9, 'Shikhar Dhawan', 2),
    (10, 'Mohammed Shami', 3),
    (11, 'Shreyas Iyer', 3),
    (12, 'Mayank Agarwal', 3),
    (13, 'K. L. Rahul', 3),
    (14, 'Hardik Pandya', 4),
    (15, 'Dinesh Karthik', 4),
    (16, 'Jasprit Bumrah', 7),
    (17, 'Kuldeep Yadav', 7),
    (18, 'Yuzvendra Chahal', 8),
    (19, 'Rishabh Pant', 8),
    (20, 'Sanju Samson', 8);
Now that the table is ready we can declare our cursor.
BEGIN;

DECLARE 
    my_cursor CURSOR FOR SELECT * FROM students;
Fetch the data.
FETCH 10 FROM my_cursor;
Output:
FETCH PRIOR FROM my_cursor;
FETCH PRIOR FROM my_cursor;
The above query will give you row 9 and 8 since right now our cursor is at 10;
FETCH 6 FROM my_cursor;
Output:
COMMIT;
Commit the transaction at the end.
Picked
postgreSQL-administration
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 - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - SELECT
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
strconv package in Golang

28 Jul, 2020
Go language provides a strconv package that implements conversions to and from string representations of basic data types. To access the functions of the strconv package you need to import the strconv package in your program with the help of the import keyword.
Example 1:
// Golang program to illustrate the // strconv.AppendQuoteRuneToASCII() functionpackage main  import (    "fmt"    "strconv")  func main() {           // Converting Unicode characters to          // ASCII strings resulting from "single quotes"         // append the result to the end of the given []byte         // Using AppendQuoteRuneToASCII() function         num := []byte("Rune : ")         num = strconv.AppendQuoteRuneToASCII(num, 'c')         fmt.Println(string(num))  }
Output:
Rune : 'c'
Example 2 :
// Golang program to illustrate // strconv.Atoi() function package main    import (     "fmt"    "strconv")    func main() {        // Using Atoi() function     a := "244"    b, e := strconv.Atoi(a)     if e == nil {         fmt.Printf("%T \n %v", b, b)     }    } 
Output:
int 
 244

Golang-strconv
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Time Durations in Golang
Constants- Go Language
Loops in Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
Setting MySQL Environment Variables on Linux

Let us understand how to set environment variables on Linux for MySQL −
Environment variables can be set at the command prompt. This is done to affect the current invocation of the command processor, or to permanently set to affect the future invocations.
To set a variable permanently, it can be set in a startup file or with the help of the interface provided by the system for the same purpose. The documentation of the command interpreter needs to be consulted for specific details. To specify a value for an environment variable, the syntax relevant for the command processor needs to be used.
Let us take an example −
The syntax on Unix depends on the user’s shell. If a TCP/IP port number needs to be specified with the help of the MYSQL_TCP_PORT variable, syntax could be for sh, ksh, bash, zsh, and so on. Below is an example −
MYSQL_TCP_PORT=3306
export MYSQL_TCP_PORT
The first command will set the variable. The export command will export the variable to the shell environment so that its value can be accessed by MySQL and other processes.
For csh and tcsh, use setenv to make the shell variable available to the environment, the below syntax can be used −
setenv MYSQL_TCP_PORT 3306
The command to set environment variables can be executed at the command prompt which will take effect immediately, but the settings will last as long as the user is logged in. Once they log out, the changes are lost.
On Unix, typical shell startup files are .bashrc or .bash_profile for bash, or .tcshrc for tcsh. If the MySQL programs are installed in /usr/local/mysql/bin and the user wishes to make it easy to invoke these programs, the value of the PATH environment variable can be set to include that directory.
If the user’s shell is bash, the below line can be added to the .bashrc file −
PATH=${PATH}:/usr/local/mysql/bin
‘bash’ uses different startup files for login and nonlogin shells, so it might be important to add the setting to .bashrc for login shells and to .bash_profile for nonlogin shells to ensure that the PATH is set irrespective of this setting.
If the shell is tcsh, the below line can be added to the .tcshrc file −
setenv PATH ${PATH}:/usr/local/mysql/bin
Program to merge strings alternately using Python

Suppose we have two strings s and t. We have to merge them by adding letters in alternating fashion, starting from s. If s and t are not of same length, add the extra letters onto the end of the merged string.
So, if the input is like s = "major" t = "general", then the output will be "mgaejnoerral", as t is larger than s, so we have added extra part "ral" at the end.
To solve this, we will follow these steps −
i := j := 0
i := j := 0
result := blank string
result := blank string
while i < size of s and j < size of t, doresult := result concatenate s[i] concatenate t[j]i := i + 1j := j + 1
while i < size of s and j < size of t, do
result := result concatenate s[i] concatenate t[j]
result := result concatenate s[i] concatenate t[j]
i := i + 1
i := i + 1
j := j + 1
j := j + 1
while i < size of s, doresult := result concatenate s[i]i := i + 1
while i < size of s, do
result := result concatenate s[i]
result := result concatenate s[i]
i := i + 1
i := i + 1
while j < size of t , doresult := result concatenate t[j]j := j + 1
while j < size of t , do
result := result concatenate t[j]
result := result concatenate t[j]
j := j + 1
j := j + 1
return result
return result
Let us see the following implementation to get better understanding −
 Live Demo
def solve(s, t):
   i = j = 0
   result = ""
   while i < len(s) and j < len(t):
      result += s[i] + t[j]
      i+=1
      j+=1
   while i < len(s):
      result += s[i]
      i += 1
   while j < len(t):
      result += t[j]
      j += 1
   return result
s = "major"
t = "general"
print(solve(s, t))
"major", "general"
mgaejnoerral
How to print all the values of a dictionary in Python?

Dictionary object possesses values() method which does this job for us.
>>> D1 = {1:'a', 2:'b', 3:'c'}
>>> D1.values()
dict_values(['a', 'b', 'c'])
>>> list(D1.values())
['a', 'b', 'c']
You can also get corresponding value by iterating through lidt of keys returned by keys() method of dictionary
>>> L1 = list(D1.keys())
>>> for i in L1:
   print (i)
a
b
c
Node.js unshift() function - GeeksforGeeks

14 Oct, 2021
unshift() is an array function from Node.js that is used to insert element to the front of an array.
Syntax:
    
array_name.unshift(element)

Parameter: This function takes parameter that has to be added to the array. It can take multiple elements also as parameter.
Return type: The function returns the array after adding the element.
The program below demonstrates the working of the function:
Program 1:
function unshiftDemo(){  var element = arr.unshift(12);  console.log(arr);}var arr=[1, 5, 7, 9, 78];unshiftDemo();
Output:
[12,1,5,7,9,78]
Program 2:
function addLang(){  var element = arr.unshift("Node.js","php");  console.log(arr);}var arr=[ "C", "Java", "JavaScript", "Python" ];addLang();
Output:
[ 'Node.js', 'php', 'C', 'Java', 'JavaScript', 'Python' ]
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Sort an array of pairs using Java Pair and Comparator - GeeksforGeeks

02 Mar, 2022
Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair.Examples: 
Input: [(1, 2), (3, 5), (2, 6), (1, 7)]
Output: [(1, 2), (3, 5), (2, 6), (1, 7)]

Input: [(10, 20), (20, 30), (5, 6), (2, 5)]
Output: [(2, 5), (5, 6), (10, 20), (20, 30)]
Approach:  
Store the pairs in an array using a user-defined Pair class.
Override the comparator method to sort the array according to the first element.
Sort the array according to the first element.
Below is the implementation of the above approach:
Java
// Java code to sort the array// according to second elementimport java.io.*;import java.util.*; // User defined Pair classclass Pair {    int x;    int y;     // Constructorpublic Pair(int x, int y)    {        this.x = x;        this.y = y;    }} // class to define user defined conparatorclass Compare {     static void compare(Pair arr[], int n)    {        // Comparator to sort the pair according to second element        Arrays.sort(arr, new Comparator<Pair>() {            @Override public int compare(Pair p1, Pair p2)            {                return p1.y - p2.y; // To compare the first element just                                      //change the variable from p1.y - p2.y to x.            }        });         for (int i = 0; i < n; i++) {            System.out.print(arr[i].x + " " + arr[i].y + " ");        }        System.out.println();    }} // Driver classclass GFG {     // Driver codepublic static void main(String[] args)    {        Scanner sc = new Scanner(System.in);         // length of array        int n = 5;         // Array of Pair        Pair arr[] = new Pair[n];         arr[0] = new Pair(10, 20);        arr[1] = new Pair(1, 2);        arr[2] = new Pair(3, 1);        arr[3] = new Pair(10, 8);        arr[4] = new Pair(4, 3);         Compare obj = new Compare();         obj.compare(arr, n);    }}
3 1 1 2 4 3 10 8 10 20
 
ashutosh44
sweetyty
Java-Array-Programs
Java-Arrays
Arrays
Java
Java Programs
Sorting
Arrays
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
HashMap in Java with Examples
Lodash _.maxBy() Method - GeeksforGeeks

02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.maxBy() method is used to compute the maximum value from the original array by iterating over each element in the array using the Iteratee function. It is almost the same as _.max() function.
Syntax:
_.maxBy( array, [iteratee = _.identity] )

Parameters: This method accepts two parameters as mentioned above and described below:
array: It is the array that the method iterates over to get the maximum element.
iteratee: It is the function that is invoked for every element in the array.
Return Value: This method returns the maximum element.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }];    // Use of _.maxBy() method let max_obj = _.maxBy(arr, function(o) { return o.n; });         // Printing the output  console.log(max_obj);
Output:
{ 'n': 6 }

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Original array var arr = [{ 'n': 10 }, { 'n': 5 },            { 'n': 3 }, { 'n': 12 }];    // Use of _.maxBy() method let max_obj = _.maxBy(arr, 'n');         // Printing the output  console.log(max_obj);
Output:
{ 'n': 12 }

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js process.pid Property

12 Oct, 2021
The process.pid property is an inbuilt application programming interface of the process module which is used to get the PID of the process.
Syntax:
process.pid
Return Value: This property returns an integer value specifying the PID of the process.
Below examples illustrate the use of process.pid property in Node.js:
Example:
// Node.js program to demonstrate the// process.pid Property   // Include process moduleconst process = require('process');  // Printing process.pid property valueconsole.log("process id is " + process.pid);
Output:
process id is 11436
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/process.html#process_process_pid
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.get_duplicates()

17 Dec, 2018
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 Index.get_duplicates() function extract duplicated index elements. This function returns a sorted list of index elements which appear more than once in the Index.
Syntax: Index.get_duplicates()
Returns : List of duplicated indexes.
Example #1: Use Index.get_duplicates() function to find all the duplicate values in the Index.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador',                    'Lhasa', 'Husky', 'Beagle'])  # Print the Indexidx
Output :
let’s find out all the duplicate values in the Index.
# print the duplicated values.idx.get_duplicates()
Output :As we can see in the output, the Index.get_duplicates() function has returned all the values which are having more than one occurrence in the Index. Example #2: Use Index.get_duplicates() function to find all the duplicate in the Index. The Index also contains NaN values.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', None, 'Labrador',             'Lhasa', 'Husky', 'Beagle', None, 'Koala'])  # Print the Indexidx
Output :As we can see in the output we are having some missing values. Lets see how the Index.get_duplicates() function treats them.
# print the duplicate values in Indexidx.get_duplicates()
Output :The occurrence of missing values more than once has been treated as duplicates.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to clamp floating numbers in Python?

Clamp function limits a value to a given range. Python doesn't have such a function in built. You can create this function like
def clamp(num, min_value, max_value):
   return max(min(num, max_value), min_value)
print(clamp(5, 1, 20))
print(clamp(1, 10, 20))
print(clamp(20, 1, 10))
This will give the output
5
10
10
Execute a String of Code in Python

04 May, 2022
Given few lines of code inside a string variable and execute the code inside the string. Examples:  
Input:
code = """ a = 6+5
           print(a)"""
Output:
11
Explanation:
Mind it that "code" is a variable and
not python code. It contains another code, 
which we need to execute.

Input:
code = """ def factorial(num):
               for i in range(1,num+1):
                   fact = fact*i
               return fact
           print(factorial(5))"""
Output:
120
Explanation:
On executing the program containing the 
variable in Python we must get the result 
after executing the content of the variable.
Here we use the exec() function to solve the code contained inside a variable. exec() function is used for the dynamic execution of Python code. It can take a block of code containing Python statements like loops, class, function/method definitions and even try/except block. This function doesn’t return anything. The code below solves the problem and explains the exec() function.  
Python3
# Python program to illustrate use of exec to# execute a given code as string. # function illustrating how exec() functions.def exec_code():    LOC = """def factorial(num):    fact=1    for i in range(1,num+1):        fact = fact*i    return factprint(factorial(5))"""    exec(LOC)     # Driver Codeexec_code()
Output:  
120
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
simranarora5sos
surinderdawra388
Python string-programs
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
HTML | <audio> autoplay Attribute

28 Jun, 2019
The HTML <audio> autoplay attribute is used to specify that the audio should automatically start playing as soon as it is loaded. It is a Boolean attribute.
Syntax:
<audio autoplay>
Below example illustrates the <audio> autoplay attribute in HTML:
Example:
<!DOCTYPE html> <html>   <head>     <title>         HTML audio autoplay Attribute    </title> </head>   <body style="text-align: center">       <h1 style="color: green">         GeeksforGeeks     </h1>           <h2>HTML audio autoplay Attribute</h2>       <audio controls autoplay>         <source src="GFG.ogg" type="audio/ogg">         <source src="GFG.mp3" type="audio/mpeg">     </audio> </body>   </html>                    
Output:
Supported Browsers: The browser supported by HTML audio autoplay attribute are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 4.0
Opera 10.5
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to change the position of legend using Plotly Python?

28 Nov, 2021
In this article, we will discuss how to change the position of the legend in Plotly using Python.
The legend appears by default when variation in one object has to be depicted with reference to the other. Legend makes it easier to read a graph since it contains descriptions for the color code or keys used. By default, the legend appears on the top right corner of the plot but outside of it, but it is possible to position them as per requirement. Let us first create a regular plot so that the difference can be apparent.
Dataset Used: Click here
Example: Regular plot
Python3
# import librariesimport plotly.express as pximport pandas as pd  # read datasetdata = pd.read_csv("bestsellers.csv")  fig = px.scatter(data, x="Year", y="Price", color="Genre")  fig.show()
Output:
To position the legend we use the update_layout function with legend set to a dictionary that describes the attributes of a legend. anchor keys set position and x and y accommodate the margin with respect to axis.  
Syntax:
update_layout(legend=dict(yanchor, y, xanchor, x))
By setting appropriate values to the above parameters the required task can be achieved.
Python3
# import the modulesimport plotly.express as pximport pandas as pd  # read the datadata = pd.read_csv("bestsellers.csv")  # scatter plotfig = px.scatter(data, x="Year", y="Price", color="Genre")fig.update_layout(legend=dict(y=0.5))fig.show()
Output:
Python3
# import the modulesimport plotly.express as pximport pandas as pd  # read the datasetdata = pd.read_csv("bestsellers.csv")  # scatter plotfig = px.scatter(data, x="Year", y="Price", color="Genre")# layoutfig.update_layout(legend=dict(yanchor="top", y=0.9, xanchor="left", x=0.4))fig.show()
Output:
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | imagecopy() Function

23 Aug, 2019
The imagecopy() function is an inbuilt function in PHP which is used to copy the image or part of image. This function returns true on success or false on failure.
Syntax:
bool imagecopy ( $dst_image, $src_image, $dst_x, $dst_y, $src_x, 
$src_y, $src_w, $src_h )
Parameters: This function accepts eight parameters as mentioned above and described below:
$dst_image: This parameter is used to set destination image link resource.
$src_image: This parameter is used to set source image link resource.
$dst_x: This parameter is used to set x-coordinate of destination point.
$dst_y: This parameter is used to set y-coordinate of destination point.
$src_x: This parameter is used to set x-coordinate of source point.
$src_y: This parameter is used to set x-coordinate of source point.
$src_w: This parameter is used to set source width.
$src_h: This parameter is used to set source height.
Return Value: This function returns True on success or False on failure.
Below programs illustrate the imagecopy() function in PHP.
Program 1:
<?php  // Create image instances$src = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/animateImages.gif');$dest = imagecreatetruecolor(400, 200);  // Image copy from source to destinationimagecopy($dest, $src, 0, 0, 0, 0, 500, 300);  // Output and free from memoryheader('Content-Type: image/gif');imagegif($dest);  imagedestroy($dest);imagedestroy($src);?>
Output:
Program 2:
<?php// Create image instances$src = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/animateImages.gif');$dest = imagecreatetruecolor(665, 180);  // Image copy from source to destinationimagecopy($dest, $src, 0, 0, 0, 0, 665, 180);  // Output and free from memoryheader('Content-Type: image/gif');imagegif($dest);  imagedestroy($dest);imagedestroy($src);?>
Output:
Related Articles:
PHP | imagecolorallocatealpha() Function
PHP | imagepolygon() Function
Reference: http://php.net/manual/en/function.imagecopy.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TypeScript | Array reduce() Method

18 Jun, 2020
The Array.reduce() is an inbuilt TypeScript function which is used to apply a function against two values of the array as to reduce it to a single value. Syntax:
array.reduce(callback[, initialValue])
Parameter: This method accept two parameter as mentioned and described below: 
callback : This parameter is the Function to execute on each value in the array.
initialValue : This parameter is the Object to use as the first argument to the first call of the callback.
Return Value: This method returns the reduced single value of the array. Below examples illustrate the  Array reduce() method in TypeScript
Example 1: 
JavaScript
<script>    // Driver code    var arr = [ 11, 89, 23, 7, 98 ];       // use of reduce() method     var val = arr.reduce(function(a, b)    {         return a + b;     });           // printing element    console.log( val );</script>
Output: 
228

Example 2: 
JavaScript
<script>    // Driver code    var arr = [2, 5, 6, 3, 8, 9];     var val;       // use of reduce() method     val = arr.reduce(function(a, b)    {         return a*b/2;     });           // printing element    console.log( val );</script>
Output: 
405

TypeScript
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
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
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 ?
Mongoose | findOne() Function

20 May, 2020
The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  // Find only one document matching// the condition(age >= 5)User.findOne({age: {$gte:5} }, function (err, docs) {    if (err){        console.log(err)    }    else{        console.log("Result : ", docs);    }});
Steps to run the program:
The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js
The project structure will look like this:
Make sure you have installed mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
So this is how you can use the mongoose findOne() function that finds one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extracting an attribute value with beautifulsoup in Python

29 Dec, 2020
Prerequisite: Beautifulsoup Installation
Attributes are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. A tag may have any number of attributes. For example, the tag <b class=”active”> has an attribute “class” whose value is “active”. We can access a tag’s attributes by treating it like a dictionary.
Syntax: 
tag.attrs

Implementation:Example 1: Program to extract the attributes using attrs approach. 
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''    <html>        <h2 class="hello"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Get the attributeattribute = tag.attrs  # Print the outputprint(attribute)
Output: 
{'class': ['hello']}

Example 2: Program to extract the attributes using dictionary approach. 
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''    <html>        <h2 class="hello"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Get the attributeattribute = tag['class']  # Print the outputprint(attribute)
Output: 
['hello']

Example 3: Program to extract the multiple attribute values using dictionary approach.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''    <html>        <h2 class="first second third"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Get the attributeattribute = tag['class']  # Print the outputprint(attribute)
Output: 
['first', 'second', 'third']

Python web-scraping-exercises
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SAS | How to read character using Ampersand(&)

23 Jul, 2019
We can use ampersand (&) to notify SAS to read the variable until there are two or more spaces encounter as a delimiter. This technique is always useful when the variable contains two or more words.
For example:
Actual Input: "Geeks for Geeks" 
Expected Input: "GeeksforGeeks"

Example 1: There are 2 spaces before 25, 32 and 30 in example code below.
data example1;input ID Name & $30. Score;cards;1 ShubhamMaurya  252 SaurabhPandey  323 NikitaChaudhary  30;proc print;run;
Output:
Example 2: When a variable contains 2 or more than 2 words.
In this scenario, we have a space between First Name and Last Name and we want to store both the first and last names in a single variable.
In this case, Colon modifier (:) does not work for a variable having multiple words.
In this case, Colon modifier (:) does not work for a variable having multiple words.
data example2;input ID Name & $30. Score;cards;1 Shubham Maurya  252 Saurabh Pandey  323 Nikita Chaudhary  30;proc print;run;
Output:
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Switch Case in Python (Replacement)

In this tutorial, we are going to write a program that acts as a switch case in Python.
Other programming languages like C, C++, Java, etc.., have switch whereas Python doesn't. Let's write a program that acts as a switch case in Python.
We are going to use the dict data structure for writing the switch case in Python. Let's see the
following code.
 Live Demo
# dictionary with keys and values
days = {
   0: 'Sunday',
   1: 'Monday',
   2: 'Tuesday',
   3: 'Wednesday',
   4: 'Thursday',
   5: 'Friday',
   6: 'Saturday'
}
# we will use 'get' method to access the days
# if we provide the correct key, then we will get the corresponding value
# if we provide a key that's not in the dictionary, then we will get the defaul
lue
print(days.get(0, 'Bad day'))
print(days.get(10, 'Bad day'))
If you run the above code, then you will get the following result.
Sunday
Bad day
We can place anything in place of the values. The default value of get method represents the default keyword in switch cases.
If you have any doubts in the tutorial, mention them in the comment section.
How to shift each letter in the given string N places down in the alphabet in JavaScript?

We are given a string of alphabets. Our task is to replace each of its alphabets with the alphabet that is n alphabets away from it in the English alphabet;
i.e.
if n = 1, replace a with b, replace b with c, etc (z would be replaced by a).
For example −
const str = "crazy";
const n = 1;
the output should be −
alphabeticShift(inputString) = "dsbaz".
Following is the code −
const str = 'crazy';
const alphabeticShift = (str = '', n = 1) => {
   let arr = [];
   for(let i = 0; i < str.length; i++) {
      arr.push(String.fromCharCode((str[i].charCodeAt() + n)));
   }
   let res = arr.join("").replace(/{/g, 'a');;
   return res;
};
console.log(alphabeticShift(str));
Following is the output on console −
dsbaz