code-rag-bench/online-tutorials huggingface dataset:
Create a tuple from string and list - Python - GeeksforGeeks

26 Nov, 2019
Sometimes, we can have a problem in which we need to construct a new container with elements from different containers. This kind of problem can occur in domains in which we use different types of data. Let’s discuss ways to convert string and list data to tuple.
Method #1 : Using List conversion to tuple + tuple()In this method, we convert the string to list and then append to target list and then convert this result list to tuple using tuple().
# Python3 code to demonstrate working of# Construct tuple from string and list# using list conversion to tuple + tuple()  # initialize list and string test_list = ["gfg", "is"]test_str = "best"  # printing original list and tupleprint("The original list : " + str(test_list))print("The original string : " + test_str)  # Construct tuple from string and list# using list conversion to tuple + tuple()res = tuple(test_list + [test_str])  # printing resultprint("The aggregated tuple is : " + str(res))
The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')

 
Method #2 : Using Tuple conversion to tuple + tuple()This is another way in which this task can be performed. In this, we convert the string and list both to tuple and add them to result tuple. This method is more efficient than the above method.
# Python3 code to demonstrate working of# Construct tuple from string and list# using tuple conversion to tuple + tuple()  # initialize list and string test_list = ["is", "best"]test_str = "gfg"  # printing original list and tupleprint("The original list : " + str(test_list))print("The original string : " + test_str)  # Construct tuple from string and list# using tuple conversion to tuple + tuple()res = (test_str, ) + tuple(test_list)  # printing resultprint("The aggregated tuple is : " + str(res))
The original list : ['gfg', 'is']
The original string : best
The aggregated tuple is : ('gfg', 'is', 'best')

Python tuple-programs
Python
Python Programs
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?
Stack toArray() method in Java with Example - GeeksforGeeks

24 Dec, 2018
The toArray() method of Stack class in Java is used to form an array of the same elements as that of the Stack. Basically, it copies all the element from a Stack to a new array.
Syntax:
Object[] arr = Stack.toArray()
Parameters: The method does not take any parameters.
Return Value: The method returns an array containing the elements similar to the Stack.
Below programs illustrate the Stack.toArray() method:
Program 1:
// Java code to illustrate toArray()  import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements into the Stack        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("For");        stack.add("Geeks");          // Displaying the Stack        System.out.println("The Stack: " + stack);          // Creating the array and using toArray()        Object[] arr = stack.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The Stack: [Welcome, To, Geeks, For, Geeks]
The array is:
Welcome
To
Geeks
For
Geeks

Program 2:
// Java code to illustrate toArray()  import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Use add() method to add elements into the Stack        stack.add(10);        stack.add(15);        stack.add(30);        stack.add(20);        stack.add(5);        stack.add(25);          // Displaying the Stack        System.out.println("The Stack: " + stack);          // Creating the array and using toArray()        Object[] arr = stack.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The Stack: [10, 15, 30, 20, 5, 25]
The array is:
10
15
30
20
5
25

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Reverse a string in Java
Arrays.sort() in Java with examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Differentiate between LOC and Function Point in Software Engineering - GeeksforGeeks

