code-rag-bench/online-tutorials huggingface dataset:
last command in Linux with Examples

22 May, 2019
The last command in Linux is used to display the list of all the users logged in and out since the file /var/log/wtmp was created. One or more usernames can be given as an argument to display their login in (and out) time and their host-name.
Syntax:
last [options] [username...] [tty...]
Example:
Options:
-[number]: This option is used to specify the number of lines to display.Example:last -5Output:
Example:
last -5
Output:
-R: This option is used to hide the host-name field.Example:last -R basil
Example:
last -R basil
-F: This option is used to display the login and logout time including the dates.Example:last -F
Example:
last -F
-a: This option is used is to display the host-name in the last column.Example:last -a
Example:
last -a
-s, -t: This option is used to display within a specific time period.(-s) since and (-t) until, these commands are used to frame the time period.Example:last -s yesterday -t todayThe valid formats for the above commands are:YYYYMMDDhhmmss
YYYY-MM-DD hh:mm:ss
YYYY-MM-DD hh:mm      (seconds will be set to 00)
YYYY-MM-DD            (time will be set to 00:00:00)
hh:mm:ss              (date will be set to today)
hh:mm                 (date will be set to today, seconds to 00)
now
yesterday             (time is set to 00:00:00)
today                 (time is set to 00:00:00)
tomorrow              (time is set to 00:00:00)
+5min
-5days

Example:
last -s yesterday -t today
The valid formats for the above commands are:
YYYYMMDDhhmmss
YYYY-MM-DD hh:mm:ss
YYYY-MM-DD hh:mm      (seconds will be set to 00)
YYYY-MM-DD            (time will be set to 00:00:00)
hh:mm:ss              (date will be set to today)
hh:mm                 (date will be set to today, seconds to 00)
now
yesterday             (time is set to 00:00:00)
today                 (time is set to 00:00:00)
tomorrow              (time is set to 00:00:00)
+5min
-5days

-d: This option is used to translate the IP address back into its host-name.Example:last -d
Example:
last -d
-x: This option is used to display information like system down entries and run level changes.Example:last -x
Example:
last -x
-w: This option is used to display full user and domain names.Example:last -w basil
Example:
last -w basil
–help: This option is used to display help regarding all options belonging to the last command.Syntax:last --help
Syntax:
last --help
linux-command
Linux-system-commands
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
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
HTML - Elements

An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag, where the element name is preceded by a forward slash as shown below with few tags −
So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br /> elements. These are known as void elements.
HTML documents consists of a tree of these elements and they specify how HTML documents should be built, and what kind of content should be placed in what part of an HTML document.
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.
For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.
It is very much allowed to keep one HTML element inside another HTML element −
<!DOCTYPE html>
<html>

   <head>
      <title>Nested Elements Example</title>
   </head>
	
   <body>
      <h1>This is <i>italic</i> heading</h1>
      <p>This is <u>underlined</u> paragraph</p>
   </body>
	
</html>
This will display the following result −
This is underlined paragraph
R - JSON Files

JSON file stores data as text in human-readable format. Json stands for JavaScript Object Notation. R can read JSON files using the rjson package.
In the R console, you can issue the following command to install the rjson package.
install.packages("rjson")

Create a JSON file by copying the below data into a text editor like notepad. Save the file with a .json extension and choosing the file type as all files(*.*).
{ 
   "ID":["1","2","3","4","5","6","7","8" ],
   "Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
   "Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
   
   "StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
      "7/30/2013","6/17/2014"],
   "Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}
The JSON file is read by R using the function from JSON(). It is stored as a list in R.
# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file = "input.json")

# Print the result.
print(result)
When we execute the above code, it produces the following result −
$ID
[1] "1"   "2"   "3"   "4"   "5"   "6"   "7"   "8"

$Name
[1] "Rick"     "Dan"      "Michelle" "Ryan"     "Gary"     "Nina"     "Simon"    "Guru"

$Salary
[1] "623.3"  "515.2"  "611"    "729"    "843.25" "578"    "632.8"  "722.5"

$StartDate
[1] "1/1/2012"   "9/23/2013"  "11/15/2014" "5/11/2014"  "3/27/2015"  "5/21/2013"
   "7/30/2013"  "6/17/2014"

