code-rag-bench/online-tutorials huggingface dataset:
What does the Star operator mean in Python?

The asterisk (star) operator is used in Python with more than one meaning attached to it.
For numeric data types, * is used as multiplication operator
>>> a=10;b=20
>>> a*b
200
>>> a=1.5; b=2.5;
>>> a*b
3.75
>>> a=2+3j; b=3+2j
>>> a*b
13j
For sequences such as string, list and tuple,  * is a repetition operator
>>> s="Hello"
>>> s*3
'HelloHelloHello'
>>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> T1=(1,2,3)
>>> T1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.
>>> def function(*arg):
    print (type(arg))
    for i in arg:
      print (i)
>>> function(1,2,3)
<class 'tuple'>
1
2
3
Difference Between x = x + y and x += y in Python - GeeksforGeeks

10 May, 2020
We often use x += y instead of x = x + y. So, are they same or different? Let’s Find it here.
Example 1:
x = [1, 2]another_x = xy = [3]  x += y  print(x)print(another_x)
Output:
[1, 2, 3]
[1, 2, 3]
Example 2:
x = [1, 2]another_x = xy = [3]  x = x + y  print(x)print(another_x)
Output:
[1, 2, 3]
[1, 2]
So here we find that both codes are almost similar but still there are difference in the outputs. So the reason behind this is that for many types of objects, x += y will modify the object referred to by x in-place, whereas x = x + y will create a new object and reassign x to it. This distinction is important if you still have another reference to the object somewhere like in this case another_a is another reference to the object.
However, many objects such as numbers and strings are “immutable” – they can’t be modified in-place – and for those objects, x += y and x = x + y will typically do exactly the same thing. But if you write your own class you can customize what + and += do when used with objects of that class, and you can make them do completely different things if you really want to.
Example 3:
x = "12345"another_x = xy = "67890"  x += y  print(x)print(another_x)
Output:
1234567890
12345
Example 4:
x = "12345"another_x = xy = "67890"  x = x + y  print(x)print(another_x)
Output:
1234567890
12345
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to find Segmentation Error in C & C++ ? (Using GDB)

The segmentation error is one of the runtime error, that is caused because of the memory access violation, like accessing invalid array index, pointing some restricted address etc. In this article, we will see how to detect this type of error using the GDB tool.
Let us see the code and respective steps to locate the error.
#include <stdio.h>
main() {
   int* ptr = NULL;
   *ptr = 1; //trying to access unknown memory location
   printf("%p\n", ptr);
}
Compile the code using ‘gcc –g program_name.c’, and run using ‘./a.out’
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out
Segmentation fault (core dumped)
The segmentation error occurred.
Write ‘gdb ./a.out core’
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gdb ./a.out core
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/soumyadeep/Cpp_progs/core: No such file or directory.
(gdb)
Type ‘r’ and press enter.
Starting program: /home/soumyadeep/Cpp_progs/a.out

Program received signal SIGSEGV, Segmentation fault.
0x000055555555465e in main () at 1230.find_seg_error.c:5
5 *ptr = 1; //trying to access unknown memory location
(gdb)
So we have got the error successfully, now quit the GDB
(gdb) quit
A debugging session is active.

Inferior 1 [process 2794] will be killed.

Quit anyway? (y or n) y
How to insert integer array in android listview?

This example demonstrate about How to insert integer array in android listview.
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:gravity="center_horizontal"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/list"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </ListView>
</LinearLayout>
In the code, we have taken listview to show integer array.
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.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {
   ListView list;
   int[] array = {2, 5, 6,8,0,7,9,4};

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list = findViewById(R.id.list);
      ArrayList<String> arrayList = new ArrayList<String>();
      for(int s:array) {
         arrayList.add(String.valueOf(s));
      }
      ArrayAdapter adapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_list_item_1, arrayList);
      list.setAdapter(adapter);
   }
}
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, we had shown an integer array.
Click here to download the project code
AWK - Regular Expression Operators

This example explains the two forms of regular expressions operators.
It is represented as ~. It looks for a field that contains the match string. For instance, the following example prints the lines that contain the pattern 9.
[jerry]$ awk '$0 ~ 9' marks.txt
On executing this code, you get the following result −
2) Rahul   Maths    90
5) Hari    History  89