26 Apr, 2021
1. Lines of Code (LOC) :The line of code (LOC) metric is any line of text in a code that is not a comment or blank line, in any case of the number of statements or fragments of statements on the line. LOC clearly consists of all lines containing program header files, declaration of any variable, and executable and non-executable statements. As Lines of Code (LOC) only counts the proportion of code, you can only utilize it to compare or estimate projects that utilize the same language and are programmed using the same coding standards. 
Example of Line of Code :
C++
void selSort(int x[], int n) {  //Below function sorts an array in ascending order    int i, j, min, temp;   for (i = 0; i < n - 1; i++) {      min = i;      for (j = i + 1; j < n; j++)      if (x[j] < x[min])      min = j;      temp = x[i];      x[i] = x[min];      x[min] = temp;   }}
So, now If LOC is simply a count of the numbers of lines then the above function shown contains 13 lines of code (LOC). But when comments and blank lines are ignored, the function shown above contains 12 lines of code (LOC).
2. Function Point (FP) :In the function point metric, the number and type of functions hold up by the software are used to find FPC (function point count).
Example of function point :Check out this article for detailed example : Calculation of Function Point (FP)Both function point and LOC are measurement units for the size of the software. The size of the software that is dependent on development is necessary in order to come up with accurate estimates of the effort, cost, and duration of a project. Most parametric estimation models such as the Constructive Cost Model (COCOMO) accept size conveyed in either FP or LOC as an input.
Difference between LOC and Function Point :
In general, people prefer the functional size of software indicated as Function Point for one very important reason, i.e, the size expressed using the Function point metric stays constant in any case and whichever language or languages are used.
 
Software Testing
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Coupling and Cohesion
Software Engineering | Spiral Model
Convert distance from km to meters and centimeters in PL/SQL - GeeksforGeeks

15 Apr, 2021
Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given distance in kilometres and task is to convert it into meters and centimeters. Examples:  
Input: KM = 10
Output: 10 KM is equivalent to 10000 meters
        10 KM is equivalent to 1000000 centimeters
Input: KM = 2.5
Output: 2.5 KM is equivalent to 2500 meters
        2.5 KM is equivalent to 250000 centimeters
Approach is to multiply the KM data with 1000 for converting into meter and with 100000 for converting into centimeter. Below is the required implementation:  
SQL
--DECLARATION SECTION DECLARE    --VARIABLE DECLARATION -KM, MET, CEM;    km  NUMBER := 6.9;    met NUMBER := 0;    cem NUMBER := 0;--CODE BLOCK BEGIN    --CALCULATE METERS    met := km * 1000;     --CALCULATE CENTIMETERS    cem := met * 100;     --DISPLAY RESULT      dbms_output.Put_line('6.9KM is equivalent to meters: ' ||met);                               dbms_output.Put_line('6.9KM is equivalent to centimeters:' ||cem);                          END;--END PROGRAM
Output :  
6.9KM is equivalent to meters: 6900
6.9KM is equivalent to centimeters:690000
 
arorakashish0911
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
MySQL | Regular expressions (Regexp)
Python Program for Sum of squares of first n natural numbers

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a positive integer N as input . We need to compute the value of 12 + 22 + 32 + ..... + N2.
Problem statement:This can be solved by two methods
Multiplication addition arithmetic
Using mathematical formula
Here we run a loop from 1 to n and for each i, 1 <= i <= n, find i2 and add to sm.
 Live Demo
def sqsum(n) :
   sm = 0
   for i in range(1, n+1) :
      sm = sm + pow(i,2)
   return sm
# main
n = 5
print(sqsum(n))
55
As we all know that the sum of squares of natural numbers is given by the formula −
(n * (n + 1) * (2 * n + 1)) // 6n *
(n + 1) * (2 * n + 1)) // 6
(n * (n + 1) * (2 * n + 1)) // 6(n * (n + 1) * (2 * n + 1)) // 6
 Live Demo
def squaresum(n) :
   return (n * (n + 1) * (2 * n + 1)) // 6
# Driven Program
n = 10
print(squaresum(n))
385
In this article, we learned about the approach to find the Sum of squares of first n natural numbers.
Boolean Type in Java

To display Boolean type, firstly take two variables and declare them as boolean.
boolean val1, val2;
Then one by one assign values to both of them, one of them is shown below −
val1 = true;
Now, use if statement to check and display the Boolean true value.
if(val1)
System.out.println("This is true and will get displayed!");
Let us now see the complete example to work with Boolean Type in Java.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      boolean val1, val2;
      System.out.println("Boolean Type in Java");
      val1 = true;
      if(val1)
      System.out.println("This is true and will get displayed!");
      val2 = false;
      if(val2)
      System.out.println("This is false and won't get displayed!");
   }
}
Boolean Type in Java
This is true and will get displayed!
C++ Regex Library - regex_iterator

It is an iterator type to iterate over different matches of a same regex pattern in a sequence.
Following is the declaration for std::regex_iterator.
emplate <class BidirectionalIterator,
          class charT=typename iterator_traits<BidirectionalIterator>::value_type,
          class traits=regex_traits<charT> > class regex_iterator;
