code-rag-bench/online-tutorials huggingface dataset:
Python 3 - File writelines() Method

The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value.
Following is the syntax for writelines() method −
fileObject.writelines( sequence )

sequence − This is the Sequence of the strings.
This method does not return any value.
The following example shows the usage of writelines() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python3

# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)

seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )

# Now read complete file from beginning.
fo.seek(0,0)
   for index in range(7):
      line = next(fo)
      print ("Line No %d - %s" % (index, line))

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt

Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
Line No 4 - This is 5th line
Line No 5 - This is 6th line
Line No 6 - This is 7th line


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Matrix Multiplication and Normalization in C program

Now procedure of Matrix Multiplication is discussed. The Matrix Multiplication can only be performed, if it satisfies certain condition. Suppose two matrices are P and Q, and their dimensions are P (a x b) and Q (z x y) the resultant matrix can be found if and only if b = x. Then the order of the resultant matrix R will be (m x q).
matrixMultiply(P, Q):
Assume dimension of P is (a x b), dimension of Q is (z x y)
Begin
   if b is not same as z, then exit
   otherwise define R matrix as (a x y)
   for i in range 0 to a - 1, do
      for j in range 0 to y – 1, do
         for k in range 0 to z, do
            R[i, j] = R[i, j] + (P[i, k] * Q[k, j])
         done
      done
   done
End
Suppose we have a 2x3 matrix:
4 5 6
1 2 3 The normalized matrix would be:
4/sqrt(pow(5,2) + pow(6,2)) 5/sqrt(pow(5,2) + pow(6,2)) 6/sqrt(pow(5,2) + pow(6,2))
1/sqrt(pow(2,2) + pow(3,2)) 2/sqrt(pow(2,2) + pow(3,2)) 3/sqrt(pow(2,2) + pow(3,2))
#include <stdio.h>
#include <math.h>
int main() {
   int row, col, row1, col1;
   int assignMatrix[50][50], rowAdd[100] = {0};
   long long int a, square[50] = {0};
   double norm[50][50], k;
   printf("Enter size of a matrix\n");
   scanf("%d %d", &row, &col);
   printf("Enter matrix of size %dX%d\n", row, col);
   for ( row1 = 0; row1 < row; row1++) {
      for (col1 = 0; col1 < col; col1++) {
         scanf("%d", &assignMatrix[row1][col1]);
      }
   }
   printf("\nrows: %d cols: %d elements:\n",row,col);
   for( row1 = 0; row1 < row; row1++) {
      for( col1 = 0; col1 < col; col1++) {
         printf("%d ", assignMatrix[row1][col1]);
      }
      printf("\n");
   }
   for (row1 = 0; row1 < row; row1++) {
      for (col1 = 1; col1 < col; col1++) {
         a = assignMatrix[r][c];
         square[row1] += a * a;
      }
      printf("Sum of squares of row %d: %lld\n",row1,square[row1]);
   }
   for ( row1 = 0; row1 < row; row1++ ) {
      k = 1.0 / sqrt(square[row1]);
      for( col1 = 0; col1 < col; col1++ ) {
         norm[row1][col1] = k * assignMatrix[row1][col1] ;
      }
   }
   printf("\nNormalized Matrix:\n");
   for( row1 = 0; row1 < row; row1++) {
      for( col1 = 0; col1 < col; col1++) {
         printf("%.3lf ", norm[row1][col1]);
      }
      printf("\n");
   }
   return 0;
}
Enter size of a matrix
2
3
Enter matrix of size 2X3
4 5 6
1 2 3
rows: 2 cols: 3 elements:
4 5 6
1 2 3
Sum of squares of row 0: 61
Sum of squares of row 1: 13
Normalized Matrix:
0.512 0.640 0.768
0.277 0.555 0.832
Process returned 0 (0x0) execution time : 12.446 s
Press any key to continue.
How to restrict the number of digits inside JPasswordField in Java?