$Dept
[1] "IT"         "Operations" "IT"         "HR"         "Finance"    "IT"
   "Operations" "Finance"

We can convert the extracted data above to a R data frame for further analysis using the as.data.frame() function.
# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file = "input.json")

# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)

print(json_data_frame)
When we execute the above code, it produces the following result −
      id,   name,    salary,   start_date,     dept
1      1    Rick     623.30    2012-01-01      IT
2      2    Dan      515.20    2013-09-23      Operations
3      3    Michelle 611.00    2014-11-15      IT
4      4    Ryan     729.00    2014-05-11      HR
5     NA    Gary     843.25    2015-03-27      Finance
6      6    Nina     578.00    2013-05-21      IT
7      7    Simon    632.80    2013-07-30      Operations
8      8    Guru     722.50    2014-06-17      Finance
Pygame – Creating Sprites

28 Jul, 2021
Sprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys.
Let first look at our first-class i.e., the class in which our sprite is defined, we will call that class Sprite. This Sprite class defines its positions(x and y coordinates), dimension of an object, color, etc. First, we will be calling our __init__() method. It is called a constructor for a class.
Example: Creating Sprite class
Python3
import pygame  # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500  # Object classclass Sprite(pygame.sprite.Sprite):    def __init__(self, color, height, width):        super().__init__()          self.image = pygame.Surface([width, height])        self.image.fill(SURFACE_COLOR)        self.image.set_colorkey(COLOR)          pygame.draw.rect(self.image,                         color,                         pygame.Rect(0, 0, width, height))          self.rect = self.image.get_rect()
Now, that the class has been created, we can create objects from the class. It enables us to create as many objects as we need using the same class. Now we will create an object using our Class Sprite. 
Syntax:
object = Sprite(RED,WIDTH,HEIGHT)
By default, the object will be on position (0,0) i.e., top-left of the screen. We can change the x and y properties of the object.
Syntax:
object.rect.x = value
object.rect.y = value
We can define n of sprites that we want to create, but for the purpose of understanding, let’s simplify. Here we have created a rectangle sprite of certain dimensions, on which we can perform different operations to perform on sprites like move forward, backward, jump, slow, accelerate, etc. 
Example: Creating sprite
Python3
import pygameimport random  # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500  # Object classclass Sprite(pygame.sprite.Sprite):    def __init__(self, color, height, width):        super().__init__()          self.image = pygame.Surface([width, height])        self.image.fill(SURFACE_COLOR)        self.image.set_colorkey(COLOR)          pygame.draw.rect(self.image,color,pygame.Rect(0, 0, width, height))          self.rect = self.image.get_rect()    pygame.init()  RED = (255, 0, 0)  size = (WIDTH, HEIGHT)screen = pygame.display.set_mode(size)pygame.display.set_caption("Creating Sprite")  all_sprites_list = pygame.sprite.Group()  object_ = Sprite(RED, 20, 30)object_.rect.x = 200object_.rect.y = 300  all_sprites_list.add(object_)  exit = Trueclock = pygame.time.Clock()  while exit:    for event in pygame.event.get():        if event.type == pygame.QUIT:            exit = False      all_sprites_list.update()    screen.fill(SURFACE_COLOR)    all_sprites_list.draw(screen)    pygame.display.flip()    clock.tick(60)  pygame.quit()
Output:
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
real() function in C++

08 Oct, 2018
The real() function is defined in the complex header file. The real() function is used to find the real part of the complex number.
Syntax:
template<class T> T 
    real(const complex<T>& z);

Parameter: This method takes a mandatory parameter z: which represents the given complex number.
Return: It returns the real part of the specified complex number.
Below programs illustrate the above function:-
Example 1:-
// C++ program to demonstrate// example of real() function.  #include <bits/stdC++.h>using namespace std;  // driver functionint main(){    // defines the complex number: (20.3 + 4.9i)    complex<double> realpart(20.3, 4.9);      // print the complex number    cout << "Complex Number = "         << realpart << endl;      // prints the real part using the real function    cout << "Real part of the complex number is ="         << real(realpart) << endl;      return 0;}
Complex Number = (20.3, 4.9)
Real part of the complex number is =20.3

