code-rag-bench/online-tutorials huggingface dataset:
C - Loops

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
C programming language provides the following types of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
It is more like a while statement, except that it tests the condition at the end of the loop body.
You can use one or more loops inside any other while, for, or do..while loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement.
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>
 
int main () {

   for( ; ; ) {
      printf("This loop will run forever.\n");
   }

   return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
 Print
 Add Notes
 Bookmark this page
Odd even sort in an array - JavaScript

We are required to write a JavaScript function that takes in an array of numbers and sorts the array such that first all the even numbers appear in ascending order and then all the odd numbers appear in ascending order.
For example: If the input array is −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
Then the output should be −
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Following is the code −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
const isEven = num => num % 2 === 0;
const sorter = ((a, b) => {
   if(isEven(a) && !isEven(b)){
      return -1;
   };
   if(!isEven(a) && isEven(b)){
      return 1;
   };
   return a - b;
});
const oddEvenSort = arr => {
   arr.sort(sorter);
};
oddEvenSort(arr);
console.log(arr);
Following is the output in the console −
[
   2, 2, 6, 8,
   1, 5, 7, 9
]
How to use isEmpty() in Android textview?

This example demonstrate about How to use isEmpty() in Android textview.
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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and check that data is empty or not.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  int index = name.getText().toString().indexOf("sai");
                  text.setText(String.valueOf(index));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}
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 −
In the above result, enter the string as “Krishna sai” and it is not empty string so it returned index of sai as 8.
Click here to download the project code
How to use an image as a link in HTML?

To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image. With that, also add the height and width.
You can try to run the following code to use an image as a link in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Image as link</title>
   </head>
   <body>
      The following image works as a link:<br>
      <a href="https://www.qries.com/">
         <img alt="Qries" src="https://www.qries.com/images/banner_logo.png"
         width=150" height="70">
      </a>
   </body>
</html>
How to use sys.argv in Python - GeeksforGeeks

27 Dec, 2019
Command line arguments are those values that are passed during calling of program along with the calling statement. Thus, the first element of the array sys.argv() is the name of the program itself. sys.argv() is an array for command line arguments in Python. To employ this module named “sys” is used. sys.argv is similar to an array and the values are also retrieved like Python array.
The sys module
The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
Examples:
# Python program to demonstrate# sys.argv    import sys  print("This is the name of the program:", sys.argv[0])  print("Argument List:", str(sys.argv))
Output:
The above program has been saved by the name “com.py” and thus has to be called in the following in command prompt
Functions that can be used with sys.argv
len()- function is used to count the number of arguments passed to the command line. Since the iteration starts with 0, it also counts the name of the program as one argument. If one just wants to deal with other inputs they can use (len(sys.argv)-1).
str()- this function is used to present the array as a string array. Makes displaying the command line array easier and better.
Example:
# Python program to demonstrate# sys.argv    import sys    print("This is the name of the program:",       sys.argv[0])print("Number of elements including the name of the program:",       len(sys.argv))print("Number of elements excluding the name of the program:",      (len(sys.argv)-1))print("Argument List:",       str(sys.argv))
Output:
The following program performs addition using inputs given during runtime:
# Python program to demonstrate# sys.argv    import sys  add = 0.0  # Getting the length of command# line argumentsn = len(sys.argv)  for i in range(1, n):    add += float(sys.argv[i])  print ("the sum is :", add)
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON?
Binary Search Trees - GeeksforGeeks

06 Sep, 2021
          10
        /
       20
      /
     30
    / 
   40

Search 40. 
Delete 40
Insert 50.

The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004) 
2 
3 
4 
6 
Constructed binary search tree will be.
 
            30
         /      \
        20       39 
       /  \     /  \
     10    25  35  42  
      \   /
      15 23


               10
             /    
            5      20
           /      /             
          4     15    30
               /  
              11       
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
C# | Get an ICollection containing the values in ListDictionary - GeeksforGeeks

01 Feb, 2019
ListDictionary.Values property is used to get an ICollection containing the values in the ListDictionary.
Syntax:
public System.Collections.ICollection Values { get; }

