code-rag-bench/online-tutorials huggingface dataset:
Secondary memory and DMA - GeeksforGeeks

19 Nov, 2018

              Initialize the address register
              Initialize the count to 500
        LOOP: Load a byte from device
              Store in memory at address given by address register
              Increment the address register
              Decrement the count
              If count != 0 go to LOOP 
 Explanation:
                        STATEMENT                                           CLOCK CYCLE(S) NEEDED
              Initialize the address register                                        1
              Initialize the count to 500                                            1
        LOOP: Load a byte from device                                                2
              Store in memory at address given by address register                   2
              Increment the address register                                         1
              Decrement the count                                                    1
              If count != 0 go to LOOP                                               1

        Interrrupt driven transfer time = 1+1+500×(2+2+1+1+1) = 3502
        DMA based transfer time = 20+500*2 = 1020
        Speedup = 3502/1020 ≈ 3.4

Source: http://clweb.csa.iisc.ernet.in/rahulsharma/gate2011key.html
(A) DMA I/O                    (1) High speed RAM
(B) Cache                      (2) Disk
(C) Interrupt I/O              (3) Printer
(D) Condition Code Register    (4) ALU

Codes:
    A   B   C   D 
a   4   3   1   2
b   2   1   3   4
c   4   3   2   1
d   2   3   4   1

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
How to Enable or Disable SELinux Boolean Values? - GeeksforGeeks

12 Mar, 2021
As SELinux has tones of policies to handle and maintain the security level of the system. SELinux has given an easy way to dynamically update the policy. You need special arguments to make these policies persistent over a reboot, this capability is provided by the SELinux management utility.
To see Boolean, you have getsebool terminal command, which shows the policies and their status.
# man getsebool
man getsebool
 To see all sebools with status:
# getsebool -a
getsebool values
To change the SELinux Boolean values we have command setsebool.
# man setsebool
setsebool
It has three options -P, -N and -V. 
-P is for persistently change the Boolean values across reboots.
-N is for the policy on disk is not reloaded into the kernel.
-V is for the verbose messages on terminal.
Let us change the bool value for policy “httpd_can_check_spam” to true or 1 or on. Also, check if it is changed.
# setsebool httpd_can_check_spam on
# getsebool -a | grep httpd_can_check_spam
setsebool on
To permanently or persistently update the Boolean value use -P option.
# setsebool -P httpd_can_check_spam on
Understanding these policies by the name would be a tedious job. We have a command to get some more information about the particular policy to make more sense and increase understanding of the topic.
We have semanage command for all these kinds of jobs.
# man semanage
man semanage
 Semanage has many options, we are going to use “boolean”,  boolean – manages Boolean to selectively enable functionality.
# semanage boolean -l | grep httpd_can_check_spam
boolean info
The output shows that “httpd_can_check_spam” can take two states ON or OFF, and it is used to give httpd server capabilities to check spam on the server. SELinux boolean is made easy to use and understand the security environment.
Picked
How To
Linux-Unix
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 Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
NPDA for accepting the language L = {a2mb3m | m ≥ 1} - GeeksforGeeks

28 Aug, 2019
Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateProblem – Design a non deterministic PDA for accepting the language L = {a2mb3m | m ≥ 1}, i.e.,
L = {aabbb, aaaabbbbbb, aaaaaabbbbbbbbb, aaaaaaaabbbbbbbbbbbb, ......} 
In each of the string, for every 2 ‘a’s there is 3 ‘b’.
Explanation –Here, we need to maintain the order of a’s and b’s.That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. Here, we have 3 ‘b’s for every 2 ‘a’s. We will take 2 stack alphabets:
 = {a, z}
Where,  = set of all the stack alphabet
z = stack start symbol 
Approach used in the construction of PDA –As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. We will push three ‘a’s into the stack for two consecutive two ‘a’s and again for the next two ‘a’s, we will push three ‘a’ into the stack. That is, for the first ‘a’ we will do nothing only state will change and for the next ‘a’ we will do the pushing operation and similarly we perform this alternatively, i.e.,For two a’s we push three ‘a’For four b’s we push six ‘a’After that, when ‘b’ comes then pop one ‘a’ from the stack each time.
So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA.
Stack transition functions –
(q0, a, z) (q1, z)     [ Indicates no operation only state change ]
(q1, a, z) (q2, aaaz)  [ Indicates push operation for alternate 'a'] 
(q2, a, aaaz) (q1, aaaz) [ Indicates no operation only state change ]
(q1, a, aaaz) (q2, aaaa) [ Indicates push operation for alternate 'a']
(q2, b, a) (q3,  )  [Indicates pop operation ]
(q3, b, a) (q3,  )  [Indicates pop operation ]
(q3, , z) (qf, z )    

