code-rag-bench/online-tutorials huggingface dataset:
clear() element method - Selenium Python - GeeksforGeeks

27 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 clear method in Selenium. clear method is used to clear text of any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser.
element.clear()
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")
To enter text into a field, for example,
element.send_keys("some text")
Now one can clear this field with
element.clear()
Also note, it is possible to call clear on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method:
Let’s try to enter text in search field on geeksforgeeks and then clear its contents.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")  # send keys element.send_keys("Arrays")  # clear contentselement.clear()
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
LinkedList AddFirst method in C#

In a Linked List, if you want to add a node at the first position, use AddFirst method.
Let’s first set a LinkedList.
string [] students = {"Jenifer","Angelina","Vera"};
LinkedList<string> list = new LinkedList<string>(students);
Now, to add an element as a first node, use AddFirst() method.
List.AddFirst(“Natalie”);
 Live Demo
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Jenifer","Angelina","Vera"};
      LinkedList<string> list = new LinkedList<string>(students);
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
      // add a node
      Console.WriteLine("Node added at the first position...");
      list.AddFirst("Natalie");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}
Jenifer
Angelina
Vera
Node added at the first position...
Natalie
Jenifer
Angelina
Vera
Perl | Array pop() Function - GeeksforGeeks

07 May, 2019
pop() function in Perl returns the last element of Array passed to it as an argument, removing that value from the array. Note that the value passed to it must explicitly be an array, not a list.
Syntax:pop(Array)
Returns:undef if list is empty else last element from the array.
Example 1:
#!/usr/bin/perl -w  # Defining an array of integers@array = (10, 20, 30, 40);  # Calling the pop function$popped_element = pop(@array);  # Printing the Popped elementprint "Popped element is $popped_element";  # Printing the resultant arrayprint "\nResultant array after pop(): \n@array";
Popped element is 40
Resultant array after pop(): 
10 20 30

Example 2:
#!/usr/bin/perl -w  # Defining an array of strings@array = ("Geeks", "For", "Geeks", "Best");  # Calling the pop function$popped_element = pop(@array);  # Printing the Popped elementprint "Popped element is $popped_element";  # Printing the resultant arrayprint "\nResultant array after pop(): \n@array";
Popped element is Best
Resultant array after pop(): 
Geeks For Geeks

Perl-Array-Functions
Perl-Arrays
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl Tutorial - Learn Perl With Examples
Perl | Operators | Set - 1
Perl | Multidimensional Hashes
Perl | Reading Excel Files
Perl | File Handling Introduction
Perl | index() Function
Perl | Data Types
Perl | shift() Function
Perl | Appending to a File
java.util.zip - GZIPOutputStream Class

The java.util.zip.GZIPOutputStream class implements a stream filter for writing compressed data in the GZIP file format.
Following is the declaration for java.util.zip.GZIPOutputStream class −
public class GZIPOutputStream
   extends DeflaterOutputStream

Following are the fields for java.util.zip.GZIPOutputStream class −
protected CRC32 crc − CRC-32 for uncompressed data.
protected CRC32 crc − CRC-32 for uncompressed data.
GZIPOutputStream(OutputStream out)
Creates a new output stream with a default buffer size.
GZIPOutputStream(OutputStream out, boolean syncFlush)
Creates a new output stream with a default buffer size and the specified flush mode.
GZIPOutputStream(OutputStream out, int size)
Creates a new output stream with the specified buffer size.
GZIPOutputStream(OutputStream out, int size, boolean syncFlush)
Creates a new output stream with the specified buffer size and flush mode.
Finishes writing compressed data to the output stream without closing the underlying stream.
Writes array of bytes to the compressed output stream.
This class inherits methods from the following classes −
java.util.zip.DeflaterOutputStream
java.io.FilterOutputStream
java.lang.Object
 Print
 Add Notes
 Bookmark this page
Finding median for every window in JavaScript

Median in mathematics, median is the middle value in an ordered(sorted) integer list.
If the size of the list is even, and there is no middle value. Median is the mean (average) of the two middle values.
We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and a number num (num <= length of array arr) as the second argument.
Now for each window of size num in the array arr, our function should calculate the median and push that median value into a new array and finally at the end of iteration return that median array.
For example, if the input to the function is −
const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];
const num = 3;
Then the output should be −
const output = [5, 5, 5, 3, 3, 8, 8, 4, 4, 6];
The code for this will be −
 Live Demo