It is represented as !~. It looks for a field that does not contain the match string. For instance, the following example prints the lines that do not contain the pattern 9.
[jerry]$ awk '$0 !~ 9' marks.txt
On executing this code, you get the following result −
1) Amit     Physics   80
3) Shyam    Biology   87
4) Kedar    English   85

 Print
 Add Notes
 Bookmark this page
How to combine two tables and add a new column with records in MySQL?

Let us first create a table −
mysql> create table DemoTable1
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable1(Name) values('Robert');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
+----+--------+
2 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.48 sec)
Insert some records in the second table using insert command −
mysql> insert into DemoTable2(Name) values('David');
Query OK, 1 row affected (0.53 sec)

mysql> insert into DemoTable2(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)
Display all records from the second table using select statement −
mysql> select *from DemoTable2;
+----+-------+
| Id | Name  |
+----+-------+
|  1 | David |
|  2 | Bob   |
+----+-------+
2 rows in set (0.00 sec)
Following is the query to add a new column to the union of two tables −
mysql> select Id,Name, 27 AS Age from DemoTable1
   -> union
   -> select Id,name,20 AS Age from DemoTable2;
+----+--------+-----+
| Id | Name   | Age |
+----+--------+-----+
|  1 | Chris  | 27  |
|  2 | Robert |  27 |
|  1 | David  | 20  |
|  2 | Bob    | 20  |
+----+--------+-----+
4 rows in set (0.00 sec)
How can data be scaled using scikit-learn library in Python?

Feature scaling is an important step in the data pre-processing stage in building machine learning algorithms. It helps normalize the data to fall within a specific range.
At times, it also helps in increasing the speed at which the calculations are performed by the machine.
Data fed to the learning algorithm as input should remain consistent and structured. All features of the input data should be on a single scale to effectively predict the values. But in real-world, data is unstructured, and most of the times, not on the same scale.
This is when normalization comes into picture. It is one of the most important data-preparation processes. It helps in changing values of the columns of the input dataset to fall on a same scale.
Let us understand how Scikit learn library can be used to perform feature scaling in Python.
import numpy as np
from sklearn import preprocessing
input_data = np.array(
[[34.78, 31.9, -65.5],
[-16.5, 2.45, -83.5],
[0.5, -87.98, 45.62],
[5.9, 2.38, -55.82]])
data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1))
data_scaled_minmax = data_scaler_minmax.fit_transform(input_data)
print ("\nThe scaled data is \n", data_scaled_minmax)
The scaled data is
[[1.  1. 0.1394052 ]
[0.  0.75433767 0. ]
[0.33151326 0. 1. ]
[0.43681747 0.75375375 0.21437423]]
The required packages are imported.
The required packages are imported.
The input data is generated using the Numpy library.
The input data is generated using the Numpy library.
The MinMaxScaler function present in the class ‘preprocessing ‘ is used to scale the data to fall in the range 0 and 1.
The MinMaxScaler function present in the class ‘preprocessing ‘ is used to scale the data to fall in the range 0 and 1.
This way, any data in the array gets scaled down to a value between 0 and 1.
This way, any data in the array gets scaled down to a value between 0 and 1.
This scaled data is displayed on the console.
This scaled data is displayed on the console.
What is the difference between Serialization and Deserialization in Java?

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
import java.io.*;

public class SerializeDemo {
   public static void main(String [] args) {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;

      try {
         FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      } catch (IOException i) {
         i.printStackTrace();
      }
   }
}
 After a serialized object has been written into a file, it can be read from the file and Deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
import java.io.*;

public class DeserializeDemo {
   public static void main(String [] args) {
      Employee e = null;
     
      try {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      } catch (IOException i) {
         i.printStackTrace();
         return;
      } catch (ClassNotFoundException c) {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
   }
}
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Find difference between sums of two diagonals in C++.

Here we will see how to get the difference between the sums of two diagonals of a given matrix. Suppose we have a matrix of order N x N, we have to get the sum of primary and secondary diagonals, then get the difference of them. To get the major diagonal, we know that the row index and column index increases simultaneously. For the second diagonal, row index and column index values are increased by this formula row_index = n – 1 – col_index. After getting the sum, take the difference and return a result.
 Live Demo
#include<iostream>
#include<cmath>
#define MAX 100
using namespace std;
int diagonalSumDifference(int matrix[][MAX], int n) {
   int sum1 = 0, sum2 = 0;
   for (int i = 0; i < n; i++) {
      sum1 += matrix[i][i];
      sum2 += matrix[i][n-i-1];
   }
   return abs(sum1 - sum2);
}
// Driven Program
int main() {
   int n = 3;
   int matrix[][MAX] = {
      {11, 2, 4},
      {4 , 5, 6},
      {10, 8, -12}
   };
   cout << "Difference of the sum of two diagonals: " << diagonalSumDifference(matrix, n);
}
Difference of the sum of two diagonals: 15
How to remove X or Y labels from a Seaborn heatmap?

To remove X or Y labels from a Seaborn heatmap, we can use yticklabel=False.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe with 5 columns.
Make a Pandas dataframe with 5 columns.
Use heatmap() method to plot rectangular data as a color-encoded matrix with yticklabels=False.
Use heatmap() method to plot rectangular data as a color-encoded matrix with yticklabels=False.
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.random((5, 5)), columns=["col1", "col2", "col3", "col4", "col5"])

