code-rag-bench/online-tutorials huggingface dataset:
Python | Check if two lists have any element in common - GeeksforGeeks

18 Feb, 2019
Sometimes we encounter the problem of checking if one list contains any element of another list. This kind of problems is quite popular in competitive programming. Let’s discuss various ways to achieve this particular task.
Method #1: Using any()
# Python code to check if two lists# have any element in common  # Initialization of listlist1 = [1, 2, 3, 4, 55]list2 = [2, 3, 90, 22]  # using any functionout = any(check in list1 for check in list2)  # Checking conditionif out:    print("True") else :    print("False")
True

 Method #2: Using in operator.
# Python code to check if two lists# have any element in common  # Initialization of listlist1 = [1, 3, 4, 55]list2 = [90, 22]  flag = 0  # Using in to check element of# second list into first listfor elem in list2:    if elem in list1:        flag = 1  # checking conditionif flag == 1:    print("True") else :    print("False")
False

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Random nextLong() method in Java with Examples - GeeksforGeeks

07 Jan, 2019
The nextGaussian() method of Random class returns the next pseudorandom, uniformly distributed long value from this random number generator’s sequence.
Syntax:
public long nextLong()

Parameters: The function does not accepts any parameter.
Return Value: This method returns the next pseudorandom, uniformly distributed long value.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
// program to demonstrate the// function java.util.Random.nextLong()  import java.util.*;public class GFG {    public static void main(String[] args)    {          // create random object        Random r = new Random();          // get next long value and print the value        System.out.println("Long value is = "                           + r.nextLong());    }}
Long value is = -9027907281942573746

// program to demonstrate the// function java.util.Random.nextLong()  import java.util.*;public class GFG {    public static void main(String[] args)    {          // create random object        Random r = new Random();          // get next long value and print the value        System.out.println("Long value is = "                           + r.nextLong());    }}
Long value is = -2817123387200223163

Java-Functions
Java-Random
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
std::less in C++ with Examples - GeeksforGeeks

01 May, 2020
The std::less is a is a member of the functional class (<functional.h>) used for performing comparisons. It is defined as a function object class for less than inequality comparison which returns a boolean value depending upon the condition. This can be used to change the functionality of the given function. It can be used with various standard algorithms like sort, lower_bound etc.
Header File:
#include <functional.h>

Template Class:
template <class T> struct less {

  // Declaration of the less operation
  bool operator() (const T& x,
                   const T& y) 
       const 
  {
     return x  < y;
  }

  // Type of first parameter
  typedef T first_argument_type;

  // Type of second parameter
  typedef T second_argument_type;

  // The result is returned
  // as bool type
  typedef bool result_type;
};

Syntax:
std::less()

Parameter: This function accepts the type of the arguments T, as the parameter, to be compared by the functional call.
Return Type: It return a boolean value depending upon condition(let a & b are 2 element):
True: If a is less than b.
False: If a is greater than b.
Below is the illustration of std::less in C++:
Program 1:
// C++ program to illustrate// std::less function#include <algorithm>#include <functional>#include <iostream>using namespace std;  // Function to print array arr[]void printArray(int arr[], int N){      for (int i = 0; i < N; i++) {        cout << arr[i] << ' ';    }}  // Driver Codeint main(){    int arr[] = { 26, 23, 21, 22,                  28, 27, 25, 24 };      int N = sizeof(arr) / sizeof(arr[0]);      // Sort the array in increasing order    sort(arr, arr + N, less<int>());      // Print sorted array    printArray(arr, N);    return 0;}
21 22 23 24 25 26 27 28

Program 2:
// C++ program to illustrate less#include <iostream>#include <algorithm>#include <functional>using namespace std;  // Templatetemplate <typename A, typename B,           typename U = std::less<int> >  // Function to check if a < b or notbool f(A a, B b, U u = U()){    return u(a, b);}  // Driver Codeint main(){    int X = 1, Y = 2;      // If X is less than Y or not    cout << std::boolalpha;    cout << f(X, Y) << '\n';      X = 2, Y = -1;      // If X is less than Y or not    cout << f(X, Y) << '\n';      return 0;}
true
false

Reference: http://www.cplusplus.com/reference/functional/less/
C++
C++ Programs
Write From Home
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
C++ List Library - sort() Function