Example 2:-
// C++ program to demonstrate// example of real() function.  #include <bits/stdC++.h>using namespace std;  // driver functionint main(){    // defines the complex number: (2 + 2i)    complex<double> realpart(2, 2);      // print the complex number    cout << "Complex Number = "         << realpart << endl;      // prints the real part using the real function    cout << "Real part of the complex number is ="         << real(realpart) << endl;      return 0;}
Complex Number = (2, 2)
Real part of the complex number is =2

CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PayTm Interview Experience | Set 23 (For 2 Years Experienced)

11 Mar, 2018
Round 1:
First round was taken on mettl, online judge. There was two questions and that required to be done in 1hr
1. A paragraph which contained some dates in format DD-MM-YYYY, find number of distinct years in the paragraph.
 
For e.g Some random words with date 12-01-1990 and some more words with date 12-12-2017 and again some random words with same date 12-05-1990
 
Output will be: 2
Since two different years (1990 and 2017)
 
2. Given an array containing positive integers. Find count of magic numbers in the array.
A magic number is that number which can be expressed as sum of two numbers and those two numbers should be reverse of each other. For e.g 22 is magic number which can be expressed as 11+11, 121 is magic number which can be expressed as 29+92
 
Input: [4, 22, 121, 13]Output: 3
Round 2:Round 2 was F2F.1. Write a function to clone a link list with random pointers.Expected complexity was O(N) with O(1) space
2. What are MySQL engines ?
3. What is load balancer ?
4. What is session and cookies ? How sessions are maintained and how these values are passed from client to server ?
5. How to handle high request per second (distributed systems)?
6. Write mysql query to find 2nd highest salary.
Round 3:
In this round there were discussions on current employment and the projects. Discussion on DB designs and some modules. Some questions on AngularJS(I have experience in that, thats why)
1. Given a long string and an array of words. Find the minimum window in the string where all the words in given array are present in that window.For e.g if string isA B B A C E Y I J A BArray is [ B, I, Y ]So the output will be 7, 11
Where 7 is starting index and 11 is end index of window.
Paytm
Experienced
Interview Experiences
Paytm
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience SDE-2 (3 Years Experienced)
Google Interview Experience for Software Engineer L3 Bangalore (6 Years Experienced)
SAMSUNG R&D Interview Experience for Team Lead
Adobe Interview Experience for MTS-1 (Off-Campus) 1 Year Experienced
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Questions
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
cc command in Linux with Examples - GeeksforGeeks

15 May, 2019
cc command is stands for C Compiler, usually an alias command to gcc or clang. As the name suggests, executing the cc command will usually call the gcc on Linux systems. It is used to compile the C language codes and create executables. The number of options available for the cc command is very high. The most important options are explained below with examples.
Syntax:
cc [options] files

Example: Below command will compile the source_file.c file, and create the default executable output file, a.out.
cc example.c
Important Options:
cc command with -o option: This command will compile the source_file.c file, and create a executable output file with the specified name.cc example.c -o examp_out
cc example.c -o examp_out
cc command with -Wall option: This command will compile the source_file.c file, and check for all errors and warnings in the program.cc example.c -Wall -o examp_out
cc example.c -Wall -o examp_out
cc command with -w option: This command will compile the source_file.c file, but suppress all the warnings.cc example.c -w 
cc example.c -w 
cc command with -g option: This command will compile the source_file.c file, and create a debugging version of the executable output file. This output file can be used by the debugger, and is usually much larger in size than the normal output files.cc example.c -g -o examp_out_debug
cc example.c -g -o examp_out_debug
cc command with -c option: This command will compile the source_file.c file, and create an object file source_file.o, which can later be linked to create an executable output file.cc example.c -c 
cc example.c -c 
cc command with -Ldir option: This command, while compiling the source_file.c file, will also search the specified directory for header files.cc example.c -L /home/mukkesh/Desktop
cc example.c -L /home/mukkesh/Desktop
cc command with -ansi option: This command will compile the source_file.c file, and makes sure that the code follows strict ANSI standards. This will make sure that the code is portable to be compiled on any other system.cc -ansi example.c 
cc -ansi example.c 
cc command with –dump options: These commands specified below will print the version of the cc command, the default target machine and built-in specification strings.cc -dumpversioncc -dumpmachinecc -dumpspecs
cc -dumpversion
cc -dumpmachine
cc -dumpspecs
cc command with -v option: This command will compile the source_file.c file, and gives a verbose output.cc example.c -v
cc example.c -v
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Accessing nth element from Python tuples in list