const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];
const num = 3;
const binarySearch = (arr, target, l, r) => {
   while (l < r) {
      const mid = Math.floor((l + r) / 2);
      if (arr[mid] < target) l = mid + 1;
      else if (arr[mid] > target) r = mid;
      else return mid;
   };
   if (l === r) return arr[l] >= target ? l : l + 1;
}
const medianSlidingWindow = (arr = [], num = 1) => {
   let l = 0, r = num - 1, res = [];
   const window = arr.slice(l, num);
   window.sort((a, b) => a - b);
   while (r < arr.length) {
      const median = num % 2 === 0 ? (window[Math.floor(num / 2) - 1] + window[Math.floor(num / 2)]) / 2 : window[Math.floor(num / 2)];
      res.push(median);
      let char = arr[l++];
      let index = binarySearch(window, char, 0, window.length - 1);
      window.splice(index, 1);
      char = arr[++r];
      index = binarySearch(window, char, 0, window.length - 1);
      window.splice(index, 0, char);
   }
   return res;
};
console.log(medianSlidingWindow(arr, num));
Idea behind this solution is to use binary search to insert right number and remove left number when moving the sliding window to the right.
And the output in the console will be −
[5, 5, 5, 3, 3, 8, 8, 4, 4, 6 ]
Reentrant Function - GeeksforGeeks

26 Apr, 2018
A function is said to be reentrant if there is a provision to interrupt the function in the course of execution, service the interrupt service routine and then resume the earlier going on function, without hampering its earlier course of action. Reentrant functions are used in applications like hardware interrupt handling, recursion, etc. The function has to satisfy certain conditions to be called as reentrant:1. It may not use global and static data. Though there are no restrictions, but it is generally not advised. because the interrupt may change certain global values and resuming the course of action of the reentrant function with the new data may give undesired results. 2. It should not modify it’s own code. This is important because the course of action of the function should remain the same throughout the code. But, this may be allowed in case the interrupt routine uses a local copy of the reentrant function every time it uses different values or before and after the interrupt. 3. Should not call another non-reentrant function.
Thread safety and Reentrant functionsReentrancy is distinct from, but closely related to, thread-safety. A function can be thread-safe and still not reentrant. For example, a function could be wrapped all around with a mutex (which avoids problems in multithreading environments), but if that function is used in an interrupt service routine, it could starve waiting for the first execution to release the mutex. The key for avoiding confusion is that reentrant refers to only one thread executing. It is a concept from the time when no multitasking operating systems existed. (Source : https://en.wikipedia.org/wiki/Reentrancy_(computing))
 Example of Non-Reentrant Functions:
// A non-reentrant example // [The function depends on global variable i]  int i;  // Both fun1() and fun2() are not reentrant  // fun1() is NOT reentrant because it uses global variable iint fun1(){    return i * 5;}  // fun2() is NOT reentrant because it calls a non-reentrant// functionint fun2(){   return fun1() * 5;}
Example of Reentrant Functions:In the below code, fun2 is a reentrant function. If an interrupt that pauses its execution and shifts the control to fun1. After fun1 completes, the control is again transferred to fun2 and it reenters the execution phase.
// Both fun1() and fun2() are reentrantint fun1(int i){    return i * 5;}  int fun2(int i){   return fun1(i) * 5;}
 
Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
VictorDev
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Min Heap and Max Heap
SQL | Date functions
Difference between Class and Object
Implementation of LinkedList in Javascript
Deploy Python Flask App on Heroku
How compare() method works in Java
SQL | CREATE
C program to find the solution of linear equation

We can apply the software development method to solve the linear equation of one variable in C programming language.
The equation should be in the form of ax+b=0
a and b are inputs, we need to find the value of x
Here,
An input is the a,b values.
An output is the x value.
Refer an algorithm given below to find solution of linear equation.
Step 1. Start
Step 2. Read a,b values
Step 3. Call function
Jump to step 5
Step 4. Print result
Step 5:
i. if(a == 0)Print value of c cannot be predictedElseCompute c=-b/aReturn cStep 6: Stop
i. if(a == 0)Print value of c cannot be predicted
Print value of c cannot be predicted
ElseCompute c=-b/a
Compute c=-b/a
Return c
Following is the C program to find the solution of linear equation −
 Live Demo
#include <stdio.h>
#include <string.h>
float solve(float a, float b){
   float c;
   if(a == 0){
      printf("value of c cannot be predicted\n");
   }else{
      c = -b / a;
   }
   return c;
}
int main(){
   float a, b, c;
   printf("\n enter a,b values: ");
   scanf("%f%f", &a, &b);
   c = solve(a, b);
   printf("\n linear eq of one variable in the form of ax+b = 0, if a=%f,b=%f,then x=    %f",a,b,c);
   return 0;
}
When the above program is executed, it produces the following result −
enter a,b values: 4 8
linear eq of one variable in the form of ax+b = 0, if a=4.000000, b=8.000000,
then x= -2.000000
Difference between user defined function and library function in C/C++ - GeeksforGeeks

21 Jun, 2020
Library function:These function are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updatation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use this functions in the program the user have to use associate header file associated to the corresponding function in the program.
For Example:If, the user have to use print the data or scan the data using input stream then we have to use functions printf() and scanf() in C program and cin and cout in C++ program. To use these functions the user have to include #include<stdio.h> preprocesser directive in C program and #include<iostream> preprocesser directive in C++ program.
C
C++
// C program to illustrate inbuilt function#include <stdio.h>  // Driver Codeint main(){      // Print Statement    printf("GeeksforGeeks!");      return 0;}
// C++ program to illustrate inbuilt function#include <iostream>using namespace std;  // Driver Codeint main(){      // Print Statement    cout << "GeeksforGeeks!";      return 0;}
GeeksforGeeks!

User-defined function:These functions are designed by the user when they are writing any program because for every task we do not have a library of functions where their definitions are predefined. To perform the according to the requirement of user the user have to develop some functions by itself, these functions are called user-defined functions. For such functions the user have to define the proper definition of the function.
For Example: If we want to perform the addition of two numbers then below is the program to illustrate the addition of two numbers using user-defined functions:
C
C++
// C program to illustrate user-defined function#include <stdio.h>  // Function Call to find the sum of a and bvoid findSum(int a, int b){      // Print the sum    printf("Sum is: %d", a + b);}  // Driver Codeint main(){    // Given two numbers    int a = 3, b = 5;      // Function Call    findSum(a, b);    return 0;}
// C++ program to illustrate inbuilt function#include <iostream>using namespace std;  // Function Call to find the sum of a and bvoid findSum(int a, int b){      // Print the sum    cout << "Sum is: " << a + b;}  // Driver Codeint main(){    // Given two numbers    int a = 3, b = 5;      // Function Call    findSum(a, b);    return 0;}
Sum is: 8

Tabular Representation to illustrate the difference between library and user-define function:
CPP-Basics
CPP-Functions
C++ Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Handling the Divide by Zero Exception in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Stack vs Heap Memory Allocation
Difference between Process and Thread
Customize the JOptionPane layout with updated color and image in Java

Customize the layout by changing the look and feel of the panel in which you added the component −
ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
JLabel label = new JLabel(icon);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setOpaque(true);
panel.setBackground(Color.ORANGE);
Above, we have added an image and even updated the background color of the panel.
Now, set it for the text panel −
JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.Magenta);
The following is an example to customize the JOptionPane layout −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
      JLabel label = new JLabel(icon);
      JPanel panel = new JPanel(new GridBagLayout());
      panel.add(label);
      panel.setOpaque(true); panel.setBackground(Color.ORANGE);
      JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.MAGENTA);
      for (int i = 0; i < 20; i++) {
         textPanel.add(new JLabel("Learn C++"));
      }
      JPanel panel2 = new JPanel(new BorderLayout());
      panel2.add(textPanel);
      panel2.add(panel, BorderLayout.EAST);
      JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION);
   }
}
HTML - Marquees

