code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas DataFrame.isin()

17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas isin() method is used to filter data frames. isin() method helps in selecting rows with having a particular(or Multiple) value in a particular column.
Syntax: DataFrame.isin(values)
Parameters:values: iterable, Series, List, Tuple, DataFrame or dictionary to check in the caller Series/Data Frame.
Return Type: DataFrame of Boolean of Dimension.
To download the CSV file used, Click Here.
Example #1: Single Parameter filteringIn the following Example, Rows are checked and a boolean series is returned which is True wherever Gender=”Male”. Then the series is passed to data frame to see new filtered data frame.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # creating a bool series from isin()new = data["Gender"].isin(["Male"])  # displaying data with gender = male onlydata[new]
Output:As shown in the output image, only Rows having gender = “Male” are returned.
 
Example #2: Multiple parameter FilteringIn the following example, the data frame is filtered on the basis of Gender as well as Team. Rows having Gender=”Female” and Team=”Engineering”, “Distribution” or “Finance” are returned.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # creating filters of bool series from isin()filter1 = data["Gender"].isin(["Female"])filter2 = data["Team"].isin(["Engineering", "Distribution", "Finance" ])  # displaying data with both filter applied and mandatory data[filter1 & filter2]
Output:As shown in the output image, Rows having Gender=”Female” and Team=”Engineering”, “Distribution” or “Finance” are returned.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How to remove an object from a list in Python?

You can use 3 different methods to remove an object from a list in Python. They are remove, del and pop. You can use them as follows −
The remove method removes the first value matching the argument to remove from the list, not a specific index. 
a = [3, 2, 3, 2]
a.remove(3)
print(a)
This will give the output −
[2, 3, 2]
The del method removes a specific index from the list. 
a = [3, "Hello", 2, 1]
del a[1]
print(a)
This will give the output −
[3, 2, 1]
The pop method returns the removed element. The argument to pop is the index you want to remove.
a = [3, "Hello", 2, 1]
print(a.pop(1))
print(a)
This will give the output −
"Hello"
[3, 2, 1]
Perl tr Function

This is not a function. This is the transliteration operator; it replaces all occurrences of the characters in SEARCHLIST with the characters in REPLACEMENTLIST.
Following is the simple syntax for this function −
tr/SEARCHLIST/REPLACEMENTLIST/

This function returns number of characters replaced or deleted.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;

print "$string\n";
When above code is executed, it produces the following result. Here option d is used to delete matched characters.
 b b   b.
JasmineJS - Matchers