A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present as the elements in the given tuple.
We can design a for loop to access the elements from the list with the in clause applied for nth index. Then we store the result into a new list.
 Live Demo
Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use index
res = [x[1] for x in Alist]

print("The 1 st element form each tuple in the list: \n",res)
Running the above code gives us the following result −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
['3 pm', '12pm', '9 am', '6 am']
The itegetter function from operator module can fetch each item form the given iterable till the end of the iterable is searched. In this program we search for index position 2 from the given list and apply a map function to apply the same function again and again to each result from the result of the itemgetter function. Finally we store the result as a list.
 Live Demo
from operator import itemgetter

Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use itemgetter
res = list(map(itemgetter(2), Alist))

print("The 1 st element form each tuple in the list: \n",res)
Running the above code gives us the following result −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
[10, 8, 8, 5]
How to create clickable links in a textView on Android?

This example demonstrates how do I create clickable links in a textView on android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <TextView
      android:id="@+id/textViewLink"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textSize="24sp"
      android:textStyle="bold"
      android:gravity="center"
      android:text="@string/messageWithLink" />
</RelativeLayout>
Step 3 – Open res/values/strings.xml and add the following code −
<resources>
   <string name="app_name">Sample</string>
   <string
      name="messageWithLink"><a href="https://www.google.com/">Tap here to open Link</a></string>
</resources>
Step 4 − Add the following code to src/MainActivity.java
package app.com.sample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      textView = findViewById(R.id.textViewLink);
      textView.setMovementMethod(LinkMovementMethod.getInstance());
   }
}
Step 5 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Builtin functions of GCC compiler in C++

In the GCC compiler there are some builtin functions. These functions are like below.
This builtin function is used to count the number of 1s in an integer type data. Let us see an example of _builtin_popcount() function.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   cout << "Count of 1s in binary of "<< n <<" is " << __builtin_popcount(n);
   return 0;
}
Count of 1s in binary of 13 is 3
This builtin function is used to check the parity of a number. If the number has odd parity, it will return true, otherwise it will return false. Let us see an example of _builtin_parity() function.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   cout << "Parity of "<< n <<" is " << __builtin_parity(n);
   return 0;
}
Parity of 13 is 1
This builtin function is used to count the leading zeros of an integer. The clz stands for Count Leading Zeros. Let us see an example of _builtin_clz() function.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   //0000 0000 0000 0000 0000 0000 0000 1101 (32bit integer )
   cout << "Leading zero count of "<< n <<" is " << __builtin_clz(n);
   return 0;
}
Leading zero count of 13 is 28
This builtin function is used to count the trailing zeros of an integer. The ctz stands for Count Trailing Zeros. Let us see an example of _builtin_ctz() function.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int n = 12; //The binary is 1100
   //0000 0000 0000 0000 0000 0000 0000 1100 (32bit integer )
   cout << "Trailing zero count of "<< n <<" is " << __builtin_ctz(n);
   return 0;
}
Trailing zero count of 12 is 2
Permutation Sequence in C++