emplate <class BidirectionalIterator,
          class charT=typename iterator_traits<BidirectionalIterator>::value_type,
          class traits=regex_traits<charT> > class regex_iterator;
emplate <class BidirectionalIterator,
          class charT=typename iterator_traits<BidirectionalIterator>::value_type,
          class traits=regex_traits<charT> > class regex_iterator;
BidirectionalIterator − It is a bidirectional iterator type that iterates on the target sequence of characters.
BidirectionalIterator − It is a bidirectional iterator type that iterates on the target sequence of characters.
charT − It is a char type.
charT − It is a char type.
traits − It is a regex traits type.
traits − It is a regex traits type.
It returns a string object with the resulting sequence.
No-noexcept − this member function never throws exceptions.
In below example for std::regex_iterator.
#include <regex>
#include <iterator>
#include <iostream>
#include <string>

int main() {
   const std::string s = "Tutorialspoint.com india pvt ltd.";
 
   std::regex words_regex("[^\\s]+");
   auto words_begin = 
      std::sregex_iterator(s.begin(), s.end(), words_regex);
   auto words_end = std::sregex_iterator();
 
   std::cout << "Found " 
      << std::distance(words_begin, words_end) 
      << " words:\n";
 
   for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
      std::smatch match = *i;
      std::string match_str = match.str();
      std::cout << match_str << '\n';
   }
}
The output should be like this −
Found 4 words:
Tutorialspoint.com
india
pvt
ltd.

 Print
 Add Notes
 Bookmark this page
AWK - Unary Operators

AWK supports the following unary operators −
It is represented by +. It multiplies a single operand by +1.
[jerry]$ awk 'BEGIN { a = -10; a = +a; print "a =", a }'
On executing this code, you get the following result −
a = -10

It is represented by -. It multiplies a single operand by -1.
[jerry]$ awk 'BEGIN { a = -10; a = -a; print "a =", a }'
On executing this code, you get the following result −
a = 10

 Print
 Add Notes
 Bookmark this page
How to display progress dialog before starting an activity in Android?

This example demonstrates how do I to display progress dialog before starting an activity in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_marginTop="30dp"
      android:text="Showing Progress dialog before starting the activity in Android.."
      android:textStyle="bold"
      android:textSize="24sp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   ProgressDialog progressDialog;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      progressDialog = new ProgressDialog(this);
      progressDialog.setTitle("Content Loader");
      progressDialog.setProgress(10);
      progressDialog.setMax(100);
      progressDialog.setMessage("Loading...");
      new MyTask().execute();
   }
   public class MyTask extends AsyncTask<Void, Void, Void> {
      public void onPreExecute() {
         progressDialog.show();
      }
      public Void doInBackground(Void... unused) {
         return null;
      }
   }
}
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 the 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 −
Click here to download the project code.
C++ Program to Find Quotient and Remainder

Quotient and Remainder are parts of division along with dividend and divisor.
The number which we divide is known as the dividend. The number which divides the dividend is known as the divisor. The result obtained after the division is known as the quotient and the number left over is the remainder.
dividend = divisor * quotient + remainder
For Example: If 15 is divided by 7, then 2 is the quotient and 1 is the remainder. Here, 15 is the dividend and 7 is the divisor.
15 = 7 * 2 + 1
A program to find quotient and remainder is as follows:
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int divisor, dividend, quotient, remainder;
   dividend = 15;
   divisor = 7;
   quotient = dividend / divisor;
   remainder = dividend % divisor;
   cout << "Dividend is " << dividend <<endl;
   cout << "Divisor is " << divisor <<endl;
   cout << "Quotient is " << quotient << endl;
   cout << "Remainder is " << remainder;
   return 0;
}
Dividend is 15
Divisor is 7
Quotient is 2
Remainder is 1
In the above program, the quotient is obtained by dividing the dividend by the divisor. The remainder is obtained by using the modulus operator on dividend and divisor.
quotient = dividend / divisor;
remainder = dividend % divisor;
After that the dividend, divisor, quotient and remainder are displayed.
cout << "Dividend is " << dividend <<endl;
cout << "Divisor is " << divisor <<endl;
cout << "Quotient is " << quotient << endl;
cout << "Remainder is " << remainder;
How to click on <input type=file> across browsers using Selenium Webdriver?