An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically down your webpage depending on the settings. This is created by using HTML <marquees> tag.
Note − The <marquee> tag deprecated in HTML5. Do not use this element, instead you can use JavaScript and CSS to create such effects.
A simple syntax to use HTML <marquee> tag is as follows −
<marquee attribute_name = "attribute_value"....more attributes>
   One or more lines or text message or image
</marquee>

Following is the list of important attributes which can be used with <marquee> tag.
width
This specifies the width of the marquee. This can be a value like 10 or 20% etc.
height
This specifies the height of the marquee. This can be a value like 10 or 20% etc.
direction
This specifies the direction in which marquee should scroll. This can be a value like up, down, left or right.
behavior
This specifies the type of scrolling of the marquee. This can have a value like scroll, slide and alternate.
scrolldelay
This specifies how long to delay between each jump. This will have a value like 10 etc.
scrollamount
This specifies the speed of marquee text. This can have a value like 10 etc.
loop
This specifies how many times to loop. The default value is INFINITE, which means that the marquee loops endlessly.
bgcolor
This specifies background color in terms of color name or color hex value.
hspace
This specifies horizontal space around the marquee. This can be a value like 10 or 20% etc.
vspace
This specifies vertical space around the marquee. This can be a value like 10 or 20% etc.
Below are few examples to demonstrate the usage of marquee tag.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML marquee Tag</title>
   </head>
	
   <body>
      <marquee>This is basic example of marquee</marquee>
   </body>
	
</html>
This will produce the following result −
<!DOCTYPE html>
<html>

   <head>
      <title>HTML marquee Tag</title>
   </head>
	
   <body>
      <marquee width = "50%">This example will take only 50% width</marquee>
   </body>
	
</html>
This will produce the following result −
<!DOCTYPE html>
<html>

   <head>
      <title>HTML marquee Tag</title>
   </head>

   <body>
      <marquee direction = "right">This text will scroll from left to right</marquee>
   </body>
	