Return Value : It returns an ICollection containing the values in the ListDictionary.
Below are the programs to illustrate the use of ListDictionary.Values property:
Example 1:
// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // Creating a ListDictionary named myDict        ListDictionary myDict = new ListDictionary();          myDict.Add("Australia", "Canberra");        myDict.Add("Belgium", "Brussels");        myDict.Add("Netherlands", "Amsterdam");        myDict.Add("China", "Beijing");        myDict.Add("Russia", "Moscow");        myDict.Add("India", "New Delhi");          // Get an ICollection containing        // the values in the ListDictionary        ICollection ic = myDict.Values;          // Displaying the values in ICollection ic        foreach(String str in ic)        {            Console.WriteLine(str);        }    }}
Canberra
Brussels
Amsterdam
Beijing
Moscow
New Delhi

Example 2 :
// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // Creating a ListDictionary named myDict        ListDictionary myDict = new ListDictionary();          myDict.Add("I", "first");        myDict.Add("II", "second");        myDict.Add("III", "third");        myDict.Add("IV", "fourth");        myDict.Add("V", "fifth");          // Get an ICollection containing        // the values in the ListDictionary        ICollection ic = myDict.Values;          // Displaying the values in ICollection ic        foreach(String str in ic)        {            Console.WriteLine(str);        }    }}
first
second
third
fourth
fifth

Note:
The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method.
The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original ListDictionary. Therefore, changes to the ListDictionary continue to be reflected in the ICollection.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.values?view=netframework-4.7.2
CSharp-Specialized-ListDictionary
CSharp-Specialized-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Replace() Method
C# | Data Types
C# | Encapsulation
p5.js | getURL() Function - GeeksforGeeks

09 Jul, 2019
The getURL() function in p5.js is used to return the current URL.
Syntax:
getURL()
Parameters: This function does not accept any parameter.
Return Value: It returns the current URL string.
Below program illustrates the getURL() function in p5.js:
Example:
// Declare a URL variablelet url;  // Function to set the height and// width of windowfunction setup() {    createCanvas(350, 200);          // Use getURL() function to    // get the current URL    url = getURL();}   function draw() {        // Set the background color    background(0, 200, 0);          // Set the font-size    textSize(30);        // Set the text alignment    textAlign(LEFT);        text(url, 100, height / 2);}
Output:
Reference: https://p5js.org/reference/#/p5/getURL
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
JQuery | isEmptyObject() method - GeeksforGeeks

27 Apr, 2020
This isEmptyObject() Method in jQuery is used to determines if an object is empty.
Syntax:
jQuery.isEmptyObject( object )

Parameters: The isEmptyObject() method accepts only one parameter that is mentioned above and described below:
object : This parameter is the object that will be checked to see if it’s empty.
Return Value: It returns the boolean value.
Below examples illustrate the use of isEmptyObject() method in jQuery:
Example 1: In this example, the isEmptyObject() method checks an object to see if it’s empty.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | isEmptyObject() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  </head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | isEmptyObject() method</h3>    <b>Whether '{}' is a Empty Object : </b>    <p></p>          <script>    $( "p" ).append( "" + $.isEmptyObject({}));    </script></body></html>                                                                        
Output:
Example 2: In this example, the isEmptyObject() method also checks an object to see if it’s empty.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | isEmptyObject() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  </head><body style="text-align:center;">           <h1 style="color: green">         GeeksForGeeks     </h1>           <h3>JQuery | isEmptyObject() method</h3>    <b>Whether String is a Empty Object : </b>    <p id ="gfg"></p>    <b>Whether Array is a Empty Object : </b>    <p id ="gfg1"></p>          <script>    // string ="Shubham"    $( "#gfg" ).append( "Shubham : " + $.isEmptyObject("Shubham"));          // array    $( "#gfg1" ).append( "[1, 3, 4, 6, 8] : " + $.isEmptyObject([1, 3, 4, 6, 8]));          </script></body></html>                                                                                                                    
Output:
jQuery-Misc
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Instant parse() method in Java with Examples - GeeksforGeeks