We can click on a button with <input type= file> across browsers with Selenium webdriver. First of all we need to identify the element with the help of locators like xpath or css, then apply sendKeys() method where the path of the file to be uploaded is passed.
Let us see the html code of an element with input type as file. The corresponding representation of the element on the screen shall be.
For working with this element we need to first interact with the Browse button and also the path of the file to be uploaded should be valid.
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 TypeFile{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[type='file']"));
      // file path passed with sendkeys()
      l.sendKeys("C:\\Users\\ghs6kor\\Pictures\\Desert.jpg");
      driver.quit();
   }
}
Unique Paths in Python

Suppose there is a robot is located at the top-left corner of a n x m grid (n rows and m columns). The robot can only move either down side or right side at any point in time. The robot wants to reach the bottom-right corner of the grid (marked 'END in the diagram below). So we have to find how many possible unique paths are there? For example if m = 3 and n = 2, then the grid will be like below −
The output will be 3, So there are total 3 different ways to reach from start position to the end position. These paths are −
Right → Right → DownRight → Down → RightDown → Right → Right
Right → Right → Down
Right → Down → Right
Down → Right → Right
Let us see the steps −
We will use the dynamic programming approach to solve this
let row := n and col := m, create a table DP of order n x m and fill this with -1
DP[row – 2, col - 1] := 1
for i in range 0 to colDP[n – 1, i] := 1
DP[n – 1, i] := 1
for i in range 0 to rowDP[i, col – 1] := 1
DP[i, col – 1] := 1
for i in range row -2 down to -1for j in range col -2 down to -1DP[i, j] := DP[i + 1, j] + DP[i, j + 1]
for j in range col -2 down to -1DP[i, j] := DP[i + 1, j] + DP[i, j + 1]
DP[i, j] := DP[i + 1, j] + DP[i, j + 1]
return DP[0, 0]
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def uniquePaths(self, m, n):
      row = n
      column = m
      dp = [[-1 for i in range(m)] for j in range(n)]
      dp[row-2][column-1] = 1
      for i in range(column):
         dp[n-1][i] = 1
      for i in range(row):
         dp[i][column-1]=1
      for i in range(row-2,-1,-1):
         for j in range(column-2,-1,-1):
            dp[i][j] = dp[i+1][j] + dp[i][j+1]
      return dp[0][0]
ob1 = Solution()
print(ob1.uniquePaths(10,3))
10
3
55
Python | os.link() method - GeeksforGeeks

02 Mar, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.os.link() method in Python is used to create a hard link. This method creates a hard link pointing to the source named destination. To read about the hard link, please refer to this article. 
Note: This method is only available on Windows and Unix platforms.  
Syntax: os.link(src, dst, *, src_dir_fd = None, dst_dir_fd = None, follow_symlinks = True)Parameters: src: A path-like object representing the file system path. This is the source file path for which the hard link will be created dst: A path-like object representing the file system path. This is the target file path where hard link will be created. A path-like object is a string or bytes object which represents a path. src_dir_fd (optional): A file descriptor referring to a directory.The default value of this parameter is None. If the specified src path is absolute then this parameter is ignored. If the specified src path is relative and src_dir_fd is not None then the specified src path is relative to the directory associated with src_dir_fd. dst_dir_fd (optional): A file descriptor referring to a directory. follow_symlinks (optional) : A Boolean value.Return type: This method does not return any value.  
Code: Use of os.link() method  
Python3
# Python program to explain os.link() method   # importing os moduleimport os  # Source file pathsrc = '/home/ihritik/file.txt' # Destination file pathdst = '/home/ihritik/Desktop/file(link).txt' # Create a hard link# pointing to src named dst# using os.link() methodos.link(src, dst) print("Hard link created successfully")
Hard link created successfully
 
Reference: https://docs.python.org/3/library/os.html#os.link 
ashishkapur10
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Count number of columns of a Pandas DataFrame - GeeksforGeeks

26 Jul, 2020
Let’s discuss how to count the number of columns of a Pandas DataFrame. Lets first make a dataframe.
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np  # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel',                 'Sanskriti', 'Abhishek Jain'],         'Age': [22, 20, np.inf, -np.inf, 22],         'Marks': [90, 84, 33, 87, 82]}  # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict)  # Print Dataframedf
Output: 
 
Method 1: Using shape property
Shape property returns the tuple representing the shape of the DataFrame. The first index consists of the number of rows and the second index consist of the number of columns. 
Python3
# Getting shape of the dfshape = df.shape  # Printing Number of columnsprint('Number of columns :', shape[1])
Output:  
 
Method 2: Using columns property
The columns property of the Pandas DataFrame return the list of columns and calculating the length of the list of columns, we can get the number of columns in the df. 
Python3
# Getting the list of columnscol = df.columns  # Printing Number of columnsprint('Number of columns :', len(col))
Output:  
 
Method 3: Casting DataFrame to list
Like the columns property, typecasting DataFrame to the list returns the list of the name of the columns.
Python3
# Typecasting df to listdf_list = list(df)  # Printing Number of columnsprint('Number of columns :', len(df_list))
Output:  
 
Method 4: Using info() method of DataFrame
This methods prints a concise summary of the DataFrame. info() method prints information about the DataFrame including dtypes of columns and index, memory usage, number of columns, etc.
Python3
# Printing info of dfdf.info()
Output:  
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
How do we compare two tuples in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on. 
>>> a = (1, 2, 3)
>>> b = (1, 2, 5)
>>> a < b
True
There is another type of comparison that takes into account similar and different elements. This can be performed using sets. Sets will take the tuples and take only unique values. Then you can perform a & operation that acts like intersection to get the common objects from the tuples. 
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a) & set(b)
{5}
You can also use set.intersection function to perform this operation. 
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])
Concept of Callable Classes in Dart - GeeksforGeeks