Where, q0 = Initial stateqf = Final state = indicates pop operation
Correct transition diagram-
Rumor
nidhi_biet
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Regular expression to ∈-NFA
Design 101 sequence detector (Mealy machine)
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Closure properties of Regular languages
How to manually add a legend with a color box on a Matplotlib figure ? - GeeksforGeeks

23 Dec, 2020
A legend is basically an area in the plot which describes the elements present in the graph. Matplotlib provides an inbuilt method named legend() for this purpose. The syntax of the method is below :
Example: Adding Simple legend
Python3
# Import librariesimport matplotlib.pyplot as plt  # Creating plotplt.plot([1, 2, 3, 4])    plt.title('simple legend example ')  # Creating legendplt.legend(['simple legend example'])   # Show plotplt.show()
Output:
To create a legend with a color box, patches are used provided by the matplotlib.patches module. A patch nothing but a 2D artist with face color and edge color. Below is a simple example of this:
Example 1:
Python3
# Import librariesimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt  # Creating plotplt.plot([1, 2, 3, 4], color='blue')  plt.title('simple legend example ')  # Creating legend with color boxblue_patch = mpatches.Patch(color='blue', label='blue legend')plt.legend(handles=[blue_patch])  # Show plotplt.show()
Output:
Example 2:
Python3
# Import librariesimport matplotlib.pyplot as pltimport matplotlib.patches as mpatchesimport scipy.statsimport numpy as np  # Setting limit for x valuesx_min = 0.0x_max = 50.0  # Setting figure sizefig = plt.figure(figsize = (16, 9))   # Creating first datasetmean = 12.0 std = 3.0  x = np.linspace(x_min, x_max, 100)y = scipy.stats.norm.pdf(x,mean,std)  # Plotting first datasetplt.plot(x,y, color='red')plt.fill_between(x, y, color='#CE5D45', alpha=1.0)  # Creating second datasetmean = 18.0 std = 6.0  x = np.linspace(x_min, x_max, 100)y = scipy.stats.norm.pdf(x,mean,std)  # Plotting second datasetplt.plot(x,y, color='green')plt.fill_between(x, y, color='#5DC83F', alpha=1.0)  # Creating legend with color boxpop_a = mpatches.Patch(color='#5DC83F', label='Population Dataset 1')pop_b = mpatches.Patch(color='#CE5D45', label='Population Dataset 2')plt.legend(handles=[pop_a,pop_b])  # Adding grid to plotplt.grid()  # Adding X and Y limitsplt.xlim(x_min,x_max)plt.ylim(0,0.25)  # Adding titleplt.title('simple legend example',fontsize=12)  # Adding labelsplt.xlabel('')plt.ylabel('Probability Distribution')  # Showing plotplt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Find length of a string in python (3 ways)

String is a python which is a series of Unicode characters. Once declared it is not changeable. In this article we'll see what are the different ways to find the length of a string.
This is the most straight forward way. Here we use a library function named len(). The string is passed as parameter to the function and we get a count of characters in the screen.
str ="Tutorials"
print("Length of the String is:", len(str))
Running the above code gives us the following result −
Length of the String is: 9
We can use the string slicing approach to count the position of each character in the string. The final count of the number of positions in the string becomes the length of the string.
str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
   position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position)
Running the above code gives us the following result −
The total number of characters in the string: 9
The join() and count() string functions can also be used
str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)
Running the above code gives us the following result −
The total number of characters in the string: 9
C program to append content of one text file to another - GeeksforGeeks

24 Jul, 2020
Pre-requisite: File Handling in C 
Given the source and destination text files, the task is to append the content from source file to destination file and then display the content of the destination file.Examples:  
Input: 

file1.text
This is line one in file1
Hello World.
file2.text
This is line one in file2
Programming is fun.