The C++ function std::list::sort() sorts the elements of the list. The order of equal elements is preserved. It uses comparison function to compare values.
Following is the declaration for std::list::sort() function form std::list header.
template <class Compare>
void sort (Compare comp);

comp − comparison function object which returns ​boolean. It has following prototype.
bool cmp(const Type1 &ar1, const Type2 &arg2);

None
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::list::sort() function.
#include <iostream>
#include <list>

using namespace std;

bool comp(int a, int b) {
   return (a > b);
}

int main(void) {
   list<int> l = {1, 4, 2, 5, 3};

   cout << "Contents of list before sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   /* Descending sort */
   l.sort(comp);

   cout << "Contents of list after sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Contents of list before sort operation
1
4
2
5
3
Contents of list after sort operation
5
4
3
2
1

 Print
 Add Notes
 Bookmark this page
How to sort array of strings by their lengths following shortest to longest pattern in Java

At first, let us create and array of strings:
String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" };
Now, for shortest to longest pattern, for example A, AB, ABC, ABCD, etc.; get the length of both the string arrays and work them like this:
Arrays.sort(strArr, (str1, str2) -> str1.length() - str2.length());
The following is an example to sort array of strings by their lengths with shortest to longest pattern:
import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF","ABCDEFGHIJ" };
      System.out.println("Sorting array on the basis of their lengths (shortest to longest) =");
      Arrays.sort(strArr, (str1, str2) -> str1.length() - str2.length());
      Arrays.asList(strArr).forEach(System.out::println);
   }
}
Sorting array on the basis of their lengths (shortest to longest) =
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGHIJ
Sorting an array objects by property having null value in JavaScript

We are required to write a JavaScript function that takes in an array of objects. The objects may have some of their keys that are mapped to null.
Our function should sort the array such that all the objects having keys mapped to null are pushed to the end of the array.
The code for this will be −
const arr = [
   {key: 'a', value: 100},
   {key: 'a', value: null},
   {key: 'a', value: 0}
];
const sortNullishValues = (arr = []) => {
   const assignValue = val => {
      if(val === null){
         return Infinity;
      }
      else{
         return val;
      };
   };
   const sorter = (a, b) => {
      return assignValue(a.value) - assignValue(b.value);
   };
   arr.sort(sorter);
}
sortNullishValues(arr);
console.log(arr);
And the output in the console will be −
[
   { key: 'a', value: 0 },
   { key: 'a', value: 100 },
   { key: 'a', value: null }
]
Create a Bordered Button Group with CSS