</html>
This will produce the following result −
<!DOCTYPE html>
<html>

   <head>
      <title>HTML marquee Tag</title>
   </head>
	
   <body>
      <marquee direction = "up">This text will scroll from bottom to up</marquee>
   </body>
	
</html>
This will 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
Explain the Post Correspondence Problem in TOC

The Post Correspondence Problem (PCP) was introduced by Emil Post in 1946 and is an undecidable decision problem.
The PCP problem over an alphabet Σ is state. Given the following two lists, M and N of non-empty strings over Σ−
M = (x1, x2, x3,........., xn)
N = (y1, y2, y3,........., yn)
We can say that there is a Post Correspondence Solution, if for some i1,i2,............ ik,
Where 1≤ ij ≤ n, the condition xi1 .......xik = yi1 .......yik satisfies.
Find whether the lists M = (abb, aa, aaa) and N = (bba, aaa, aa) have a Post Correspondence Solution.
Here,
x2x1x3 = ‘aaabbaaa’
and y2y1y3 = ‘aaabbaaa’
We can see that
x2x1x3 = y2y1y3
Hence, the solution is i = 2, j = 1, and k = 3.
Let us consider ,in PCP problem we have N number of Dominos (tiles). The aim is to arrange tiles in such order that string made by Numerators is same as string made by Denominators.
In simple words, lets assume we have two lists both containing N words, aim is to find out concatenation of these words in some sequence such that both lists yield same result.
Let’s try understanding this by taking two lists A and B
A=[aa, bb, abb] and B=[aab, ba, b]
Now for sequence 1, 2, 1, 3 first list will yield aabbaaabb and second list will yield same string aabbaaabb.
So the solution to this PCP becomes 1, 2, 1, 3.
Domino’s Form.
Domino’s Form.
Table form
Table form
Python – Extract Percentages from String

02 Sep, 2020
Given a String, extract all the numbers that are percentages.
Input : test_str = ‘geeksforgeeks 20% is 100% way to get 200% success’Output : [‘20%’, ‘100%’, ‘200%’]Explanation : 20%, 100% and 200% are percentages present.
Input : test_str = ‘geeksforgeeks is way to get success’Output : []Explanation : No percentages present.
Method #1 : Using findall() + regex
In this, we employ appropriate regex having “%” symbol in suffix and use findall() to get all occurrences of such numbers from String.
Python3
# Python3 code to demonstrate working of # Extract Percentages from String # Using regex + findall()import re  # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success'  # printing original stringprint("The original string is : " + str(test_str))  # getting required result from string res = re.findall('\d*%', test_str)  # printing result print("The percentages : " + str(res)) 
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']

Method #2 : Using re.sub() + split()
In this, we perform split of all words, and then from words that have %,  we remove all non-numeric strings. This can be buggy in cases, we have different ordering of % and numbers in string.
Python3
# Python3 code to demonstrate working of # Extract Percentages from String # Using re.sub() + split()import re  # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success'  # printing original stringprint("The original string is : " + str(test_str))  # extracting wordstemp = test_str.split()  # using res = []for sub in temp:    if '%' in sub:                  # replace empty string to all non-number chars        res.append(re.sub(r'[^\d, %]', '', sub))    # printing result print("The percentages : " + str(res)) 
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']

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
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
GATE-CS-2016 (Set 2) - GeeksforGeeks

11 Oct, 2021
put up with - is a phrasal verb
Meaning : to accept somebody/something that is annoying, unpleasant without complaining

mock, deride, praise, jeer 
--> Author has not said anything against internet and mobile computing 
but is talking about the surprising usage of these.

"Many believe that the internet itself is an unintended consequence of 
the original invention."
--> The author says that many believe that 'internet itself' is unplanned 
but actually both internet and mobile computers are unplanned(unintended) 
inventions.



(i) Ooty is not a hill-station.
(ii) No hill-station can have more than one lake. 
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
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Optimization of Basic Blocks
TCS NQT Coding Sheet
A Freshers Guide To Programming
Array Partition I in Python