20 Jul, 2020
Dart allows the user to create a callable class which allows the instance of the class to be called as a function. To allow an instance of your Dart class to be called like a function, implement the call() method. 
Syntax:
class class_name {
  ... // class content
  
  return_type call ( parameters ) {
    ... // call function content
  }
  
}

In the above syntax, we can see that to create a callable class we have to define a call method with a return type and parameters within it.
Example 1: Implementing a callable class in Dart.
Dart
// Creating Class GeeksForGeeksclass GeeksForGeeks {      // Defining call method which create the class callable  String call(String a, String b, String c) => 'Welcome to $a$b$c!';}  // Main Functionvoid main() {  // Creating instance of class  var geek_input = GeeksForGeeks();      // Calling the class through its instance  var geek_output = geek_input('Geeks', 'For', 'Geeks');      // Printing the output  print(geek_output);}
 
Output:
Welcome to GeeksForGeeks!

It must be noted that Dart doesn’t support multiple callable methods i.e. if we try to create more than one callable function for the same class it will display error.
Example 2: Implementing multiple callable functions in a class of Dart.
Dart
// Creating Class GeeksForGeeksclass GeeksForGeeks {  // Defining call method which create the class callable  String call(String a, String b, String c) => 'Welcome to $a$b$c!';      // Defining another call method for the same class  String call(String a) => 'Welcome to $a!';}  // Main Functionvoid main() {  // Creating instance of class  var geek_input = GeeksForGeeks();      // Calling the class through its instance  var geek_output = geek_input('Geeks', 'For', 'Geeks');      // Printing the output  print(geek_output);}
 
Output:
Error compiling to JavaScript:
main.dart:3:10:
Error: 'call' is already declared in this scope.
  String call(String a) => 'Welcome to $a!';
         ^^^^
main.dart:2:10:
Info: Previous declaration of 'call'.
  String call(String a, String b, String c) => 'Welcome to $a$b$c!';
         ^^^^
main.dart:8:31:
Error: Can't use 'call' because it is declared more than once.
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
                              ^^^^