Suppose the set is like [1,2,3,...,n], contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get these sequence for n = 3: ["123","132","213","231","312","321"] So if n and k are given, then return the kth permutation sequence. The n will be between 1 to 9 (inclusive) and k will be between 1 to n! (inclusive). For example if n = 3.
Let us see the steps −
ans := empty string, define array called candidates of size n
for i in range 0 to n – 1candidates[i] := ((i + 1) + character ‘0’)
candidates[i] := ((i + 1) + character ‘0’)
create one array called fact of size n + 1, set fact[0] := 1
for i in range 1 to nfact[i] := fact[i – 1] * i
fact[i] := fact[i – 1] * i
decrease k by 1
for i := n – 1 down to 0idx := k / fact[i]ans := ans + candidates[idx]for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]k := k mod fact[i]
idx := k / fact[i]
ans := ans + candidates[idx]
for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]
candidates[j] := candidates[j + 1]
k := k mod fact[i]
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   string getPermutation(int n, int k) {
      string ans = "";
      vector <char> candidates(n);
      for(lli i = 0; i < n; i++)
         candidates[i] = ((i + 1) + '0');
      vector <lli> fact(n + 1);
      fact[0] = 1;
      for(lli i = 1; i <= n; i++)
         fact[i] = fact[i - 1] * i;
      k--;
      for(lli i = n - 1; i >= 0; i--){
         lli idx = k / fact[i];
         ans += candidates[idx];
         for(lli j = idx; j + 1< candidates.size(); j++)
            candidates[j] = candidates[j + 1];
         k = k % fact[i];
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << ob.getPermutation(4, 9);
}
4
9
2314
numpy.squeeze

This function removes one-dimensional entry from the shape of the given array. Two parameters are required for this function.
numpy.squeeze(arr, axis)

Where,
arr
Input array
axis
int or tuple of int. selects a subset of single dimensional entries in the shape
import numpy as np  
x = np.arange(9).reshape(1,3,3) 

print 'Array X:' 
print x 
print '\n'  
y = np.squeeze(x) 

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

print 'The shapes of X and Y array:' 
print x.shape, y.shape
Its output is as follows −
Array X:
[[[0 1 2]
 [3 4 5]
 [6 7 8]]]

Array Y:
[[0 1 2]
 [3 4 5]
 [6 7 8]]

The shapes of X and Y array:
(1, 3, 3) (3, 3)


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
What is Non-Immediate Left Recursion in compiler design?

A Grammar G (V, T, P, S) is left recursive if it has a production in the form.
A → A α |β.
The above Grammar is left recursive because the left of production is occurring at a first position on the right side of production. It can eliminate left recursion by replacing a pair of production with
A → βA′
A → αA′|ε
The general form for left recursion is
A → Aα1|Aα2| ... . |Aαm|β1|β2| ... . . βn
can be replaced by
A → β1A′|β2A′| ... . . | ... . . |βnA′
A → α1A′|α2A′| ... . . |αmA′|ε
In the following grammar, it does not have the immediate or direct left recursion. But here, it can have non-immediate left recursion.
S → Ab
A → Sc|d
Here, S is left Recursive, because S ⇒ A b ⇒ S c b
Algorithm to Remove Left-Recursion
Input − Grammar G with no cycles or ε − productions.
Output − Equivalent Grammar with no Left Recursion.
Method
Order the non-terminals as A1, A2, ... ... ... . . An
Order the non-terminals as A1, A2, ... ... ... . . An
for i = 1 to n
{
   for j = 1 to i – 1
   {
      replace each production Ai → Ajγ
      by productions Ai → δ1γ| δ2γ| ... ... . . |δKγ
      where Aj → δ1|δ2| ... ... . |δK
   }
Remove immediate left Recursion among Ai productions.
}
Example1 − Remove or Eliminate Left Recursion from the following Grammar.
S → Ab
A → Sc | d
Solution
These productions don’t have immediate left Recursion. So it cannot be eliminated directly. We can use the algorithm here to remove Left Recursion.
Step1 − Order the non-terminals S, A as A1, A2i.e., Mark S =A1, A = A2
Substituting values
∴   A1 → A2b                             ............... (1)
     A2 → A1c|d                           ............... (2)
Step2 − Put values of (1) in (2)
∴  A1 → A2b
    A2 → A1bc|d
Step3 − Again substitutes A1 = S and A2 = A
∴  S → A b                              ................ (3)
    A → A b c | d                        ................ (4)
Step4 − Remove Immediate Left recursion in A → A b c | d
So,
Example2 − Remove left recursion from the following Grammar.
S → Aa |b
A → Ac | Sd|e
Solution
As we don’t have immediate left recursion so, we have to apply the algorithm here.
Step1 − Rename S, A as A1, A2 respectively.
A1 → A2 a | b                        ............... (1)
A2 → A2c | A1d|e                  ................ (2)
Step2 − Substitute value of A1 of the statement (1) in R.H.S of the statement (2).
A1 → A2 a | b
A2 → A2 c |A2 a d|bd|e.
Step3 − Again, substitute A1 = S, A2 = A
S → Aa |b                               ................. (3)
A → Ac |A a d|bd|e                   .................. (4)
Step4 − Statement (4) has an immediate left recursion. Removing immediate left recursion we get
Find the size of a HashMap in Java

Use the size() method to get the size of HashMap. Let us first create a HashMap
HashMap hm = new HashMap();
Now, add some elements −
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Franes", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Since, we added 5 elements above, therefore, the size() method will give 5 as the result −
set.size()
The following is an example to find the size of HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Franes", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Size of HashMap = "+set.size());
   }
}
Elements in HashMap...
Franes: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
Size of HashMap = 5
$("#submitButton").attr("disabled", "disabled")