Output: 
 
This is line one in file2
Programming is fun.
This is line one in file1
Hello World.



Approach: 
Open file1.txt and file2.txt with “a+”(append and read) option, so that the previous content of the file is not deleted. If files don’t exist, they will be created.Explicitly write a newline (“\n”) to the destination file to enhance readability.Write content from source file to destination file.Display the contents in file2.txt to console (stdout).  
Open file1.txt and file2.txt with “a+”(append and read) option, so that the previous content of the file is not deleted. If files don’t exist, they will be created.
Explicitly write a newline (“\n”) to the destination file to enhance readability.
Write content from source file to destination file.
Display the contents in file2.txt to console (stdout).  
C
// C program to append the contents of// source file to the destination file// including header files#include <stdio.h> // Function that appends the contentsvoid appendFiles(char source[],                 char destination[]){    // declaring file pointers    FILE *fp1, *fp2;     // opening files    fp1 = fopen(source, "a+");    fp2 = fopen(destination, "a+");     // If file is not found then return.    if (!fp1 && !fp2) {        printf("Unable to open/"               "detect file(s)\n");        return;    }     char buf[100];     // explicitly writing "\n"    // to the destination file    // so to enhance readability.    fprintf(fp2, "\n");     // writing the contents of    // source file to destination file.    while (!feof(fp1)) {        fgets(buf, sizeof(buf), fp1);        fprintf(fp2, "%s", buf);    }     rewind(fp2);     // printing contents of    // destination file to stdout.    while (!feof(fp2)) {        fgets(buf, sizeof(buf), fp2);        printf("%s", buf);    }} // Driver Codeint main(){    char source[] = "file1.txt",         destination[] = "file2.txt";     // calling Function with file names.    appendFiles(source, destination);     return 0;}
Output: 
Below is the output of the above program:  
 
Time Complexity: O(N) Auxiliary Space Complexity: O(1) 
 
nidhi_biet
C-File Handling
Arrays
C Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Strings in C
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Self–invoking function in JavaScript?

The self-invoking function in JavaScript are known as Immediately Invoked Function Expressions (IIFE). Immediately Invoked Function Expressions (IIFE) is a JavaScript function that executes immediately after it has been defined so there is no need to manually invoke IIFE.
Following is the code for self-invoking function (IIFE) in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="javascript:void(0);en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Immediately Invoked Function Expressions (IIFE)</h1>
<div class="sample"></div>
<script>
   let sampleEle = document.querySelector(".sample");
   (function () {
      sampleEle.innerHTML = "This code is invoked immediately as soon as it is defined";
   })();
</script>
</body>
</html>
The above code will produce the following output −
Trigonometric Functions in Java

The java.lang.Math class contains methods for trigonometric operations like cos(), sin(), tan(), tanh(), cosh(), atan(), etc.
Let us work around some of these trigonometric functions in Java −
static double asin(double a)
The java.lang.Math.asin(double a) returns the arc sine of an angle, in the range of -pi/2 through pi/2.
Let us now see an example −
import java.util.*;
public class Main {
   public static void main(String args[]) {
      // get a variable x which is equal to PI/2
      double x = Math.PI / 2;
      // convert x to radians
      x = Math.toRadians(x);
      // get the arc sine of x
      System.out.println("Math.asin(" + x + ")=" + Math.asin(x));
   }
}
Math.asin(0.027415567780803774)=0.02741900326072046
static double atan(double a)
The atan() method returns the arc tangent of an angle, in the range of -pi/2 through pi/2.
Let us now see an example to implement the atan() method in Java −
import java.util.*;
public class Main {
   public static void main(String args[]) {
      // get a variable x which is equal to PI/2
      double x = Math.PI / 2;
      // convert x to radians
      x = Math.toRadians(x);
      // get the arc tangent of x
      System.out.println("Math.atan(" + x + ")" + Math.atan(x));
   }
}
Math.atan(0.027415567780803774)0.0274087022410345
static double cosh(double x)
The java.lang.Math.cosh(double a) returns the hyperbolic cosine of a double value.
Let us now see an example to implement the cosh() method in Java −
import java.util.*;
public class Main {
   public static void main(String args[]) {
      // get two double numbers
      double x = 45.0;
      double y = 180.0;
      // convert them to radians
      x = Math.toRadians(x);
      y = Math.toRadians(y);
      // print their hyperbolic cosine
      System.out.println("Math.cosh(" + x + ")=" + Math.cosh(x));
      System.out.println("Math.cosh(" + y + ")=" + Math.cosh(y));
   }
}
Math.cosh(0.7853981633974483)=1.3246090892520057
Math.cosh(3.141592653589793)=11.591953275521519
HTML5 Canvas - Rotation