You can try to run the following code to create a bordered button group with border property
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .btn {
            color: black;
            background-color: yellow;
            width: 120px;
            text-align: center;
            font-size: 15px;
            padding: 20px;
            float: left;
            border: 3px solid blue;
         }
         .mybtn {
            background-color: orange;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <div class = "mybtn">
         <button class = "btn">Result</button>
         <button class = "btn">Result</button>
         <button class = "btn">Result</button>
         <button class = "btn">Result</button>
         <button class = "btn">Result</button>
      </div>
   </body>
</html>
Compound assignment operators in Java


The Assignment Operators
Following are the assignment operators supported by Java language −
Live Demo
public class Test {

   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 0;

      c = a + b;
      System.out.println("c = a + b = " + c );

      c += a ;
      System.out.println("c += a  = " + c );

      c -= a ;
      System.out.println("c -= a = " + c );

      c *= a ;
      System.out.println("c *= a = " + c );

      a = 10;
      c = 15;
      c /= a ;
      System.out.println("c /= a = " + c );

      a = 10;
      c = 15;
      c %= a ;
      System.out.println("c %= a  = " + c );

      c <<= 2 ;
      System.out.println("c <<= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c &amp;= a ;
      System.out.println("c &amp;= a  = " + c );

      c ^= a ;
      System.out.println("c ^= a   = " + c );

      c |= a ;
      System.out.println("c |= a   = " + c );
   }
}
This will produce the following result −
c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &amp;= a  = 0
c ^= a   = 10
c |= a   = 10
Python program to left rotate the elements of an array

When it is required to left rotate the elements of an array, the array can be iterated over, and depending on the number of left rotations, the index can be incremented that many times.
Below is a demonstration of the same −
 Live Demo
my_list = [11, 12, 23, 34, 65]
n = 3

print("The list is : ")
for i in range(0, len(my_list)):
   print(my_list[i])

for i in range(0, n):
   first_elem = my_list[0]

   for j in range(0, len(my_list)-1):
      my_list[j] = my_list[j+1]

   my_list[len(my_list)-1] = first_elem

print()

print("Array after left rotating is : ")
for i in range(0, len(my_list)):
   print(my_list[i])
The list is :
11
12
23
34
65

Array after left rotating is :
34
65
11
12
23
A list is defined, and is displayed on the console.
A list is defined, and is displayed on the console.
The value for left rotation is defined.
The value for left rotation is defined.
The list is iterated over, and the index of elements in the list is incremented, and assigned to previous index of the same list.
The list is iterated over, and the index of elements in the list is incremented, and assigned to previous index of the same list.
Once it comes out of the loop, the first element (at the 0th index) is assigned to the last element.
Once it comes out of the loop, the first element (at the 0th index) is assigned to the last element.
This is the output that is displayed on the console.
This is the output that is displayed on the console.
Virtual Destructor in C++

Deleting a derived class object using a pointer to a base class, the base class should be defined with a virtual destructor.
#include<iostream>
using namespace std;
class b {
   public:
      b() {
         cout<<"Constructing base \n";
      }
      virtual ~b() {
         cout<<"Destructing base \n";
      }
};
class d: public b {
   public:
      d() {
         cout<<"Constructing derived \n";
      }
      ~d() {
         cout<<"Destructing derived \n";
      }
};
int main(void) {
   d *derived = new d();
   b *bptr = derived;
   delete bptr;
   return 0;
}
Constructing base
Constructing derived
Destructing derived
Destructing base
How to use selenium to check if element contains specific class attribute?

We can check if an element contains a specific class attribute value. The getAttribute() method is used to get the value of the class attribute. We need to pass class as a parameter to the getAttribute() method.
First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css. Then obtain the class value of the attribute. Finally, we need to check if the class attribute contains a specific value.
Let us take an element with the below html code having class attribute. The tp-logo is the value of the class attribute.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class SpecificClassVal{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
      // get class attribute with getAttribute()
      String clsVal = t.getAttribute("class");
      //iterate through class value
      for (String i : clsVal.split(" ")) {
         //check the class for specific value
         if (i.equals("tp-logo")) {
               System.out.println("class attribute contains: " + clsVal);
         } else {
               System.out.println("class attribute does not contain: " + clsVal);}
         }
      driver.close();
   }
}
Node.js __filename object - GeeksforGeeks

06 Apr, 2021
The __filename in the Node.js returns the filename of the code which is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project.
Syntax:
console.log(__filename)
Prerequisites:
Basic knowledge of Node.js
Node.js installed (version 12+)
NPM installed (version 6+)
Return Value: It returns the absolute filename of the current module.
 
Example 1: Create a JavaScript file index.js and write down the following code:
index.js
// Node.js code to demonstrate the absolute// file name of the current Module.console.log("Filename of the current file is: ",    __filename);
Run the index.js file using the following command:
node index.js
Output:
Filename of the current file is:  
  C:\Users\Pallavi\Desktop\node_func\app.js
Example 2:
index.js
// Node.js code to demonstrate the absolute// file name of the current Module  console.log(__filename);  // To show to parts of file using filename.const parts = __filename.split(/[\\/]/);console.log( "This the all the parts "    + "present in file :",parts);
Output:
C:\Users\Pallavi\Desktop\node_func\app.js
This the all the parts present in file : 
  [ 'C:', 'Users', 'Pallavi', 'Desktop', 
  'node_func', 'app.js' ]
Reference: https://nodejs.org/api/globals.html#globals_filename
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Node.js Event Loop
Mongoose Populate() Method
Mongoose find() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Apache Flume - Environment