Jasmine is a testing framework, hence it always aims to compare the result of the JavaScript file or function with the expected result. Matcher works similarly in Jasmine framework.
Matchers are the JavaScript function that does a Boolean comparison between an actual output and an expected output. There are two type of matchers Inbuilt matcher and Custom matchers.
The matchers which are inbuilt in the Jasmine framework are called inbuilt matcher. The user can easily use it implicitly.
The following example shows how Inbuilt Matcher works in Jasmine framework. We have already used some matchers in the previous chapter.
describe("Adding single number ", function () {  

   //example of toEqual() matcher    
   it("should add numbers",function() { 
      expect(nested.add(5)).toEqual(5); 
      expect(nested.add(5)).toEqual(10); 
   });   
   
   it("should add numbers",function() { 
      expect(nested.addAny(1,2,3)).toEqual(6); 
   });
}
In the example toEqual() is the inbuilt matcher which will compare the result of the add() and addAny() methods with the arguments passed to toEqual() matchers.
The matchers which are not present in the inbuilt system library of Jasmine is called as custom matcher. Custom matcher needs to be defined explicitly(). In the following example, we will see how the custom matcher works.
describe('This custom matcher example', function() {
   
   beforeEach(function() { 
      // We should add custom matched in beforeEach() function. 
      jasmine.addMatchers ({ 
         validateAge: function() { 
            Return {    
               compare: function(actual,expected) {
                  var result = {}; 
                  result.pass = (actual > = 13 && actual < = 19);
                  result.message = 'sorry u are not a teen ';
                  return result; 
               }   
            };   
         }    
      });    
   }); 
    
   it('Lets see whether u are teen or not', function() { 
      var myAge = 14; 
      expect(myAge).validateAge();         
   });   
    
   it('Lets see whether u are teen or not ', function() { 
      var yourAge = 18;
      expect(yourAge).validateAge();  
   });
});
In the above example, validateAge() works as a matcher which is actually validating your age with some range. In this example, validateAge() works as a custom matcher. Add this JS file into SpecRunner.html and run the same. It will generate the following output.
Python – Similar characters Strings comparison

02 Sep, 2020
Given two Strings, separated by delim, check if both contain same characters.
Input : test_str1 = ‘e!e!k!s!g’, test_str2 = ‘g!e!e!k!s’, delim = ‘!’Output : TrueExplanation : Same characters, just diff. positions.
Input : test_str1 = ‘e!e!k!s’, test_str2 = ‘g!e!e!k!s’, delim = ‘!’Output : FalseExplanation : g missing in 1st String.
Method #1 : Using sorted() + split()
In this, we perform split using split(), and then perform task of sorting to get strings in order, post that strings are compared using the comparison operator.
Python3
# Python3 code to demonstrate working of # Similar characters Strings comparison# Using split() + sorted()  # initializing stringstest_str1 = 'e:e:k:s:g'test_str2 = 'g:e:e:k:s'  # printing original stringsprint("The original string 1 is : " + str(test_str1))print("The original string 2 is : " + str(test_str2))  # initializing delim delim = ':'  # == operator is used for comparisonres = sorted(test_str1.split(':')) == sorted(test_str2.split(':'))      # printing result print("Are strings similar : " + str(res)) 
The original string 1 is : e:e:k:s:g
The original string 2 is : g:e:e:k:s
Are strings similar : True


Method #2 : Using set() + split()
In this, instead of sort(), we convert strings to set(), to get ordering. This works only on unique character strings.
Python3
# Python3 code to demonstrate working of # Similar characters Strings comparison# Using set() + split()  # initializing stringstest_str1 = 'e:k:s:g'test_str2 = 'g:e:k:s'  # printing original stringsprint("The original string 1 is : " + str(test_str1))print("The original string 2 is : " + str(test_str2))  # initializing delim delim = ':'  # == operator is used for comparison# removes duplicates and comparesres = set(test_str1.split(':')) == set(test_str2.split(':'))      # printing result print("Are strings similar : " + str(res)) 
The original string 1 is : e:k:s:g
The original string 2 is : g:e:k:s
Are strings similar : True


Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Set | update()

08 Oct, 2021
Python update() function in set adds elements from a set (passed as an argument) to the set. 
Syntax :  set1.update(set2) 
Here set1 is the set in which set2 will be added.
Parameters : Update() method takes only a single argument. The single argument can be a set, list, tuples or a dictionary. It automatically converts into a set and adds to the set. 
Return value : This method adds set2 to set1 and returns nothing. 
Python3
# Python program to demonstrate the# use of update() method list1 = [1, 2, 3]list2 = [5, 6, 7]list3 = [10, 11, 12] # Lists converted to setsset1 = set(list2)set2 = set(list1) # Update methodset1.update(set2) # Print the updated setprint(set1) # List is passed as an parameter which# gets automatically converted to a setset1.update(list3)print(set1)
Output : 
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}
Python3
# Python program to demonstrate the# use of update() method list1 = [1, 2, 3, 4]list2 = [1, 4, 2, 3, 5]alphabet_set = {'a', 'b', 'c'} # lists converted to setsset1 = set(list2)set2 = set(list1) # Update methodset1.update(set2) # Print the updated setprint(set1) set1.update(alphabet_set)print(set1)
Output : 
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}
Python3
number = {1, 2, 3, 4, 5} num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight',            9: 'Nine', 10: 'Ten'} number.update(num_Dict) print("Updated set: ", number)
Output:
Updated set:  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
kumar_satyam
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Matplotlib - Contour Plot

Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as contours. These contours are sometimes called the z-slices or the iso-response values.
A contour plot is appropriate if you want to see how alue Z changes as a function of two inputs X and Y, such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value.
The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values.
Matplotlib API contains contour() and contourf() functions that draw contour lines and filled contours, respectively. Both functions need three parameters x,y and z.
import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp) # Add a colorbar to a plot
ax.set_title('Filled Contours Plot')
GATE | GATE-CS-2016 (Set 2) | Question 42