sns.heatmap(df, yticklabels=False)

plt.show()
Fortran - Relational Operators

Following table shows all the relational operators supported by Fortran. Assume variable A holds 10 and variable B holds 20, then −
Try the following example to understand all the logical operators available in Fortran −
! this program checks relational operators
implicit none  

   ! variable declaration
   integer :: a, b
   
   ! assigning values 
   a = 10   
   b = 20
   
   if (a .eq. b) then
      print *, "Line 1 - a is equal to b"
   else
      print *, "Line 1 - a is not equal to b"
   end if

   if (a > b) then
      print *, "Line 2 - a is greater than b"
   else
      print *, "Line 2 - a is less than b"
   end if
   
   if (a <= b) then
      print *, "Line 3 - a is less than or equal to b"
   else
      print *, "Line 3 - a is greater than b"
   end if
   
   a = 20   
   b = 20
   
   if (a .eq. b) then
      print *, "Line 4 - a is equal to b"
   else
      print *, "Line 4 - a is not equal to b"
   end if
end
When you compile and execute the above program it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is less than b
Line 3 - a is less than or equal to b
Line 4 - a is equal to b

 Print
 Add Notes
 Bookmark this page
How to Install cx_oracle in Python on Linux? - GeeksforGeeks

30 Sep, 2021
The cx_oracle package is used to connect with the Oracle database using python. In this, article, we will look into the process of installing the cx_oracle package on Linux.
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (Depending upon the user preference)
If you want the installation to be done through conda, you can use the below command:
conda install cx_oracle
Type in “y” for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Use the below command to verify if the above package has successfully installed:
conda list cx_oracle
You will get a similar message as shown below if the installation has been successful:
Users who prefer to use pip can use the below command to install the package:
pip install cx_oracle
You will get a similar message once the installation is complete:
It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment:
python3 -m venv my-env
Activate the virtual environment (ie, my-env) using the below command:
source my-env/bin/activate
Use the below command to check if the package has been successfully installed:
python3 -m pip show cx_oracle
You will get a similar message as shown below if the installation is successful:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
LinkedList get() Method in Java

10 Dec, 2018
The Java.util.LinkedList.get() method is used to fetch or retrieve an element at a specific index from a LinkedList.
Syntax:
LinkedList.get(int index)
Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList.
Return Value: The method returns the element present at the position specified by the parameter index.
Below program illustrate the Java.util.LinkedList.get() method:
// Java code to illustrate get() methodimport java.io.*;import java.util.LinkedList;  public class LinkedListDemo {   public static void main(String args[]) {        // Creating an empty LinkedList      LinkedList<String> list = new LinkedList<String>();        // Use add() method to add elements in the list      list.add("Geeks");      list.add("for");      list.add("Geeks");      list.add("10");      list.add("20");        // Displaying the list      System.out.println("LinkedList:" + list);              // Fetching the specific element from the list      System.out.println("The element is: " + list.get(2));     }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The element is: Geeks

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue Interface In Java
Stack Class in Java
Interfaces in Java
Collections in Java
ChronoZonedDateTime isAfter() method in Java with Examples
Multidimensional Arrays in Java
Introduction to Java
PriorityQueue in Java
Constructors in Java
How to add an element to an Array in Java?
Java program to delete duplicate lines in text file

The interface set does not allow duplicate elements. The add() method of this interface accepts elements and adds to the Set object, if the addition is successful it returns true, if you try to add an existing element using this method, the addition operations fails returning false.
Therefore, to remove duplicate lines from a File −
Instantiate Scanner class (any class that reads data from a file)
Instantiate Scanner class (any class that reads data from a file)
Instantiate the FileWriter class (any class that writes data into a file)
Instantiate the FileWriter class (any class that writes data into a file)
Create an object of the Set interface.
Create an object of the Set interface.
Read each line of the file Store it in a Sting say input.
Read each line of the file Store it in a Sting say input.
Try to add this String to the Set object.
Try to add this String to the Set object.
If the addition is successful, append that particular line to file writer.
If the addition is successful, append that particular line to file writer.
Finally, flush the contents of the FileWriter to the output file.
Finally, flush the contents of the FileWriter to the output file.
If a file contains a particular line more than one time, for the 1st time it is added to the set object and thus appended to the file writer.
If the same line is encountered again while reading all the lines in the file, since it already exists in the set object the add() method rejects it.
Assume we have a file with name sample.txt with the following contents −
Hello how are you
Hello how are you
welcome to Tutorialspoint
The following Java program removes the duplicate lines from the above file and adds them to the file named output.txt.
import java.io.File;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DeletingDuplcateLines {
   public static void main(String args[]) throws Exception {
      String filePath = "D://sample.txt";
      String input = null;
      //Instantiating the Scanner class
      Scanner sc = new Scanner(new File(filePath));
      //Instantiating the FileWriter class
      FileWriter writer = new FileWriter("D://output.txt");
      //Instantiating the Set class
      Set set = new HashSet();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         if(set.add(input)) {
            writer.append(input+"\n");
         }
      }
      writer.flush();
      System.out.println("Contents added............");
   }
}
Contents added............
The contents of the output.txt will be:
Hello how are you
welcome to Tutorialspoint
Python | remove() and discard() in Sets

28 Dec, 2017
In this article, we will see how to remove an element in a set, using the discard() and remove() method. We will also learn the difference between the two methods, although both of them produce the same results.
Examples:
Input : set = ([10, 20, 26, 41, 54, 20])
Output : {41, 10, 26, 54}

Input : set = (["ram", "aakash", "kaushik", "anand", "prashant"])
Output : {'ram', 'prashant', 'kaushik', 'anand'}

Method 1: Use of discard() method
The built-in method, discard() in Python, removes the element from the set only if the element is present in the set. If the element is not present in the set, then no error or exception is raised and the original set is printed.If the element is present in the set:
# Python program to remove random elements of choice# Function to remove elements using discard()def Remove(sets):    sets.discard(20)    print (sets)      # Driver Codesets = set([10, 20, 26, 41, 54, 20])Remove(sets)
Output:
{41, 10, 26, 54}

If the element is not present in the set:
# Python program to remove random elements of choice# Function to remove elements using discard()def Remove(sets):    sets.discard(21)    print (sets)      # Driver Codesets = set([10, 20, 26, 41, 54, 20])Remove(sets)
Output:
{41, 10, 26, 20, 54}

Method 2: Use of remove() method
The built-in method, remove() in Python, removes the element from the set only if the element is present in the set, just as the discard() method does but If the element is not present in the set, then an error or exception is raised.If the element is present in the set:
# Python program to remove random elements of choice# Function to remove elements using remove()def Remove(sets):    sets.remove("aakash")    print (sets)      # Driver Codesets = set(["ram", "aakash", "kaushik", "anand", "prashant"])Remove(sets)
Output:
{'ram', 'anand', 'prashant', 'kaushik'}

If the element is not present in the set:
# Python program to remove random elements of choice# Function to remove elements using remove()def Remove(sets):    sets.remove("gaurav")    print (sets)      # Driver Codesets = set(["ram", "aakash", "kaushik", "anand", "prashant"])Remove(sets)
Output:
No Output

Error:
Traceback (most recent call last):
  File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 9, in 
    Remove(sets)
  File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 4, in Remove
    sets.remove("gaurav")
KeyError: 'gaurav'
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
GATE | GATE-CS-2001 | Question 42

28 Jun, 2021
What is printed by the print statements in the program P1 assuming call by reference parameter passing?
Program P1()
{
   x = 10;
   y = 3;
   func1(y,x,x);
   print x;
   print y;
}
func1(x,y,z)
{
   y = y+4;
   z = x+y+z;
}
(A) 10, 3(B) 31, 3(C) 27, 7(D) None of the aboveAnswer: (B)Explanation: Here, we are passing the variables by call by reference. This means that the changes that we will make in the parameter would be reflected in the passed argument.
Here, the first variable passed in the function func1 (i.e., y) points to the address of the variable x.
Similarly, the second variable passed in the function func1 (i.e., x) points to the address of the variable y and the third variable passed in the function func1 (i.e., x) points to the address of the variable z.
 
So, we have y = y + 4 ⇒ y = 10 + 4 = 14
and z = x + y + z ⇒ z = 14 + 14 + 3 = 31
z will be returned to x. So, x = 31 and y will remain 3.
Thus, the correct choice is B.
 
Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set a Seaborn chart figure size?

24 Feb, 2021
Seaborn is a Python data visualization library based on matplotlib. It is used to draw attractive and informative statistical graphics. To adjust the figure size of the seaborn plot we will use the subplots function of matplotlib.pyplot.
matplotlib.pyplot.subplots() Create a figure and a set of subplots. It has a parameter called figsize which takes a tuple as an argument that contains the height and the width of the plot. It returns the figure and the array of axes.
While calling the seaborn plot we will set the ax parameter equal to the array of axes that was returned by matplotlib.pyplot.subplots after setting the dimensions of the desired plot.
Example 1: We will consider two students and plot their marks in a bar plot, and we will set the plot of size ( 4,5 ).
Python3
# Importing librariesimport seaborn as snsimport matplotlib.pyplot as plt  # Setting the datax = ["Student1", "Student2"]y = [70, 87]  # setting the dimensions of the plotfig, ax = plt.subplots(figsize=(4, 5))  # drawing the plotsns.barplot(x, y, ax=ax)plt.show()
Output:
fig size ( 6,4 )
Example 2: We will draw a plot of size (6, 6).
Python3
# Importing librariesimport seaborn as snsimport matplotlib.pyplot as plt  # Setting the datax = ["Student1", "Student2"]y = [80, 68]  # setting the dimensions of the plotfig, ax = plt.subplots(figsize=(6, 6))  # drawing the plotsns.barplot(x, y, ax=ax)plt.show()
fig size ( 6,6 )
Example 3: In this example, We will create boxplot and set the size of a chart with figsize.
Python3
# Importing librariesimport seaborn as snsimport matplotlib.pyplot as plt  # Setting the datax = ["Student1", "Student2"]y = [70, 87]  # setting the dimensions of the plotfig, ax = plt.subplots(figsize=(40, 5))  # drawing the plotsns.boxplot(x = y)plt.show()
Output:
Picked
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Print Colored Text in Java Console?

12 Aug, 2021
Remember that in Java Programming the background color and text color of the output screen is black or white by default. If we want to Highlight some text on the output screen then we can use the ANSI color codes and highlight the particular text. One can refer to the ANSI escape code in order to explore more.
Syntax:
System.out.println(ANSI_COLORNAME + "This text is colored" + ANSI_RESET);
As perceived from the above syntax contains This Syntax contains 3 parts:
In ANSI_COLORNAME we have to write the name in which we have given the particular ANSI code. for e.g  public static final String ANSI_BLACK = “\u001B[30m”;
The above is pseudo-code is to print text in black color. So here we can use ANSI_BLACK in place of ANSI_COLORNAME to print the text in Black color.
The second part is to write the text which we want to print in that color.
The ANSI_RESET code turns off all ANSI attributes set so far, which should return the console to its defaults.
Below is the ANSI color code table :
Illustration: Text coloring in Java:
Example 1:
Java
// Java Program to Print Colored Text in Console  // Importing input output classesimport java.io.*;  // Main classpublic class GFG {      // Declaring ANSI_RESET so that we can reset the color    public static final String ANSI_RESET = "\u001B[0m";      // Declaring the color    // Custom declaration    public static final String ANSI_YELLOW = "\u001B[33m";      // Main driver method    public static void main(String[] args)    {        // Printing the text on console prior adding        // the desired color        System.out.println(ANSI_YELLOW                           + "This text is yellow"                           + ANSI_RESET);    }}
Output:
Example 2:
Java
// Java Program to Print Colored Text in Console  // Importing required classesimport java.io.*;  // Main classclass GFG {      // Declaring ANSI_RESET so that we can reset the color    public static final String ANSI_RESET = "\u001B[0m";    // Declaring the background color    public static final String ANSI_RED_BACKGROUND        = "\u001B[41m";      // Main driver method    public static void main(String[] args)    {        // Now add the particular background color        System.out.println(ANSI_RED_BACKGROUND                           + "The background color is red"                           + ANSI_RESET);    }}
Output:
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add External JAR File to an IntelliJ IDEA Project?
How to download and install Python Latest Version on Android
Spring Boot | How to publish JSON messages on Apache Kafka
How to Install Scala on MacOS?
How to create an Expandable CardView in Android
Arrays.sort() in Java with examples
For-each loop in Java
Arrays in Java
Multidimensional Arrays in Java
Split() String method in Java with examples
How to retrieve files and folders attributes using PowerShell?

To retrieve files and folders attributes using PowerShell, you can use Get-Item or Get-ChildItem command. For example, We have a file called testfile.txt to get its attributes,
PS C:\> Get-ChildItem C:\Temp\TestFile.txt |Select Name,Attributes
Name          Attributes
----          ----------
TestFile.txt  Archive
So this file has the Archive attribute. To retrieve multiple files and folders' attributes, just refer to the folder name instead of the file name.
Get-ChildItem C:\Temp -Recurse -Force | Select Name, FullName, Attributes
Name          Attributes
----          ----------
TestFile.txt  Archive
-Force parameter will retrieve all the files and folders including Hidden and read-only.
The above same thing can be achieved with the Get-Item command.
Get-Item C:\Temp\TestFile.txt |Select Name,Attributes
Computer Organization and Architecture | Pipelining | Set 3 (Types and Stalling)

28 Jun, 2021
Please see Set 1 for Execution, Stages and Performance (Throughput) and Set 2 for Dependencies and Data Hazard. Types of pipeline
Uniform delay pipelineIn this type of pipeline, all the stages will take same time to complete an operation.In uniform delay pipeline, Cycle Time (Tp) = Stage DelayIf buffers are included between the stages then, Cycle Time (Tp) = Stage Delay + Buffer Delay
If buffers are included between the stages then, Cycle Time (Tp) = Stage Delay + Buffer Delay
 
Non-Uniform delay pipelineIn this type of pipeline, different stages take different time to complete an operation.In this type of pipeline, Cycle Time (Tp) = Maximum(Stage Delay)For example, if there are 4 stages with delays, 1 ns, 2 ns, 3 ns, and 4 ns, thenTp = Maximum(1 ns, 2 ns, 3 ns, 4 ns) = 4 nsIf buffers are included between the stages,Tp = Maximum(Stage delay + Buffer delay)Example : Consider a 4 segment pipeline with stage delays (2 ns, 8 ns, 3 ns, 10 ns). Find the time taken to execute 100 tasks in the above pipeline.Solution : As the above pipeline is a non-linear pipeline,Tp = max(2, 8, 3, 10) = 10 nsWe know that ETpipeline = (k + n – 1) Tp = (4 + 100 – 1) 10 ns = 1030 nsNOTE: MIPS = Million instructions per second
For example, if there are 4 stages with delays, 1 ns, 2 ns, 3 ns, and 4 ns, then
Tp = Maximum(1 ns, 2 ns, 3 ns, 4 ns) = 4 ns
If buffers are included between the stages,
Tp = Maximum(Stage delay + Buffer delay)
Example : Consider a 4 segment pipeline with stage delays (2 ns, 8 ns, 3 ns, 10 ns). Find the time taken to execute 100 tasks in the above pipeline.Solution : As the above pipeline is a non-linear pipeline,Tp = max(2, 8, 3, 10) = 10 nsWe know that ETpipeline = (k + n – 1) Tp = (4 + 100 – 1) 10 ns = 1030 ns
NOTE: MIPS = Million instructions per second
 
Performance of pipeline with stalls
Speed Up (S) = Performancepipeline / Performancenon-pipeline
=> S = Average Execution Timenon-pipeline / Average Execution Timepipeline
=> S = CPInon-pipeline * Cycle Timenon-pipeline / CPIpipeline * Cycle Timepipeline
Ideal CPI of the pipelined processor is ‘1’. But due to stalls, it becomes greater than ‘1’.=>
S = CPInon-pipeline * Cycle Timenon-pipeline  / (1 + Number of stalls per Instruction) * Cycle Timepipeline

As Cycle Timenon-pipeline =   Cycle Timepipeline,

Speed Up (S) = CPInon-pipeline / (1 + Number of stalls per instruction) 
 Sources : goo.gl/J9KVNthttps://en.wikipedia.org/wiki/Hazard_(computer_architecture)https://en.wikipedia.org/wiki/Data_dependency This article has been contributed by Saurabh Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VaibhavRai3
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find Quotient And Remainder in Java - GeeksforGeeks

12 Jul, 2018
The remainder is the integer left over after dividing one integer by another. The quotient is the quantity produced by the division of two numbers.
For example,
(7/2) = 3
In the above expression 7 is divided by 2, so the quotient is 3 and the remainder is 1.
Approach: Divide the dividend by the divisor using / operator. Both dividend and divisor can be of any type except string, the result will also be computed accordingly. Get the remainder using % operator.
Expressions used in program to calculate quotient and remainder:
quotient = dividend / divisor;
remainder = dividend % divisor;

Note: The program will throw an ArithmeticException: / by zero when divided by 0.
Explanation:
Consider Dividend = 100 and Divisor = 6
Therefore,Quotient = 100/6 = 16Remainder = 100%6 = 4
Below programs illustrate the above approach:
Program 1:
public class QuotientAndRemainder {      public static void main(String[] args)    {          int dividend = 556, divisor = 9;          int quotient = dividend / divisor;        int remainder = dividend % divisor;          System.out.println("The Quotient is = " + quotient);        System.out.println("The Remainder is = " + remainder);    }}
The Quotient is = 61
The Remainder is = 7

Program 2: For a negative number.
public class QuotientAndRemainder {      public static void main(String[] args)    {          int dividend = -756, divisor = 8;          int quotient = dividend / divisor;        int remainder = dividend % divisor;          System.out.println("The Quotient is = " + quotient);        System.out.println("The Remainder is = " + remainder);    }}
The Quotient is = -94
The Remainder is = -4

Program 3: This program will throw an ArithmeticException as the divisor = 0.
public class QuotientAndRemainder {      public static void main(String[] args)    {          int dividend = 56, divisor = 0;          int quotient = dividend / divisor;        int remainder = dividend % divisor;          System.out.println("The Quotient is = " + quotient);        System.out.println("The Remainder is = " + remainder);    }}
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at QuotientAndRemainder.main(QuotientAndRemainder.java:7)

java-basics
school-programming
Java Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Iterate through List in Java
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
How to make a table in Python? - GeeksforGeeks

22 Feb, 2022
In this article, we are going to discuss how to make a table in Python. Python provides vast support for libraries that can be used for creating different purposes. In this article we will talk about two such modules that can be used to create tables.
Method 1: Using Tabulate module
The tabulate() method is a method present in the tabulate module which creates a text-based table output inside the python program using any given inputs. It can be installed using the below command
pip install tabulate
Below are some examples which depict how to create tables in python:
Example 1
Python3
# import modulefrom tabulate import tabulate # assign datamydata = [    ["Nikhil", "Delhi"],    ["Ravi", "Kanpur"],    ["Manish", "Ahmedabad"],      ["Prince", "Bangalore"]] # create headerhead = ["Name", "City"] # display tableprint(tabulate(mydata, headers=head, tablefmt="grid"))
Output:
Example 2
Python3
# import modulefrom tabulate import tabulate # assign datamydata = [    ['a', 'b', 'c'],      [12, 34, 56],      ['Geeks', 'for', 'geeks!']] # display tableprint(tabulate(mydata))
Output:
Method 2: Using PrettyTable module
PrettyTable class inside the prettytable library is used to create relational tables in Python. It can be installed using the below command.
pip install prettytable 
Example:
Python3
from prettytable import PrettyTable # Specify the Column Names while initializing the TablemyTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"]) # Add rowsmyTable.add_row(["Leanord", "X", "B", "91.2 %"])myTable.add_row(["Penny", "X", "C", "63.5 %"])myTable.add_row(["Howard", "X", "A", "90.23 %"])myTable.add_row(["Bernadette", "X", "D", "92.7 %"])myTable.add_row(["Sheldon", "X", "A", "98.2 %"])myTable.add_row(["Raj", "X", "B", "88.1 %"])myTable.add_row(["Amy", "X", "B", "95.0 %"]) print(myTable)
 
 
Output:
 
 
gstoica27
Picked
python-modules
python-utility
Python
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python List sort() method - GeeksforGeeks

03 Aug, 2021
Python list sort() function can be used to sort a List in ascending, descending, or user-defined order. 
Syntax:
List_name.sort() 
This will sort the given list in ascending order. This function can be used to sort a list of integers, floating-point numbers, strings, and others.
Python3
numbers = [1, 3, 4, 2]  # Sorting list of Integers in ascendingnumbers.sort()  print(numbers)
Output:
[1, 2, 3, 4]
Python3
strs = ["geeks", "code", "ide", "practice"]  # Sorting list of Integers in ascendingstrs.sort()  print(strs)
Output:
['code', 'geeks', 'ide', 'practice']
Syntax:
list_name.sort(reverse=True) 
This will sort the given list in descending order.
Python3
numbers = [1, 3, 4, 2]  # Sorting list of Integers in descendingnumbers.sort(reverse = True)  print(numbers)
Output:
[4, 3, 2, 1]
Syntax:
list_name.sort(key=..., reverse=...) – it sorts according to user’s choice 
Parameters:
reverse: reverse=True will sort the list descending. Default is reverse=False
key: A function to specify the sorting criteria(s)
Python
# Python program to demonstrate sorting by user's# choice  # function to return the second element of the# two elements passed as the parameterdef sortSecond(val):    return val[1]   # list1 to demonstrate the use of sorting # using using second key list1 = [(1, 2), (3, 3), (1, 1)]  # sorts the array in ascending according to # second elementlist1.sort(key = sortSecond) print(list1)  # sorts the array in descending according to# second elementlist1.sort(key = sortSecond, reverse = True)print(list1)
Output:
[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]
shubham_singh
AmiyaRanjanRout
python-list
python-list-functions
Python
Sorting
python-list
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Python - Leaf and Non-Leaf Nodes Dictionary - GeeksforGeeks

06 Nov, 2020
Sometimes, while working with Python, we can have a problem in which we need to work with Graph data represented in form of a Dictionary. In this, we may need to check for all the leaf and non-lead nodes. This kind of problem has direct applications in algorithms of Machine Learning. Let’s discuss a way in which this task can be performed. 
Input : test_dict = {‘Gfg’: {‘is’: 2, ‘best’: 1}} Output : {‘leaf’: 2, ‘non-leaf’: 1}Input : test_dict = {‘Gfg’: {‘best’: 2}} Output : {‘non-leaf’: 1, ‘leaf’: 1}  
Method : Using recursion + isinstance() + loop The combination of the above functionalities can be used to solve this problem. In this, we recur for the inner nesting using recursion and check for leaves or non-leaves by value types using isinstance(). 
Python3
# Python3 code to demonstrate working of# Leaf and Non-Leaf Nodes Dictionary# Using recursion + isinstance() + loop def hlpr_fnc(dict1, res = {'non-leaf':0, 'leaf':0}):         #res['non-leaf'] += 1      nodes = dict1.keys()    for node in nodes:      subnode = dict1[node]      if isinstance(subnode, dict):        res['non-leaf'] += 1        hlpr_fnc(subnode, res)      else:        res['leaf'] += 1     return res # initializing dictionarytest_dict = {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Leaf and Non-Leaf Nodes Dictionary# Using recursion + isinstance() + loopres = hlpr_fnc(test_dict)     # printing resultprint("The leaf and Non-Leaf nodes : " + str(res))
Output:
The original dictionary : {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
The leaf and Non-Leaf nodes : {'non-leaf': 5, 'leaf': 5}
ayazaki2012
Python dictionary-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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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?
How to disable dropdown options in ReactJS? - GeeksforGeeks

18 Jan, 2021
Disable options means the dropdown options become disable i.e. not clickable. Basically a disable option is unusable and un-clickable. Material UI for React has this component available for us and it is very easy to integrate. We can make an option disable in dropdown using the following approach.
Creating React Application and Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install material-ui/lab
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';  const App = () => {    // Sample options for dropdown  const myOptions = ['One', 'Two', 'Three', 'Four', 'Five'];    return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        style={{ width: 400 }}        options={myOptions}        getOptionDisabled={(option) => {          // Mention options which needs to be disable          return option === myOptions[1] || option === myOptions[3]        }}        renderInput={(params) => (          <TextField {...params} label="Disabled options"           variant="outlined" />        )}      />    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
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?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components