main.dart:8:31:
Error: The method 'call' isn't defined for the class 'GeeksForGeeks'.
 - 'GeeksForGeeks' is from 'main.dart'.
  var geek_output = geek_input('Geeks', 'For', 'Geeks');
                              ^
Error: Compilation failed.

Dart-Function
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Flutter - BorderRadius Widget
Format Dates in Flutter
Flutter - Positioned Widget
Flutter - Dialogs
Perl read Function

This function reads, or attempts to read, LENGTH number of bytes from the file associated with FILEHANDLE into BUFFER. If an offset is specified, the bytes that are read are placed into the buffer starting at the specified offset.
Following is the simple syntax for this function −
read FILEHANDLE, SCALAR, LENGTH, OFFSET

read FILEHANDLE, SCALAR, LENGTH

This function the number of bytes read or the undefined value.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

my($buffer) = "";
open(FILE, "/etc/services") or
     die("Error reading file, stopped");
while(read(FILE, $buffer, 100) ) {
   print("$buffer\n");
}
close(FILE);
When above code is executed, it produces the following result −
kerberos_master 751/udp  # Kerberos authentication
kerberos_master 751/tcp  # Kerberos authentication
passwd_server   752/udp  # Kerberos passwd server


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C++ Program to Print Cross or X Pattern

04 Jun, 2022
Given a number n, we need to print a X pattern of size n.
Input : n = 3
Output : 
$ $
 $ 
$ $

Input : n = 5
Output : 
$   $
 $ $ 
  $  
 $ $ 
$   $

Input : n = 4
Output : 
$  $
 $$ 
 $$ 
$  $
We need to print n rows and n columns. So we run two nested loops. The outer loop prints all rows one by one (runs for i = 1 to n). The inner loop (runs for j = 1 to n) runs all columns of current row. Now a row can contain spaces and ‘$’. How do we decide where to put space and where ‘$’. For i = 1 : First and last column should contain ‘$’ For i = 2 : Second and second last column should contain ‘$’ In general, i-th and (n + 1 – i)-th columns should contain ‘$’ 
CPP
// Program to make an X shape $ pattern in c++#include <iostream>using namespace std; int main(){    // n denotes the number of lines in which    // we want to make X pattern    int n;         // i denotes the number of rows    cout << "Enter the value of n \n";    cin >> n;     // Print all rows one by one    for (int i = 1; i <= n; i++) {         // Print characters of current row        for (int j = 1; j <= n; j++)        {            // For i = 1, we print a '$' only in            // first and last columns            // For i = 2, we print a '$' only in            // second and second last columns            // In general, we print a '$' only in            // i-th and n+1-i th columns             if (j == i || j == (n + 1 - i))                cout << "$";            else                cout << " ";        }          // Print a newline before printing the        // next row.        cout << endl;    }    return 0;}
Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
samim2000
pattern-printing
C++
C++ Programs
Design Pattern
School Programming
pattern-printing
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How To Manually Specify Colors for Barplot in ggplot2 in R?

21 Dec, 2021
In this article, we will discuss how to manually specify colors for Barplot in ggplot2 in R Programming Language.
To specify colors of the bar in Barplot in ggplot2, we use the scale_fill_manual function of the ggplot2 package. Within this function, we need to specify a color for each of the bars as a vector. We can use colors using names as well as hex codes.
Syntax: plot+ scale_fill_manual(values=<color-vector>)
Here, is a basic ggplot2 bar plot with the default colors:
R
# Create sample dataset.seed(5642)                             sample_data <- data.frame(name = c("Geek1","Geek2",                                   "Geek3","Geek4",                                   "Geeek5") ,                          value = c(31,12,15,28,45)) # Load ggplot2 packagelibrary("ggplot2")   # Create bar plot with default colorsplot<-ggplot(sample_data,             aes(name,value, fill=name)) + geom_bar(stat = "identity")plot
Output:
To manually specify colors just add scale_fill_manual() function to plot:
R
# Create sample dataset.seed(5642)                             sample_data <- data.frame(name = c("Geek1","Geek2",                                   "Geek3","Geek4",                                   "Geeek5") ,                          value = c(31,12,15,28,45)) # Load ggplot2 packagelibrary("ggplot2")   # Create bar plot with default colorsplot<-ggplot(sample_data,             aes(name,value, fill=name))+ geom_bar(stat = "identity")  # add scale_fill_manual function to specify colorsplot + scale_fill_manual(values = c("green","yellow",                                    "red","pink","blue"))
Output:
We can even use hex codes of color instead of names:
R
# Create sample dataset.seed(5642)                             sample_data <- data.frame(name = c("Geek1","Geek2",                                   "Geek3","Geek4",                                   "Geeek5") ,                          value = c(31,12,15,28,45)) # Load ggplot2 packagelibrary("ggplot2")   # Create bar plot with default colorsplot<-ggplot(sample_data, aes(name,value, fill=name)) +geom_bar(stat = "identity")  # add scale_fill_manual function to specify colorsplot + scale_fill_manual(values = c("#207345","#0d576e",                                    "#610d6e","#6e0d27",                                    "#6e470d"))
Output:
sumitgumber28
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Replacing ‘public’ with ‘private’ in “main” in Java