This would modify the disabled attribute to the value "disabled" while clicking Submit button.
Here is the simple syntax to use this method −
selector.attr("disabled","disabled");

Here is the description of all the parameters used by this method −
disabled This is the CSS property of the matched element.
disabled This is the CSS property of the matched element.
disabled This is the value to be set to the matched element.
disabled This is the value to be set to the matched element.
Following example would modify the disabled attribute to the value "disabled" while clicking Submit button.
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>		
      <script type = "text/javascript" language = "javascript">	 
         function disableSubmit(){
            $("#submitButton").attr("disabled", "disabled");
         }
      </script>
   </head>	
   
   <body>
      <div>
         <form name = "sampleForm">
            <input type = "text" id = "result1" title="The jQuery Example" value = "sample" ></input><br/><br/>
            <input type = "text" id = "result2" title="The jQuery Example" value = "sample" ></input> <br/><br/>
            <input type = "button" id = "submitButton" onclick="disableSubmit();" value = "submit"/>
         </form>
      </div>
   </body>	
</html>
This will produce following result −
 Print
 Add Notes
 Bookmark this page
How to get file URI reference in Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
In general, an URI (Uniform Resource Identifier) represents a resource. The URI class of Java represents this format You can get the URI format of a file by invoking the toURI() method.
Following Java example, prints the URI format of the file named samplefile.txt
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class GetURI {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      String filePath = "D:\\ExampleDirectory\\sampleFile.txt";
      File file = new File(filePath);
      //Getting the URI object
      URI uri = file.toURI();
      System.out.println(uri.toString());
   }
}
file:/D:/ExampleDirectory/sampleFile.txt
Count the numbers divisible by ‘M’ in a given range in C++

We are given three numbers A,B and M. A and B define the range [A,B] of numbers.The goal is
to count numbers between A and B that are divisible by M.
We will start from i=A till first multiple of M. Increment count if i%M=0. Now increment i till i<=B
and increase count.
Let’s understand with examples.
A=11,B=20, M=5
Count of numbers divisible by M in given range: 2
15 and 20 are only numbers that are divisible by 5 and lie in range [11,20].
A=20, B=50, M=11
Count of numbers divisible by M in given range: 3
22,33,44 are only numbers that are divisible by 11 and lie in range [20,50].
We take A,B and M as integers.
Function divisiblebyM (int a, int b, int m) take A,B and M as parameters and return the
count of numbers between A and B that are divisible by M.
Take the initial count as 0.
Using for loop, start from i=A to i=B. Increment i by 1.
If i%m=0, increment count.
At the end, count as numbers between A and B that are divisible by m.
Return count as result.
 Live Demo
// Program to count the numbers divisible by
// M in a given range
#include <bits/stdc++.h>
using namespace std;
int divisiblebyM(int a, int b, int m){
   int count = 0;
   // Running a loop from A to B and check
   // if a number is divisible by M.
   for (int i = a; i <= b;i++ ){
      if (i % m == 0){
          count++;
       }
   }
   return count;
}
int main(){
   // A and B define the range, M is the dividend
   int A = 3, B = 15, M = 4;
   cout<<"Numbers divisible by M in given range:"<<divisiblebyM(A, B, M) << endl;
   return 0;
}
Numbers divisible by M in given range:3
Bootstrap 4 .card-header-tabs class

Use the card-header-tabs in Bootstrap to style navigation links in card header −
<div class="card-header">
  <ul class="nav nav-tabs card-header-tabs">
    <li class="nav-item">
      <a class="nav-link active" href="#">Drupal Commerce</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">WooCommerce</a>
    </li>
  </ul>