29 Sep, 2021
The width of the physical address on a machine is 40 bits. The width of the tag field in a 512 KB 8-way set associative cache is ____________ bits(A) 24(B) 20(C) 30(D) 40Answer: (A)Explanation: An easy approach would be we know that physical address is 40 bytes
We know cache size = no.of.sets*
                     lines-per-set*
                     block-size

Let us assume no of sets = 2^x 
And block size= 2^y

So applying it in formula.
2^19 = 2^x + 8 + 2^y;
So x+y = 16

Now we know that to address block size and 
set number we need 16 bits so remaining bits
must be for tag 
i.e., 40 - 16 = 24
The answer is 24 bits 
If question extends and asks as what is the size of comparator, we need then it is 24 bit comparator.
The above explanation is contributed by Sumanth Sunny
Alternate Explanation:
Physical Address Bits = T(Tag Bits) + S(Set Bits) + O(Offset Bits) = 40 bits    (given)
Set = 8    (given)
Size of cache = 512 KB     (given)

Size of lines = 512 / 8 = 64 KB 
So, O = 64/8 = 8 bits

Now, S + O = 8 + 8 = 16 bits
Hence, T = 40 - 16 = 24 bits 

This explanation is contributed by Mohit Gupta.

Refer the following links for more understanding in the above topic:

Cache Memory
Cache Organization | Introduction

Questions on Cache Mapping Techniques with Ashish Verma | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersQuestions on Cache Mapping Techniques with Ashish Verma | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0034:38 / 58:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lz3J33WzNOo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
Python – Update dictionary with other dictionary

10 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is a brute force way in which this task can be performed. In this, we check for keys in other dictionary, and add the items in new dictionary.
# Python3 code to demonstrate working of # Update dictionary with other dictionary# Using loop  # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}test_dict2 = {'for' : 3, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2))  # Update dictionary with other dictionary# Using loopfor key in test_dict1:    if key in test_dict2:        test_dict1[key] = test_dict2[key]  # printing result print("The updated dictionary is : " + str(test_dict1)) 
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6}The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5}The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}
 
Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we iterate for dictionary and perform update in single line using comprehension.
# Python3 code to demonstrate working of # Update dictionary with other dictionary# Using dictionary comprehension  # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}test_dict2 = {'for' : 3, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2))  # Update dictionary with other dictionary# Using dictionary comprehensionres = {key : test_dict2.get(key, val)  for key, val in test_dict1.items()}  # printing result print("The updated dictionary is : " + str(res)) 
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6}The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5}The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}
Python dictionary-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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
How to Install Packages in Python on Linux?

23 Sep, 2021
To install a package in python, we use pip. The pip is a python package manager. In this tutorial, we will be discussing how we can install packages in python on a Linux system.
To install packages in python on Linux, we must have python and pip installed on our Linux machine. As python comes preinstalled with the Linux system, we may have to install pip manually if we are using python 2.9 or below.
To install pip, follow the following methods:
sudo apt install pip
Step 1: Go through the following website and download the script.
https://bootstrap.pypa.io/get-pip.py
Or using the following command, you can download the python script to install pip:
wget https://bootstrap.pypa.io/get-pip.py
    Step 2: Run the script using python
python3 get-pip.py
Output:
installing pip
After installing pip, do the following steps to install a python package:
Step 1: Go through the following website and search for the package that you want to install and hit enter.
https://pypi.org/
For example, we are going to search for pandas. A popular library to manipulate CSV files.
installing pandas
Step 2: Click on the package that you want to install and copy the installation instruction.
installing pandas
Step 3: Now open up the terminal and paste the above-copied command and hit enter.
successfully installed pandas package
This will install the pandas package in python on your Linux machine.
To uninstall a package simply use the following command:
pip uninstall pandas
Here, pandas can be replaced with any other package name.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Laravel