A JPasswordField is a subclass of JTextField and each character entered in a JPasswordField can be replaced by an echo character. This allows confidential input for passwords. The important methods of JPasswordField are getPassword(), getText(), getAccessibleContext() and etc. By default, we can enter any number of digits inside JPasswordField. If we want to restrict the digits entered by a user by implementing a DocumentFilter class and need to override the replace() method.
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
import java.awt.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JPasswordFieldDigitLimitTest extends JFrame {
   private JPasswordField passwordField;
   private JPanel panel;
   public JPasswordFieldDigitLimitTest() {
      panel = new JPanel();
      ((FlowLayout) panel.getLayout()).setHgap(2);
      panel.add(new JLabel("Enter Pin: "));
      passwordField = new JPasswordField(4);
      PlainDocument document = (PlainDocument) passwordField.getDocument();
      document.setDocumentFilter(new DocumentFilter() {
         @Override
         public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;
               if (string.length() <= 4) {
                  super.replace(fb, offset, length, text, attrs);
               }
         }
      });
      panel.add(passwordField);
      add(panel);
      setSize(400, 300);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JPasswordFieldDigitLimitTest();
   }
}
How To Show Mean Value in Boxplots with ggplot2?

10 Oct, 2021
In this article, we will discuss how to show mean value in Boxplot with ggplot2 using R programming language.
Firstly, we will create a basic boxplot using the geom_boxplot() function of the ggplot2 package and then do the needful, so that the difference is apparent.
Syntax:
ggplot() + geom_boxplot()
Example: Basic boxplot
R
# load library tidyverselibrary(tidyverse)library(ggplot2)  # basic boxplotggplot(diamonds, aes(x=cut, y=price)) +  # geom_boxplot is used to plot the boxplot  geom_boxplot()
Output:
In order to show mean values in boxplot using ggplot2, we use the stat_summary() function to compute new summary statistics and add them to the plot. We use stat_summary() function with ggplot() function.
Syntax:
stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, color=”value”, shape=”value”,...)
Example: Adding mean value to boxplot
R
# load librarieslibrary(ggplot2)library(tidyverse)  # basic boxplotggplot(diamonds, aes(x=cut, y=price)) +  # geom_boxplot is used to plot the boxplot  geom_boxplot() +  # stat_summary computes the statistics summary# fun.y arguments as mean determines that # statistical summary will be mean of y-axisstat_summary(fun.y="mean")
Output:
In the output produced above, the point in the center of the boxplot shows the variation of the mean of the y-axis for each category of data on the x-axis.
We can also change the color and shape of the mean mark using the color and shape parameter of the stat_summary() function. This helps us visualize the data better by distinguishing the mark from other symbols.
Example: Customizing added mean values
R
# load library tidyverselibrary(tidyverse)library(ggplot2)  # basic boxplotggplot(diamonds, aes(x=cut, y=price)) +  # geom_boxplot is used to plot the boxplot  geom_boxplot() +  # stat_summary computes the statistics summarystat_summary(fun.y="mean",color="red", shape=13)
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
GATE | GATE-CS-2006 | Question 68

12 Apr, 2018
Consider the relation “enrolled(student, course)” in which (student, course) is the primary key, and the relation “paid(student, amount)” where student is the primary key. Assume no null values and no foreign keys or integrity constraints. Given the following four queries:
Query1: select student from enrolled where 
        student in (select student from paid)
Query2: select student from paid where 
        student in (select student from enrolled)
Query3: select E.student from enrolled E, paid P 
         where E.student = P.student
Query4:  select student from paid where exists
        (select * from enrolled where enrolled.student
         = paid.student) 
Which one of the following statements is correct?(A) All queries return identical row sets for any database(B) Query2 and Query4 return identical row sets for all databases but there exist databases for which Query1 and Query2 return different row sets.(C) There exist databases for which Query3 returns strictly fewer rows than Query2(D) There exist databases for which Query4 will encounter an integrity violation at runtime.Answer: (B)Explanation: Take an example:
Table enrolled
student   course
----------------
 abc      c1   
 xyz      c1
 abc      c2
 pqr      c1

Table paid
student  amount
-----------------
 abc      20000
 xyz      10000
 rst      10000


Output of Query 1
 abc
 abc
 xyz