28 Nov, 2018
The parse() method of Instant class help to get an instance of Instant from a string value passed as parameter. This string is an instant in the UTC time zone. It is parsed using DateTimeFormatter.ISO_INSTANT.
Syntax:
public static Instant 
    parse(CharSequence text)
Parameters: This method accepts one parameter text which is the text to parse in instant. It should not be null.
Returns: This method returns an Instant which is the valid instant in the UTC time xone of the String passed as the parameter.
Exception: This method throws DateTimeException if the text cannot be parsed.
Below programs illustrate the parse() method:
Program 1:
// Java program to demonstrate// Instant.parse() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // get Instant using parse method        Instant instant            = Instant.parse("2018-11-30T18:35:24.00Z");          // print result        System.out.println("Instant: "                           + instant);    }}
Instant: 2018-11-30T18:35:24Z

Program 2:
// Java program to demonstrate// Instant.parse() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // get Instant using parse method        Instant instant            = Instant.parse("2019-10-01T08:25:24.00Z");          // print result        System.out.println("Instant: "                           + instant);    }}
Instant: 2019-10-01T08:25:24Z

References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#parse(java.lang.CharSequence)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Python | Find maximum length sub-list in a nested list - GeeksforGeeks

19 Feb, 2019
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length).
Examples:
Input : [['A'], ['A', 'B'], ['A', 'B', 'C']]
Output : (['A', 'B', 'C'], 3)

Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]]
Output : ([1, 2, 3, 9, 4], 5)

 Let’s discuss different approaches to solve this problem.
Approach #1 : Using for loop (Naive)This is a brute force method in which we iterate through each list item(list) and find the list with maximum length. Similarly, we use the for loop to find length of each list and output the maximum length.
# Python3 program to Find maximum # length list in a nested list  def FindMaxLength(lst):    maxList = max((x) for x in lst)    maxLength = max(len(x) for x in lst )      return maxList, maxLength      # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)

 Approach #2 : Using mapIn this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function.
# Python3 program to Find maximum # length list in a nested list  def FindMaxLength(lst):    maxList = max(lst, key = len)    maxLength = max(map(len, lst))          return maxList, maxLength  # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C'], ]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)

 Approach #3 : Using lambda operatorOne more method in Python to find the longest length list is the lambda operator. It is used for creating small, one-time and anonymous function objects in Python. Here we pass a variable i as argument in the len(i) expression and find the maximum length.
# Python3 program to Find maximum # length list in a nested list  def FindMaxLength(lst):    maxList = max(lst, key = lambda i: len(i))    maxLength = len(maxList)          return maxList, maxLength# Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)

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 Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python program to check whether a number is Prime or not
HTML - Color Names

The following table shows the 16 color names that were introduced in HTML 3.2 −
There are other colors which are not part of HTML or XHTML but they are supported by most of the versions of major browsers.
Some characters are reserved in HTML and they have special meaning when used in HTML document. For example, you cannot use the greater than and less than signs or angle brackets within your HTML text because the browser will treat them differently and will try to draw a meaning related to HTML tag.
HTML processors must support following five special characters listed in the table that follows.
If you want to write <div id = "character"> as a code, then you will have to write as follows −
<!DOCTYPE html>
<html>

   <head>
      <title>HTML Entities</title>
   </head>

   <body>
      &lt;div id = "character"&gt;
   </body>

</html>
This will produce the following result −
There is also a long list of special characters in HTML 4.0. In order for these to appear in your document, you can use either the numerical codes or the entity names. For example, to insert a copyright symbol you can use either of the following −
&copy; 2007
or
&#169; 2007


    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Face Detection in 2 Minutes using OpenCV & Python | by Adarsh Menon | Towards Data Science