21 Aug, 2018
Consider following Java program:
class GFG {    public static void main(String args[])    {        System.out.println("GeeksforGeeks");    }}
GeeksforGeeks
Explanation:1)public: It is an access specifier which allows the JVM(Java Virtual Machine) to access the main method from anywhere.2)static: static keyword allows the JVM to access the main method without any instance(object).3)void: It specifies that the main method doesn’t return anything.4)main: name of the method(function) configured in JVM.5)String args[]: Command line arguments.
Now, if we replace ‘public’ with ‘private’ in “public static void main”, the above code becomes:
class GFG {    private static void main(String args[])    {        System.out.println("GeeksforGeeks");    }}
Explanation:The above code will be compiled successfully, but will throw a runtime error as follows:
Error: Main method not found in class GFG, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Click to view output
Reason: Since the access specifier was changed from “public” to “private” JVM was unable to access/locate the main method.
java-puzzle
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
numpy.add() in Python

28 Nov, 2018
numpy.add() function is used when we want to compute the addition of two array. It add arguments element-wise. If shape of two arrays are not same, that is arr1.shape != arr2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).
Syntax : numpy.add(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘add’)
Parameters :arr1 : [array_like or scalar] Input array.arr2 : [array_like or scalar] Input array.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs :Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray or scalar] The sum of arr1 and arr2, element-wise. Returns a scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# numpy.add() function# when inputs are scalar  import numpy as geekin_num1 = 10in_num2 = 15  print ("1st Input  number : ", in_num1)print ("2nd Input  number : ", in_num2)    out_num = geek.add(in_num1, in_num2) print ("output number after addition  : ", out_num) 
Output :
1st Input  number :  10
2nd Input  number :  15
output number after addition  :  25

 Code #2 :
# Python program explaining# numpy.add() function# when inputs are array  import numpy as geek  in_arr1 = geek.array([[2, -7, 5], [-6, 2, 0]])in_arr2 = geek.array([[5, 8, -5], [3, 6, 9]])   print ("1st Input array : ", in_arr1) print ("2nd Input array : ", in_arr2)     out_arr = geek.add(in_arr1, in_arr2) print ("output added array : ", out_arr) 
Output :
1st Input array :  [[ 2 -7  5]
 [-6  2  0]]
2nd Input array :  [[ 5  8 -5]
 [ 3  6  9]]
output added array :  [[ 7  1  0]
 [-3  8  9]]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Math.Atan() Method in C#