Output of Query 2
 abc
 xyz

Output of Query 3
 abc
 xyz

Output of Query 4
 abc
 xyz
Query 1 and Query 3 may return repetitive student values as “student” is not a key in relation enrolled, however query 2 and query 4 always return same row sets.
So, option (B) is correct.Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2010 | Question 54
GATE | GATE-CS-2015 (Set 1) | Question 19
GATE | GATE CS 2018 | Question 43
GATE | Gate IT 2008 | Question 59
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2006 | Question 45
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2013 | Question 25
GATE | GATE-CS-2003 | Question 77
HTML - Progress Tag

The HTML <progress> tag specifies a completion progress of a task. It is displayed as a progress bar. The value of progressbar can be manipulated by JavaScript.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML Progress Tag</title>
   </head>

   <body>
      <h1>Student's Intelligence level</h1>
      <progress value = "80" max = "100"/>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <progress> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
Switch case calculator in JavaScript

Let’s say, we are required to write a JavaScript function that takes in a string like these to create a calculator −
"4 add 6"
"6 divide 7"
"23 modulo 8"
Basically, the idea is that the string will contain two numbers on either sides and a string representing the operation in the middle.
The string in the middle can take one of these five values −
"add", "divide", "multiply", "modulo", "subtract"
Our job is to return the correct result based on the string
Let’s write the code for this function −
const problem = "3 add 16";
const calculate = opr => {
   const [num1, operation, num2] = opr.split(" ");
   switch (operation) {
      case "add":
         return +num1 + +num2;
      case "divide":
         return +num1 / +num2;
      case "subtract":
         return +num1 - +num2;
      case "multiply":
         return +num1 * +num2;
      case "modulo":
         return +num1 % +num2;
      default:
         return 0;
   }
}
console.log(calculate(problem));
The output in the console: −
19
Download web page using Java

20 Jan, 2018
Java Program to read and download webpage
Steps:1. Create a URL object and pass url as string to download the webpage.URL example = new URL(pass url of webpage you want to download)2. Create Buffered Reader object and pass openStream(). Method of URL in Input Stream object.3. Create a string object to read each line one by one from stream.4. Write each line in html file where webpage will be downloaded.5. Close all objects.6. Catch exceptions if url failed to download.
Program:
package normal;// Java program to read and download// webpage in html fileimport java.io.*;import java.net.URL;import java.net.MalformedURLException;  public class download {      public static void DownloadWebPage(String webpage)    {        try {              // Create URL object            URL url = new URL(webpage);            BufferedReader readr =               new BufferedReader(new InputStreamReader(url.openStream()));              // Enter filename in which you want to download            BufferedWriter writer =               new BufferedWriter(new FileWriter("Download.html"));                          // read each line from stream till end            String line;            while ((line = readr.readLine()) != null) {                writer.write(line);            }              readr.close();            writer.close();            System.out.println("Successfully Downloaded.");        }          // Exceptions        catch (MalformedURLException mue) {            System.out.println("Malformed URL Exception raised");        }        catch (IOException ie) {            System.out.println("IOException raised");        }    }    public static void main(String args[])        throws IOException    {        String url = "https://www.geeksforgeeks.org/";        DownloadWebPage(url);    }}
Output:
Successfully Downloaded.
Java-Networking
Java
Web Technologies
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL query to avoid displaying duplicates values?

For this, you can use GROUP BY and use COUNT to get only non-duplicate values. Following is the syntax −
select yourColumnName from yourTableName group by yourColumnName having count(*)=1;
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Subject varchar(100)
   -> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Subject) values('C++');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+---------+
| Id | Subject |
+----+---------+
| 1  | MySQL   |
| 2  | MongoDB |
| 3  | Java    |
| 4  | MongoDB |
| 5  | C       |
| 6  | C++     |
| 7  | Java    |
| 8  | C       |
+----+---------+
8 rows in set (0.00 sec)
Here is the query to avoid displaying duplicates −
mysql> select Subject from DemoTable group by Subject having count(*)=1;
+---------+
| Subject |
+---------+
| MySQL   |
| C++     |
+---------+
2 rows in set (0.00 sec)
Python | Convert list of tuples to list of list