We already discussed the architecture of Flume in the previous chapter. In this chapter, let us see how to download and setup Apache Flume.
Before proceeding further, you need to have a Java environment in your system. So first of all, make sure you have Java installed in your system. For some examples in this tutorial, we have used Hadoop HDFS (as sink). Therefore, we would recommend that you go install Hadoop along with Java. To collect more information, follow the link − http://www.tutorialspoint.com/hadoop/hadoop_enviornment_setup.htm
First of all, download the latest version of Apache Flume software from the website  https://flume.apache.org/.
Open the website. Click on the download link on the left-hand side of the home page. It will take you to the download page of Apache Flume.
In the Download page, you can see the links for binary and source files of Apache Flume. Click on the link apache-flume-1.6.0-bin.tar.gz
You will be redirected to a list of mirrors where you can start your download by clicking any of these mirrors. In the same way, you can download the source code of Apache Flume by clicking on apache-flume-1.6.0-src.tar.gz.
Create a directory with the name Flume in the same directory where the installation directories of Hadoop, HBase, and other software were installed (if you have already installed any) as shown below.
$ mkdir Flume 

Extract the downloaded tar files as shown below.
$ cd Downloads/ 
$ tar zxvf apache-flume-1.6.0-bin.tar.gz  
$ tar zxvf apache-flume-1.6.0-src.tar.gz