First of all make sure you have OpenCV installed. You can install it using pip:
pip install opencv-python
Face detection using Haar cascades is a machine learning based approach where a cascade function is trained with a set of input data. OpenCV already contains many pre-trained classifiers for face, eyes, smiles, etc.. Today we will be using the face classifier. You can experiment with other classifiers as well.
You need to download the trained classifier XML file (haarcascade_frontalface_default.xml), which is available in OpenCv’s GitHub repository. Save it to your working location.
To detect faces in images:
A few things to note:
The detection works only on grayscale images. So it is important to convert the color image to grayscale. (line 8)
detectMultiScale function (line 10) is used to detect the faces. It takes 3 arguments — the input image, scaleFactor and minNeighbours. scaleFactor specifies how much the image size is reduced with each scale. minNeighbours specifies how many neighbors each candidate rectangle should have to retain it. You can read about it in detail here. You may have to tweak these values to get the best results.
faces contains a list of coordinates for the rectangular regions where faces were found. We use these coordinates to draw the rectangles in our image.
Results:
Similarly, we can detect faces in videos. As you know videos are basically made up of frames, which are still images. So we perform the face detection for each frame in a video. Here is the code:
The only difference here is that we use an infinite loop to loop through each frame in the video. We use cap.read() to read each frame. The first value returned is a flag that indicates if the frame was read correctly or not. We don’t need it. The second value returned is the still frame on which we will be performing the detection.
Find the code here: https://github.com/adarsh1021/facedetection
Hope you found this useful. Do reach out to me if you have any trouble implementing this or if you need any help.
Email: adarsh1021@gmail.com
Social Media: LinkedIn, Twitter, Instagram, YouTube
Set a container that spans the full width of the screen with Bootstrap

Use the .container-fluid class in Bootstrap to set a container that spans the full width of the screen.
You can try to run the following code to implement the container-fluid class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/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.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container-fluid">
         <h3>Container fluid</h3>
         <div class = "w-100 bg-danger">Normal width</div>
         <div class = "w-75 bg-warning">Width is 75%</div>
         <div class = "w-50 bg-success">Width is 50%</div>
         <div class = "w-25 bg-warning">Width is 25%</div>
      </div>
   </body>
</html>
PySpark - Environment Setup

In this chapter, we will understand the environment setup of PySpark.
Note − This is considering that you have Java and Scala installed on your computer.
Let us now download and set up PySpark with the following steps.
Step 1 − Go to the official Apache Spark download page and download the latest version of Apache Spark available there. In this tutorial, we are using spark-2.1.0-bin-hadoop2.7.
Step 2 − Now, extract the downloaded Spark tar file. By default, it will get downloaded in Downloads directory.
# tar -xvf Downloads/spark-2.1.0-bin-hadoop2.7.tgz

It will create a directory spark-2.1.0-bin-hadoop2.7. Before starting PySpark, you need to set the following environments to set the Spark path and the Py4j path.
export SPARK_HOME = /home/hadoop/spark-2.1.0-bin-hadoop2.7
export PATH = $PATH:/home/hadoop/spark-2.1.0-bin-hadoop2.7/bin
export PYTHONPATH = $SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip:$PYTHONPATH
export PATH = $SPARK_HOME/python:$PATH

Or, to set the above environments globally, put them in the .bashrc file. Then run the following command for the environments to work.
# source .bashrc

Now that we have all the environments set, let us go to Spark directory and invoke PySpark shell by running the following command −
# ./bin/pyspark

This will start your PySpark shell.
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.1.0
      /_/
Using Python version 2.7.12 (default, Nov 19 2016 06:48:10)
SparkSession available as 'spark'.
<<<

 Print
 Add Notes
 Bookmark this page
How to multiply two matrices using pointers in C?

Pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
The execution time of a pointer is faster because of the direct access to a memory location.
With the help of pointers, the memory is accessed efficiently i.e. memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Pointer declaration, initialization and accessing
Consider the following statement −
int qty = 179;
In the memory, the variable can be represented as shown below −
Declaring a pointer can be done as shown below −
Int *p;
It means ‘p’ is a pointer variable which holds the address of another integer variable.
The address operator (&) is used to initialize a pointer variable.
For example,
int qty = 175;
int *p;
p= &qty;
To access the value of the variable, indirection operator (*) is used.
Following is the C program to multiply the two matrices by using pointers −
 Live Demo