27 Mar, 2019
This is a quite simple problem but can have a good amount of application due to certain constraints of python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let’s discuss certain ways in which we can convert a list of tuples to list of list.
Method #1 : Using list comprehensionThis can easily be achieved using the list comprehension. We just iterate through each list converting the tuples to the list.
# Python3 code to demonstrate# convert list of tuples to list of list# using list comprehension  # initializing list test_list = [(1, 2), (3, 4), (5, 6)]  # printing original list print("The original list of tuples : " + str(test_list))  # using list comprehension# convert list of tuples to list of listres = [list(ele) for ele in test_list]  # print resultprint("The converted list of list : " + str(res))
The original list of tuples : [(1, 2), (3, 4), (5, 6)]
The converted list of list : [[1, 2], [3, 4], [5, 6]]

 
Method #2 : Using map() + listWe can use the combination of map function and list operator to perform this particular task. The map function binds each tuple and converts it into list.
# Python3 code to demonstrate# convert list of tuples to list of list# using map() + list  # initializing list test_list = [(1, 2), (3, 4), (5, 6)]  # printing original list print("The original list of tuples : " + str(test_list))  # using map() + list# convert list of tuples to list of listres = list(map(list, test_list))  # print resultprint("The converted list of list : " + str(res))
The original list of tuples : [(1, 2), (3, 4), (5, 6)]
The converted list of list : [[1, 2], [3, 4], [5, 6]]

Python list-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tkinter | Adding style to the input text using ttk.Entry widget

29 Nov, 2021
Tkinter is a GUI (Graphical User Interface) module which is widely used to create GUI applications. It comes along with the Python itself.
Entry widgets are used to get the entry from the user. It can be created as follows-
 entry = ttk.Entry(master, option = value, ...) 
Code #1: Creating Entry widget and taking input from user (taking only String data).
# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno  # creating rootroot = Tk()  # specifying geometryroot.geometry('200x100')  # This is used to take input from user# and show it in Entry Widget.# Whatever data that we get from keyboard# will be treated as string.input_text = StringVar()  entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER)  # focus_force is used to take focus# as soon as application startsentry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 6)  save = ttk.Button(root, text = 'Save', command = lambda : askyesno(                                'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10)  root.mainloop()
Output:
In above output, as soon as you run the code a Tkinter window will appear and Entry widget is already focussed that means we don’t have to give focus to the Entry area.When we press Button a confirmation message will appear, saying whether you want to save the text or not (it will not save the text, it is only used to show the functioning of Button). Code #2: Adding Style to the entered text in Entry widget.
# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno  # creating rootroot = Tk()root.geometry('200x100')  input_text = StringVar()  # This class is used to add styling# to any widget which are availablestyle = ttk.Style()style.configure('TEntry', foreground = 'green')  entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER,                                     font = ('courier', 15, 'bold'))   entry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 10)  save = ttk.Button(root, text = 'Save', command = lambda : askyesno(                                 'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10)  root.mainloop()
Output:In the above output, you may notice that the color of the font is changed, font family is changed, size of the text is bigger than normal as well as text is written in bold. This is because we are adding style to the input text.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.str.extractall()

27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extractall() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level=’match’) is the same as extract(pat).
Syntax: Series.str.extractall(pat, flags=0)
Parameter :pat : Regular expression pattern with capturing groups.flags : A re module flag, for example re.IGNORECASE.
Returns : DataFrame
Example #1: Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])  # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object.
# extract all groups having a vowel followed by# any characterresult = sr.str.extractall(pat = '([aeiou].)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group.
Example #2 : Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])  # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object.
# extract all groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extractall(pat = '([A-Z]i.)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group.
Python-pandas
Python-pandas-series-str
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
Python | datetime.timedelta() function
Create a white space in HTML

The HTML <spacer> tag specifies a whitespace. It supports the following additional attributes −
Note − The <spacer> tag is available in Netscape 4 and higher versions only.
You can try to run the following code to create a white space in HTML (visible in Netscape Web Browser only) −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML spacer Tag</title>
   </head>
   <body>
      Create some space <spacer type = "block" width = "70" /> now.
   </body>
</html>
Ruby | Array class include?() operation

08 Jan, 2020
Array#include?() : include?() is a Array class method checks if the argumented object is present in the array or not.
Syntax: Array.include?()
Parameter: obj – element to find
Return: true – if the element is present; otherwise false
Code #1 : Example for include?() method
# Ruby code for include?() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, nil, nil, 50, 6]  # include?puts "include? : #{a.include?(5)}\n\n"  # include?puts "include? : #{b.include?(0)}\n\n"  # include?puts "include? : #{c.include?(nil)}\n\n"
Output :
include? : true

include? : false

include? : true

Code #2 : Example for include?() method
# Ruby code for include?() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayb = ["cow", nil, "dog"]  # declaring arrayc = ["cat", nil, nil]  # include?puts "include? : #{a.include?("cat")}\n\n"  # include?puts "include? : #{b.include?("nil")}\n\n"  # include?puts "include? : #{c.include?("cat")}\n\n"
Output :
include? : false

include? : false

include? : true

Ruby Array-class
Ruby Collections
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Arden’s Theorem in Theory of Computation

02 Mar, 2020
Arden’s theorem state that:“If P and Q are two regular expressions over , and if P does not contain , then the following equation in R given by R = Q + RP has an unique solution i.e., R = QP*.”That means, whenever we get any equation in the form of R = Q + RP, then we can directly replaced by R = QP*. So, here first we will prove that R = QP* is the solution of this equation and then we will also prove that it is the unique solution of this equation.
Let’s start by taking this equation as equation (i)
R = Q + RP  ......(i)
Now, replacing R by R = QP*, we get,
R = Q + QP*P 
Taking Q as common,
R = Q( + P*P)
R = QP*  
(As we know that  + R*R = R*). Hence proved.
Thus, R = QP* is the solution of the equation R = Q + RP.
Now, we have to prove that this is the only solution of this equation. Let me take this equation again:
R = Q + RP
Now, replace R by R = Q + RP,
R = Q + (Q + RP)P
  = Q + QP + R 
Again, replace R by R = Q + RP:-
R = Q + QP + (Q + RP) 
  = Q + QP + Q + R
  = ...
  = ...
  =  Q + QP + Q + .. + Q + R 
Now, replace R by R = QP*, we get,
R = Q + QP + Q + .. + Q + QP* 
Taking Q as common,
R = Q( + P +  + .. +  + P*)
  = QP*    [As  + P +  + .. +  + P* represent 
          the closure of P] 