Suppose we have an array of 2n number of integers, we have to group these integers into n pairs of integer, like (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i in range 1 to n as large as possible. So if the input is [1, 4, 3, 2], then output will be 4. So n is 2. And the maximum sum of pairs is 4. This is min(1, 2) + min(3, 4) = 4
To solve this, we will follow these steps −
let n is the size of the array
sort the array
answer := 0
for i in range 0 to n, jump by 2answer := answer + array[i]
answer := answer + array[i]
return answer
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def arrayPairSum(self, a):
      """
      :type nums: List[int]
      :rtype: int
      """
      n = len(a)
      a.sort()
      ans = 0
      for i in range(0,n,2):
         ans += a[i]
      return ans
ob1 = Solution()
print(ob1.arrayPairSum([1,4,3,2]))
[1,4,3,2]
4
How to convert a matrix into a data frame with column names and row names as variables in R?

To convert a matrix into a data frame with column names and row names as variables, we first need to convert the matrix into a table and then read it as data frame using as.data.frame. For example, if we have a matrix M then it can be done by using the below command −
as.data.frame(as.table(M))
Live Demo
> M1<-matrix(1:36,nrow=6)
> M1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 7 13 19 25 31
[2,] 2 8 14 20 26 32
[3,] 3 9 15 21 27 33
[4,] 4 10 16 22 28 34
[5,] 5 11 17 23 29 35
[6,] 6 12 18 24 30 36
> rownames(M1)<-1:6
> colnames(M1)<-LETTERS[1:6]
> M1
A B C D E F
1 1 7 13 19 25 31
2 2 8 14 20 26 32
3 3 9 15 21 27 33
4 4 10 16 22 28 34
5 5 11 17 23 29 35
6 6 12 18 24 30 36
> as.data.frame(as.table(M1))
Var1 Var2 Freq
1 1 A 1
2 2 A 2
3 3 A 3
4 4 A 4
5 5 A 5
6 6 A 6
7 1 B 7
8 2 B 8
9 3 B 9
10 4 B 10
11 5 B 11
12 6 B 12
13 1 C 13
14 2 C 14
15 3 C 15
16 4 C 16
17 5 C 17
18 6 C 18
19 1 D 19
20 2 D 20
21 3 D 21
22 4 D 22
23 5 D 23
24 6 D 24
25 1 E 25
26 2 E 26
27 3 E 27
28 4 E 28
29 5 E 29
30 6 E 30
31 1 F 31
32 2 F 32
33 3 F 33
34 4 F 34
35 5 F 35
36 6 F 36
Live Demo
> M2<-matrix(rnorm(25),nrow=5)
> M2
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
[2,] 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
[3,] 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
[4,] 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
[5,] -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645
> rownames(M2)<-c("R1","R2","R3","R4","R5")
> colnames(M2)<-c("C1","C2","C3","C4","C5")
> M2
C1 C2 C3 C4 C5
R1 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
R2 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
R3 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
R4 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
R5 -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645
> as.data.frame(as.table(M2))
Var1 Var2 Freq
1 R1 C1 0.18116436
2 R2 C1 0.32326518
3 R3 C1 0.44080495
4 R4 C1 2.99376289
5 R5 C1 -0.94482784
6 R1 C2 0.11869776
7 R2 C2 1.45457299
8 R3 C2 -0.14029090
9 R4 C2 -0.18043699
10 R5 C2 -0.26155322
11 R1 C3 -0.48697926
12 R2 C3 -1.81291997
13 R3 C3 -0.08482793
14 R4 C3 -0.05752013
15 R5 C3 -0.05046240
16 R1 C4 -1.12666228
17 R2 C4 1.88503065
18 R3 C4 0.50073769
19 R4 C4 -2.70116904
20 R5 C4 -0.99943242
21 R1 C5 0.34164554
22 R2 C5 -1.76415604
23 R3 C5 0.27540019
24 R4 C5 -0.16288833
25 R5 C5 1.45886447
Method overriding in Java

Overriding is the ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.
In object-oriented terms, overriding means to override the functionality of an existing method.
Let us look at an example.
Live Demo
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog();  // Animal reference but Dog object
      a.move();  // runs the method in Animal class
      b.move(); // runs the method in Dog class
   }
}
This will produce the following result −
Animals can move
Dogs can walk and run
In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: At compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
C library macro - offsetof()

The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
Following is the declaration for offsetof() Macro.
offsetof(type, member-designator)
type − This is the class type in which member-designator is a valid member designator.
type − This is the class type in which member-designator is a valid member designator.
member-designator − This is the member designator of class type.
member-designator − This is the member designator of class type.
This macro returns the value of type size_t which is the offset value of member in type.
The following example shows the usage of offsetof() Macro.
#include <stddef.h>
#include <stdio.h>

struct address {
   char name[50];
   char street[50];
   int phone;
};
   
int main () {
   printf("name offset = %d byte in address structure.\n",
   offsetof(struct address, name));

   printf("street offset = %d byte in address structure.\n",
   offsetof(struct address, street));

   printf("phone offset = %d byte in address structure.\n",
   offsetof(struct address, phone));

   return(0);
} 
Let us compile and run the above program, this will produce the following result −
name offset = 0 byte in address structure.
street offset = 50 byte in address structure.
phone offset = 100 byte in address structure.


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to retrieve the content of the file in PowerShell?