#include <stdio.h>
#define ROW 3
#define COL 3
/* Function declarations */
void matrixInput(int mat[][COL]);
void matrixPrint(int mat[][COL]);
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);
int main() {
   int mat1[ROW][COL];
   int mat2[ROW][COL];
   int product[ROW][COL];
   printf("Enter elements in first matrix of size %dx%d\n", ROW, COL);
   matrixInput(mat1);
   printf("Enter elements in second matrix of size %dx%d\n", ROW, COL);
   matrixInput(mat2);
   matrixMultiply(mat1, mat2, product);
   printf("Product of both matrices is : \n");
   matrixPrint(product);
   return 0;
}
void matrixInput(int mat[][COL]) {
   int row, col;
   for (row = 0; row < ROW; row++) {
      for (col = 0; col < COL; col++) {
         scanf("%d", (*(mat + row) + col));
      }
   }
}
void matrixPrint(int mat[][COL]) {
   int row, col;
   for (row = 0; row < ROW; row++) {
      for (col = 0; col < COL; col++) {
         printf("%d ", *(*(mat + row) + col));
      }
      printf("\n");
   }
}
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]) {
   int row, col, i;
   int sum;
   for (row = 0; row < ROW; row++) {
      for (col = 0; col < COL; col++) {
         sum = 0;
         for (i = 0; i < COL; i++) {
            sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));
         }
         *(*(res + row) + col) = sum;
      }
   }
}
When the above program is executed, it produces the following output −
Enter elements in first matrix of size 3x3
2 3 1
2 5 6
2 6 8
Enter elements in second matrix of size 3x3
1 2 1
2 3 4
5 6 7
Product of both matrices is :
13 19 21
42 55 64
54 70 82
GATE | GATE CS 1996 | Question 38

03 Jul, 2020
The average number of key comparisons done in a successful sequential search in a list of length it is(A) log n(B) (n-1)/2(C) n/2(D) (n+1)/2Answer: (D)Explanation: If element is at 1 position then it requires 1 comparison.If element is at 2 position then it requires 2 comparison.If element is at 3 position then it requires 3 comparison.Similarly , If element is at n position then it requires n comparison.
Total comparison 
= n(n+1)/2

For average comparison 
= (n(n+1)/2) / n 
= (n+1)/2 
Option (D) is correct.Quiz of this Question
vivekkumarmth0077
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optional isPresent() method in Java with examples

30 Jul, 2019
The isPresent() method of java.util.Optional class in Java is used to find out if there is a value present in this Optional instance. If there is no value present in this Optional instance, then this method returns false, else true.
Syntax:
public boolean isPresent()

Parameters: This method do not accept any parameter.
Return value: This method returns a boolean value stating whether if there is a value present in this Optional instance.
Below programs illustrate isPresent() method:Program 1:
// Java program to demonstrate// Optional.isPresent() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);          // check for the value        System.out.println("Is any value present: "                           + op.isPresent());    }}
Optional: Optional[9455]
Is any value present: true

Program 2:
// Java program to demonstrate// Optional.isPresent() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // check for the value            System.out.println("Is any value present: "                               + op.isPresent());        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
Is any value present: false

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#isPresent–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Python List pop() Method

Python list method pop() removes and returns last object or obj from the list.
Following is the syntax for pop() method −
list.pop(obj = list[-1])

obj − This is an optional parameter, index of the object to be removed from the list.
obj − This is an optional parameter, index of the object to be removed from the list.
This method returns the removed object from the list.
The following example shows the usage of pop() method.
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc'];
print "A List : ", aList.pop()
print "B List : ", aList.pop(2)
When we run above program, it produces following result −
A List :  abc
B List :  zara
Limited rows selection with given column in Pandas | Python