Move the content of apache-flume-1.6.0-bin.tar file to the Flume directory created earlier as shown below. (Assume we have created the Flume directory in the local user named Hadoop.)
$ mv apache-flume-1.6.0-bin.tar/* /home/Hadoop/Flume/

To configure Flume, we have to modify three files namely, flume-env.sh, flumeconf.properties, and bash.rc.
In the .bashrc file, set the home folder, the path, and the classpath for Flume as shown below.
If you open the conf folder of Apache Flume, you will have the following four files −
flume-conf.properties.template,
flume-env.sh.template,
flume-env.ps1.template, and
log4j.properties.
Now rename
flume-conf.properties.template file as flume-conf.properties and
flume-conf.properties.template file as flume-conf.properties and
flume-env.sh.template as flume-env.sh
flume-env.sh.template as flume-env.sh
Open flume-env.sh file and set the JAVA_Home to the folder where Java was installed in your system.
Verify the installation of Apache Flume by browsing through the bin folder and typing the following command.
$ ./flume-ng 

If you have successfully installed Flume, you will get a help prompt of Flume as shown below.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Addition and Concatenation Using + Operator in Java - GeeksforGeeks

07 Dec, 2021
Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves the same way as it was supposed to because the decimal system was getting added up deep down at binary level and the resultant binary number is thrown up at console in the generic decimal system. But geeks even wondered what if we play this + operator between integer and string.
Example
Java
// Java Program to Illustrate Addition and Concatenation  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)    {          // Print statements to illustrate        // addition and Concatenation         // using + operators over string and integer        // combination        System.out.println(2 + 0 + 1 + 6 + "GeeksforGeeks");        System.out.println("GeeksforGeeks" + 2 + 0 + 1 + 6);        System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + 2 + 0 + 1 + 6);        System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + (2 + 0 + 1 + 6));    }}
9GeeksforGeeks
GeeksforGeeks2016
8GeeksforGeeks2016
8GeeksforGeeks9
Output Explanation: This unpredictable output is due to the fact that the compiler evaluates the given expression from left to right given that the operators have the same precedence. Once it encounters the String, it considers the rest of the expression as of a String (again based on the precedence order of the expression).
System.out.println(2 + 0 + 1 + 6 + "GeeksforGeeks");  
It prints the addition of 2,0,1 and 6 which is equal to 9
System.out.println("GeeksforGeeks" + 2 + 0 + 1 + 6); 
It prints the concatenation of 2,0,1 and 6 which is 2016  since it encounters the string initially. Basically, Strings take precedence because they have a higher casting priority than integers do.
System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + 2 + 0 + 1 + 6); 
It prints the addition of 2,0,1 and 5 while the concatenation of 2,0,1 and 6 is based on the above-given examples.
System.out.println(2 + 0 + 1 + 5 + "GeeksforGeeks" + (2 + 0 + 1 + 6)); 
It prints the addition of both 2,0,1 and 5  and 2,0,1 and 6 based due to the precedence of ( ) over +. Hence expression in ( ) is calculated first and then further evaluation takes place.
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
solankimayank
Java-Output
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
How to convert a string in an R data frame to NA?

We often see mistakes in data collection processes and these mistakes might lead to incorrect results of the research. When the data is collected with mistakes, it makes the job of analyst difficult. One of the situations, that shows the data has mistakes is getting strings in place of numerical values. Therefore, we need to convert these strings to NA in R so that we can proceed with our intended analysis.
Consider the below data frame −
> x1<-rep(c(1,3,6,7,5,2,"XYZ",12,4,5),times=2)
> x2<-rep(c(67,"XYZ",45,32,52),each=4)
> df<-data.frame(x1,x2)
> df
 x1 x2
1 1 67
2 3 67
3 6 67
4 7 67
5 5 XYZ
6 2 XYZ
7 XYZ XYZ
8 12 XYZ
9 4 45
10 5 45
11 1 45
12 3 45
13 6 32
14 7 32
15 5 32
16 2 32
17 XYZ 52
18 12 52
19 4 52
20 5 52
Converting all XYZ’s to NA −
> df[df=="XYZ"]<-NA
> df
     x1  x2
 1   1   67
 2   3   67
 3   6   67
 4   7   67
 5   5  <NA>
 6   2  <NA>
 7 <NA> <NA>
 8  12  <NA>
 9   4   45
10   5   45
11   1   45
12   3   45
13   6   32
14   7   32
15   5   32
16   2   32
17 <NA>  52
18  12   52
19   4   52
20   5   52
Let’s have a look at one more example −
> ID<-c("Class",2:20)
> ID<-c("Class",1:19)
> Group<-rep(c("Class",2,3,4,5),times=4)
> df1<-data.frame(ID,Group)
> df1
     ID  Group
 1 Class Class
 2  1   2
 3  2   3
 4  3   4
 5  4   5
 6  5 Class
 7  6   2
 8  7   3
 9  8   4
10  9   5
11 10 Class
12 11   2
13 12   3
14 13   4
15 14   5
16 15 Class
17 16   2
18 17   3
19 18   4
20 19   5
> df1[df1=="Class"]<-NA
> df1
ID Group
1 <NA> <NA>
2 1 2
3 2 3
4 3 4
5 4 5
6 5 <NA>
7 6 2
8 7 3
 9 8 4
10 9 5
11 10 <NA>
12 11 2
13 12 3
14 13 4
15 14 5
16 15 <NA>
17 16 2
18 17 3
19 18 4
20 19 5
What are the differences between a pointer variable and a reference variable in C++?

When a variable is declared as a reference, it becomes an alternative name for an existing variable.
Type &newname = existing name;
Type &pointer;
pointer = variable name;
Pointers are used to store the address of a variable.
Type *pointer;
Type *pointer; 
pointer = variable name;
The main differences between references and pointers are -
References are used to refer an existing variable in another name whereas pointers are used to store the address of a variable.
References cannot have a null value assigned but pointer can.
A reference variable can be referenced bypass by value whereas a pointer can be referenced but pass by reference
A reference must be initialized on declaration while it is not necessary in case of a pointer.
A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack.
Program to find minimum number of busses are required to pass through all stops in Python

Suppose we have a list of numbers called nums and that is showing the bus stops on a line where nums[i] shows the time a bus must arrive at station i. Now that buses can only move forward, we have to find the minimum number of buses that are needed to pass through all the stops.
So, if the input is like nums = [1, 2, 7, 9, 3, 4], then the output will be 2, as one bus can take stops [1, 2, 3, 4] and another can do [7, 9].
To solve this, we will follow these steps−
ans := 0
ans := 0
seen := a list whose length is same as nums and initially filled with false
seen := a list whose length is same as nums and initially filled with false
for each index i and corresponding n in nums, doif seen[i] is false, thenseen[i] := Trueans := ans + 1prev := nfor j in range i+1 to size of nums, doif nums[j] > prev and seen[j] is false, thenseen[j] := Trueprev := nums[j]
for each index i and corresponding n in nums, do
if seen[i] is false, thenseen[i] := Trueans := ans + 1prev := nfor j in range i+1 to size of nums, doif nums[j] > prev and seen[j] is false, thenseen[j] := Trueprev := nums[j]
if seen[i] is false, then
seen[i] := True
seen[i] := True
ans := ans + 1
ans := ans + 1
prev := n
prev := n
for j in range i+1 to size of nums, doif nums[j] > prev and seen[j] is false, thenseen[j] := Trueprev := nums[j]
for j in range i+1 to size of nums, do
if nums[j] > prev and seen[j] is false, thenseen[j] := Trueprev := nums[j]
if nums[j] > prev and seen[j] is false, then
seen[j] := True
seen[j] := True
prev := nums[j]
prev := nums[j]
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
   ans = 0
   seen = [False] * len(nums)
   for i, n in enumerate(nums):
      if not seen[i]:
         seen[i] = True
         ans += 1
         prev = n
   for j in range(i+1, len(nums)):
      if nums[j] > prev and not seen[j]: seen[j] = True
         prev = nums[j]
   return ans
ob = Solution()
nums = [1, 2, 7, 9, 3, 4]
print(ob.solve(nums))
[1, 2, 7, 9, 3, 4]
2
Printing Triangle Pattern in Java - GeeksforGeeks

17 Aug, 2018
Given a number N, the task is to print the following pattern:-
Examples:
Input : 10
Output :                    
          * 
         * * 
        * * * 
       * * * * 
      * * * * * 
     * * * * * * 
    * * * * * * * 
   * * * * * * * * 
  * * * * * * * * * 
 * * * * * * * * * * 

Input :5
Output :
     * 
    * * 
   * * * 
  * * * * 
 * * * * * 

There is a nested loop required to print the above pattern. The outer loop is used to run for the number of rows given as input. The first loop within the outer loop is used to print the spaces before each star. As you can see the number of spaces decreases with each row while we move towards the base of the triangle, so this loop runs one time less with each iteration. The second loop within the outer loop is used to print the stars. As you can see the number of stars increases in each row as we move towards the base of the triangle, so this loop runs one time more with each iteration. Clarity can be achieved if this program is dry run.
// Java Program to print the given patternimport java.util.*; // package to use Scanner classclass pattern {    public static void main(String[] args)    {        Scanner sc = new Scanner(System.in);        System.out.println("Enter the number of rows to be printed");        int rows = sc.nextInt();          // loop to iterate for the given number of rows        for (int i = 1; i <= rows; i++) {              // loop to print the number of spaces before the star            for (int j = rows; j >= i; j--) {                System.out.print(" ");            }              // loop to print the number of stars in each row            for (int j = 1; j <= i; j++) {                System.out.print("* ");            }              // for new line after printing each row            System.out.println();        }    }}
pattern-printing
Java
Java Programs
School Programming
pattern-printing
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Java Program to convert int array to IntStream

To convert int array to IntStream, let us first create an int array:
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
Now, create IntStream and convert the above array to IntStream:
IntStream stream = Arrays.stream(arr);
Now limit some elements and find the sum of those elements in the stream:
IntStream stream = Arrays.stream(arr);
stream = stream.limit(7);

System.out.println("Sum of first 7 elements = "+stream.sum());
The following is an example to convert int array to IntStream:
import java.util.Arrays;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
      System.out.println("Array elements...");
      for (int res : arr)
      {
         System.out.println(res);
      }
      IntStream stream = Arrays.stream(arr);
      stream = stream.limit(7);
      System.out.println("Sum of first 7 elements = "+stream.sum());
   }
}
Array elements...
10
20
30
40
50
60
70
80
90
100
Sum of first 7 elements = 280
How to simulate touch event with android at a given position?

This example demonstrates how do I simulate touch even with android at a given position.
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"
   android:padding="4dp"
   tools:context=".MainActivity">
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   private boolean isTouch = false;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   @Override
   public boolean onTouchEvent(MotionEvent event) {
      int X = (int) event.getX();
      int Y = (int) event.getY();
      int eventAction = event.getAction();
      switch (eventAction) {
         case MotionEvent.ACTION_DOWN:
            Toast.makeText(this, "ACTION_DOWN "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
            isTouch = true;
         break;
         case MotionEvent.ACTION_MOVE:
            Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y,
               Toast.LENGTH_SHORT).show();
         break;
         case MotionEvent.ACTION_UP:
            Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
         break;
      }
      return true;
   }
}
Step 4 − 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 −
MATLAB - Magnitude of a Vector

Magnitude of a vector v with elements v1, v2, v3, ..., vn, is given by the equation −
|v| = √(v12 + v22 + v32 + ... + vn2)
You need to take the following steps to calculate the magnitude of a vector −
Take the product of the vector with itself, using array multiplication (.*). This produces a vector sv, whose elements are squares of the elements of vector v. 
sv = v.*v;
Take the product of the vector with itself, using array multiplication (.*). This produces a vector sv, whose elements are squares of the elements of vector v. 
sv = v.*v;
Use the sum function to get the sum of squares of elements of vector v. This is also called the dot product of vector v.
dp= sum(sv);
Use the sum function to get the sum of squares of elements of vector v. This is also called the dot product of vector v.
dp= sum(sv);
Use the sqrt function to get the square root of the sum which is also the magnitude of the vector v.
mag = sqrt(s);
Use the sqrt function to get the square root of the sum which is also the magnitude of the vector v.
mag = sqrt(s);
Create a script file with the following code −
v = [1: 2: 20];
sv = v.* v;       %the vector with elements 
                  % as square of v's elements
dp = sum(sv);     % sum of squares -- the dot product
mag = sqrt(dp);   % magnitude
disp('Magnitude:'); 
disp(mag);
When you run the file, it displays the following result −
Magnitude:
36.469


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Comparing Strings with (possible) null values in java?

Strings in Java represents an array of characters. They are represented by the String class.
The compareTo() method of the String class two Strings (char by char) it also accepts null values. This method returns an integer representing the result, if the value of the obtained integer is −
0: Given two Strings are equal or, null.
1 or less: The current String preceeds the argument.
1 or more: The current String succeeds the argument.
import java.util.Scanner;
public class CompringStrings {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your first string value: ");
      String str1 = sc.next();
      System.out.println("Enter your second string value: ");
      String str2 = sc.next();
      //Comparing two Strings
      int res = str1.compareTo(str2);
      System.out.println(res);
      if(res==0) {
         System.out.println("Both Strings are null or equal");
      }else if(res<0){
         System.out.println(""+str1+" preceeds "+str2+"");
      }else if(res>0){
         System.out.println(""+str2+" preceeds "+str1+"");
      }
   }
}
Enter your first string value:
null
Enter your second string value:
null
0
Both Strings are null or equal
Enter your first string value:
mango
Enter your second string value:
apple
-1
apple preceeds mango
In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not.
import java.util.Scanner;
public class CompringStrings {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your first string value: ");
      String str1 = sc.next();
      System.out.println("Enter your second string value: ");
      String str2 = sc.next();
      if(str1.equals(str2)) {
         System.out.println("Both Strings are null or equal");
      }else {
         System.out.println("Both Strings are not equal");
      }
   }
}
Enter your first string value:
null
Enter your second string value:
null
0
Both Strings are null or equal
How to overplot a line on a scatter plot in Python?

First, we can create a scatter for different data points using the scatter method, and then, we can plot the lines using the plot method.
Create a new figure, or activate an existing figure with figure size(4, 3), using figure() method.
Create a new figure, or activate an existing figure with figure size(4, 3), using figure() method.
Add an axis to the current figure and make it the current axes, create x using plt.axes().
Add an axis to the current figure and make it the current axes, create x using plt.axes().
Draw scatter points using scatter() method.
Draw scatter points using scatter() method.
Draw line using ax.plot() method.
Draw line using ax.plot() method.
Set the X-axis label using plt.xlabel() method.
Set the X-axis label using plt.xlabel() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
To show the plot, use plt.show() method.
To show the plot, use plt.show() method.
import random
import matplotlib.pyplot as plt

plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter([random.randint(1, 1000) % 50 for i in range(100)],
[random.randint(1, 1000) % 50 for i in range(100)])
ax.plot([1, 2, 4, 50], [1, 2, 4, 50])

ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()
How to use mat-icon in angular?

09 Jun, 2020
To include icons in your webpage, you can use mat-icon directive. Previously it was known as md-icon. It is better to use mat-icon as they serve SVG icons i.e. vector-based icons which are adaptable to any resolution and dimension, on the other hand, raster-based icons have a fixed pattern of dots with specified values and if resized, the resolution changes.
Approach:
First of all we have to load the font library in your HTML file using the following syntax:<link href=”https://fonts.googleapis.com/icon?family=Material+Icons” rel=”stylesheet”>
First of all we have to load the font library in your HTML file using the following syntax:
<link href=”https://fonts.googleapis.com/icon?family=Material+Icons” rel=”stylesheet”>
 Now import MatIconModule in the ngmodule.ts file by using this command:import {MatIconModule} from '@angular/material/icon';
 Now import MatIconModule in the ngmodule.ts file by using this command:
import {MatIconModule} from '@angular/material/icon';
Use the following command to display an icon:<mat-icon>icon-name</mat-icon>
Use the following command to display an icon:
<mat-icon>icon-name</mat-icon>
You can change the color of the icons as per the requirement:
Primary .Accent.Warn.
Primary .
Accent.
Warn.
These icon may be used as buttons or may convey some message such as type of form field, status, etc.
Example:
Using mat-icon let’s  create three different buttons.
In your index.html file, load the font library.
<html lang="en"><head>  <meta charset="utf-8">  <title>Tutorial</title>      <!--font library is loaded prior to using mat-icons-->      <link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block"         rel="stylesheet">  </head><body>  <app-child></app-child></body></html>
Now use mat-icon as buttons.
import { Component } from '@angular/core';  @Component({  selector: 'app-child',  template: `    <button ><mat-icon color = "primary">check</mat-icon></button>  <button ><mat-icon color = "accent">check</mat-icon></button>  <button ><mat-icon color = "warn">check</mat-icon></button>    `,  styleUrls: []})export class childComponent {  }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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 ?
How to Zip two lists of lists in Python?

29 Jun, 2022
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let’s discuss certain ways in which solution can be devised. 
Method #1 : Using map() + __add__ This problem can be solved using the map function with the addition operation. The map function performs the similar kind of function as the zip function and in  this case can help to reach to a solution. 
Python3
# Python3 code to demonstrate# zipping lists of lists# using map() + __add__ # initializing liststest_list1 = [[1, 3], [4, 5], [5, 6]]test_list2 = [[7, 9], [3, 2], [3, 10]] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using map() + __add__# zipping lists of listsres = list(map(list.__add__, test_list1, test_list2))     # printing resultprint ("The modified zipped list is : " +  str(res))
Output :
The original list 1 is : [[1, 3], [4, 5], [5, 6]]
The original list 2 is : [[7, 9], [3, 2], [3, 10]]
The modified zipped list is : [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]
  Method #2 : Using itertools.chain() + zip() This combination of these two functions can be used to perform this particular task. The chain function can be used to perform the interlist aggregation, and the intralist aggregation is done by zip function. 
Python3
# Python3 code to demonstrate# zipping lists of lists# using map() + __add__import itertools # initializing liststest_list1 = [[1, 3], [4, 5], [5, 6]]test_list2 = [[7, 9], [3, 2], [3, 10]] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using map() + __add__# zipping lists of listsres = [list(itertools.chain(*i))       for i in zip(test_list1, test_list2)]     # printing resultprint ("The modified zipped list is : " +  str(res))
Output :
The original list 1 is : [[1, 3], [4, 5], [5, 6]]
The original list 2 is : [[7, 9], [3, 2], [3, 10]]
The modified zipped list is : [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]
surinderdawra388
Marketing
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to check whether all elements in a string list are numeric

24 Jan, 2021
Given a list that contains only string elements the task here is to write a Python program to check if all of them are numeric or not. If all are numeric return True otherwise, return False.
Input : test_list = [“434”, “823”, “98”, “74”]
Output : True
Explanation : All Strings are digits.
Input : test_list = [“434”, “82e”, “98”, “74”]
Output : False
Explanation : e is not digit, hence verdict is False.
Method 1 : Using all(), isdigit() and generator expression
In this, we check for number from isdigit(). all() is used to check for all strings to be number, iteration for each string is done using generator expression.
Example:
Python3
# initializing listtest_list = ["434", "823", "98", "74"]  # printing original listprint("The original list is : " + str(test_list))  # checking all elements to be numeric using isdigit()res = all(ele.isdigit() for ele in test_list)  # printing resultprint("Are all strings digits ? : " + str(res))
Output:
The original list is : [‘434’, ‘823’, ’98’, ’74’]
Are all strings digits ? : True
Method 2 : Using  all(), isdigit() and map()
In this, we extend test logic to each string using map(), rather than generator expression. Rest all the functionalities are performed similar to above method.
Example:
Python3
# initializing listtest_list = ["434", "823", "98", "74"]  # printing original listprint("The original list is : " + str(test_list))  # checking all elements to be numeric using isdigit()# map() to extend to each elementres = all(map(str.isdigit, test_list))  # printing resultprint("Are all strings digits ? : " + str(res))
Output:
The original list is : [‘434’, ‘823’, ’98’, ’74’]
Are all strings digits ? : True
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number