25 Aug, 2021
What is Laravel ?
Laravel is a web application framework created by Taylor Otwell in 2011 and like all other modern frameworks, it also follows the Model-View-Controller (MVC) architectural pattern. Laravel values Elegance, Simplicity, and Readability and if one talks of building applications with PHP frameworks, Laravel is second to none.
Since Laravel is open-source, one can find the source code in its Github repository here. Also, the documentation for the framework can be found on the here.
 
What are Laracasts?
If you need help getting started with Laravel, you can right away start learning and developing using Laracasts which has hundreds of video tutorials on it. Skim the basics or start your journey to Laravel mastery, all from Laracasts!
Want to start now? Laravel 5.7 from Scratch Laracast link.What makes Laravel so special ?
Laravel is power-packed with its own ready-to-use first-party packages some of which are :
Scheduler: It includes support for scheduling periodically executed tasks.
Cashier: for managing subscription billing services.
Flysystem: allows remote storage to be used as in the same way as local file systems.
Socialite: simplified mechanism for OAuth authentication with providers like Facebook, Github, Google,  etc.
How good is Laravel ?
Let us now have a reality check on how good Laravel is as a web application framework based on a few key points :
 Language Support: PHP Version >= 5.5.9
 MVC Framework: Yes (from Laravel 2 onwards)
 Object Relational Mapping: Yes. Needed to enforce constraints on the relationship between database objects.
Testing: Yes. Unit Testing is provided as an integral part of Laravel that prevents regressions in the framework. PHPUnit
DataBase Migration: Yes. It helps in simplifying the deployment and updating of applications.
Security: Yes. SSH(Secure Shell )is used as an encrypted network protocol for execution of CLI(command-line interface) commands.
 Caching: Yes.
 Form Validation: Yes . Event listeners are bind internally which invokes the form validation methods and thus the actual form is generated.
 Scaffolding: Yes. In Laravel, the programmer can specify how the application database may be used.
 Rapid Application Development: Yes.
 Mobility: No.
Synopsis
Developer: Taylor Otwell
Language: PHP
Latest Stable Release: Laravel 6.0.0 (As of September 2019)
Operating System: Cross-platform
Framework Link: https://laravel.com/
Github Link : https://github.com/laravel/
Websites built using Laravel : Deltanet Travel , Neighbourhood Lender
Article By Harshit Gupta:Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks. You can reach him at https://in.linkedin.com/pub/harshit-gupta/102/b71/605
If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.
gurrrung
GBlog
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Update From One Table to Another Based on an ID Match