24 Oct, 2019
Methods in Pandas like iloc[], iat[] are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods.
Example 1: Select two columns
# Import pandas package import pandas as pd     # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],         'Age':[27, 24, 22, 32],         'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],         'Qualification':['Msc', 'MA', 'MCA', 'Phd']}     # Convert the dictionary into DataFrame  df = pd.DataFrame(data)     # select three rows and two columns print(df.loc[1:3, ['Name', 'Qualification']])
Output:
     Name Qualification
1  Princi            MA
2  Gaurav           MCA
3    Anuj           Phd

Example 2: First filtering rows and selecting columns by label format and then Select all columns.
# Import pandas package import pandas as pd     # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],         'Age':[27, 24, 22, 32],         'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],         'Qualification':['Msc', 'MA', 'MCA', 'Phd']        }   # Convert the dictionary into DataFrame  df = pd.DataFrame(data)     # .loc DataFrame method # filtering rows and selecting columns by label format # df.loc[rows, columns] # row 1, all columns print(df.loc[0, :] )
Output:
Address          Delhi
Age                 27
Name               Jai
Qualification      Msc
Name: 0, dtype: object


Example 3: Select all or some columns, one to another using .iloc.
# Import pandas package import pandas as pd     # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],         'Age':[27, 24, 22, 32],         'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],         'Qualification':['Msc', 'MA', 'MCA', 'Phd']}     # Convert the dictionary into DataFrame  df = pd.DataFrame(data)     # iloc[row slicing, column slicing] print(df.iloc [0:2, 1:3] )
Output:
   Age    Name
0   27     Jai
1   24  Princi

pandas-dataframe-program
Python-pandas
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Quorum Consistency in Cassandra

24 Jun, 2022
In this article, we will discuss how quorum consistency is helpful in Cassandra and how we can calculate it, and also discuss how quorum consistency works. 
What is Quorum Consistency? 
Quorum consistency is consistency in Cassandra for high mechanism and to ensure that how many nodes will respond when we will define the read and write consistency in Cassandra. In Quorum consistency a majority of (n/2 +1) nodes of the replicas must respond. In Quorum, we check the majority of replicas (which simply means the number of replication factors). for example, if we have a replication factor of 3 in 2 data centers then how many their replicas will be there. so, there will be 6 and the majority is 4. (total_sum_replicas/2 + 1). Generally, we use local quorum in most cases in which we need 2 nodes from the LOCAL DC to succeed when if there are three replicas each in 3 data centers. Now, here we are just going to define the CQL query for the same. let’s have a look.
CREATE KEYSPACE cluster1
with replication =  {'class' : 'NetworkTopologyStrategy', 
                     'DC1': 3, 'DC2': 3, 'DC3': 3}
AND DURABLE_WRITES = false; 
To verify the results used the following CQL query given below.
SELECT * 
FROM system_schema.keyspaces; 
Output:  How QUORUM is calculated? 
This is how we calculate quorum which simply means how many nodes will acknowledge.
Quorum = (sum_of_replication_factors / 2) + 1 
Quorum is equal to the sum of replication factors division by 2 and added 1. It’s because to make it a whole number. 
Quorum consistency: The sum of all the replication_factor settings for each data center is the sum_of_replication_factors.
Total_sum_of_replication_factor = DC1_RF + DC2_RF + DC3_RF+ ... +DC_RF 
How does Quorum consistency work? 
If there are three nodes that are in majority and they have to respond in Quorum consistency then in the below-given diagram acknowledgment is showing that there are three nodes responding and at the time writing data then committed nodes showing that we committed our data into three nodes.
  
In the above  “Commit data” diagram if we are inserting data into a table and RF =3 that means data will be replicated on three nodes that are available. The commit operation is complete only after successfully replicating in at least 3 nodes. In the  “Acknowledgement” diagram, it shows that if we are reading data and there are a total of 5 nodes while applying the quorum consistency we get (5/2 +1)=3 nodes. Hence we need acknowledgment from 3 nodes before responding to a read request.
srinitishkp0309
Apache
Technical Scripter 2019
DBMS
Technical Scripter
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unordered_map count() in C++

26 Sep, 2018
The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key.
Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the unordered_map with a given key or not.
Syntax:
size_type count(Key);