HTML5 canvas provides rotate(angle) method which is used to rotate the canvas around the current origin.
This method only takes one parameter and that's the angle the canvas is rotated by. This is a clockwise rotation measured in radians.
Following is a simple example which we are running two loops where first loop determines the number of rings, and the second determines the number of dots drawn in each ring.
<!DOCTYPE HTML>

<html>
   <head>
      
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <script type = "text/javascript">
         function drawShape() {
            
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
               
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               ctx.translate(100,100);
               
               for (i = 1; i<7; i++) {
                  ctx.save();
                  ctx.fillStyle = 'rgb('+(51*i)+','+(200-51*i)+',0)';
                  
                  for (j = 0; j < i*6; j++) {
                     ctx.rotate(Math.PI*2/(i*6));
                     ctx.beginPath();
                     ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
                     ctx.fill();
                  }
                  ctx.restore();
               }
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas" width = "400" height = "400"></canvas>
   </body>

</html>
The above example would produce the following result −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Arithmetic Aptitude - GeeksforGeeks

06 Nov, 2019
10152 = (1000+15)2
= 10002 + 152 +2 x 1000 x 15
=1000000 + 225 + 30000
=1030225
10152 = (1000+15)2

= 10002 + 152 +2 x 1000 x 15

=1000000 + 225 + 30000

=1030225
Largest 5 digit number is 99999.
Let us divide 99999 by 39

39) 99999 (2564
      78
      -----
      219
      195
      -----
        249
        234
        -----
           159
           156
           ----
              3

From above calculation, we know 39*2564 + 3 = 99999
Therefore 99999-3 = 99996 is the largest divisible number by 39.

103 x 103 + 97 x 97
= (100+3)2 + (100-3)2
= 2 (1002 + 32 )  
[ (X +Y)2 + ( X – Y)2 = 2 ( X2 + Y2 ) ]
= 2 (10000 + 9 )
= 2 x 10009
= 20018
9848 x 125 = 9848 x (250 / 2)
           = 4924 x (500 / 2)
           = 2462 x (1000 / 2)
           = 1231 x (1000)
           = 1231000

96381.....9+6+3+8+1= 27    (/)
46729.....4+6+7+2+9= 28    (x)
54459.....5+4+4+5+9= 27    (/)
85369.....8+5+3+6+9= 31    (x)
46818.....4+6+8+1+8= 27    (/)
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 Show Images on Click using HTML ?
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
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
Primitive and Non-primitive data-types in JavaScript
PostgreSQL - Date Data Type - GeeksforGeeks

28 Aug, 2020
PostgreSQL supports a DATE data type to store date values. It takes 4 bytes of storage and ranges from 4713 BC to 5874897 AD. PostgreSQL uses the yyyy-mm-dd format for storing and inserting date values. If you create a table that has a DATE column and you want to use the current date as the default value for the column, you can use the CURRENT_DATE after the DEFAULT keyword.
Syntax: variable_name DATE
Let’s look into some examples for better understanding.Example 1:In this example we will create a new employee table that consists of employee_id, first_name, last_name, birth_date, and hire_date columns, and the data types of the birth_date and hire_date columns are DATE.
CREATE TABLE employees (
    employee_id serial PRIMARY KEY,
    first_name VARCHAR (255),
    last_name VARCHAR (355),
    birth_date DATE NOT NULL,
    hire_date DATE NOT NULL
);
Now insert some data to the tables using the below command:
INSERT INTO employees (first_name, last_name, birth_date, hire_date)
VALUES ('Raju', 'Kumar', '1996-12-02', '2020-01-01'),
       ('Nikhil', 'Aggarwal', '1997-08-24', '2019-01-01'),
       ('Anshul', 'Aggarwal', '1994-05-11', '2017-01-01');
Now that the data has been inserted let’s verify them by using the below command:
SELECT * FROM employees;
Output:
Example 2:In the same table that we created in example 1, we will now query the age of the employees from the already present data using the command below:
SELECT
    employee_id,
    first_name,
    last_name,
    AGE(birth_date)
FROM
    employees;
Output:
Note: In the above example notice the use of AGE() function. To calculate age at the current date in years, months, and days, you use the AGE() function.
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function
PyQt5 QListWidget - Making Sorting Enabled - GeeksforGeeks

01 Aug, 2020
In this article we will see how we can set the sorting enabled property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether sorting is enabled, if this property is true, sorting is enabled for the list, if the property is false, sorting is not enabled. By default it is false.
In order to do this we will use setSortingEnabled method with the list widget object.
Syntax : list_widget.setSortingEnabled(True)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting sorting enabled        list_widget.setSortingEnabled(True)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 300, 80)          # making label multi line        label.setWordWrap(True)      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
screenshot_as_png element method - Selenium Python - GeeksforGeeks

30 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use screenshot_as_png method in Selenium. screenshot_as_png method is used to gets the screenshot of the current element as binary data.
element.screenshot_as_png
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
Now one can get screenshot of this element with binary data –
element.screenshot_as_png
Let’s try to get element and its screenshot at geeksforgeeks using screenshot_as_png method.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_id("gsc-i-id2")  # get rectprint(element.screenshot_as_png)
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Numerical Methods and Calculus - GeeksforGeeks

21 Jan, 2014
Which one of the following functions is continuous at x = 3?  
 
D 
C 
B 
A 
A function is continuous at some point c, Value of f(x) defined for x > c = Value of f(x) defined for x < c = Value of f(x) defined for x = c All values are 2 in option A 
Function f is known at the following points:  
 
9.017  
9.003  
8.983  
9.045 
Since the intervals are uniform, apply the uniform grid formula of trapezoidal rule. 
Consider the function f(x) = sin(x) in the interval [π/4, 7π/4]. The number and location(s) of the local minima of this function are 
Two, at π/2 and 3π/2
One, at 3π/2
One, at π/2
Two, at π/4 and 3π/2
The bisection method is applied to compute a zero of the function f(x) = x4 – x3 – x2 – 4 in the interval [1,9]. The method converges to a solution after ––––– iterations 
7 
5 
3 
1 
In bisection method, we calculate the values at extreme points of given interval, if signs of values are opposite, then we find the middle point. Whatever sign we get at middle point, we take the corner point of opposite sign and repeat the process till we get 0. f(1) < 0 and f(9) > 0 mid = (1 + 9)/2 = 5 f(5) > 0, so zero value lies in [1, 5] mid = (1+5)/2 = 3 f(3) > 0, so zero value lies in [1, 3] mid = (1+3)/2 = 2 f(2) = 0 
Given i=√-1, what will be the evaluation of the integral ? 
-i 
2 
0 
i 
Newton-Raphson method is used to compute a root of the equation x2-13=0 with 3.5 as the initial value. The approximation after one iteration is 
3.607 
3.667 
3.676 
3.575 
In Newton-Raphson's method, We use the following formula to get the next value of f(x). f'(x) is derivative of f(x).  
f(x)  =  x2-13
f'(x) =  2x

Applying the above formula, we get
Next x = 3.5 - (3.5*3.5 - 13)/2*3.5
Next x = 3.607
 
What is the value of Limn->∞(1-1/n)2n ? 
e-1/2 
1 
e-2 
0 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
How to Find Length of String in Bash Script?
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Amazon Interview Experience for SDE-1
How to use Material-UI with Next.js ?
How can a page be forced to load another page in JavaScript ?
How to Add 3 Fractions with Different Denominators?
Bash Script - Difference between Bash Script and Shell Script
Converting an image to a Torch Tensor in Python
Find out how much memory is being used by an object in Python

23 Aug, 2021
In this article, we are going to see how to find out how much memory is being used by an object in Python. For this, we will use sys.getsizeof() function can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.
Syntax: sys.getsizeof(object*)
Parameters: arg can be int, str, function, etc.
Returns: Size of the given object.
This function is versatile and can work with any data type and even a function. For this first sys module has to be imported and then the object in consideration is passed to the function. Given below are various implementations for different objects.
Example 1: Get the size of an integer. 
Python3
import sys  var = 1  print(sys.getsizeof(var))
Output:
28
Example 2: Get the size of an decimal.
Python3
import sys  var = 1.2  print(sys.getsizeof(var))
Output:
24
Example 3: Get the size of an String.
Python3
import sys  # string initvar1 = ""var2 = "gfg"var3 = "Welcome to gfg"  # get size of an objectprint(sys.getsizeof(var1))print(sys.getsizeof(var2))print(sys.getsizeof(var3))
Output:
64
72
96
Example 4: Get the size of an List. 
Python3
# import moduleimport sys  # list initvar1 = []var2 = [1]var3 = [1, 2, 3, 4]  # check size of objprint(sys.getsizeof(var1))print(sys.getsizeof(var2))print(sys.getsizeof(var3))
Output:
64
72
96
Example 5: Get the size of an Set. 
Python3
import sys  # set initvar1 = set([])var2 = set([1, 2, 3, 4, 5])  # get size of objectprint(sys.getsizeof(var1))print(sys.getsizeof(var2))
Output:
224
736
Example 6: Get the size of an Dictionary. 
Python3
import sys  # dicvar1 = {'Apple':1}var2 = {'Apple':1, 'ball': 2, 'cat':3,         'dog': 4, 'egg': 5, 'frog': 6}  # get the size of objectprint(sys.getsizeof(var1))print(sys.getsizeof(var2))
Output:
240
368
Example 7: Get the size of an Function. 
Python3
import sys  def func():    passvar = funcprint(sys.getsizeof(var))
Output:
136
Picked
Python-sys
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python | Maximum and minimum element’s position in a list

31 May, 2020
Given a list of N integers, find the maximum and minimum element’s position in the list.
Examples:
Input :  3, 4, 1, 3, 4, 5
Output :  The maximum is at position 6
          The minimum is at position 3

The naive approach will be to traverse in the list and keep track of the minimum and maximum along with their indices. We have to do N comparisons for minimum and at the same time N comparisons for maximum.Below is the implementation of the naive approach.
#Naive approach#to find index of maximum and#minimum element in the array.gfg_list=[8,1,7,10,5]#min and max indexes are taken 1st element #In some cases list might be a single elementmin_ele,max_ele=gfg_list[0],gfg_list[0] for i in range(1,len(gfg_list)):    if gfg_list[i]<min_ele:        min_ele=gfg_list[i]    if gfg_list[i]>max_ele:        max_ele=gfg_list[i]print('Minimum Element in the list',gfg_list,'is',min_ele)print('Maximum Element in the list',gfg_list,'is',max_ele)
Minimum Element in the list [8, 1, 7, 10, 5] is 1
Maximum Element in the list [8, 1, 7, 10, 5] is 10

Python inbuilt function allows us to find it in one line, we can find the minimum in the list using the min() function and then us index() function to find out the index of that minimum element. Similarly we can do the same for finding out the maximum element using max() function and then find out the index of the maximum element using index() inbuilt function in python.Note : index() returns index of first occurrence in case there are multiple occurrences of an element. So if maximum (or minimum) occurs more than once, the first occurrence is returned.
Below is the implementation of the above approach:
# function to find minimum and maximum position in listdef minimum(a, n):      # inbuilt function to find the position of minimum     minpos = a.index(min(a))          # inbuilt function to find the position of maximum     maxpos = a.index(max(a))           # printing the position     print "The maximum is at position", maxpos + 1      print "The minimum is at position", minpos + 1            # driver codea = [3, 4, 1, 3, 4, 5] minimum(a, len(a))
The maximum is at position 6
The minimum is at position 3

Akanksha_Rai
avsadityavardhan
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add unique constraint in collection of MongoDB using Node.js?

08 Feb, 2021
Mongoose module is one of the most powerful external modules of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database.
Unique constraint: We can add a unique constraint on the value of the document collection in MongoDB so that all the documents can be distinguished easily. A unique constraint is added during the creation of the structure of the collection in Node.js
Installing Module:
npm install mongoose
Project Structure:
Running the server on Local IP: Data is the directory where the MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
Filename- index.js:
Javascript
// Importing mongoose moduleconst mongoose = require("mongoose");  // Database Addressconst url = "mongodb://localhost:27017/GFG";  // Connecting to databasemongoose  .connect(url)  .then((ans) => {    console.log("ConnectedSuccessful");  })  .catch((err) => {    console.log("Error in the Connection");  });    // Calling Schema classconst Schema = mongoose.Schema;  // Creating Structure of the collectionconst collection_structure = new Schema({  name: {    type: String,    require: true,  },  marks: {    type: Number,    default: 0,  },});  // Creating collectionconst collections =     mongoose.model("GFG2", collection_structure);  // Inserting one documentcollections  .create({    name: "aayush",  })  .then((ans) => {    console.log("Document inserted");          // Inserting invalid document    collections      .create({        name: "saini",        marks: "#234",        phone: 981,      })      .then((ans) => {        console.log(ans);      })      .catch((err) => {                // Printing the documents        collections.find().then((ans) => {          console.log(ans);        });                  // Printing the Error Message        console.log(err.message);      });  })  .catch((err) => {        // Printing Error Message    console.log(err.message);  });
Run index.js file using below command:
node index.js
Output: Record already present in the collection(Console).
NodeJS-Questions
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to put a border around a Frame in Python Tkinter?

To put a border around a Frame in Tkinter, we have to use the highlightbackground and highlightthickeness parameters while creating the Frame. Let's take an example and see how to use these two parameters.
Import the tkinter library and create an instance of tkinter frame.
Import the tkinter library and create an instance of tkinter frame.
Set the size of the frame using geometry method.
Set the size of the frame using geometry method.
Create a frame with Frame() method. Highlight the border of the frame with a color, highlightbackground="blue". Then, set the thickness of the border, highlightthickness=2.
Create a frame with Frame() method. Highlight the border of the frame with a color, highlightbackground="blue". Then, set the thickness of the border, highlightthickness=2.
Next, create some widgets inside the frame. In the example, we have placed four checkbuttons and a button inside the frame.
Next, create some widgets inside the frame. In the example, we have placed four checkbuttons and a button inside the frame.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
from tkinter import *

top = Tk()
top.geometry("700x350")

frame1 = Frame(top, highlightbackground="blue", highlightthickness=2)
frame1.pack(padx=20, pady=20)

C1 = Checkbutton(frame1, text = "Music", width=200, anchor="w")
C1.pack(padx=10, pady=10)

C2 = Checkbutton(frame1, text = "Video", width=200, anchor="w")
C2.pack(padx=10, pady=10)

C3 = Checkbutton(frame1, text = "Songs", width=200, anchor="w")
C3.pack(padx=10, pady=10)

C4 = Checkbutton(frame1, text = "Games", width=200, anchor="w")
C4.pack(padx=10, pady=10)

Button(frame1, text="Button-1", font=("Calibri",12,"bold")).pack(padx=10, pady=10)

top.mainloop()
It will produce the following output −
There's an easier method to create a simple border around a frame. Instead of having a Frame, create a LabelFrame and it will automatically set a border around the frame widgets.
GATE | GATE-CS-2004 | Question 83

28 Jun, 2021
The time complexity of the following C function is (assume n > 0)
int recursive (int n) {   if (n == 1)      return (1);   else      return (recursive (n - 1) + recursive (n - 1));}
(A) O(n)(B) O(n log n)(C) O(n2)(D) O(2n)Answer: (D)Explanation:
See Question 4 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-4/
This solution is contributed by Anil Saikrishna Devarasetty
Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert list into list of lists in Python

During data analysis we face scenarios to convert every element of a list into a sublist. So in this article we will need to take a normal list as an input and convert into a list of lists where each element becomes a sublist.
This is a very straight forward approach in which we create for loop to read each element. We read it as a list and store the result in the new list.
 Live Demo
Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

# Each element as list
NewList= [[x] for x in Alist]

# Print
print("The new lists of lists: ",NewList)
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
In this approach we use the split function to extract each of the elements as they are separated by comma. We then keep appending this element as a list into the new created list.
 Live Demo
Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

NewList= []

# Using split
for x in Alist:
   x = x.split(',')
   NewList.append(x)

# Print
print("The new lists of lists: ",NewList)
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
The map function is used to apply the same function again and again to a sequence of parameters. So we use a lambda function to create a series of list elements by reading each element from the original list and apply map function to it.
 Live Demo
Alist = ['Mon','Tue','Wed','Thu','Fri']

#Given list
print("Given list: ",Alist)

# Using map
NewList= list(map(lambda x:[x], Alist))

# Print
print("The new lists of lists: ",NewList)
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
How to generate lat and long coordinates from an address column using Pandas and Googlemaps API | by Tobi Sam | Towards Data Science

If you would like to plot map graphs using geographical coordinates from your address data, Google provides an API called Geocoding that lets you convert addresses to geographical coordinates and vice versa.
Geocoding is the process of converting addresses (like “1600 Amphitheatre Parkway, Mountain View, CA”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map. Read more here if you would like to dig deeper.
Google offers $200 free credit per month for this API (based on the type of account you have), so please make sure you understand the cost that may be incurred while running this API for yourself.
Pricing Details 1
Pricing Details 2
I used Jupyter notebook to run the script in this tutorial.
First, you will want to import the GoogleMaps and Pandas packages. If you haven’t already, make sure these packages have been installed into your environment with pip.
from googlemaps import Client as GoogleMapsimport pandas as pd 
Now, you will need to create an API key from the Credentials Section in your Google Cloud Platform account. It’s pretty straight forward.
Type API & Services in your console search bar.
Click on ENABLE APIS AND SERVICES
Search for Geocoding API and make sure it is enabled
Now click on Credentials > Create Credentials and create a new API key
You will use this API key when creating a new GoogleMaps object in Python.
Now back in Jupyter notebook, create a GoogleMaps object using the API key you just generated.
gmaps = GoogleMaps('YOUR_API_KEY')
Next step is to import the csv file that includes a column with full addresses that you would like to convert.
addresses = pd.read_csv("YOUR_CSV_FILE.csv")addresses.head()
Add two empty columns that will hold the longitude and latitude data.
addresses['long'] = ""addresses['lat'] = ""
Running googleMaps.geocode command returns a JSON object which looks like this. There are many more attributes you can make use of if required. However, like stated earlier, we will focus only on the longitude and latitude geographical coordinates which has a key of “geometry” and “location” in the JSON response.- geometry>location>lat- geometry>location>lng
It is now time to loop through your dataframe and insert the ‘lng’ and ‘lat’ for each address record.
for x in range(len(addresses)):    try:        time.sleep(1) #to add delay in case of large DFs        geocode_result = gmaps.geocode(addresses['FullAddress'][x])        addresses['lat'][x] = geocode_result[0]['geometry']['location'] ['lat']        addresses['long'][x] = geocode_result[0]['geometry']['location']['lng']    except IndexError:        print("Address was wrong...")    except Exception as e:        print("Unexpected error occurred.", e )addresses.head()
With the generated coordinates, you can plot map views like this one.
Finally, export your results to csv if required.
addresses.to_csv('address_coords.csv')
That’s it! Hope this was helpful. Let me know if you have any questions or suggestions.
How to convert an int to string in C++?

You can use the itoa function from C to convert an int to string. 
#include<iostream>
int main() {
   int a = 10;
   char *intStr = itoa(a);
   string str = string(intStr);
   cout << str;
}
This will give the output −
10
This will convert the integer to a string. In C++11, a new method, to_string was added that can be used for the same purpose. You can use it as follows −
#include<iostream>
using namespace std;
int main() {
   int a = 10;
   string str = to_string(a);
   cout << str;
}
This will give the output −
10
Python Pandas - Get the seconds from Timedelta object using integer input

To return the seconds from Timedelta object, use the timedelta.seconds property. At first, import the required libraries −
import pandas as pd
TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Set integer input for seconds using unit 's'. Create a Timedelta object
timedelta = pd.Timedelta(50, unit ='s')

Display the Timedelta
print("Timedelta...\n", timedelta)
Return the seconds value
timedelta.seconds

Following is the code
import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# set integer input for seconds using unit 's'
# create a Timedelta object
timedelta = pd.Timedelta(50, unit ='s')

# display the Timedelta
print("Timedelta...\n", timedelta)

# return the seconds value
res = timedelta.seconds

# display the seconds
print("\nTimedelta (seconds value)...\n", res)
This will produce the following code
Timedelta...
0 days 00:00:50

Timedelta (seconds value)...
50