code-rag-bench/online-tutorials huggingface dataset:
Perl | Scalars - GeeksforGeeks

12 Feb, 2021
A scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on.Example :  
Perl
# Perl program to demonstrate# scalars variables # a string scalar$name = "Alex"; # Integer Scalar$rollno = 13; # a floating point scalar$percentage = 87.65; # to display the resultprint "Name = $name\n";print "Roll number = $rollno\n";print "Percentage = $percentage\n";
Output :  
Name = Alex
Roll number = 13
Percentage = 87.65
 
Numeric Scalars
Numeric scalar variables hold values like whole numbers, integers(positive and negative), float(containing decimal point). The following example demonstrates different types of numerical scalar variables in perl.Example :  
Perl
# Perl program to demonstrate various types# of numerical scalar variables # Positive integer numerical# scalar variables$intpositive = 25; # Negative integer numerical# scalar variables$intnegative = -73; # Floating point numerical# scalar variables$float = 23.5; # In hexadecimal form$hexadec = 0xcd; # to display the resultprint "Positive Integer = $intpositive\n";print "Negative Integer = $intnegative\n";print "Floating Point = $float\n";print "Hexadecimal Form = $hexadec\n";
Output :  
Positive Integer = 25
Negative Integer = -73
Floating Point = 23.5
Hexadecimal Form = 205
 
String Scalars
String scalar variables hold values like a word(made of different characters), a group of words or a paragraph. The following example demonstrates different types of string scalar variables.Example : 
Perl
# Perl program to demonstrate various types# of string scalar variables # String scalar$alphastring = "GeeksforGeeks";$numericstring = "17";$alphanumeric = "gfg21";  #special character in string scalar$specialstring = "^gfg"; # in single quotes$singlequt = 'Hello Geeks'; # To display the resultprint "String with alphabets = $alphastring\n";print "String with numeric values = $numericstring\n";print "String with alphanumeric values = $alphanumeric\n";print "String within Single quotes = $singlequt\n";print "String with special characters = $specialstring\n";
Output :  
String with alphabets = GeeksforGeeks
String with numeric values = 17
String with alphanumeric values = gfg21
String within Single quotes = Hello Geeks
String with special characters = ^gfg
 
arorakashish0911
perl-basics
Perl-Scalars
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | split() Function
Perl | push() Function
Perl | exists() Function
Perl | chomp() Function
Perl | grep() Function
Perl | substr() function
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | Subroutines or Functions
Perl | Removing leading and trailing white spaces (trim)
Machine Learning with Python - AdaBoost

It is one the most successful boosting ensemble algorithm. The main key of this algorithm is in the way they give weights to the instances in dataset. Due to this the algorithm needs to pay less attention to the instances while constructing subsequent models.
In the following Python recipe, we are going to build Ada Boost ensemble model for classification by using AdaBoostClassifier class of sklearn on Pima Indians diabetes dataset.
First, import the required packages as follows −
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import AdaBoostClassifier
Now, we need to load the Pima diabetes dataset as did in previous examples −
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
Next, give the input for 10-fold cross validation as follows −
seed = 5
kfold = KFold(n_splits = 10, random_state = seed)

We need to provide the number of trees we are going to build. Here we are building 150 trees with split points chosen from 5 features −
num_trees = 50

Next, build the model with the help of following script −
model = AdaBoostClassifier(n_estimators = num_trees, random_state = seed)

Calculate and print the result as follows −
results = cross_val_score(model, X, Y, cv = kfold)
print(results.mean())

Output
0.7539473684210527

The output above shows that we got around 75% accuracy of our AdaBoost classifier ensemble model.

    168 Lectures 
     13.5 hours 

 Er. Himanshu Vasishta

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions

    91 Lectures 
     10 hours 

 Abhilash Nelson

    54 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     4 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Python Program to Find the Second Largest Number in a List Using Bubble Sort

When it is required to find the second largest number in a list using bubble sort, a method named ‘bubble_sort’ is defined, that sorts the elements of the list. Once this is done, another method named ‘get_second_largest’ is defined that returns the second element from the end as output.
Below is the demonstration of the same −
 Live Demo
my_list = []
my_input = int(input("Enter the number of elements..."))
for i in range(1,my_input+1):
   b=int(input("Enter the element..."))
   my_list.append(b)
for i in range(0,len(my_list)):
   for j in range(0,len(my_list)-i-1):
      if(my_list[j]>my_list[j+1]):
         temp=my_list[j]
         my_list[j]=my_list[j+1]
         my_list[j+1]=temp
print('The second largest element is:')
print(my_list[my_input-2])
Enter the number of elements...5
Enter the element...1
Enter the element...4
Enter the element...9
Enter the element...11
Enter the element...0
The second largest element is:
9
An empty list is defined.
An empty list is defined.
The number of elements is taken by user.
The number of elements is taken by user.
The elements are entered by the user.
The elements are entered by the user.
The list is iterated over, and the elements are appended to the list.
The list is iterated over, and the elements are appended to the list.
The elements of the list are sorted using bubble sort.
The elements of the list are sorted using bubble sort.
The second element from the last is displayed as output on the console.
The second element from the last is displayed as output on the console.
SortedMap Interface in C#

Java has SortedMap Interface, whereas an equivalent of it in C# is SortedList.
SortedList collection in C# use a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
Let us see an example to work with SortedList and display the keys −
 Live Demo
using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         SortedList sl = new SortedList();
         sl.Add("ST0", "One");
         sl.Add("ST1", "Two");
         sl.Add("ST2", "Three");
         ICollection key = sl.Keys;

         foreach(string k in key) {
            Console.WriteLine(k);
         }
      }
   }
}
ST0
ST1
ST2
C Program to count the Number of Characters in a File - GeeksforGeeks

29 May, 2019
Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat.
Determining character limits become crucial when the tweet and Facebook post updates are being done through API’s.
Note: This program would not run on online compilers. Please make a text (.txt) file on your system and give its path to run this program on your system.
Approach: The characters can be counted easily by reading the characters in the file using getc() method. For each character read from the file, increment the counter by one.
Below is the implementation of the above approach:
Program:
// C Program to count// the Number of Characters in a Text File  #include <stdio.h>#define MAX_FILE_NAME 100  int main(){    FILE* fp;      // Character counter (result)    int count = 0;      char filename[MAX_FILE_NAME];      // To store a character read from file    char c;      // Get file name from user.    // The file should be either in current folder    // or complete path should be provided    printf("Enter file name: ");    scanf("%s", filename);      // Open the file    fp = fopen(filename, "r");      // Check if file exists    if (fp == NULL) {        printf("Could not open file %s",               filename);        return 0;    }      // Extract characters from file    // and store in character c    for (c = getc(fp); c != EOF; c = getc(fp))          // Increment count for this character        count = count + 1;      // Close the file    fclose(fp);      // Print the count of characters    printf("The file %s has %d characters\n ",           filename, count);      return 0;}
Note: The text file used to run this code can be downloaded from here
C-File Handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Multiple Inheritance in C++
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
How to split a string in C/C++, Python and Java?
UDP Server-Client implementation in C
How to open a port in the Windows Operating System using PowerShell?

To open a port in the Windows Operating system, we need to know a few things. Like
For which Profile we need to open port (Public, private, or Domain)? - Optional
For which Profile we need to open port (Public, private, or Domain)? - Optional
Which port do we need to open (port Number)?
Which port do we need to open (port Number)?
The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests).
The direction of the port – Inbound (i.e Incoming requests) or Outbound (i.e. Outgoing requests).
Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255).
Protocol by name (TCP, UDP, ICMPv4, or ICMPv6) or Number (0-255).
Once we have all the details we can open the port. In the below example, we need to open a port 5985 (WINRM HTTP) port on the computer which is currently blocked. So we will use the below command.
New-NetFirewallRule -DisplayName "Allow WINRM HTTP Port" `
                    -Direction Outbound `
                    -LocalPort 5985 `
                    -Protocol TCP `
                    -Action Allow
To open multiple ports,
New-NetFirewallRule -DisplayName "Allow web ports" `
                    -Direction Outbound `
                    -LocalPort 80,8080 `
                    -Protocol TCP `
                    -Action All


Once you open the Firewall settings, you can check the ports are listed in the allowed list.
To perform the same settings on the remote computer, you need to use the Invoke-Command cmdlet. Make sure that the remote computer is accessible and has the WINRM connectivity before opening the port on the remote computer.
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{
    New-NetFirewallRule -DisplayName "Allow web ports" `
    -Direction Outbound `
    -LocalPort 80,8080 `
    -Protocol TCP `
    -Action All
}
If we don’t specify Direction (Inbound or Outbound), both directions ports will be opened by default.
What is Shallow Copy and how it is different from Deep Copy in C#?

Shallow Copy −
A shallow copy of an object copies the "main" object, but doesn’t copy the inner
objects.
The "inner objects" are shared between the original object and its copy.
The problem with the shallow copy is that the two objects are not independent. If you
modify the one object, the change will be reflected in the other object.
Deep Copy −
A deep copy is a fully independent copy of an object. If we copied our object, we
would copy the entire object structure.
If you modify the one object, the change will not be reflected in the other object.
class Program{
   static void Main(string[] args){
      //Shallow Copy
      ShallowCopy obj = new ShallowCopy();
      obj.a = 10;
      ShallowCopy obj1 = new ShallowCopy();
      obj1 = obj;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); // 10,10
      obj1.a = 5;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); //5,5
      //Deep Copy
      DeepCopy d = new DeepCopy();
      d.a = 10;
      DeepCopy d1 = new DeepCopy();
      d1.a = d.a;
      Console.WriteLine("{0} {1}", d1.a, d.a); // 10,10
      d1.a = 5;
      Console.WriteLine("{0} {1}", d1.a, d.a); //5,10
      Console.ReadLine();
   }
}
class ShallowCopy{
   public int a = 10;
}
class DeepCopy{
   public int a = 10;
}
10 10
5 5
10 10
5 10
Tryit Editor v3.7

Tryit basic HTML paragraphs
C# Example for Single Inheritance

The following is an example of Single Inheritance in C#. In the example, the base class is Father and declared like the following code snippet −
class Father {
   public void Display() {
      Console.WriteLine("Display");
   }
}
Our derived class is Son and is declared below −
class Son : Father {
   public void DisplayOne() {
      Console.WriteLine("DisplayOne");
   }
}
The following is the complete example to implement Single Inheritance in C#.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyAplication {
   class Demo {
      static void Main(string[] args) {
         // Father class
         Father f = new Father();
         f.Display();
         // Son class
         Son s = new Son();
         s.Display();
         s.DisplayOne();

         Console.ReadKey();
      }
      class Father {
         public void Display() {
            Console.WriteLine("Display");
         }
      }
      class Son : Father {
         public void DisplayOne() {
            Console.WriteLine("DisplayOne");
         }
      }
   }
}
Display
Display
DisplayOne
HTML | <textarea> rows Attribute

16 Oct, 2019
The HTML textarea rows Attribute is used to specify the number of visible text lines for the control i.e the number of rows to display. It also specifies the visible height of the Textarea.
Syntax:
<textarea rows = "value">
Attribute Values:
number: It specify the height of the Textarea. Its Default value is 2.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML Textarea rows Attribute    </title></head>  <body>    <center>        <h1 style="color: green;">             GeeksforGeeks         </h1>          <h2>             HTML Textarea rows Attribute         </h2>          <!-- Below textarea element has rows             attribute assigned to 5 -->        <textarea rows="5" cols="23">            This paragraph has number           of rows equal to 5.        </textarea>    </center></body>  </html>
Output:
Supported Browsers: The browsers supported by HTML textarea rows Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
shubham_singh
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM Input Password pattern Property

08 Mar, 2019
The Input password pattern Property in HTML DOM is used to set or return the value of pattern attribute of a Password Field. This attribute is used to specify the regular expression on which the input elements value is checked against. Use the Global title attribute to describe the pattern for helping the user.
Syntax:
It returns the Input password pattern Property.passwordObject.pattern
passwordObject.pattern
It is used to set the Input password pattern Property.passwordObject.pattern = regexp
passwordObject.pattern = regexp
Property Values: It accepts single value regexp which is used to specify the regular expression that a password field value is checked against.
Return Value: It returns a string value which represents the regular expression that a password field value is checked against.
Example: This example describes the use of Input password pattern Property.
<!DOCTYPE html> <html>   <head>    <title>        HTML DOM Input Password pattern Property    </title></head>  <body style="text-align:center;">       <h1 style="color:green;">             GeeksForGeeks         </h1>       <h2>DOM Input Password pattern Property</h2>           <form id="myGeeks">        Password: <input type="password" id="myPsw" name="Geeks"            pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2, 3}$" >    </form>          <br><br>          <button onclick="myFunction()">         Click Here!     </button>       <p id="demo" style="color:green;font-size:25px;"></p>           <!-- Script to use Input Password pattern Property -->    <script>         function myFunction() {             var x =             document.getElementById(             "myPsw").pattern;                          document.getElementById(             "demo").innerHTML = x;        }     </script> </body>   </html>                            
Output:Before Clicking the Button:After Clicking the Button:
Supported Browsers: The browser supported by DOM input Password pattern Property are listed below:
Google Chrome
Internet Explorer 10.0
Firefox
Opera
Safari
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
JavaScript performance.now() Method

29 Oct, 2021
In JavaScript performance.now() method can be used to check the performance of your code. You can check the execution time of your code using this method.
It returns the value of time (of type double) in milliseconds. The returned value represents the time elapsed since the execution started.
Syntax:
let t = performance.now();
The code below will give you a brief idea of how this code performs.
Example 1:
Javascript
<script>  const t0 = performance.now();  for (let i = 0; i < 10; i++) {    console.log(i);  }  const t1 = performance.now();  console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script>
Output: In the above code, variables t0 and t1 are used to store starting time and ending time respectively, and while printing we subtracted t0 from t1 to print the time required in the execution of the code.
0
1
2
3
4
5
6
7
8
9
"Call to doSomething took 1.7899998929351568 milliseconds."
Example 2:
Javascript
<script>  const t0 = performance.now();  for (let i = 0; i < 5; i++) {    console.log(i);  }  const t1 = performance.now();  console.log(`Call to doSomething took ${t1 - t0} milliseconds.`);</script>
Output:
0
1
2
3
4
"Call to doSomething took 0.7100000511854887 milliseconds."
prachisoda1234
JavaScript-Methods
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
Lodash _.groupBy() Method
What is #if DEBUG and How to use it in C#?

In Visual Studio Debug mode and Release mode are different configurations for building your .Net project.
Select the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe).
The Debug mode does not optimize the binary it produces because the relationship between source code and generated instructions is more complex.
This allows breakpoints to be set accurately and allows a programmer to step through the code one line at a time.
The Debug configuration of your program is compiled with full symbolic debug information which help the debugger figure out where it is in the source code
The release configuration of your program has no symbolic debug information and is fully optimized.
From the Build menu, select Configuration Manager, then select Debug or Release.
or
On the toolbar, choose either Debug or Release from the Solution Configurations list
The code which is written inside the #if debug will be executed only if the code is running inside the debug mode
If the code is running in the release mode then the #if Debug will be false and it will not execute the code present inside this
class Program {
   static void Main() {
      #if DEBUG
      Console.WriteLine("You are in debug");
      #endif
      Console.ReadKey();
   }
}
If the Program is running in the debug mode then the If bloc will return true
And prints "You are in debug"
If the program is not in the debug mode then If Debug return false
SQL | SELECT data from Multiple Tables

17 Aug, 2020
Below statement could be used to get data from multiple tables, so, we need to use join to get data from multiple tables.
Syntax :
SELECT tablenmae1.colunmname, tablename2.columnnmae    
FROM tablenmae1  
JOIN tablename2  
ON tablenmae1.colunmnam = tablename2.columnnmae
ORDER BY columnname;  

Let us take three tables, two tables of customers named Geeks1, Geeks2 and Geeks3.
Geeks1 table :
Geeks2 table :
Geeks3 table :
Example to select from multiple tables :
SELECT Geeks3.GID, Geeks3.PID, 
       Geeks3.Asset, Geeks1.FirstName, 
       Geeks2.LastName  
FROM Geeks3
LEFT JOIN Geeks1 
ON Geeks3.GID = Geeks1.ID
LEFT JOIN Geeks2 
ON Geeks3.GID = Geeks2.ID  
Output :
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Introduction of DBMS (Database Management System) | Set 1
Difference between Clustered and Non-clustered index
SQL Trigger | Student Database
Introduction of B-Tree
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
SQL Trigger | Student Database
Check if a given year is leap year in PL/SQL - GeeksforGeeks

02 Jul, 2018
Prerequisite – PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a year, the task is to check that given year is a leap year or not.
Examples:
Input: 1500
Output: 1500 is not leap year.

Input: 1600
Output: 1600 is a leap year

A year is a leap year if following conditions are satisfied:1) Year is multiple of 4002) Year is multiple of 4 and not multiple of 100
-- To check if a-- given year is leap year or notDECLARE  year NUMBER := 1600;BEGIN  --  true if the year is a multiple  -- of 4 and not multiple of 100.  -- OR year is multiple of 400.  IF MOD(year, 4)=0    AND    MOD(year, 100)!=0    OR    MOD(year, 400)=0 THEN    dbms_output.Put_line(year    || ' is a leap year ');  ELSE    dbms_output.Put_line(year    || ' is not a leap year.');  END IF;END; 
Output:
1600 is a leap year.

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
How to Clear RAM Memory Cache, Buffer and Swap Space on Linux - GeeksforGeeks

30 May, 2021
In this article, we will see How to Clear RAM Memory Cache, Buffer, and Swap Space on Linux. In every system we do come across caches that have unwanted files and can harm our system, the same thing happens in Linux cache and if you want to clear the cache and free some memory then Linux has many commands to do that.
In all the Linux systems we have three options to clear cache without interrupting any services or processes.
Example 1: To Clear PageCache only
Syntax :
sudo sh -c 'echo 1 >  /proc/sys/vm/drop_caches'
The command # free -h will give us the status of the memory 
drop_caches is used a clean cache without killing any application, you can run the # free -h command to see the difference between used and free memory before and after clearing the cache
Example 2: To Clear dentries and inodes
Syntax:
sudo sh -c 'echo 2 >  /proc/sys/vm/drop_caches' 
Example 3: To Clear PageCache, dentries and inodes
Syntax:
sudo sh -c 'echo 3 >  /proc/sys/vm/drop_caches'  
Now using Linux Kernel, to free Buffer and Cache in Linux we will Create a shell script to auto clear RAM cache daily, through a cron scheduler task., the command vim script.sh is used to create a shell script “script.sh”
Now in script, you have to add the below syntax:
echo " echo 3 >  /proc/sys/vm/drop_caches"
Now to set run permission, to clear ram cache, you have to call the script whenever required, setting a cron to clear RAM caches every day for 3 hours.
# chmod 755 script.sh
# crontab -e
Example 4: To Clear Swap Space in Linux
You can clear the swap space by running the below command 
Syntax :
sudo swapoff -a

sudo swapon -a
You can run the # free -h command to see the difference between used and free memory before and after clearing the swap space
Add the above command to a cron script, Here we are going to combine this two different command into one single command, to form a proper script which will help us to clear Swap Space and RAM Cache.
echo 3 >  /proc/sys/vm/drop_caches & &  swapoff -a & &  swapon -a & &  printf ‘\n%s\n’  ‘  ‘ Ram-cache and the swap get cleared’
Now  Ram cache and swap will be cleared you can run # free -h command to see
After running the command you will get output like this 
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
echo command in Linux with Examples
Compiling with g++
GATE | GATE CS 2013 | Question 47 - GeeksforGeeks

28 Jun, 2021
(A) A(B) B(C) C(D) DAnswer: (A) (D)Explanation:  
Given statement is :
¬ ∃ x ( ∀y(α) ∧ ∀z(β) )
where ¬ is a negation operator, ∃ is Existential Quantifier with the 
meaning of "there Exists", and ∀ is a Universal Quantifier 
with the meaning   " for all " , and α, β can be treated as predicates.

here we can apply some of the standard 
results of Propositional and 1st order logic on the given statement, 
which are as follows :

[ Result 1 : ¬(∀x P(x)) <=> ∃ x¬P(x), i.e. negation 
of "for all" gives "there exists" and negation also gets applied to scope of 
quantifier, which is P(x) here. And also negation of "there exists" gives "for all", 
and negation also gets applied to scope of quantifier  ]

[ Result 2 :  ¬ ( A ∧ B ) = ( ¬A  ∨ ¬B )  ]

[ Result 3 :  ¬P  ∨ Q <=> P -> Q ]

[ Result 4 : If P ->Q, then by Result of Contrapositive,  ¬Q -> ¬P  ]


Now we need to use these results as shown below:

 

¬ ∃ x ( ∀y(α) ∧ ∀z(β) )                 [ Given ]

=> ∀ x (¬∀y(α) ∨ ¬∀z(β) )          [ after applying Result 1 & Result 2 ]

=> ∀ x ( ∀y(α) -> ¬∀z(β) )     [after applying Result 3 ]

=> ∀ x ( ∀y(α) -> ∃z(¬β) )      [after applying Result 1]

which is same as the statement C. 

Hence the Given Statement is logically Equivalent
to the statement C.

Now, we can also prove that given statement is logically equivalent to the statement
 in option  B.

Let's see how !

The above derived statement is :

∀ x ( ∀y(α) -> ∃z(¬β) )

Now this statement can be written as (or equivalent to) :

=> ∀ x ( ∀z(β) -> ∃y(¬α) )     [after applying Result 4 ]

And this statement is same as statement B. 
Hence the Given statement is also logically equivalent 
to the statement B.

So, we can conclude that the Given statement is NOT logically equivalent to the 
statements A and D.

Hence, the correct answer is Option A and Option D. But in GATE 2013, markswere given to all for this question.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Full Subtractor in Digital Logic - GeeksforGeeks

25 Nov, 2019
A full subtractor is a combinational circuit that performs subtraction of two bits, one is minuend and other is subtrahend, taking into account borrow of the previous adjacent lower minuend bit. This circuit has three inputs and two outputs. The three inputs A, B and Bin, denote the minuend, subtrahend, and previous borrow, respectively. The two outputs, D and Bout represent the difference and output borrow, respectively.
Truth Table –
From above table we can draw the K-Map as shown for “difference” and “borrow”.
Logical expression for difference –
D   = A’B’Bin + A’BBin’ + AB’Bin’ + ABBin
    = Bin(A’B’ + AB)  + Bin’(AB’ + A’B)
    = Bin( A XNOR B) + Bin’(A XOR B)
    = Bin (A XOR B)’  +  Bin’(A XOR B)
    = Bin XOR (A XOR B)
    = (A XOR B) XOR Bin

Logical expression for borrow –
Bout = A’B’Bin + A’BBin’ + A’BBin + ABBin      
     = A’B’Bin +A’BBin’ + A’BBin + A’BBin + A’BBin + ABBin
     = A’Bin(B + B’) + A’B(Bin + Bin’) + BBin(A + A’)
     = A’Bin + A’B + BBin

OR

Bout = A’B’Bin + A’BBin’ + A’BBin + ABBin      
     = Bin(AB + A’B’) + A’B(Bin + Bin’)
     = Bin( A XNOR B) + A’B
     = Bin (A XOR B)’ + A’B

Logic Circuit for Full Subtractor –
Implementation of Full Subtractor using Half Subtractors –2 Half Subtractors and an OR gate is required to implement a Full Subtractor.
Reference – Full Subtractor – Wikipedia
This article is contributed by Harshita Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Difference between RAM and ROM
Introduction to memory and memory units
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Python | Pandas Series.sample() - GeeksforGeeks

07 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.sample() function return a random sample of items from an axis of object. We can also use random_state for reproducibility.
Syntax: Series.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Parameter :n : Number of items from axis to return.frac : Fraction of axis items to return.replace : Sample with or without replacement.weights : Default ‘None’ results in equal probability weighting.random_state : Seed for the random number generator (if int), or numpy RandomState object.axis : Axis to sample.
Returns : Series or DataFrame
Example #1: Use Series.sample() function to draw random sample of the values from the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.sample() function to draw a random sample of values from the given Series object.
# Draw random sample of 3 valuesselected_cities = sr.sample(n = 3)  # Print the returned Series objectprint(selected_cities)
Output :As we can see in the output, the Series.sample() function has successfully returned a random sample of 3 values from the given Series object. Example #2: Use Series.sample() function to draw random sample of the values from the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.sample() function to select a random sample of size equivalent to 25% of the size of the given Series object.
# Draw random sample of size of 25 % of the original objectselected_items = sr.sample(frac = 0.25)  # Print the returned Series objectprint(selected_items)
Output :
As we can see in the output, the Series.sample() function has successfully returned a random sample of 2 values from the given Series object, which is 25% of the size of the original series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to plot half or quarter polar plots in Matplotlib?

To plot half or quarter polar plots in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add an axes to the figure as part of a subplot arrangement.
Add an axes to the figure as part of a subplot arrangement.
For half or quarter polar plots, use set_thetamax() method.
For half or quarter polar plots, use set_thetamax() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt

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

fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")
max_theta = 90
ax.set_thetamax(max_theta)
plt.show()
Reference to a constructor using method references in Java8

Lambda expressions In Java allows you to pass functionality as an argument to a
method. You can also call an existing method using lambda expressions.
list.forEach(n -> System.out.println(n));
Method references are simple, easy-to-read lambda expressions to call/refer and the existing method by name in a lambda expression. In addition to the instance and static methods, you can also refer a constructor by using the new keyword.
Following is the syntax to reference a constructor in Java.
ClassName::new
interface myInterface{
   Test greet(String data);
}
class Test{
   Test(String data){
         System.out.println(data);
   }
}
public class MethodReferences {
   public static void main(String args[]) {
      myInterface in = Test::new;
      in.greet("Welcome to Tutorilspoint");
   }
}
Welcome to Tutorilspoint
Which MySQL Data Type can be used to store Negative Number?

You can use TINYINT data type in MySQL to store negative number. Following is the syntax −
CREATE TABLE yourTableName
   (

   yourColumnName TINYINT
   .
   .
   .
   .
   N
   );
Let us first create a table with a column set as type TINYINT −
mysql> create table DemoTable
   (

   Number tinyint
   );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values(-128);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values(128);
ERROR 1264 (22003): Out of range value for column 'Number' at row 1

mysql> insert into DemoTable values(127);
Query OK, 1 row affected (0.23 sec)

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

mysql> insert into DemoTable values(14);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+
| Number |
+--------+
|    -10 |
|   -128 |
|    127 |
|     -1 |
|     14 |
+--------+
5 rows in set (0.00 sec)
RAPTOR Tool - A Flowchart Interpreter - GeeksforGeeks

09 Feb, 2018
RAPTOR(Rapid Algorithmic Prototyping Tool for Ordered Reasoning) is a free graphical authoring tool created by Martin C. Carlisle, Terry Wilson, Jeff Humphries and Jason Moore, designed specifically to help students visualize their algorithms and avoid syntactic baggage.Students can create flow-chart for a particular program and raptor tool will generate code for it in various programming languages, such as C, C++, Java and so on.
Symbols in RAPTOR
Raptor has 6 types of symbols, each of which represents a unique kind of instruction. They are – Assignment, Call, Input, Output, Selection and Loop symbols. The following image shows these symbols-
RAPTOR Program Structure
A RAPTOR program consists of connected symbols that represent actions to be executed.
The arrows that connect the symbols determine the order in which the actions are performed.The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program.The program stops executing when the End symbol is reached.
The arrows that connect the symbols determine the order in which the actions are performed.
The execution of a RAPTOR program begins at the Start symbol and goes along the arrows to execute the program.
The program stops executing when the End symbol is reached.
With the help of Generate option, the generated C++ code for the above flow chart is:
// CPP program for illustrating RAPTOR#include <iostream>#include <string>  using namespace std;int main(){   string raptor_prompt_variable_zzyz;   float m;     raptor_prompt_variable_zzyz ="enter the marks";   cout << raptor_prompt_variable_zzyz << endl;   cin >> m;   if (m>=90)   {      cout << "The grade is A" << endl;   }   else   {      if (m>=80)      {         cout << "The grade is B" << endl;      }      else      {         if (m>=60)         {            cout << "The grade is C" << endl;         }         else         {            cout << "The grade is D" << endl;         }      }   }     return 0;}
In this way, any algorithm can be visualised by the students, and it can be converted into a code using the raptor tool.
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
6 Best IDE's For Python in 2022
A Freshers Guide To Programming
ML | Underfitting and Overfitting
Virtualization In Cloud Computing and Types
Top 10 Programming Languages to Learn in 2022
What is web socket and how it is different from the HTTP?
Top Selenium Frameworks You Should Know
Introduction to Hill Climbing | Artificial Intelligence
C# program to find all duplicate elements in an integer array

Firstly, set the array with duplicate elements.
int[] arr = {
   24,
   10,
   56,
   32,
   10,
   43,
   88,
   32
};
Now declare a Dictionary and loop through the array to get the repeated elements.
var d = new Dictionary < int, int > ();
foreach(var res in arr) {
   if (d.ContainsKey(res))
         d[res]++;
   else
   d[res] = 1;
}
 Live Demo
using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            24,
            10,
            56,
            32,
            10,
            43,
            88,
            32
         };
         var d = new Dictionary < int, int > ();
         foreach(var res in arr) {
            if (d.ContainsKey(res))
            d[res]++;
            else
            d[res] = 1;
         }
         foreach(var val in d)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}
24 occurred 1 times
10 occurred 2 times
56 occurred 1 times
32 occurred 2 times
43 occurred 1 times
88 occurred 1 times
How to create a zip file using Python?

Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively.
import os
import zipfile
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))
zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./my_folder', zipf)
zipf.close()
The above code will zip the contents of my_folder in a file 'Zipped_file.zip'. and store it in the current directory.
Redis - Keys Ttl Command

Redis TTL command is used to get the remaining time of the key expiry in seconds.
Integer value TTL in milliseconds, or a negative value.
TTL in milliseconds.
-1, if key does not have expiry timeout.
-2, if key does not exist.
Following is the basic syntax of Redis TTL command.
redis 127.0.0.1:6379> TTL KEY_NAME 

First, create a key in Redis and set some value in it.
redis 127.0.0.1:6379> SET tutorialname redis 
OK 

Now, set the expiry of the key, and later check the remaining expiry time.
redis 127.0.0.1:6379> EXPIRE tutorialname 60 
1) (integer) 1 
redis 127.0.0.1:6379> TTL tutorialname 
1) (integer) 59


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
jsoup - Extract HTML

Following example will showcase use of methods to get inner html and outer html after parsing an HTML String into a Document object.
Document document = Jsoup.parse(html);
Element link = document.select("a").first();         

System.out.println("Outer HTML: " + link.outerHtml());
System.out.println("Inner HTML: " + link.html());

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
Jsoup − main class to parse the given HTML String.
html − HTML String.
html − HTML String.
link − Element object represent the html node element representing anchor tag.
link − Element object represent the html node element representing anchor tag.
link.outerHtml() − outerHtml() method retrives the element complete html.
link.outerHtml() − outerHtml() method retrives the element complete html.
link.html() − html() method retrives the element inner html.
link.html() − html() method retrives the element inner html.
Element object represent a dom elment and provides various method to get the html of a dom element.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content</p>"
         + "<div id='sampleDiv'><a href='www.google.com'>Google</a>"
         + "<h3><a>Sample</a><h3>"
         +"</div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      //a with href
      Element link = document.select("a").first();         

      System.out.println("Outer HTML: " + link.outerHtml());
      System.out.println("Inner HTML: " + link.html());
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Outer HTML: <a href="www.google.com">Google</a>
Inner HTML: Google

 Print
 Add Notes
 Bookmark this page
How to create full-page tabs with CSS and JavaScript?

To create full-page tabs with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
body, html {
   height: 100%;
   margin: 0;
}
.tablink {
   background-color: #555;
   color: white;
   float: left;
   border: none;
   outline: none;
   cursor: pointer;
   padding: 10px 14px;
   font-size: 15px;
   width:33.33%;
}
.tablink:hover {
   background-color: black;
}
.tabcontent {
   color: white;
   display: none;
   padding: 100px 20px;
   height: 100%;
}
#Home {background-color: blue;}
#About {background-color: gray;}
#Contact {background-color: orange;}
</style>
</head>
<body>
<button class="tablink" onclick="demo('Home', this, 'blue')">Home</button>
<button class="tablink" onclick="demo('About', this, 'gray')" id="clickme">About</button>
<button class="tablink" onclick="demo('Contact', this, 'orange')">ContactUs</button>
<div id="Home" class="tabcontent">
   <h3>Home</h3>
   <p>This is the Home page.</p>
</div>
<div id="About" class="tabcontent">
   <h3>About</h3>
   <p>This is information about the company.</p>
</div>
<div id="Contact" class="tabcontent">
   <h3>ContactUs</h3>
   <p>Contact us for any feedback, query and complaints.</p>
</div>
<script>
function demo(pageName,elmnt,color) {
   var i, tabcontent, tablinks;
   tabcontent = document.getElementsByClassName("tabcontent");
   for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
   }
   tablinks = document.getElementsByClassName("tablink");
   for (i = 0; i < tablinks.length; i++) {
      tablinks[i].style.backgroundColor = "";
   }
   document.getElementById(pageName).style.display = "block";
   elmnt.style.backgroundColor = color;
}
document.getElementById("clickme").click();
</script>
</body>
</html>
This will produce the following output −
Let’s now click the “ContactUs” tab −