Parameters: This function accepts a single parameter key which is needed to be checked in the given unordered_map container.
Return Value: This function returns 1 if there exists a value in the map with the given key, otherwise it returns 0.
Below programs illustrate the unordered_map::count() function:
Program 1:
// C++ program to illustrate the // unordered_map::count() function  #include<iostream>#include<unordered_map>  using namespace std;  int main(){    // unordered map    unordered_map<int , string> umap;          // Inserting elements into the map    umap.insert(make_pair(1,"Welcome"));    umap.insert(make_pair(2,"to"));    umap.insert(make_pair(3,"GeeksforGeeks"));          // Check if element with key 1 is present using     // count() function    if(umap.count(1))    {        cout<<"Element Found"<<endl;    }    else    {        cout<<"Element Not Found"<<endl;        }          return 0;}
Element Found

Program 2:
// C++ program to illustrate the // unordered_map::count() function  #include<iostream>#include<unordered_map>  using namespace std;  int main(){    // unordered map    unordered_map<int , string> umap;          // Inserting elements into the map    umap.insert(make_pair(1,"Welcome"));    umap.insert(make_pair(2,"to"));    umap.insert(make_pair(3,"GeeksforGeeks"));          // Try inserting element with    // duplicate keys    umap.insert(make_pair(3,"CS Portal"));          // Print the count of values with key 3    // to check if duplicate values are stored     // or not    cout<<"Count of elements in map, mapped with key 3: "            <<umap.count(3);          return 0;}
Count of elements in map, mapped with key 3: 1

cpp-unordered_map-functions
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decimal.Compare() Method in C#

29 Jan, 2019
This method is used to compare two specified Decimal values.
Syntax: public static int Compare (decimal a1, decimal a2);
Parameters:a1:This parameter specifies the first value to compare.a2:This parameter specifies the second value to compare.
Return Value: It returns a signed number indicating the relative values of a1 & a2.
If the value is less than zero, it means a1 is less than a2.
If the value is greater than zero, it means a1 is greater than a2.
If the value is zero, it means a1 is equal to a2.
Below programs illustrate the use of Decimal.Compare(Decimal, Decimal) Method
Example 1: When a1 is greater than a2.
// C# program to demonstrate the// Decimal.Compare(Decimal, // Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variables        Decimal a1 = 4;        Decimal a2 = 3;          // comparing the two Decimal value        // using Compare() method;        Decimal value = Decimal.Compare(a1, a2);          // Display the compare value        Console.WriteLine("The compare value is : {0}",                                                value);    }}
The compare value is : 1

Example 2: When a1 is less than a2.
// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variables        Decimal a1 = 1;        Decimal a2 = 9;          // comparing the two Decimal value        // using Compare() method;        Decimal value = Decimal.Compare(a1, a2);          // Display the compare value        Console.WriteLine("The compare value is : {0}",                                                value);    }}
The compare value is : -1

Example 3: When a1 is equals to a2.
// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring the decimal variables        Decimal a1 = 5;        Decimal a2 = 5;          // comparing the two Decimal value        // using Compare() method;        Decimal value = Decimal.Compare(a1, a2);          // Display the compare value        Console.WriteLine("The compare value is : {0}",                                                value);    }}
The compare value is : 0

CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors
p5.js | fullscreen() function

16 Apr, 2019
The fullscreen() function in p5.js is used to get the current fullscreen state of the user’s browser window. If an argument is given, sets the sketch to fullscreen or not based on the value of the argument. If no argument is given, returns the current fullscreen state. Note that due to browser restrictions this can only be called on user input.
Syntax:
fullscreen()
Parameters: The function does not accept any parameters.
Below program illustrates the fullscreen() function in p5.js:
Example:
function setup() {          // Set the background color    background(200);}function mousePressed() {          // Set the value of fullscreen    // into the variable    let fs = fullscreen();          // Call to fullscreen function    fullscreen(!fs); }
Output:Before Clicking the screen:
After Clicking the screen:
Reference: https://p5js.org/reference/#/p5/fullscreen
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.