To retrieve the content of the file in PowerShell, you need to use Get-Content cmdlet. For example, we are going to retrieve the content of the text file called Aliases.txt from a specific location.
Get-Content D:\Temp\aliases.txt
PS C:\WINDOWS\system32> Get-Content D:\Temp\aliases.txt
# Alias File
# Exported by : admin
# Date/Time : 26 January 2020 19:20:24
# Computer : DESKTOP-9435KM9
"foreach","ForEach-Object","","ReadOnly, AllScope"
"%","ForEach-Object","","ReadOnly, AllScope"
"where","Where-Object","","ReadOnly, AllScope"
"?","Where-Object","","ReadOnly, AllScope"
"ac","Add-Content","","ReadOnly, AllScope"
"clc","Clear-Content","","ReadOnly, AllScope"
"cli","Clear-Item","","ReadOnly, AllScope"
"clp","Clear-ItemProperty","","ReadOnly, AllScope"
"clv","Clear-Variable","","ReadOnly, AllScope"
"compare","Compare-Object","","ReadOnly, AllScope"
"cpi","Copy-Item","","ReadOnly, AllScope"
"cpp","Copy-ItemProperty","","ReadOnly, AllScope"
"cvpa","Convert-Path","","ReadOnly, AllScope"
"dbp","Disable-PSBreakpoint","","ReadOnly, AllScope"
"diff","Compare-Object","","ReadOnly, AllScope"
"ebp","Enable-PSBreakpoint","","ReadOnly, AllScope"
"epal","Export-Alias","","ReadOnly, AllScope"
"epcsv","Export-Csv","","ReadOnly, AllScope"
"fc","Format-Custom","","ReadOnly, AllScope"
"fl","Format-List","","ReadOnly, AllScope"
"ft","Format-Table","","ReadOnly, AllScope"
"fw","Format-Wide","","ReadOnly, AllScope"
"gal","Get-Alias","","ReadOnly, AllScope"
"gbp","Get-PSBreakpoint","","ReadOnly, AllScope"
"gc","Get-Content","","ReadOnly, AllScope"
You can also retrieve the content of the file from the remote location.
For example,
Get-Content \\Test-PC\Shared\Powershellaliases.txt
How to encode a string in JavaScript?