The Math.Atan() method in C# is used to return the angle whose tan is the specified number. The number is a double value argument. The method returns an angle, θ, measured in radians, such that -Π/2 ≤θ≤Π/2.
Following is the syntax −
public static double Atan(double num)
Let us now see an example to implement the Math.Atan() method −
using System;
public class Demo {
   public static void Main(){
      double val1 = 0.0;
      double val2 = 1.0;
      Console.WriteLine("Return value of {0} : {1}", val1, Math.Atan(val1));
      Console.WriteLine("Return value of {0} : {1}", val2, Math.Atan(val2));
   }
}
This will produce the following output −
Return value of 0 : 0
Return value of 1 : 0.785398163397448
Let us see another example to implement the Math.Atan() method −
using System;
public class Demo {
   public static void Main(){
      double val1 = Double.PositiveInfinity;
      double val2 = Double.NegativeInfinity;
      Console.WriteLine("Return value of {0} : {1}", val1, Math.Atan(val1));
      Console.WriteLine("Return value of {0} : {1}", val2, Math.Atan(val2));
   }
}
This will produce the following output −
Return value of ∞ : 1.5707963267949
Return value of -∞ : -1.5707963267949
How to write a common title for par(mfrow) plots in R?

We can create multiple plots using par(mfrow) on a single plot window in R. It might be possible that all of these plots are different or same as well. Irrespective of the type of plots, we can give a common title to all the plots. This can be a situation where we want to show, say, scatterplots, and histograms of few variables but the object of our analysis is fixed. To write a common title between plots in the plot window we can use mtext and adjust the title position by changing line argument.
set.seed(100)
x1<-rnorm(100)
x2<-rnorm(100,0.2)
x3<-rnorm(100,0.5)
x4<-rnorm(100,0.8)
x5<-rnorm(100,1.1)
x6<-rnorm(100,1.8)
par(mfrow=c(2,3))
hist(x1)
hist(x2)
hist(x3)
hist(x4)
hist(x5)
hist(x6)
The code to write a common title “Histograms” between the top and bottom histograms −
mtext("Histograms",side=3,line=-22,outer=TRUE)
Redirection in PHP

The header function in PHP can be used to redirect the user from one page to another. It is an in-built function that sends raw HTTP header to the destination (client).
Syntax of header function
header( $header_value, $replace_value, $http_response_code)
Following are the parameters −
The ‘header_value’ in the function is used to store the header string.
The ‘replace_value’ parameter stores the value that needs to be replaced.
The ‘response_code’ is used to store the HTTP response code.
<?php
   header("Location: http://www.tutorialspoint.com");
   exit;
?>
The website to which the page needs to be redirected is specified in the header function.
Subtracting a number from a single MySQL column value?

For this, just update the table and subtract. Let us first create a table −
mysql> create table DemoTable1372
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.77 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1372 values(500);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1372 values(100);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1372 values(900);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1372 values(1000);
Query OK, 1 row affected (0.32 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1372;
This will produce the following output −
+-------+
| Value |
+-------+
|   500 |
|   100 |
|   900 |
|  1000 |
+-------+
4 rows in set (0.00 sec)
Following is the query to subtract a number from a single MySQL column value −
mysql> update DemoTable1372 set Value=Value-50 where Value=900;
Query OK, 1 row affected (0.52 sec)
Rows matched: 1  Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1372;
This will produce the following output −
+-------+
| Value |
+-------+
|   500 |
|   100 |
|   850 |
|  1000 |
+-------+
4 rows in set (0.00 sec)
Perl wait Function

This function Waits for a child process to terminate, returning the process ID of the deceased process. The exit status of the process is contained in $?.
Following is the simple syntax for this function −
wait

This function returns -1 if there are no child processes else the Process ID of deceased process

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Pass by reference vs value in Python

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
 Live Demo
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
 Live Demo
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
numpy.flip() in Python - GeeksforGeeks

09 Mar, 2022
The numpy.flip() function reverses the order of array elements along the specified axis, preserving the shape of the array. 
Syntax: numpy.flip(array, axis)
Parameters : 
array : [array_like]Array to be input 
axis  : [integer]axis along which array 
        is reversed.
Returns : 
reversed array with shape preserved
Python
# Python Program illustrating# numpy.flip() method import numpy as geek array = geek.arange(8).reshape((2,2,2))print("Original array : \n", array) print("Flipped array : \n", geek.flip(array, 0))
Output : 
Original array : 
 [[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]

Flipped array : 
 [[[4, 5]
  [6, 7]]

 [[0, 1]
  [2, 3]]]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flip.html#numpy.flipNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. 
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vinayedula
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe