code-rag-bench/online-tutorials huggingface dataset:
Robot Framework - Environment Setup

Robot framework is built using python. In this chapter, we will learn how to set up Robot Framework. To work with Robot Framework, we need to install the following −
Python
pip
Robot Framework
wxPython for Ride IDE
Robot Framework Ride
To install python, go to python official site − https://www.python.org/downloads/ and download the latest version or the prior version of python as per your operating system (Windows, Linux/Unix, Mac, and OS X) you are going to use.
Here is the screenshot of the python download site −
The latest version available as per release dates are as follows −
Before you download python, it is recommended you check your system if python is already present by running the following command in the command line −
python --version

If we get the version of python as output then, we have python installed in our system. Otherwise, you will get a display as shown above.
Here, we will download python version 2.7 as it is compatible to the windows 8 we are using right now. Once downloaded, install python on your system by double-clicking on .exe python download. Follow the installation steps to install Python on your system. Once installed, to make python available globally, we need to add the path to environment variables in windows as follows −
Right-click on My Computer icon and select properties. Click on Advanced System setting and the following screen will be displayed.
Click on Environment Variables button highlighted above and it will show you the screen as follows −
Select the Variable Path and click the Edit button.
Get the path where python is installed and add the same to Variable value at the end as shown above.
Once this is done, you can check if python is installed from any path or directory as shown below −

    17 Lectures 
     1 hours 

 Musab Zayadneh

    11 Lectures 
     31 mins

 Musab Zayadneh

    20 Lectures 
     1.5 hours 

 Maksym Rudnyi

    25 Lectures 
     3 hours 

 Kamal Kishor Girdher

    16 Lectures 
     3.5 hours 

 Onur

    10 Lectures 
     34 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
How to pass arrays as function arguments in JavaScript?

In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don't need to use apply() function. Lets' discuss it in a nutshell.
In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used.
Live Demo
<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar.apply(null, names);
</script>
</body>
</html>
NSE
BSE
NIFTY
If we observe the following example, apply() function and null weren't used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value.
Live Demo
<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar(...names);
</script>
</body>
</html>
NSE
BSE
NIFTY
HTML5 Input type=number removes leading zero

The leading zero issues may arise when you want to add an international phone number.
To solve this −
<input type="tel" pattern="[0-9]*">
On iOS, the numeric keyboard appears with only numbers.
On Android phones, the "tel" is rightly interpreted but not the pattern.
You can also use −
<input type="text" pattern="[0-9]*" ...
The above will call and display the numeric keypad on iPhone and Android devices.
Go - Passing pointers to functions

Go programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
In the following example, we pass two pointers to a function and change the value inside the function which reflects back in the calling function −
package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 100
   var b int = 200

   fmt.Printf("Before swap, value of a : %d\n", a )
   fmt.Printf("Before swap, value of b : %d\n", b )

   /* calling a function to swap the values.
   * &a indicates pointer to a ie. address of variable a and 
   * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b);

   fmt.Printf("After swap, value of a : %d\n", a )
   fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
   var temp int
   temp = *x    /* save the value at address x */
   *x = *y      /* put y into x */
   *y = temp    /* put temp into y */
}
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Difference between throw and throws in Java

Both throw and throws are the concepts of exception handing in which throw is used to explicitly throw an exception from a method or any block of code while throws are used in the signature of the method to indicate that this method might throw one of the listed type exceptions.
The following are the important differences between throw and throws.
JavaTester.java
 Live Demo
public class JavaTester{
   public void checkAge(int age){
      if(age<18)
         throw new ArithmeticException("Not Eligible for voting");
      else
         System.out.println("Eligible for voting");
   }
   public static void main(String args[]){
      JavaTester obj = new JavaTester();
      obj.checkAge(13);
      System.out.println("End Of Program");
   }
}
Exception in thread "main" java.lang.ArithmeticException:
Not Eligible for voting
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)
JavaTester.java
 Live Demo
public class JavaTester{
   public int division(int a, int b) throws ArithmeticException{
      int t = a/b;
      return t;
   }
   public static void main(String args[]){
      JavaTester obj = new JavaTester();
      try{
         System.out.println(obj.division(15,0));
      }
      catch(ArithmeticException e){
         System.out.println("You shouldn't divide number by zero");
      }
   }
}
You shouldn't divide number by zero
How do I access subdocuments in MongoDB queries?

To access subdocuments in MongoDB, use find() with dot notation. Let us create a collection with documents −
> db.demo670.insertOne({
... id:101,
... "details":
... {
... Name:"Chris",
... Age:21,
... CountryName:"US",
... SubjectName:"MongoDB"
... }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e31d04263e90dac943de")
}
> db.demo670.insertOne({ id:102, "details": { Name:"David", Age:22, CountryName:"UK", SubjectName:"MySQL" } } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e33604263e90dac943df")
}
Display all documents from a collection with the help of find() method −
> db.demo670.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "id" : 101, "details" : { "Name" : "Chris", "Age" : 21, "CountryName" : "US", "SubjectName" : "MongoDB" } }
{ "_id" : ObjectId("5ea3e33604263e90dac943df"), "id" : 102, "details" : { "Name" : "David", "Age" : 22, "CountryName" : "UK", "SubjectName" : "MySQL" } }
Following is the query to access subdocuments −
> db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});7
This will produce the following output −
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "details" : { "CountryName" : "US" } }
BitArray.RightShift() Method in C# with Examples - GeeksforGeeks

27 Mar, 2019
BitArray class manages a array of bit values, which are represented as Booleans, where true indicates bit is 1 and false indicates bit is 0. This class is contained in namespace, System.Collections. BitArray.RightShift(Int32) method is used to shift the bits of the bit array to the right by one position and adds zeros on the shifted position. Original BitArray object will be modified on performing the operation right shift.
Syntax: public System.Collections.BitArray RightShift (int count);
Parameter:count is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647.
Return value : It returns Bit Array.
Example 1: Suppose we have the bit array 10011 we want to shift it right by two positions.
The final result is 00100.
// C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections;  class GeeksforGeeks {      // Main Method    public static void Main()    {          // Creating a BitArray of         // size 5 named BitArr        BitArray BitArr = new BitArray(5);          // Initializing values in BitArr        BitArr[0] = true;        BitArr[1] = true;        BitArr[2] = false;        BitArr[3] = false;        BitArr[4] = true;          // function calling        Display(BitArr.RightShift(2));    }      // Displaying the result    public static void Display(IEnumerable myList)    {        foreach(Object obj in myList)        {            Console.WriteLine(obj);        }    }}
False
False
True
False
False

Example 2: Suppose we have the bit array 100011 we want to shift it right by three positions.
The final result is 011000.
// C# program to illustrate the // RightShift(Int32) Methodusing System;using System.Collections;  class GeeksforGeeks {      // Main Method    public static void Main()    {          // Creating a BitArray        BitArray BitArr = new BitArray(6);          // Initializing values in BitArr        BitArr[0] = true;        BitArr[1] = false;        BitArr[2] = false;        BitArr[3] = false;        BitArr[4] = true;        BitArr[5] = true;          // function calling        Display(BitArr.RightShift(3));    }      // Displaying the result    public static void Display(IEnumerable myList)    {        foreach(Object obj in myList)        {            Console.WriteLine(obj);        }    }}
False
True
True
False
False
False

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.rightshift?view=netcore-2.2
CSharp-Collections-BitArray
CSharp-Collections-Namespace
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
Extension Method in C#
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
How to use href attribute in HTML Page?

The href attribute in an HTML page is used to specify the URL for a page. If the href attribute is not present, then the <a> tag will not be considered as a hyperlink.
Just keep in mind the href attribute should get included as an attribute for <a> tag. It should be used inside the <body>...</body> tags.
You can try the following code to make page links in an HTML page using the href attribute
<!DOCTYPE html>
<html>
   <head>
      <title>HTML href attribute</title>
   </head>

   <body>
      <h1>Learn about the company</h1>
      <a href="/about/index.htm">About</a>
      <a href="/about/about_team.htm">Team</a>
   </body>
</html>
Creating a Table in MySQL to set current date as default

Following is the syntax for creating a table and adding DEFAULT constraint to set default value −
CREATE TABLE yourTableName
(
yourColumnName1 dataType not null ,
yourColumnName2 dataType default anyValue,
.
.
.
N
);;
Let us create a table wherein we have set “employee_joining_date” with default constraint for current date as default −
mysql> create table demo43
−> (
−> employee_id int not null auto_increment primary key,
−> employee_name varchar(40) not null,
−> employee_status varchar(60) default "NOT JOINED",
−> employee_joining_date date default(CURRENT_DATE)
−> );
Query OK, 0 rows affected (0.66 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('John','JOINED','2020-05-10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into demo43(employee_name,employee_status,employee_joining_date) values('David','JOINED','2020-10-12');
Query OK, 1 row affected (0.21 sec)
mysql> insert into demo43(employee_name) values('Bob');
Query OK, 1 row affected (0.15 sec)
Display records from the table using select statement −
mysql> select *from demo43;
This will produce the following output −
+-------------+---------------+-----------------+-----------------------+
| employee_id | employee_name | employee_status | employee_joining_date |
+-------------+---------------+-----------------+-----------------------+
|           1 | John          | JOINED          | 2020−05−10            |
|           2 | David         | JOINED          | 2020−10−12            |
|           3 | Bob           | NOT JOINED      | 2020−10−31            |
+-------------+---------------+-----------------+-----------------------+
3 rows in set (0.00 sec)
Display the dropdown’s (select) selected value on console in JavaScript?

Let’s say the following is our dropdown (select) −
<select onchange="selectedSubjectName()" id="subjectName">
   <option>Javascript</option>
   <option>MySQL</option>
   <option>MongoDB</option>
   <option>Java</option>
</select>
Following is the code to display the selected value on Console −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<select onchange="selectedSubjectName()" id="subjectName">
<option>Javascript</option>
<option>MySQL</option>
<option>MongoDB</option>
<option>Java</option>
</select>
<script>
   function selectedSubjectName() {
      var subjectIdNode = document.getElementById('subjectName');
      var value =
      subjectIdNode.options[subjectIdNode.selectedIndex].text;
      console.log("The selected value=" + value);
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am going to select Java. The snapshot is as follows −
After that I am going to select MongoDB. The snapshot is as follows −
Clear a StringBuilder in C#

To clear a StringBuilder, use the Clear() method.
Let’s say we have set the following StringBuilder −
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
Now, use the Clear() method to clear the StringBuilder −
str.Clear();
Let us see the complete code −
 Live Demo
using System;
using System.Text;

public class Demo {
   public static void Main() {
      // string array
      string[] myStr = { "One", "Two", "Three", "Four" };
      StringBuilder str = new StringBuilder("We will print now...").AppendLine();

      // foreach loop to append elements
      foreach (string item in myStr) {
         str.Append(item).AppendLine();
      }
      Console.WriteLine(str.ToString());
      int len = str.Length;
      Console.WriteLine("Length: "+len);

      // clearing
      str.Clear();
      int len2 = str.Length;
      Console.WriteLine("Length after using Clear: "+len2);
      Console.ReadLine();
   }
}
We will print now...
One
Two
Three
Four

Length: 40
Length after using Clear: 0
PyQt - QSplitter Widget

This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls.
The widgets in a QSplitter object are laid horizontally by default although the orientation can be changed to Qt.Vertical.
Following are the methods and signals of QSplitter class −
addWidget()
Adds the widget to splitter’s layout
indexOf()
Returns the index of the widget in the layout
insetWidget()
Inserts a widget at the specified index
setOrientation()
Sets the layout of splitter to Qt.Horizontal or Qt.Vertical
setSizes()
Sets the initial size of each widget
count()
Returns the number of widgets in splitter widget
splitterMoved() is the only signal emitted by QSplitter object whenever the splitter handle is dragged.
The following example has a splitter object, splitter1, in which a frame and QTextEdit object are horizontally added.
topleft = QFrame()
textedit = QTextEdit()
splitter1.addWidget(topleft)
splitter1.addWidget(textedit)

This splitter object splitter1 and a bottom frame object are added in another splitter, splitter2, vertically. The object splitters is finally added in the top level window.
bottom = QFrame()
splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(splitter1)
splitter2.addWidget(bottom)

hbox.addWidget(splitter2)
self.setLayout(hbox)

The complete code is as follows −
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Example(QWidget):

   def __init__(self):
      super(Example, self).__init__()
		
   self.initUI()
	
   def initUI(self):
	
      hbox = QHBoxLayout(self)
		
      topleft = QFrame()
      topleft.setFrameShape(QFrame.StyledPanel)
      bottom = QFrame()
      bottom.setFrameShape(QFrame.StyledPanel)
		
      splitter1 = QSplitter(Qt.Horizontal)
      textedit = QTextEdit()
      splitter1.addWidget(topleft)
      splitter1.addWidget(textedit)
      splitter1.setSizes([100,200])
		
      splitter2 = QSplitter(Qt.Vertical)
      splitter2.addWidget(splitter1)
      splitter2.addWidget(bottom)
		
      hbox.addWidget(splitter2)
		
      self.setLayout(hbox)
      QApplication.setStyle(QStyleFactory.create('Cleanlooks'))
		
      self.setGeometry(300, 300, 300, 200)
      self.setWindowTitle('QSplitter demo')
      self.show()
		
def main():
   app = QApplication(sys.argv)
   ex = Example()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
Scala | Functions – Basics

17 Jan, 2019
A function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same code again and again for different inputs, we can simply call the function. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values.
Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.
In general, function declaration & definition have 6 components:
def keyword: “def” keyword is used to declare a function in Scala.
function_name: It should be valid name in lower camel case. Function name in Scala can have characters like +, ~, &, –, ++, \, / etc.
parameter_list: In Scala, comma-separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis.
return_type: User must mention return type of parameters while defining function and return type of a function is optional. If you don’t specify any return type of a function, default return type is Unit which is equivalent to void in Java.
= : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value. If he doesn’t use it, the function will not return any value and will work like a subroutine.
Method body: Method body is enclosed between braces { }. The code you need to be executed to perform your intended operations.
Syntax:
def function_name ([parameter_list]) : [return_type] = {
   
  // function body

}

Note: If the user will not use the equals sign and body then implicitly method is declared abstract.
There are mainly two ways to call the function in Scala. First way is the standard way as follows:
function_name(paramter_list)
In the Second way, a user can also call the function with the help of the instance and dot notation as follows:
[instance].function_name(paramter_list)
Example:
object GeeksforGeeks {         def main(args: Array[String]) {               // Calling the function      println("Sum is: " + functionToAdd(5,3));   }             // declaration and definition of function   def functionToAdd(a:Int, b:Int) : Int =    {                var sum:Int = 0       sum = a + b         // returning the value of sum       return sum   }}
Output:
Sum is: 8
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2010 | Question 26

28 Jun, 2021
Consider a company that assembles computers. The probability of a faulty assembly of any computer is p. The company therefore subjects each computer to a testing process.This testing process gives the correct result for any computer with a probability of q. What is the probability of a computer being declared faulty?(A) pq + (1 – p)(1 – q)(B) (1 – q) p(C) (1 – p) q(D) pqAnswer: (A)Explanation:
A computer can be declared faulty in two cases
1) It is actually faulty and correctly declared so (p*q)
2) Not faulty and incorrectly declared (1-p)*(1-q). Quiz of this Question

    
        My Personal Notes
        arrow_drop_up
    
    
        
        
            
            Save
        
    
                        

GATE-CS-2010


GATE-GATE CS 2010


GATE

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
How to Truncate the Double Value to Given Decimal Places in Java?

15 Dec, 2020
In simplest terms, truncation means to chop off the decimal portion of a number. A method of approximating a decimal number by dropping all decimal places past a certain point without rounding.
Given a double value and a decimal place truncate the value to the given decimal point.
Example: 
Input: val = 3.142857142857143
Decimal point = 3
Output =  3.142

Upto 3 decimal places
 Approach 1: Using Mathematically :
Shift the decimal of the given value to the given decimal point by multiplying 10^n
Take the floor of the number and divide the number by 10^n
The final value is the truncated value
Java
// Java program to truncate the double value to// a particular decimal point  import java.io.*;  class GFG {      static void change(double value, int decimalpoint)    {          // Using the pow() method        value = value * Math.pow(10, decimalpoint);        value = Math.floor(value);        value = value / Math.pow(10, decimalpoint);          System.out.println(value);          return;    }          // Main Method    public static void main(String[] args)    {          double firstvalue = 1212.12131131;        int decimalpoint = 4;          change(firstvalue, decimalpoint);          double secondvalue = 3.142857142857143;        int decimalpoint2 = 3;          change(secondvalue, decimalpoint2);    }}
1212.1213
3.142
Approach 2: Using String matching approach
Convert the number into String
Start the counter variable when “.” found in the String
Increment the counter till decimal point
Store the new String and parse it in double format
Java
// Java program to truncate the double// value using string matching  import java.io.*;  class GFG {    public static void main(String[] args)    {        double firstvalue = 1212.12131131;          // decimal point        int decimalpoint = 6;          // convert the double value in string        String temp_value = "" + firstvalue;        String string_value = "";          int counter = -1;          for (int i = 0; i < temp_value.length(); ++i) {              // checking the condition            if (counter > decimalpoint) {                break;            }            else                  if (temp_value.charAt(i) == '.') {                counter = 1;            }            else if (counter >= 1) {                  ++counter;            }              // converting the number into string            string_value += temp_value.charAt(i);        }          // parse the string        double new_value = Double.parseDouble(string_value);          System.out.println(new_value);    }}
1212.121311
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.pmt() in Python

29 Nov, 2018
numpy.pmt(rate, nper, pv, fv, when = ‘end’): This financial function helps user to compute payment value as per the principal and interest.
Parameters :rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodsfv : [scalar or (M, )array] Future valuepv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period.Default is {‘end’, 0}
Return :Payment value
Equation being solved :
fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper – 1) == 0
or when rate == 0fv + pv + pmt * nper == 0
Code:
# Python program explaining # pmt() function   import numpy as np   ''' Question :   monthly payment needed to pay off a $10, 000 loanin 12 years at an annual interest rate of 10 %'''  # rate np  pv Solution = np.pmt(0.10 / 12, 12 * 12,  10, 000)   # Here fv = 0 ; Also Default value of fv = 0 print("Solution : ", Solution) 
Output:
Solution :  -0.1195078262827336
Python numpy-Financial Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python – Bitwise AND of List

06 Oct, 2020
Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Let’s discuss certain ways in which this task can be performed.Method #1 : Using reduce() + lambda + “&” operator The above functions can be combined to perform this task. We can employ reduce() to accumulate the result of AND logic specified by the lambda function. Works only with Python2. 
Python3
# Python code to demonstrate working of# Bitwise AND of List# Using reduce() + lambda + "&" operator # initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint("The original list is : " + str(test_list)) # Bitwise AND of List# Using reduce() + lambda + "&" operatorres = reduce(lambda x, y: x & y, test_list) # printing resultprint("The Bitwise AND of list elements are : " + str(res))
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise AND of list elements are : 0


 
 Method #2 : Using reduce() + operator.iand This task can also be performed using this method. In this the task performed by lambda function in above method is performed using iand function for cumulative AND operation. Works with Python2 only. 
Python3
# Python code to demonstrate working of# Bitwise AND of List# Using functools.reduce() + operator.iandfrom operator import iandfrom functools import reduce# initializing listtest_list = [4, 6, 2, 3, 8, 9] # printing original listprint("The original list is : " + str(test_list)) # Bitwise AND of List# Using functools.reduce() + operator.iandres = reduce(iand, test_list) # printing resultprint("The Bitwise AND of list elements are : " + str(res))
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise AND of list elements are : 0


 
sujy
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python 3 - os.unlink() Method

The method unlink() removes (deletes) the file path.If the path is a directory, OSError is raised. function is identical to remove(); the unlink name is its traditional Unix name.
Following is the syntax for unlink() method −
os.unlink(path)

path − This is the path, which is to be removed.
This method does not return any value.
The following example shows the usage of unlink() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
os.unlink("foo.txt")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))
When we run the above program, it produces the following result −
The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'python2'
]

The dir after removal of path : [
   'Applicationdocs.docx', 'book.zip', 
   'Java Multiple Inheritance.htm', 
   'Java Multiple Inheritance_files', 'java.ppt', 'python2'
Import multiple excel sheets into in R

17 Jun, 2021
In this article, we are going to see how to import multiple Excel sheets into the R language. 
Excel provides us with multiple worksheets. For example, in the below Excel workbook StudentData, we have two worksheets – sheet 1 is Student Details and sheet 2 is Subject Details.
For importing multiple Excel sheets into R, we have to, first install a package in R which is known as readxl. After successfully installing the package, we have to load the package using the library function is R.
install.packages('readxl')
Once we have completely installed and loaded the package in RStudio, the next job is to import the excel workbook and check the number of sheet it contains. We can do this using the  excel_sheets function. 
R
library("read_excel")     # Importing the excel workbook for# checking the number of sheets it containsexcel_sheets("StudentData.xlsx")
Output:
'StudentDetails' 'SubjectDetails'
We have an Excel file named as “StudentData” and we have already saved it in our working directory. It contains two sheets named StudentDetails and SubjectDetails. We have a function in R called read_excel() which we will use to import specific sheet into R. If no argument is specified, then the read_excel() will by default import the first Excel sheet.
Syntax: read_excel(arg)
Code:
R
# Importing specific sheets into R using the read_excel()StudentDet<-read_excel("StudentData.xlsx",                        sheet = 1)StudentDet<-read_excel("StudentData.xlsx",                        sheet = "StudentDetails")SubjectDet<-read_excel("StudentData.xlsx",                       sheet = "SubjectDetails")  # For viewing the details of sheet 1head(StudentDet)# For viewing the details of sheet 2head(SubjectDet)
Output:
Picked
R-Excel
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

30 Sep, 2021
Consider two processors P1 and P2 executing the same instruction set. Assume that under identical conditions, for the same input, a program running on P2 takes 25% less time but incurs 20% more CPI (clock cycles per instruction) as compared to the program running on P1. If the clock frequency of P1 is 1GHz, then the clock frequency of P2 (in GHz) is _________.(A) 1.6(B) 3.2(C) 1.2(D) 0.8Answer: (A)Explanation:
For P1 clock period = 1ns 

Let clock period for P2 be t.

Now consider following equation based on specification
7.5 ns = 12*t ns

We get t and inverse of t will be 1.6GHz 
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0035:15 / 40:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h-14CfDEprU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
Subarray Product Less Than K in C++

Suppose we have given an array of positive integers nums. We have to count and print the number of (contiguous) subarrays where the product of each the elements in the subarray is less than k. So if the input is like [10,5,2,6] and k := 100, then the output will be 8. So the subarrays will be [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]]
To solve this, we will follow these steps −
temp := 1, j := 0 and ans := 0
for i in range 0 to size of the arraytemp := temp * nums[i]while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1ans := ans + (i – j + 1)
temp := temp * nums[i]
while temp >= k and j <= i, dotemp := temp / nums[j]increase j by 1
temp := temp / nums[j]
increase j by 1
ans := ans + (i – j + 1)
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int numSubarrayProductLessThanK(vector<int>& nums, int k) {
      lli temp = 1;
      int j = 0;
      int ans = 0;
      for(int i = 0; i < nums.size(); i++){
         temp *= nums[i];
         while(temp >= k && j <= i) {
            temp /= nums[j];
            j++;
         }
         ans += (i - j + 1);
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {10,5,2,6};
   cout << (ob.numSubarrayProductLessThanK(v, 100));
}
[10,5,2,6]
100
8
Python program for the permutation of a given string inbuilt function in python

String is given. Our task is to display permutation of given string. Here solve this problem in python using inbuilt function permutations (iterable).
Input : string = 'XYZ'
Output : XYZ
XZY
YXZ
YZX
ZXY
ZYX
Step 1: given string.
Step 2: Get all permutations of string.
Step 3: print all permutations.
from itertools import permutations
def allPermutations(str1):
   # Get all permutations of string 'ABC'
   per = permutations(str1)
   # print all permutations
   print("Permutation Of this String ::>")
   for i in list(per):
   print (''.join(i))
# Driver program
if __name__ == "__main__":
   str1 = input("Enter the string ::>")
allPermutations(str1)
Enter the string ::> abc
Permutation Of this String ::>
abc
acb
bac
bca
cab
cba
Ratio and Proportion - GeeksforGeeks

21 Apr, 2016
Then (3x+5) / (4x+5)  = 7 / 9 

∴ 9(3x + 5) = 7(4x + 5)
∴ 27x + 45 = 28x + 35
∴ x = 10
∴ Ashok’s present age = 4x = 40 years 
Let the present age of Ram and Shyam be 6x years and 5x years respectively.

Then 5x + 7 = 32
∴      5x = 25
∴        x = 5
∴ Present age of Ram = 6x = 30 years
Then (4x-9) + (5x-9) + (9x-9) =45
∴ 18x – 27 = 45
∴ 18x = 72
∴ x = 4
Let the numbers be 2X and 9X
Then their H.C.F. is X, so X = 19
∴ Numbers are (2x19 and 9x19) i.e. 38 and 171
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
SQLAlchemy Core - Creating Table
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
Display a percentage in Java

To display a percentage in Java, use the following DecimalFormat.
DecimalFormat decFormat = new DecimalFormat("#%");
Since, we have used the DecimalFormat class, therefore do not forget to import the following package −
import java.text.DecimalFormat;
Now, let us learn how to display percentage −
decFormat.format(0.80)
decFormat.format(-0.19)
decFormat.format(1.88)
The above will be displayed as −
80%
-19%
188%
The following is the complete example −
 Live Demo
import java.text.DecimalFormat;
public class Demo {
   public static void main(String[] argv) throws Exception {
      DecimalFormat decFormat = new DecimalFormat("#%");
      System.out.println(decFormat.format(0.80));
      System.out.println(decFormat.format(-0.19));
      System.out.println(decFormat.format(1.88));
      System.out.println(decFormat.format(0.9099));
      System.out.println(decFormat.format(12.788));
      System.out.println(decFormat.format(-9.678));
   }
}
80%
-19%
188%
91%
1279%
-968%
How to create an array of integers in JavaScript?

To create an array of integers in JavaScript, try the following −
var rank = [1, 2, 3, 4];
You can also use the new keyword to create array of integers in JavaScript −
var rank = new Array(1, 2, 3, 4);
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.
Let’s see an example to create an array of integers in JavaScript −
Live Demo
<html>    
   <body>  
      <script>
         var arr1 = [50,60,65,90];
         var arr2 = [25,35,50,90];  
         for (i = 0; i < arr1.length; i++) {  
            for (z = 0; z < arr1.length; z++) {
               if (arr1[i] === arr2[z]) {
                  document.write("<br>Matched element: "+arr2[z]);
               }  
            }  
         }  
      </script>
   </body>
</html>
Matched element: 50
Matched element: 90
Progress Bars in Python - GeeksforGeeks

17 Aug, 2020
Understandably, we get a little impatient when we do not know how much time a process is going to take, for example, a for loop or a file downloading or an application starting up.
To distract us from that we were given the libraries tqdm and progressbar in Python language which allows us to give a visual illustration of the process completion time using a progress bar. Loading bars are often seen on game screens as the resources required for the game to run are being acquired to the main memory.
It wraps an iterable with the tqdm to decorate it with the methods built-in with tqdm and make a loading bar. This will take the users’ mind off of how long the process is taking to complete.
All we need to do is, install the tqdm package by typing this line in your terminal and start writing the code.
->pip install tqdm
And type this code in your editor.
from tqdm import tqdm  for i in tqdm (range (100), desc="Loading..."):    pass
Output:
This gives a very fast loading bar because there’s nothing in the loop., you can replace the pass keyword with whatever work you want to do in the for loop.
from tqdm import tqdmimport time    for i in tqdm (range (101),                desc="Loading...",                ascii=False, ncols=75):    time.sleep(0.01)      print("Complete.")
Output:
For command-line interface
pip install progressbar 
(or)
pip install progressbar2
It does everything the same as tqdm package, that is it decorates the iterable with the built-in widgets to make an animated progress bar or even a colorful one. Widgets are objects which display depending on the progress bar.
However, the progress bar and the progress bar 2 packages have a lot of extra, useful methods than the tqdm package. For example, we can make an animated loading bar.
import progressbarimport time    # Function to create def animated_marker():          widgets = ['Loading: ', progressbar.AnimatedMarker()]    bar = progressbar.ProgressBar(widgets=widgets).start()          for i in range(50):        time.sleep(0.1)        bar.update(i)          # Driver's codeanimated_marker()
Output:
In progressbar.AnimatedMarker(), we can pass any sequence of characters to animate. The default arguments are '|/-\|'
Here’s another example using some of the commonly used widgets of the ProgressBar class.
import timeimport progressbar  widgets = [' [',         progressbar.Timer(format= 'elapsed time: %(elapsed)s'),         '] ',           progressbar.Bar('*'),' (',           progressbar.ETA(), ') ',          ]  bar = progressbar.ProgressBar(max_value=200,                               widgets=widgets).start()  for i in range(200):    time.sleep(0.1)    bar.update(i)
Output:
Akanksha_Rai
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Playit

You can change the text-align by clicking on one of the properties on the left.
  This text is where you will see the result of the selected text-align property.
UUID getLeastSignificantBits() Method in Java with Examples - GeeksforGeeks

27 Dec, 2018
The UUIDs are 128-bit values. The getLeastSignificantBits() Method of UUID class in Java is used to get the least significant 64 bits of this UUID.
Syntax:
public long getLeastSignificantBits()
Parameters: The method does not take any parameters.
Return Value: The method returns an integer value which is the least significant 64 bit of this 128 valued UUID.
Below programs illustrate the working of getLeastSignificantBits() method:
Program 1:
// Java code to illustrate// getLeastSignificantBits() method  import java.util.*;  public class UUID_Demo {    public static void main(String[] args)    {        // Creating two UUIDs        UUID UUID_1            = UUID                  .fromString(                      "58e0a7d7-eebc-11d8-9669-0800200c9a66");          // Displaying the UUID        System.out.println("UUID: "                           + UUID_1);          // Displaying the value of UUID        System.out.println("The value is: "                           + UUID_1.clockSequence());          // Getting the least significant 64 bit        System.out.println("The least significant 64 bit: "                           + UUID_1                                 .getLeastSignificantBits());    }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The value is: 5737
The least significant 64 bit: -7608541298835023258

Program 2:
// Java code to illustrate// getLeastSignificantBits() method  import java.util.*;  public class UUID_Demo {    public static void main(String[] args)    {          // Creating two UUIDs        UUID UUID_1            = UUID                  .fromString(                      "58e0a7d7-eebc-11d8-9669-0800200c9a66");          // Displaying the UUID        System.out.println("UUID: "                           + UUID_1);          // Displaying the value of UUID        System.out.println("The value is: "                           + UUID_1.clockSequence());          // Getting the least significant 64 bit        System.out.println("The least significant 64 bit: "                           + UUID_1.getLeastSignificantBits());    }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The value is: 5737
The least significant 64 bit: -7608541298835023258

Java - util package
Java-Functions
Java-UUID
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java