28 Oct, 2021
In this article, we will see, how to update from one table to another table based on ID match. We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.
UPDATE syntax:
UPDATE table_name
SET column_name = value
WHERE condition;
To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID.
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database.
Query(demo_table1):
CREATE TABLE demo_table1(
ID int,
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Query(demo_table2):
CREATE TABLE demo_table2(
ID int,
NAME VARCHAR(20),
AGE int);
Step 4: Insert data into a table
Query(demo_table1):
INSERT INTO demo_table1 VALUES
(1,'Romy',23,'Delhi'),
(2,'Rahul',23,'Delhi'),
(3,'Nikhil',24,'Punjab'),
(4,'Ranvir',23,'Punjab'),
(5,'Samiksha',23,'Banglore'),
(6,'Ashtha',24,'Banglore'),
(7,'Tannu',30,'Patna'),
(8,'Girish',30,'Patna'),
(9,'Ram', 20 , 'Patna'),
(10,'Raj', 12, 'Delhi');
Query(demo_table2):
INSERT INTO demo_table2 VALUES
(3,'Fanny',25 ),
(7,'Prem', 30),
(1,'Preeti',21),
(4,'Samita',32);
Step 5: View the content
Execute the below query to see the content of the table
Query(demo_table1):
SELECT * FROM demo_table1;
Output:
Query(demo_table2):
SELECT * FROM demo_table2;
Step 6: Update demo_table1 data from demo_table2 based on ID match
For the demonstration, update all the fields of demo_table1 from demo_table2 based on ID match. If two table has the same column name we can write column name using syntax “table_name.column_name” to avoid confusion.
For example:
demo_table1 and demo_table 2 both has NAME column. 
demo_table1.ID: specifies ID column of demo_table1
demo_table2.ID: specifies ID column of demo_table2
Query:
UPDATE demo_table1
SET demo_table1.NAME=demo_table2.NAME, 
demo_table1.AGE=demo_table2.AGE
FROM demo_table1, demo_table2
WHERE demo_table1.ID=demo_table2.ID;
View the content of demo_table1 again to see the updated table.
Output:
We can see the content is updated now based on ID values of demo_table2.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Test Oracles

24 Mar, 2022
Test Oracle is a mechanism, different from the program itself, that can be used to test the accuracy of a program’s output for test cases. Conceptually, we can consider testing a process in which test cases are given for testing and the program under test. The output of the two then compares to determine whether the program behaves correctly for test cases. This is shown in figure. 
 
Testing oracles are required for testing. Ideally, we want an automated oracle, which always gives the correct answer. However, often oracles are human beings, who mostly calculate by hand what the output of the program should be. As it is often very difficult to determine whether the behavior corresponds to the expected behavior, our “human deities” may make mistakes. Consequently, when there is a discrequently, between the program and the result, we must verify the result produced by the oracle before declaring that there is a defect in the result. 
The human oracles typically use the program’s specifications to decide what the correct behavior of the program should be. To help oracle determine the correct behavior, it is important that the behavior of the system or component is explicitly specified and the specification itself be error-free. In other words actually specify the true and correct behavior. 
There are some systems where oracles are automatically generated from the specifications of programs or modules. With such oracles, we are assured that the output of the oracle conforms to the specifications. However, even this approach does not solve all our problems, as there is a possibility of errors in specifications. As a result, a divine generated from the specifications will correct the result if the specifications are correct, and this specification will not be reliable in case of errors. In addition, systems that generate oracles from specifications require formal specifications, which are often not generated during design. 
prachisoda1234
surinderdawra388
Software Engineering
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2016 (Set 2) | Question 23

28 Jun, 2021
Assume that the algorithms considered here sort the input sequences in ascending order. If the input is already in ascending order, which of the following are TRUE ?
I.   Quicksort runs in Θ(n2) time
II.  Bubblesort runs in Θ(n2) time
III. Mergesort runs in  Θ(n) time
IV.  Insertion sort runs in  Θ(n) time 
(A) I and II only(B) I and III only(C) II and IV only(D) I and IV onlyAnswer: (D)Explanation: I. Given an array in ascending order, Recurrence relation for total number of comparisons for quicksort will beT(n) = T(n-1)+O(n) //partition algo will take O(n) comparisons in any case.= O(n^2)
II. Bubble Sort runs in Θ(n^2) time
If an array is in ascending order, we could make a small modification in Bubble Sort Inner for loop which is responsible for bubbling the kth largest element to the end in kth iteration. Whenever there is no swap after the completion of inner for loop of bubble sort in any iteration, we can declare that array is sorted in case of Bubble Sort taking O(n) time in Best Case.
III. Merge Sort runs in Θ(n) timeMerge Sort relies on Divide and Conquer paradigm to sort an array and there is no such worst or best case input for merge sort. For any sequence, Time complexity will be given by following recurrence relation,
T(n) = 2T(n/2) + Θ(n) // In-Place Merge algorithm will take Θ(n) due to copying an entire array.= Θ(nlogn)
IV. Insertion sort runs in Θ(n) time
Whenever a new element which will be greater than all the elements of the intermediate sorted sub-array ( because given array is sorted) is added, there won’t be any swap but a single comparison. In n-1 passes we will be having 0 swaps and n-1 comparisons.Total time complexity = O(n) // N-1 Comparisons
This solution is contributed by Pranjul Ahuja////For an array already sorted in ascending order,Quicksort has a complexity Θ(n2) [Worst Case]Bubblesort has a complexity Θ(n) [Best Case]Mergesort has a complexity Θ(n log n) [Any Case]Insertsort has a complexity Θ(n) [Best Case]Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
SQL Query to Update Columns Values With Column of Another Table

23 Sep, 2021
In SQL update belongs to DDL (Data definition language). Using the UPDATE command we can update the present data in the table using the necessary queries. In this article, we see how to update column values with column values of another table using MSSQL as a server.
Syntax: For update query
UPDATE table_name 
SET old_value = new_value
WHERE condition 
Step 1: Creating a Database
We use the below command to create a database named GeeksforGeeks:
Query:
CREATE DATABASE GeeksforGeeks;
Output:
Step 2: Using the Database
To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks;
Output:
Step 3: Creating two Tables
Create a table student_details with  3 columns and table Updated_CG with 2 columns using the following SQL queries:  
Query:
CREATE TABLE student_details(
  stu_id VARCHAR(8),
  stu_name VARCHAR(20),
  stu_cgpa DECIMAL(4,2) );
Query:
CREATE TABLE Updated_CG(
stu_id VARCHAR(20),
updated_cg DECIMAL(4,2));
Output:
Step 4: The query for Inserting rows into the Table
Inserting rows into student_details table using the following SQL query
Query:
INSERT INTO student_details VALUES('40001','PRADEEP',9.6);
INSERT INTO student_details VALUES('40002','ASHOK',8.2);
INSERT INTO student_details VALUES('40003','PAVAN KUMAR',7.6);
INSERT INTO student_details VALUES('40004','NIKHIL',8.2);
INSERT INTO student_details VALUES('40005','RAHUL',7.0);
Output:
Step 5: Inserting rows into Updated_CG using the following SQL query
Query:
INSERT INTO Updated_CG VALUES('40001',8.6);
INSERT INTO Updated_CG VALUES('40002',8.4);
INSERT INTO Updated_CG VALUES('40003',6.6);
INSERT INTO Updated_CG VALUES('40004',7.2);
INSERT INTO Updated_CG VALUES('40005',7.8);
Output:
 Step 6: Viewing the inserted data
Query:
SELECT * FROM student_details
SELECT * FROM Updated_CG
Output:
Query to update the old C.G.P.A in student_details table to new C.G.P.A   from the table Upadated_CG
Query:
UPDATE student_details 
SET stu_cgpa = (SELECT updated_cg 
FROM Updated_CG 
WHERE student_details.stu_id = Updated_CG.stu_id)
Output:
Step 7: Viewing the updated table
Query:
SELECT * FROM stuent_details
Output:
Blogathon-2021
Picked
SQL-Query
SQL-Server
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
Reading rpt files with Pandas

16 May, 2021
In most cases, we usually have a CSV file to load the data from, but there are other formats such as JSON, rpt, TSV, etc. that can be used to store data. Pandas provide us with the utility to load data from them. In this article, we’ll see how we can load data from an rpt file with the use of Pandas.
An RPT file is a report or output file created by Crystal Reports, a program used for business-oriented reporting. It can store data from multiple sources and different types of databases. 
File in use: here
One way to read the rpt file is by simply using the read_fwf method. All you need to do is to pass the file path, and it’ll load the data into a dataframe and define the delimiter for it.  That is why it usually becomes essential in the case of rpt files to understand the arrangement of data. After this, you just have to pass the delimiter and file name to the method. 
Example:
Python3
import pandas as pd  df = pd.read_fwf('sample.rpt', delimiter='|')  display(df)
Output:
Once you know the delimiter, you can also use the read_csv() method to read that file by passing the delimiter in the method. Let’s read the above file using read_csv. 
Example:
Python3
import pandas as pd  df = pd.read_csv('sample.rpt', delimiter = '|')  display(df)
Output:
Picked
Python pandas-io
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 ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Quantile and Decile rank of a column in Pandas-Python

10 Jul, 2020
Let’s see how to find the Quantile and Decile ranks of a column in Pandas. We will be using the qcut() function of the pandas module.
Pandas library’s function qcut() is a Quantile-based discretization function. This means that it discretize the variables into equal-sized buckets based on rank or based on sample quantiles.
Syntax : pandas.qcut(x, q, labels=None, retbins: bool = False, precision: int = 3, duplicates: str = ‘raise’)
Parameters :
x : 1d ndarray or Series.
q : Number of quantiles. For example, 10 refers to deciles and 4 refers to quantiles.
labels : Used as labels for the resulting bins. If it is set as False, it returns only integer indicators of the bins. If True, then it raises an error. By default, it is set to None.
retbins : (Optional) It is a boolean which returns the (bins, labels) when set to True.
precision : (Optional) The precision at which to store and display the bins labels.
duplicates : (Optional) If bin edges are not unique, raise ValueError or drop non-uniques.
Algorithm :
Import pandas and numpy modules.Create a dataframe.Use pandas.qcut() function, the Score column is passed, on which the quantile discretization is calculated. And q is set to 4 so the values are assigned from 0-3Print the dataframe with the quantile rank.
Import pandas and numpy modules.
Create a dataframe.
Use pandas.qcut() function, the Score column is passed, on which the quantile discretization is calculated. And q is set to 4 so the values are assigned from 0-3
Print the dataframe with the quantile rank.
# importing the modulesimport pandas as pdimport numpy as np    # creating a DataFramedf = {'Name' : ['Amit', 'Darren', 'Cody', 'Drew',                'Ravi', 'Donald', 'Amy'],      'Score' : [50, 71, 87, 95, 63, 32, 80]}df = pd.DataFrame(df, columns = ['Name', 'Score'])  # adding Quantile_rank column to the DataFramedf['Quantile_rank'] = pd.qcut(df['Score'], 4,                               labels = False)  # printing the DataFrameprint(df)
Output :
Algorithm :
Import pandas and numpy modules.Create a dataframe.Use pandas.qcut() function, the Score column is passed, on which the quantile discretization is calculated. And q is set to 10 so the values are assigned from 0-9Print the dataframe with the decile rank.
Import pandas and numpy modules.
Create a dataframe.
Use pandas.qcut() function, the Score column is passed, on which the quantile discretization is calculated. And q is set to 10 so the values are assigned from 0-9
Print the dataframe with the decile rank.
# importing the modulesimport pandas as pdimport numpy as np    # creating a DataFramedf = {'Name' : ['Amit', 'Darren', 'Cody', 'Drew',                'Ravi', 'Donald', 'Amy'],      'Score' : [50, 71, 87, 95, 63, 32, 80]}df = pd.DataFrame(df, columns = ['Name', 'Score'])  # adding Decile_rank column to the DataFramedf['Decile_rank'] = pd.qcut(df['Score'], 10,                            labels = False)  # printing the DataFrameprint(df)
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MoviePy – Saving a Frame of Video Clip

01 Aug, 2020
In this article we will see how we can save a single frame at given time of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can store the specific frame at any time.
In order to do this we will use save_frame method with the VideoFileClip object
Syntax : clip.save_frame(“frame.png”, t)
Argument : It takes image name as argument and time as optional argument
Return : It returns None
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *     # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")   # getting only first 5 secondsclip = clip.subclip(0, 5)  # saving a frame at 2 secondclip.save_frame("frame2.png", t = 2)  # showing  clipclip.ipython_display(width = 360)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Below is the saved image
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")    # getting duration of the videoduration = clip.duration  # saving a frame at 1 secondclip.save_frame("frame1.png", t = 1)  # showing  clipclip.ipython_display(width = 360)
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Below is how the saved image will look like
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to draw color filled star in Python-Turtle?

08 Oct, 2020
Prerequisite: Turtle Programming Basics, Draw Color Filled Shapes in Turtle
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move the turtle, there are some functions i.e forward(), backward(), etc. 
Approach:
The following steps are used:
Import turtle
Set window screen
Set color of the turtle
Form a star
Fill the star with the color
Below is the implementation.
Python3
# importing packageimport turtle # function to draw# colored stardef colored_star():         # size of star    size = 80         # object color    turtle.color("red")         # object width    turtle.width(4)         # angle to form star    angle = 120         # color to fill    turtle.fillcolor("yellow")    turtle.begin_fill()         # form star    for side in range(5):        turtle.forward(size)        turtle.right(angle)        turtle.forward(size)        turtle.right(72 - angle)             # fill color    turtle.end_fill() # Driver codecolored_star()
  
Output :
 
Since, as of now, you must have learned how to draw and fill color in a star. So, let’s try something unique with this knowledge. Let’s use some creativity and programming to build a night full of stars.
Python3
import turtlefrom random import randint window = turtle.Screen()turtle.bgcolor("black")turtle.color("yellow")turtle.speed(0) def draw_star():    turns = 6    turtle.begin_fill()    while turns>0:        turtle.forward(25)        turtle.left(145)        turns = turns-1    turtle.end_fill() nums_stars = 0while nums_stars <50:    x=randint(-300,300)    y=randint(-300,300)    draw_star()    turtle.penup()    turtle.goto(x,y)    turtle.pendown()    nums_stars = nums_stars + 1 window.exitonclick()
 Output:
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | Sort lists in tuple

14 May, 2020
Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple() + sorted() + generator expressionThis task can be performed using the combination of above functions. In this, we iterate through each list using generator expression and perform the sort operation using sorted().
# Python3 code to demonstrate working of# Sort lists in tuple# Using tuple() + sorted() + generator expression  # Initializing tupletest_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5])  # printing original tupleprint("The original tuple is : " + str(test_tup))  # Sort lists in tuple# Using tuple() + sorted() + generator expressionres = tuple((sorted(sub) for sub in test_tup))  # printing resultprint("The tuple after sorting lists : " + str(res))
The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
The tuple after sorting lists : ([4, 5, 7], [2, 4, 8], [0, 5, 7])

 
Method #2 : Using map() + sorted()This method performs the similar task as the above method, but it uses map() to extend the logic to each element of tuple, the task performed by list comprehension in above method.
# Python3 code to demonstrate working of# Sort lists in tuple# Using map() + sorted()  # Initializing tupletest_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5])  # printing original tupleprint("The original tuple is : " + str(test_tup))  # Sort lists in tuple# Using map() + sorted()res = tuple(map(sorted, test_tup))  # printing resultprint("The tuple after sorting lists : " + str(res))
The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
The tuple after sorting lists : ([4, 5, 7], [2, 4, 8], [0, 5, 7])

Python tuple-programs
Python-sort
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Batch Script - HELP

This batch command shows the list of Windows-supplied commands.
help

@echo off 
help
The above command will display a list of all commands and their description. Following is an example of a subset of the output.
SCHTASKS    Schedules commands and programs to run on a computer. 
SHIFT       Shifts the position of replaceable parameters in batch files. 
SHUTDOWN    Allows proper local or remote shutdown of machine. 
SORT        Sorts input. 
START       Starts a separate window to run a specified program or command. 
SUBST       Associates a path with a drive letter. 
SYSTEMINFO  Displays machine specific properties and configuration. 
TASKLIST    Displays all currently running tasks including services. 
TASKKILL    Kill or stop a running process or application. 
TIME        Displays or sets the system time. 
TITLE       Sets the window title for a CMD.EXE session. 
TREE        Graphically displays the directory structure of a drive or path.
TYPE        Displays the contents of a text file. 
VER         Displays the Windows version. 
VERIFY      Tells Windows whether to verify that your files are written correctly to a disk. 
VOL         Displays a disk volume label and serial number. 
XCOPY       Copies files and directory trees. 
WMIC        Displays WMI information inside interactive command shell.

For more information on tools see the command-line reference in the online help.

 Print
 Add Notes
 Bookmark this page
How to import csv file in PHP?

The below code can be used to import CSV file in PHP −
<?php
$row = 1;
if (($handle = fopen("name_of_file.csv", "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      $num = count($data);
      echo "<p> $num fields in line $row: <br /></p>\n";
      $row++;
      for ($c=0; $c < $num; $c++) {
         echo $data[$c] . "<br />\n";
      }
   }
   fclose($handle);
}
?>
The file will display the contents of the csv file are displayed on the screen.
In the above code, beginning from row 1 (since row 0 would usually contain headers/column names), the csv file is opened in read mode and the fgetcsv function is called to read in 1000 rows of data present in the csv file.
The number of columns in every row is displayed along with the contents of it.