Hence proved.
Thus, R = QP* is the unique solution of the equation R = Q + RP.
To understand this theorem, we will solve an example:
Example –
q1 = q1.0  + 
q2 = q1.1 + q2.0
q3 = q2.1 + q3.0 + q3.1 
Now,
q1 =  + q1.0
q1 = .0*    [By Arden's theorem]
q1 = 0*      [R = R]

.'. q2 = 0*1 +q2.0
    q2 = 0*10*    
[Applying Arden’s theorem]. Hence, the value of q2 is 0*10*.
AllenDeAlpha
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ranlib command in Linux with Examples

17 Apr, 2019
ranlib command in Linux is used to generate index to archive. ranlib generates an index to the contents of an archive and it will be stored in the archive. The index lists each symbol defined by a member of an archive which is simply relocatable object file. You may use nm -s or nm –print-armap to list all of this index. An archive with such an index speeds up the linking to the library and allows routines in the library to call each other without regard to their placement in the archive. The GNU ranlib program is another form of GNU ar; running ranlib is completely equivalent to running ar -s.
Syntax:
ranlib [--plugin name] [-DhHvVt] archive

Example: It will generate index to archive as shown in the below example.
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command generating an index to the contents of an archive and it will be stored in the archive.
Options:
–help: This option will show usage information for ranlib.ranlib --help
ranlib --help
–version: This option will show the version number of ranlib.ranlib --version
ranlib --version
-D : This option will operate in deterministic mode. The symbol map archive of member’s header will show zero for the UID, GID, and timestamp. When this option is being used, multiple runs will produce identical output files.Example:ranlib -D fruits.aExplanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive.
Example:
ranlib -D fruits.a
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive.
-t : This option will update the timestamp of the symbol map of an archive.Example :ranlib -t fruits.a
Example :
ranlib -t fruits.a
-U: This option do not operate in deterministic mode. This is exactly the inverse of the -D option. The archive index will get actual UID, GID, timestamp, and file mode values. If binutils was configured without using –enable-deterministic-archives, then this mode is set by default.Example:ranlib -U fruits.a
Example:
ranlib -U fruits.a
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Shuffle two lists with same order - GeeksforGeeks

22 Feb, 2022
Sometimes, while working with Python list, we can have a problem in which we need to perform shuffle operation in list. This task is easy and there are straightforward functionalities available in Python to perform this. But sometimes, we need to shuffle two lists so that their shuffle orders are consistent. Let’s discuss a way in which this task can be performed.Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.  
Python3
# Python3 code to demonstrate working of# Shuffle two lists with same order# Using zip() + * operator + shuffle()import random # initializing liststest_list1 = [6, 4, 8, 9, 10]test_list2 = [1, 2, 3, 4, 5] # printing listsprint(f"The original list 1 : {test_list1}")print(f"The original list 2 : {test_list2}") # Shuffle two lists with same order# Using zip() + * operator + shuffle()temp = list(zip(test_list1, test_list2))random.shuffle(temp)res1, res2 = zip(*temp)# res1 and res2 come out as tuples, and so must be converted to lists.res1, res2 = list(res1), list(res2) # Printing resultprint(f"List 1 after shuffle :  {res1}")print(f"List 2 after shuffle :  {res2}")
 
The original list 1 : [6, 4, 8, 9, 10]
The original list 2 : [1, 2, 3, 4, 5]
List 1 after shuffle : [6, 10, 4, 8, 9]
List 2 after shuffle : [1, 5, 2, 3, 4]
 
snny2b8fx3cw6oudpwqpr7xvo6nb98gq2qblbywl
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Java Regular Expression that doesn't contain a certain String.

import java.util.regex.*;
class PatternMatch{
   public static void main(String args[]) {
      String content = "I am a student";
      String string = ".*boy.*";
      boolean isMatch = Pattern.matches(string,content);
      System.out.println("The line contains 'boy'?"+ isMatch);
   }
}
the line contains 'boy'?false
It is used to check if the whole text matches a pattern. Its output is boolean. It returns true if match is found otherwise false.This is one of simplest and easiest way of searching a String in a text using Regex .There is a another method compile() , if you want to do a CASE INSENSITIVE search or want to do search multiple occurrences it can be used.
For above example it will be then −
String content = "I am a student";
String string = ".*BoY.";
Pattern pattern = Pattern.compile(string, Pattern.CASE_INSENSITIVE);
How to add background Image to JFrame in Java

To add background image to JFrame, use the getImage() method of the Image class −
Image img = Toolkit.getDefaultToolkit().getImage("E:\\rahul.jpg");
Now, draw the image −
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   g.drawImage(img, 0, 0, null);
}
The following is an example to add Background Image to JFrame −
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import javax.swing.JPanel;
public class SwingDemo extends javax.swing.JFrame {
   Image img = Toolkit.getDefaultToolkit().getImage("E:\\rahul.jpg");
   public SwingDemo() throws IOException {
      this.setContentPane(new JPanel() {
         @Override
         public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, null);
         }
      });
      pack();
      setVisible(true);
   }
   public static void main(String[] args) throws Exception {
      new SwingDemo();
   }
}
List of Keywords in Python Programming

The keyword module in Python's standard library allows a Python program to determine if a string is a keyword.
keyword.iskeyword(s): This function returns true if s is a Python keyword.
keyword.kwlist: This attribute returns Sequence containing all the keywords defined for the interpreter. If any keywords are to be appearing in future versions, these will be included as well.
>>> import keyword
>>> kwlist = keyword.kwlist
>>> kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
>>> kw = input('enter a keyword..')
enter a keyword..catch
>>> kw in kwlist
False
>>> kw = input('enter a keyword..')
enter a keyword..import
>>> kw in kwlist
True
Java Program to compare two sets

Let’s say the following is our 1st Set:
String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set1 = new HashSet<String>(Arrays.asList(arr));
Let’s say the following is our 2nd Set:
arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set2 = new HashSet<String>(Arrays.asList(arr));
Now let us compare the two sets. TRUE return value means both the sets are equals, whereas FALSE is
returned:
set1.equals(set2)
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
      Set<String> set1 = new HashSet<String>(Arrays.asList(arr));
      arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
      Set<String> set2 = new HashSet<String>(Arrays.asList(arr));
      System.out.println("Both the sets are equal? = "+set1.equals(set2));
   }
}
Both the sets are equal? = true
How to create 2-tuple or pair tuple in C#?

29 Nov, 2019
In C#, a 2-tuple is a tuple that contains two elements and it is also known as pair. You can create a 2-tuple using two different ways:
Using Tuple<T1,T2>(T1, T2) Constructor
Using the Create method
You can create 2-tuple using Tuple<T1, T2>(T1, T2) constructor. It initializes a new instance of the Tuple<T1,T2> class. But when you create a tuple using this constructor then you have to specify the type of the element stored in the tuple.
Syntax:
public Tuple (T1 item1, T2 item2);
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
Example:
// C# program to create 2-tuple// using the tuple constructorusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating tuple with two elements        // Using Tuple<P1, P2>(T1, T2) constructor        Tuple<string, int> My_Tuple = new Tuple<string, int>("GeeksforGeeks", 10);          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);    }}
Element 1: GeeksforGeeks
Element 2: 10

You can also create 2-tuple with the help of Create method. When you use this method then there is no need to specify the type of the elements stored in the tuple.
Syntax:
public static Tuple<T1,T2> Create<T1, T2> (T1 item1, T2 item2);
Type Parameters:
T1: It is the type of the first tuple component.
T2: It is the type of the second tuple component.
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
Return Type: This method returns 2-tuple whose value is item1 and item2.
Example:
// C# program to create 2-tuple// using create methodusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating tuple with two elements        // Using Create method        var My_Tuple = Tuple.Create("Geeks", 20);          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);    }}
Element 1: Geeks
Element 2: 20

References:
https://docs.microsoft.com/en-us/dotnet/api/system.tuple-2.-ctor?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/api/system.tuple.create?view=netframework-4.8#System_Tuple_Create__2___0___1_
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
USB Rubber Ducky – PenetrationTesting

22 May, 2020
USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device.
HID stands for Human Interface Devices, it includes devices like keyboard, mouse, joystick. which acts as an interface between the computer and human beings. That is why it cannot get detected as the computer thinks its an interface.
USB Rubber ducky is a kind of key injection tool, can be used as malicious or non-malicious keystroke.
It is one of the favorite devices of hackers penetration testers as it is very fast and did not detect by ant PC.
USB Rubber Ducky can also be used for targeting vulnerable systems or programming processes and save times.
USB rubber ducky acts as a keyboard and has keystrokes installed in it
When we connect it to PC the keystrokes run automatically.
It has a high speed of approx. 1000 words per minute. So those works which can be done by keyboard can also be done by USB rubber ducky
When ever it is connected to a System it acts as a keyboard and executes the command which is uploaded on it.
The commands used in this are known as payloads and written in Ducky script. One basic script is written below.
Example: Anyone who wants to steal the data from other computers has just to command the keystrokes into the rubber ducky and has to plug-in the device to the victim’s computer, then the device automatically runs a command and steals the data at a very high speed.
The payload used in this device has its payload script known as Ducky Script, And we can write this script in Notepad.
Ducky Code:
REM Type Hello World into Windows notepad. Target: Windows 95 and beyond
DELAY 500
GUI r
DELAY 50
STRING c:\windows\notepad.exe
ENTER
DELAY 500
STRING Hello World

The microSD card: This is a storage device in which all your payloads are saved, so when you attach a device to the victim’s system it will steal data. The keyboard adapter used microSD card to send the payloads.
microSD-to-USB adapter: This is a simple plastic Dongle which is used to mount the SD card to machine.
mini “keyboard” adapter: This is a silicon chip to insert a micro SD card to it. This is the main part and sends the keystrokes to the computer.
USB Rubber Ducky costs around 45$ but you can make it at a cheap rate at home also. You can buy this Device Online.
Software Testing
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM Audio load() Method

30 Mar, 2021
The Audio load() method is used for reload the audio element. The Audio load() method is used to update the audio element after changing the source or other settings. The Audio load() method does not accept any parameters and does not return any values.Syntax  
audio.load()
Example:  
html
<!DOCTYPE html><html> <body style="text-align:center;">         <h1 style="color:green">GeeksforGeeks</h1>         <h2>HTML DOM Audio load() Method</h2>         <button onclick="my_Audio()" type="button">        Change Audio    </button>    <br>     <audio id="my_Audio" controls autoplay>        <source id="mp4_src" src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg"                    type="audio/mp3">         <source id="ogg_src" src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"                    type="audio/ogg">    </audio>     <script>        function my_Audio() {            document.getElementById("ogg_src").src ="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg";                     document.getElementById("mp4_src").src ="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3";             document.getElementById("my_Audio").load();        }    </script></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML DOM Audio load() Method are listed below:  
Google ChromeOperaMozilla Firefox
Google Chrome
Opera
Mozilla Firefox
 
arorakashish0911
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | form Attribute - GeeksforGeeks

20 Sep, 2021
The HTML form Attribute is used to specify that the element can contain one or more forms. This attributes can be used on the following elements such as:  
HTML | <button> form Attribute
HTML | <fieldset> form Attribute
HTML | <input> form Attribute
HTML | <label> form Attribute
HTML | <meter> form Attribute
HTML | <object> form Attribute
HTML | <output> form Attribute
HTML | <select> form Attribute
HTML | <textarea> form Attribute
HTML | <keygen> form Attribute
Syntax:  
<element form="form_id"> 
Attribute Value: It contains single value form_id which contains the value i.e form_id which specify the one or more than the button element belongs to. The value of this attribute should be the id of the <form> element.Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML button form Attribute    </title></head> <body style="text-align:center">         <h1 style="color:green;">        GeeksforGeeks    </h1>     <h2>        HTML <button> form Attribute    </h2>         <form id="myGeeks"></form>         <button id="btn" name="myGeeks" form="myGeeks"            onclick="geek()">        Click me!    </button></body> </html>                   
Output:  
Supported Browsers: The browser supported by HTML form Attribute are listed below:  
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to create a MenuButton in JavaFX?

A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.
A button controls in user interface applications, in general, on clicking the button it performs the respective action.
A MenuButton is simply, a button that shows a menu on clicking it. You can create a menu button by instantiating the javafx.scene.control.MenuButton class.
To populate its menu, create a required number of objects of the MenuItem class, add them to the observable list of MenuButton as −
menuButton.getItems(item1, item2, item3);
The following Example demonstrates the creation of a MenuButton.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MenuButtonExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a menu
      MenuButton menu = new MenuButton("Technology");
      //Creating menu Items
      menu.setMnemonicParsing(true);
      MenuItem item1 = new MenuItem("Java");
      MenuItem item2 = new MenuItem("Python");
      MenuItem item3 = new MenuItem("C++");
      MenuItem item4 = new MenuItem("Big Data");
      MenuItem item5 = new MenuItem("Machine Learning");
      //Adding all the menu items to the menu
      menu.getItems().addAll(item1, item2, item3, item4, item5);
      //Adding the choice box to the scene
      HBox layout = new HBox(25);
      layout.getChildren().addAll(menu);
      layout.setPadding(new Insets(15, 50, 50, 150));
      layout.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(layout, 595, 200);
      stage.setTitle("Menu Button");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}