</div>
The header tabs are set on Unordered List using nav-tabs and card-header-tabs class as shown above −
<ul class="nav nav-tabs card-header-tabs">
Let us see an example to learn how to create Bootstrap 4 card header − 
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
<body>
  <div class="container">
    <h2>E-commerce Technologies</h2>
    <div class="card">
      <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs">
          <li class="nav-item">
            <a class="nav-link active" href="#">Drupal Commerce</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">WooCommerce</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Prestashop</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Shopify</a>
          </li>
        </ul>
    </div>
    <div class="card-body">
      <h5 class="card-title">Add title here</h5>
      <p class="card-text">Add content here</p>
     </div>
   </div>
</div>
</body>
</html>
Python – PyTorch abs() method

26 May, 2020
PyTorch torch.abs() method computes the element-wise absolute value of the given input tensor.
Syntax: torch.abs(inp, out=None) ? Tensor
Arguments
inp: This is input tensor.
out: This is optional parameter and is the output tensor.
Return: It returns a Tensor having absolute value of input inp.
# Importing the PyTorch library import torch     # A constant tensor of size 1 a = torch.FloatTensor([-15]) print(a)     # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b) 
Output:
-15
[torch.FloatTensor of size 1]
 15
[torch.FloatTensor of size 1]

Example 2:
# Importing the PyTorch library import torch     # A constant tensor of size n a = torch.FloatTensor([15, -5, 3, -2]) print(a)     # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b) 
Output:
 15
 -5
  3
 -2
[torch.FloatTensor of size 4]
 15
  5
  3
  2
[torch.FloatTensor of size 4]

Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Nested list in C++ STL