Javascript has provided escape() function to encode a string. But since the escape()
function is now deprecated, it is better to use encodeURI() or encodeURIComponent(). 
escape(string);
encodeURIComponent(str);
In the following example, using the escape() method the string "Tutorix is the best e-learning platform!!!" is encoded and displayed the result in as shown in the output.
Live Demo
<html>
<body>
<script>
   document.write(escape("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>
Tutorix%20is%20the%20best%20e-learning%20platform%21%21%21
In the following example, using the encodeURIComponent() method the provide string is encoded and displayed the result as shown in the output. 
Live Demo
<html>
<body>
<script>
   document.write(encodeURIComponent("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>
Tutorix%20is%20the%20best%20e-learning%20platform!!!
How to get the input from the Tkinter Text Widget?

In tkinter, we can create text widgets using Text attributes using packages. However, while creating a GUI application, sometimes we need to capture the input from a text widget.
We can get the input from the user in a text widget using the .get() method. We need to specify the input range which will be initially from 1.0 to END that shows the characters starting and ending till the END.
#Import tkinter library
from tkinter import *

#Create an instance of tkinter window or frame
win=Tk()
win.geometry("700x300")

def get_input():
   value=my_text_box.get("1.0","end-1c")
   print(value)

#Creating a text box widget
my_text_box=Text(win, height=5, width=40)
my_text_box.pack()

#Create a button for Comment
comment= Button(win, height=5, width=10, text="Comment", command=lambda: get_input())

#command=get_input() will wait for the key to press and displays the entered text
comment.pack()

win.mainloop()
Running the above code will display a textbox which will accept the input from the user and print the output on the console.
How to divide each column by a particular column in R?

To divide each column by a particular column, we can use division sign (/). For example, if we have a data frame called df that contains three columns say x, y, and z then we can divide all the columns by column z using the command df/df[,3].
Consider the below data frame −
 Live Demo
x1<-rpois(20,5)
x2<-rpois(20,5)
x3<-rpois(20,5)
df1<-data.frame(x1,x2,x3)
df1
   x1 x2 x3
1  7  7  5
2  7  6  5
3  7  3  7
4  2  4  5
5  3  8  1
6  2  3  2
7  4  5  4
8  3  4  8
9  6  7  4
10 5  8  7
11 5  6  3
12 6  6  4
13 6  2  5
14 6  4  2
15 4  2  2
16 7  6  7
17 5  8  5
18 4  4  3
19 0  2  4
20 6  5  6
Dividing all columns of df1 by column x3 −
df1/df1[,3]
     x1         x2       x3
1  1.4000000  1.4000000  1
2  1.4000000  1.2000000  1
3  1.0000000  0.4285714  1
4  0.4000000  0.8000000  1
5  3.0000000  8.0000000  1
6  1.0000000  1.5000000  1
7  1.0000000  1.2500000  1
8  0.3750000  0.5000000  1
9  1.5000000  1.7500000  1
10 0.7142857  1.1428571  1
11 1.6666667  2.0000000  1
12 1.5000000  1.5000000  1
13 1.2000000  0.4000000  1
14 3.0000000  2.0000000  1
15 2.0000000  1.0000000  1
16 1.0000000  0.8571429  1
17 1.0000000  1.6000000  1
18 1.3333333  1.3333333  1
19 0.0000000  0.5000000  1
20 1.0000000  0.8333333  1
 Live Demo
y1<-rpois(20,10)
y2<-rpois(20,10)
y3<-rpois(20,10)
df2<-data.frame(y1,y2,y3)
df2
    y1  y2  y3
1   4   7   9
2  11   7   9
3  12  13  11
4  16   6  15
5   8  16  11
6  10   7   4
7  12  18   9
8  13   7  11
9  11  14  10
10  8  12   9
11 13  15  14
12 13  13   5
13 11   7   9
14 10  12   5
15  9  10  13
16  9  10  12
17  8   8   7
18 11   9   9
19  9   8  11
20  8  13  12
Dividing all columns of df2 by column y3 −
df2/df2[,3]
     y1         y2       y3
1  0.4444444  0.7777778  1
2  1.2222222  0.7777778  1
3  1.0909091  1.1818182  1
4  1.0666667  0.4000000  1
5  0.7272727  1.4545455  1
6  2.5000000  1.7500000  1
7  1.3333333  2.0000000  1
8  1.1818182  0.6363636  1
9  1.1000000  1.4000000  1
10 0.8888889  1.3333333  1
11 0.9285714  1.0714286  1
12 2.6000000  2.6000000  1
13 1.2222222  0.7777778  1
14 2.0000000  2.4000000  1
15 0.6923077  0.7692308  1
16 0.7500000  0.8333333  1
17 1.1428571  1.1428571  1
18 1.2222222  1.0000000  1
19 0.8181818  0.7272727  1
20 0.6666667  1.0833333  1
BigInt in JavaScript

The BigInt is an inbuilt object that is used for representing whole numbers larger than 253 - 1.
Following is the code to implement BigInt in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="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;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>BigInt in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display a BigInt number</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = BigInt(9007199254740991) + "<br>";
      resEle.innerHTML += BigInt(Number.MAX_SAFE_INTEGER) + "<br>";
   });
</script>
</body>
</html>
On clicking on ‘CLICK HERE’ button −
Count the number of objects using Static member function in C++ Program

The goal here is to count the number of objects of a class that are being created using a static member function.
A static data member is shared by all objects of the class commonly. If no value is given, a static data member is always initialized with 0.
A static member function can only use static data members of that class.
We are using a class Student here. We will declare a static data member count which will store the count of objects. A static member function rollCall(void) which will display the count of objects as roll no.s of students in a class.
We declare a class Student which has public data members int rollno and static data member count.
We declare a class Student which has public data members int rollno and static data member count.
There is a constructor which calls rollcall() and initializes rollno with count.
There is a constructor which calls rollcall() and initializes rollno with count.
There is a destructor which decreases count.
There is a destructor which decreases count.
Static member function rollcall() displays the count of objects as Student count and increments the count.
Static member function rollcall() displays the count of objects as Student count and increments the count.
Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object.
Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object.
In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects.
In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects.
 Live Demo
// C++ program to Count the number of objects
// using the Static member function
#include <iostream>
using namespace std;
class Student {
public:
   int rollno;
   static int count;
public:
   Student(){
      rollCall();
      rollno=count;
   }
   ~Student()
   { --count; }
   static void rollCall(void){
      cout <<endl<<"Student Count:" << ++count<< "\n"; //object count
   }
};
int Student::count;
int main(){
   Student stu1;
   cout<<"Student 1: Roll No:"<<stu1.rollno;
   Student stu2;
   cout<<"Student 2: Roll No:"<<stu2.rollno;
   Student stu3;
   cout<<"Student 3: Roll No:"<<stu3.rollno;
   Student stu4;
   cout<<"Student 4: Roll No:"<<stu4.rollno;
   return 0;
}
If we run the above code it will generate the following output −
Student Count:1
Student 1: Roll No:1
Student Count:2
Student 2: Roll No:2
Student Count:3
Student 3: Roll No:3
Student Count:4
Student 4: Roll No:4
Find the first repeated word in a string in Java

To find the first repeated word in a string in Java, the code is as follows −
 Live Demo
import java.util.*;
public class Demo{
   static char repeat_first(char my_str[]){
      HashSet<Character> my_hash = new HashSet<>();
      for (int i=0; i<=my_str.length-1; i++){
         char c = my_str[i];
         if (my_hash.contains(c))
         return c;
         else
         my_hash.add(c);
      }
      return '\0';
   }
   public static void main (String[] args){
      String my_str = "thisisasampleonlysample";
      char[] my_arr = my_str.toCharArray();
      System.out.println("The first repeating character in the string is :");
      System.out.println(repeat_first(my_arr));
   }
}
The first repeating character in the string is :
I
A class named Demo contains a function named ‘repeat_first’, that takes a character string as a parameter. It creates a new hash set and iterates over the string and checks if the character in the string is equal to a specific character.
If yes, then the character is returned, otherwise, the character is added to the hash set. This way, the second time a word is found, it is added to the hash set, and this becomes the first word, that was in the string more than once. In the main function, the string is defined and a character array is defined. The function ‘repeat_first’ is called on this character array. The relevant array is displayed on the console.
Knuth-Morris-Pratt Algorithm

Knuth Morris Pratt (KMP) is an algorithm, which checks the characters from left to right. When a pattern has a sub-pattern appears more than one in the sub-pattern, it uses that property to improve the time complexity, also for in the worst case.
The time complexity of KMP is O(n).
Input:
Main String: “AAAABAAAAABBBAAAAB”, The pattern “AAAB”
Output:
Pattern found at location: 1
Pattern found at location: 7
Pattern found at location: 14
findPrefix(pattern, m, prefArray)
Input − The pattern, the length of pattern and an array to store prefix location
Output − The array to store where prefixes are located
Begin
   length := 0
   prefArray[0] := 0

   for all character index ‘i’ of pattern, do
      if pattern[i] = pattern[length], then
         increase length by 1
         prefArray[i] := length
      else
         if length ≠ 0 then
            length := prefArray[length - 1]
            decrease i by 1
         else
            prefArray[i] := 0
   done
End
kmpAlgorithm(text, pattern)
Input: The main text, and the pattern, which will be searched
Output − The location where patterns are found
Begin
   n := size of text
   m := size of pattern
   call findPrefix(pattern, m, prefArray)

   while i < n, do
      if text[i] = pattern[j], then
         increase i and j by 1
      if j = m, then
         print the location (i-j) as there is the pattern
         j := prefArray[j-1]
      else if i < n AND pattern[j] ≠ text[i] then
         if j ≠ 0 then
            j := prefArray[j - 1]
         else
            increase i by 1
   done
End
#include<iostream>
using namespace std;

void findPrefix(string pattern, int m, int prefArray[]) {
   int length = 0;
   prefArray[0] = 0;     //first place is always 0 as no prefix

   for(int i = 1; i<m; i++) {
      if(pattern[i] == pattern[length]) {
         length++;
         prefArray[i] = length;    
      }else {
         if(length != 0) {
            length = prefArray[length - 1];
            i--;     //decrease i to avoid effect of increasing after iteration
         }else
            prefArray[i] = 0;
      }
   }
}

void kmpPattSearch(string mainString, string pattern, int *locArray, int &loc) {
   int n, m, i = 0, j = 0;
   n = mainString.size();
   m = pattern.size();
   int prefixArray[m];    //prefix array as same size of pattern
   findPrefix(pattern, m, prefixArray);
   loc = 0;

   while(i < n) {
      if(mainString[i] == pattern[j]) {
         i++; j++;
      }

      if(j == m) {
         locArray[loc] = i-j;      //item found at i-j position.
         loc++;
         j = prefixArray[j-1];    //get the prefix length from array
      }else if(i < n && pattern[j] != mainString[i]) {
         if(j != 0)
            j = prefixArray[j-1];
         else
            i++;
      }
   }
}

int main() {
   string str = "AAAABAAAAABBBAAAAB";
   string patt = "AAAB";
   int locationArray[str.size()];
   int index;
   kmpPattSearch(str, patt, locationArray, index);

   for(int i = 0; i<index; i++) {
      cout << "Pattern found at location: " <<locationArray[i] << endl;
   }
}
Pattern found at location: 1
Pattern found at location: 7
Pattern found at location: 14
Bootstrap .modal("toggle") method

Use the .modal(“toggle”) method in Bootstrap to toggle the modal.
As shown below, the modal generates on the click of a button −
$(document).ready(function(){
  $("#button1").click(function(){
    $("#newModal").modal("toggle");
  });
});
Here is the button used above −
<button type="button" class="btn btn-default btn-lg" id="button1">
  Modal One
</button>
You can try to run the following code to implement the modal(“toggle”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
<body>
  <div class="container">
    <h2>Sample</h2>
    <button type="button" class="btn btn-default btn-lg" id="button1">Modal One</button>
    <div class="modal fade" id="newModal" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Sample Modal</h4>
          </div>
          <div class="modal-body">
            <p>Click outside to close it.</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
          </div>
       </div>
     </div>
   </div>
 </div>

 <script>
  $(document).ready(function(){
    $("#button1").click(function(){
      $("#newModal").modal("toggle");
    });
  });
 </script>

</body>
</html>