18 Sep, 2018
list in STL is used to represent a linked list in C++. How to create a nested list. We are given n lists, we need to create a list of n lists.
Examples:
Input :  Number of lists: 2
1st list: {1 2}
2nd list:  {3 4 5 6
Output : 
[
  [ 1  2 ]
  [ 3  4  5  6 ]
]

Input : Number of lists: 3
1st list : {0 1} 
2nd list : {1 2 3}
3rd list : {2 3 4 5}
Output :
[
  [ 0  1 ]
  [ 1  2  3 ]
  [ 2  3  4  5 ]
]

// c++ program for nested list  #include <iostream>#include <iterator>#include <list>using namespace std;  void printNestedList(list<list<int> > nested_list){    cout << "[\n";      // nested_list`s iterator(same type as nested_list)    // to iterate the nested_list    list<list<int> >::iterator nested_list_itr;      // Print the nested_list    for (nested_list_itr = nested_list.begin();         nested_list_itr != nested_list.end();         ++nested_list_itr) {          cout << "  [";          // normal_list`s iterator(same type as temp_list)        // to iterate the normal_list        list<int>::iterator single_list_itr;          // pointer of each list one by one in nested list        // as loop goes on        list<int>& single_list_pointer = *nested_list_itr;          for (single_list_itr = single_list_pointer.begin();             single_list_itr != single_list_pointer.end();             single_list_itr++) {            cout << " " << *single_list_itr << " ";        }        cout << "]\n";    }    cout << "]";}  // Driver codeint main(){    // instead integer type can have any data type    list<list<int> > nested_list;    list<int> single_list;    int n, m, num;      // number of lists in nested list    n = 3;      for (int i = 0; i < n; i++) {          // number of elements in list        m = i + 2;        for (int j = 0; j < m; j++) {            num = i + j;            single_list.push_back(num);        }          nested_list.push_back(single_list);          // delete all elements from single_list        single_list.erase(single_list.begin(),                          single_list.end());    }      printNestedList(nested_list);      return 0;}
[
  [ 0  1 ]
  [ 1  2  3 ]
  [ 2  3  4  5 ]
]

cpp-list
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Generate all Combinations of xCm in R Programming – combn() Function

08 Jun, 2020
combn() function in R Language is used to generate all combinations of the elements of x taken m at a time.
Syntax: combn(x, m)
Parameters:x: total number of elements takenr: number of elements taken at a time out of “x” elements
Example 1:
# R program to illustrate# combn function  # Calling the combn() functioncombn(5, 3)combn(6, 5)combn(2, 2)
Output:
     [, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]
[1, ]    1    1    1    1    1    1    2    2    2     3
[2, ]    2    2    2    3    3    4    3    3    4     4
[3, ]    3    4    5    4    5    5    4    5    5     5

     [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
[1, ]    1    1    1    1    1    2
[2, ]    2    2    2    2    3    3
[3, ]    3    3    3    4    4    4
[4, ]    4    4    5    5    5    5
[5, ]    5    6    6    6    6    6

     [, 1]
[1, ]    1
[2, ]    2

Example 2:
# R program to illustrate# combn function  # Calling the combn() functioncombn(LETTERS[1: 4], 2)combn(LETTERS[2: 6], 3)
Output:
     [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
[1, ] "A"  "A"  "A"  "B"  "B"  "C" 
[2, ] "B"  "C"  "D"  "C"  "D"  "D" 

     [, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]
[1, ] "B"  "B"  "B"  "B"  "B"  "B"  "C"  "C"  "C"  "D"  
[2, ] "C"  "C"  "C"  "D"  "D"  "E"  "D"  "D"  "E"  "E"  
[3, ] "D"  "E"  "F"  "E"  "F"  "F"  "E"  "F"  "F"  "F"  

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
Why Does C Treat Array Parameters as Pointers?

25 Nov, 2021
In C, array parameters are treated as pointers mainly to,
To increase the efficiency of code
To save time
It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array.
The following two definitions of fun() look different, but to the compiler, they mean exactly the same thing. 
void fun(int arr[]) { 
    // body
}
// This is valid


void fun(int *arr) { 
    // body
}
// This is valid too
It’s preferable to use whichever syntax is more accurate for readability.
Note: If the pointer coming in really is the base address of a whole array, then we should use [ ].
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Example: In this example, the array parameters are being used as pointers.
C
// C Program to demonstrate that C treats array parameters// as pointers#include <stdio.h> void findSum1(int arr[]){    int sum = 0;    for (int i = 0; i < 5; i++)        sum = sum + arr[i];    printf("The sum of the array is: %d\n", sum);} void findSum2(int* arr){    int sum = 0;    for (int i = 0; i < 5; i++)        sum = sum + arr[i];    printf("\nThe sum of the array is: %d \n", sum);} // Driver codeint main(){    int arr[5] = { 1, 2, 3, 4, 5 };     findSum1(arr);    findSum2(arr);    return 0;}
The sum of the array is: 15

The sum of the array is: 15 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
anshikajain26
C-Pointers
pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction
Memory Layout of C Programs
Python Program for Finding the vertex, focus and directrix of a parabola

03 Dec, 2018
A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve.
The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix.
Example –
Input : 5 3 2
Output : Vertex:(-0.3, 1.55)
         Focus: (-0.3, 1.6)
         Directrix: y=-198
Consult the formula below for explanation.

# Python program to calculate Vertex, Focus and Directrix  def parabola(a, b, c):    print ("Vertex: (" , (-b / (2 * a)) , ", "        ,(((4 * a * c) - (b * b)) / (4 * a)) , ")" )              print ("Focus: (" , (-b / (2 * a)) , ", "        , (((4 * a * c) - (b * b) + 1) / (4 * a)) , ")" )          print ("Directrix: y="            , (int)(c - ((b * b) + 1) * 4 * a ))                # main()a = 5b = 3c = 2  parabola(a, b, c)  # Contributed by _omg
Output :
Vertex:(-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198

Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to interchange first and last elements in a list
How to check for empty string in PHP ?

07 Oct, 2021
In this article, we will see how to check for empty string in PHP. String is a set of characters. A string is said to be empty, if it contains no characters. We can use empty() function to check whether a string is empty or not.
The function is used to check whether the string is empty or not. It will return true if the string is empty.
Syntax:
bool empty(string)
Parameter: Variable to check whether it is empty or not.
Return Value: If string is empty, it returns true and false otherwise.
Example 1: PHP program to check whether the string is empty or not.
PHP
<?php  // Consider a string which is empty$s = "";  // Return a message if string is emptyif(empty($s)) {    echo "Empty string";}else {    echo "Not empty";}  ?>
Empty string
Example 2:
PHP
<?php  // Consider a string which is not empty$s = "Welcome to GFG";  // Return a message if string is emptyif(empty($s)) {    echo "Empty string";}else {    echo "Not empty";}  ?>
Not empty
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.