code-rag-bench/online-tutorials huggingface dataset:
Difference between Software Engineering process and Conventional Engineering Process

16 Aug, 2021
1. Software Engineering Process : It is a engineering process which is mainly related to computers and programming and developing different kinds of applications through the use of information technology. 
2. Conventional Engineering Process : It is a engineering process which is highly based on empirical knowledge and is about building cars, machines and hardware. 
Difference between Software Engineering Process and Conventional Engineering Process :  
clintra
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Consecutive Division in List

01 Nov, 2020
Given a List, perform consecutive division from each quotient obtained in the intermediate step and treating consecutive elements as divisors.
Input : test_list = [1000, 50, 5, 10, 2] Output : 0.2 Explanation : 1000 / 50 = 20 / 5 = 4 / 10 = 0.4 / 2 = 0.2. Hence solution.
Input : test_list = [100, 50] Output : 2 Explanation : 100 / 50 = 2. Hence solution.  
Approach: Using loop + “/” operator
In this, we iterate for each element and store the quotient obtained to process as a dividend for the next operation while in the loop. The end result is the final quotient of list.
Python3
# Python3 code to demonstrate working of# Consecutive Division in List# Using loop + / operator  # utility fnc.def conc_div(test_list):          res = test_list[0]    for idx in range(1, len(test_list)):                  # Consecutive Division        res /= test_list[idx]    return res  # initializing listtest_list = [1000, 50, 5, 10, 2]  # printing original listprint("The original list is : " + str(test_list))  # getting conc. Divisionres = conc_div(test_list)  # printing result print("The Consecutive Division quotient : " + str(res))
The original list is : [1000, 50, 5, 10, 2]
The Consecutive Division quotient : 0.2

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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 | Convert string dictionary to dictionary
How to reset input type = “file” using JavaScript/jQuery?

18 Feb, 2022
Jquery:  
Using wrap method in jquery: The best way to reset input type=file is resetting the whole form. Wrap <input type = “file”> into <form> tags and reset the form: Example-1:  
html
<!DOCTYPE html><html> <head>    <title>reset input type = “file”</title>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>     <!-- jQuery code to show the         working of this method -->    <script>        $(document).ready(function() {            $('#resetbtn').on('click', function(e) {                var $el = $('#infileid');                $el.wrap('<form>').closest(                  'form').get(0).reset();                $el.unwrap();            });        });    </script></head> <body>    <center>        <h2 style="color:green">GeeksforGeeks</h2>        <form id="find" name="formname">            <p>                <label>File</label>                <input id="infileid" type="file">            </p>            <p>                <button id="resetbtn"                        type="button">                  Reset file              </button>            </p>        </form>    </center></body> </html>
Output: Before:  
After:  
 
Using file.value = ”: The simplest way to reset the input is changing the filled value with nothing. this method is workes in every browser. Example-2:  
HTML
<!DOCTYPE html><html> <head>    <title>        reset input type = “file”    </title>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>     <!-- jQuery code to show the         working of this method -->    <script>        function resetFile() {            const file =                document.querySelector('.file');            file.value = '';        }    </script></head> <body>    <center>        <h2 style="color:green">    GeeksforGeeks  </h2>        <input type="file" class="file" />        <button onclick="resetFile()">            Reset file        </button>    </center></body> </html>
Output: Before:  
After:  
 
Using wrap method in jquery: Wrap <input type = “file”> in to <form> tags and reset the form: Example-3:  
html
<!DOCTYPE html><html> <head>    <title>      reset input type = “file”  </title> </head> <body>    <center>        <h2 style="color:green">          GeeksforGeeks      </h2>        <form id="find"              name="formname">            <p>                <label>File</label>                <input type="file">            </p>            <p>                <button id="resetbtn"                        type="button"                        onClick="this.form.reset()">                  Reset file              </button>            </p>        </form>    </center></body> </html>
Output: Before:  
After:  
 
 
varshagumber28
JavaScript-Misc
jQuery-Misc
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Fruitful Functions and Void Functions in Julia

25 Aug, 2020
Functions are one of the most useful tools when writing a program. Every programming language including Julia uses functions, it can be for keeping the code simple and readable or to keep the program secure from outside interference. In almost every programming language there are two types of functions:
Fruitful Functions
Void Functions
These are the functions that return a value after their completion. A fruitful function must always return a value to where it is called from. A fruitful function can return any type of value may it be string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one variable, the value to be returned can be an array or a vector. A fruitful function can also return multiple values.
Example 1:
# Creation of Functionfunction add_f(a, b);    c = a + b;          # Returning the value    return c;end  # Function calld = add_f(3, 4);print(d)
Output:
Example 2:
# Creation of Functionfunction mul_f(a, b, c);    d = a * b * c;          # Returning the result     # to caller function    return d;end  # Function callx = mul_f(2, 4, 6);print(x)
Output:
Void functions are those that do not return any value after their calculation is complete. These types of functions are used when the calculations of the functions are not needed in the actual program. These types of functions perform tasks that are crucial to successfully run the program but do not give a specific value to be used in the program.
Example 1:
# Creation of Functionfunction add_v(a, b);    c = a + b;    print(c);end  # Function Calladd_v(3, 4)
Output:
Example 2:
# Creation of Functionfunction mul_v(a, b, c)    print(a * b * c);end  # Function Callmul_v(2, 4, 6)
Output:
Julia-functions
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exception handling in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
NamedTuple in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Getting the maximum value from a list in Julia - max() Method
Join an array of strings into a single string in Julia - join() Method
Difference Between MATLAB and Julia
Python – turtle.exitonclick()

17 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to Go into mainloop until the mouse is clicked. It doesn’t require any argument. Bind bye() method to mouseclick on TurtleScreen. If using_IDLE – value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE’s mainloop is active also for the client script.
This is a method of the Screen-class and not available for TurtleScreen instances.
Syntax : turtle.exitoncick()Parameters : NoneReturns : Nothing
Below is the implementation of above method with an example :
Example :
# import packageimport turtle  # loop for motionfor i in range(3):  turtle.circle(40)  turtle.right(120)  # exit from the screen # if and only if# mouse is clickedturtle.exitonclick()
Output :
Here we can see that :
Turtle screen is loaded
Turtle draw some stuff
Turtle window remain as it is
When user click (yellow colored sign) on turtle window it closes i.e; exit on click.
Python-turtle
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
DROP SCHEMA in SQL Server

04 Sep, 2020
The DROP SCHEMA statement could be used to delete a schema from a database. SQL Server have some built-in schema, for example : dbo, guest, sys, and INFORMATION_SCHEMA which cannot be deleted.
Syntax :
DROP SCHEMA [IF EXISTS] schema_name;

Note : Delete all objects from the schema before dropping the schema. If the schema have any object in it, the output will be an error.
Example :Let us create a new schema named geeksh (https://www.geeksforgeeks.org/create-schema-in-sql-server/);
CREATE SCHEMA geeksh;
GO

Now create a table named geektab inside the geeksh schema :
CREATE TABLE geeksh.geektab
(id INT PRIMARY KEY,
date DATE NOT NULL,
city varchar(200) NOT NULL);

Drop the schema geeksh :
DROP SCHEMA geeksh;SQL Server will throw similar error as the schema is not empty.
Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'geeksh' because it is being referenced by object 'geektab'.

Let us drop the table geeksh.geektab :
DROP TABLE geeksh.geektab;

Again run the DROP SCHEMA again to drop the geeksh schema :
DROP SCHEMA IF EXISTS geeksh;

Now, the geeksh schema has been deleted from the database.
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
Using Else Conditional Statement With For loop in Python

13 Jul, 2022
Using else conditional statement with for loop in python
In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. 
The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
Else block is executed in below Python 3.x program: 
Python
for i in range(1, 4):    print(i)else:  # Executed because no break in for    print("No Break")
Output : 
1
2
3
No Break
Else block is NOT executed in Python 3.x or below: 
Python
for i in range(1, 4):    print(i)    breakelse: # Not executed as there is a break    print("No Break")
Output : 
1
Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in the third iteration of the loop and hence the else present after the for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.
Python
# Python 3.x program to check if an array consists # of even numberdef contains_even_number(l):    for ele in l:        if ele % 2 == 0:            print ("list contains an even number")            break      # This else executes only if break is NEVER    # reached and loop terminated after all iterations.    else:             print ("list does not contain an even number")  # Driver codeprint ("For List 1:")contains_even_number([1, 9, 8])print (" \nFor List 2:")contains_even_number([1, 3, 5])
Output: 
For List 1:
list contains an even number

For List 2:
list does not contain an even number
As an exercise, predict the output of the following program. 
Python
count = 0while (count < 1):        count = count+1    print(count)    breakelse:    print("No Break")
tarun2207
ddeevviissaavviittaa
tyunsworth
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a Box Layout in Java?

To create a Box Layout in Java Swing, use the BoxLayout class. Here, we have also set that the components should be laid our left to right or top to bottom −
Box box = new Box(BoxLayout.X_AXIS);
box.add(button1);
box.add(button2);
box.add(button3);
box.add(button4);
box.add(Box.createGlue());
box.add(button5);
box.add(button6);
box.add(button7);
box.add(button8);
Above, we have 8 buttons in our Box Layout. We have separated 4 buttons each using the createGlue() method.
The following is an example to create a BoxLayout in Java −
package my;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Groups");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton button1 = new JButton("CSK");
      JButton button2 = new JButton("DC");
      JButton button3 = new JButton("MI");
      JButton button4 = new JButton("SRH");
      JButton button5 = new JButton("RR");
      JButton button6 = new JButton("KKR");
      JButton button7 = new JButton("KXIP");
      JButton button8 = new JButton("RCB");
      Box box = new Box(BoxLayout.X_AXIS);
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(Box.createGlue());
      box.add(button5);
      box.add(button6);
      box.add(button7);
      box.add(button8);
      JScrollPane jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(box);
      frame.add(jScrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}
Get or Set names of Elements of an Object in R Programming – names() Function

05 Jun, 2020
names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named.
Syntax: names(x) <- value
Parameters:x: Object i.e. vector, matrix, data frame, etc.value: Names to be assigned to x
Example 1:
# R program to assign name to an object  # Creating a vectorx <- c(1, 2, 3, 4, 5)  # Assigning names using names() functionnames(x) <- c("gfg1", "gfg2", "gfg3", "gfg4", "gfg5")  # Printing name vector that is assigned names(x)  # Printing updated vectorprint(x)
Output:
[1] "gfg1" "gfg2" "gfg3" "gfg4" "gfg5"
gfg1 gfg2 gfg3 gfg4 gfg5 
   1    2    3    4    5 

Example 2:
# R program to get names of an Object  # Importing Library library(datasets)     # Importing dataset head(airquality)   # Calling names() function to get namesnames(airquality)
Output:
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6
[1] "Ozone"   "Solar.R" "Wind"    "Temp"    "Month"   "Day"    

R DataFrame-Function
R List-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Is an array a primitive type or an object in Java?

11 Dec, 2018
An array in Java is an object. Now the question how is this possible? What is the reason behind that? In Java, we can create arrays by using new operator and we know that every object is created using new operator. Hence we can say that array is also an object. Now the question also arises, every time we create an object for a class then what is the class of array?
In Java, there is a class for every array type, so there’s a class for int[] and similarly for float, double etc.
The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable.
In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
For every array type corresponding classes are available and these classes are the part of java language and not available to the programmer level. To know the class of any array, we can go with the following approach:
// Here x is the name of the array.
System.out.println(x.getClass().getName()); 
// Java program to display class of // int array typepublic class Test{    public static void main(String[] args)    {        int[] x = new int[3];        System.out.println(x.getClass().getName());    }}
Output:
[I 

NOTE:[I this is the class for this array, one [ (square bracket) because it is one dimensional and I for integer data type.Here is the table specifying the corresponding class name for some array types:-
Array type             Corresponding class Name
int[]                     [I
int[][]                   [[I
double[]                  [D
double[][]                [[D
short[]                   [S
byte[]                    [B
boolean[]                 [Z

In Java programming language, arrays are objects which are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array.
// Java program to check the class of // int array typepublic class Test {    public static void main(String[] args)    {        // Object is the parent class of all classes         // of Java. Here args is the object of String        // class.        System.out.println(args instanceof Object);          int[] arr = new int[2];          // Here arr is also an object of int class.        System.out.println(arr instanceof Object);    }}
Output:
true
true

Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
This article is contributed by Bishal Kumar Dubey. 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.
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sizeof() for Floating Constant in C

02 Jun, 2017
In C language, we have three floating data types i.e. float, double and long double. And the exact size of each of these 3 types depends on the C compiler implementation/platform. The following program can be used to find out the size of each floating data type on your machine.
#include "stdio.h"int main(){ printf("%d %d %d",sizeof(float), sizeof(double), sizeof(long double)); return 0;}
But what about the size of a floating point constant (e.g. 31.4 or 2.718)? For example if we have PI macro defined as follows, what would be the sizeof(3.14).
#define PI 3.14
Now if we do sizeof(PI), what will be its size? Is is equal to sizeof(float) ? Or is it also compiler implementation dependent. Well, for floating constants, C standard (C11 i.e. ISO/IEC 9899:2011) has given guideline. As per C11 clause 6.4.4.2, “An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.“
It means the type of a floating constant is same as that of double data type. So if size of a double on a machine is 8 bytes, the size of floating constant would be 8 bytes. One can find out this using the below program
#include "stdio.h"#define PI 3.14int main(){ printf("%d",sizeof(PI)); return 0;}
As per the above mentioned C standard clause, a floating constant can be converted to float type by using f or F. Similarly, a floating constant can be converted to long double by using l or L. So it shouldn’t take much thought on guessing the output of the following:
#include "stdio.h"int main(){ printf("%d %d",sizeof(3.14F), sizeof(3.14L)); return 0;}
Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us comment for further clarification or info. We would love to help and learn 
C-Data Types
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nagarro Archives - GeeksforGeeks

Check whether two strings are anagram of each other
Find the middle of a given linked list
Print a given matrix in spiral form
GCD of more than two (or array) numbers
Nagarro Interview Experience
Nagarro Interview Experience | On-Campus 2021
Nagarro Interview Experience
Nagarro Interview Experience for Trainee-Software Engineer
Nagarro Interview Experience for Associate Engineer Trainee | On-Campus 2022
Nagarro Interview Experience | Set 1 (On-Campus)
JavaScript String toLowerCase() Method

07 Oct, 2021
Below is the example of the String toLowerCase() Method.  
Example:  
JavaScript
<script>function func() {    var str = 'GEEKSFORGEEKS';    var string = str.toLowerCase();    document.write(string);}func();</script>
Output:  
geeksforgeeks
str.toLowerCase() method converts the entire string to lower case. This method does not affect any of the special characters, digits, and the alphabets that are already in the lower case. Syntax:  
str.toLowerCase()
Return value: This method returns a new string in which all the upper case letters are converted to lower case.Examples for the above method are provided below:Example 1:  
var str = 'It iS a Great Day.';
var string = str.toLowerCase();
print(string);
Output:  
it is a great day.
In this example, the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits, and all those characters that are already in the lower case.Example 2:  
var str = 'It iS a 5r&e@@t Day.';
var string = str.toLowerCase();
print(string);
Output:  
it is a 5r&e@@t day.
In this example the method toLowerCase() converts all the upper case alphabets into lower case alphabets without affecting the special characters, digits and all those characters that are already in lower case.Codes for the above method are provided below:Program 1:  
JavaScript
<script>// JavaScript Program to illustrate//  toLowerCase() method function func() {        // Original string    var str = 'It iS a Great Day.';        // Converting to lower case    var string = str.toLowerCase();    document.write(string);} func();</script>
Output:  
it is a great day.
Program 2:  
JavaScript
<script>// JavaScript Program to illustrate//  toLowerCase() method function func() {        //Original string    var str = 'It iS a 5r&e@@t Day.';        //Converting to lower case    var string = str.toLowerCase();    document.write(string);} func();</script>
Output:  
it is a 5r&e@@t day.
 
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python – Coefficient of Determination-R2 score

16 Jul, 2020
Coefficient of determination also called as R2 score is used to evaluate the performance of a linear regression model. It is the amount of the variation in the output dependent attribute which is predictable from the input independent variable(s). It is used to check how well-observed results are reproduced by the model, depending on the ratio of total deviation of results described by the model.
Mathematical Formula:
R2= 1- SSres / SStot
Where,SSres is the sum of squares of the residual errors.SStot is the total sum of the errors.
Interpretation of R2 score:Assume R2 = 0.68It can be referred that 68% of the changeability of the dependent output attribute can be explained by the model while the remaining 32 % of the variability is still unaccounted for.R2 indicates the proportion of data points which lie within the line created by the regression equation. A higher value of R2 is desirable as it indicates better results.
ExamplesCase 1 Model gives accurate results
  R2 = 1- 0/200 = 1
Case 2 Model gives same results always
 R2 = 1- 200/200 = 0
Case 3 Model gives ambiguous results
 R2 = 1- 600/200 = -2
We can import r2_score from sklearn.metrics in Python to compute R2 score.
Python Implementation:Code 1: Import r2_score from sklearn.metrics
from sklearn.metrics import r2_score
Code 2: Calculate R2 score for all the above cases.
### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[10, 20, 30]r2 = r2_score(y, f)print('r2 score for perfect model is', r2)
Output:
r2 score for perfect model is 1.0
### Assume y is the actual value and f is the predicted valuesy =[10, 20, 30]f =[20, 20, 20]r2 = r2_score(y, f)print('r2 score for a model which predicts mean value always is', r2)  
Output:
r2 score for a model which predicts mean value always is 0.0
Code 3:
### Assume y is the actual value and f is the predicted valuesy = [10, 20, 30]f = [30, 10, 20]r2 = r2_score(y, f)print('r2 score for a worse model is', r2)
Output:
r2 score for a worse model is -2.0
Conclusion:
The best possible score is 1 which is obtained when the predicted values are the same as the actual values.
R2 score of baseline model is 0.
During the worse cases, R2 score can even be negative.
Python numpy-Statistics Functions
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Python | Remove and print every third from list until it becomes empty

21 Nov, 2018
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty.Examples:
Input : [10, 20, 30, 40, 50, 60, 70, 80, 90]Output : 30 60 90 40 80 50 20 70 10Explanation:The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 60, after that 90 is encountered. Then again the count starts from 10 for the next third element which is 40. Proceeding in the same manner as we did before we get next third element after 40 is 80. This process is repeated until the list becomes empty.
Input : [1, 2, 3, 4]Output : 3 2 4 1Explanation:The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed.
Approach The index of the list starts from 0 and the first third element will be at position 2. Traverse till the list becomes empty and each time find the index of the next third element and print its corresponding value. After printing reduce the length of the list.
# Python program to remove to every third# element until list becomes emptydef removeThirdNumber(int_list):          # list starts with    # 0 index    pos = 3 - 1    index = 0    len_list = (len(int_list))          # breaks out once the    # list becomes empty    while len_list > 0:               index = (pos + index) % len_list                  # removes and prints the required        # element        print(int_list.pop(index))         len_list -= 1  # Driver codenums = [1, 2, 3, 4] removeThirdNumber(nums)
Output:
3
2
4
1

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.path.commonprefix() method

22 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used for common path name manipulation.
os.path.commonprefix() method in Python is used to get longest common path prefix in a list of paths. This method returns only common prefix value in the specified list, returned value may or may not be a valid path as it check for common prefix by comparing character by character in the list.For example consider the following list of paths:
          list of paths                     common prefix
['/home/User/Photos', /home/User/Videos']    /home/User/         A valid path
['/usr/local/bin', '/usr/lib']               /usr/l              Not a valid path

Syntax: os.path.commonprefix(list)
Parameter:path: A list of path-like object. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string value which represents the longest common path prefix in specified list.
Code #1: Use of os.path.commonprefix() method
# Python program to explain os.path.commonprefix() method     # importing os module import os  # List of Pathspaths = ['/home/User/Desktop', '/home/User/Documents',          '/home/User/Downloads']   # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths)    # Print the # longest common path prefix# in the specified list print("Longest common path prefix:", prefix)    # List of Pathspaths = ['/usr/local/bin', '/usr/bin']   # Get the# longest common path prefix# in the specified list prefix = os.path.commonprefix(paths)    # Print the # longest common path prefix# in the specified list print("Longest common path prefix:", prefix)
Longest common path prefix: /home/User/D
Longest common path prefix: /usr/

Note: If the specified list is empty, os.path.commonprefix() method will return a empty string.
Reference: https://docs.python.org/3/library/os.path.html
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Pafy Module in Python

06 Aug, 2021
In this article we will learn about the pafy module. Pafy is a Python library to download YouTube content and retrieve metadata. 
Below are the list of features Pafy offers1. Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords 2. Download video or audio at requested resolution / bitrate / format / filesize 2. Command line tool (ytdl) for downloading directly from the command line 3. Retrieve the URL to stream the video in a player such as vlc or mplayer 4. Works with age-restricted videos and non-embeddable videos 5. Small, standalone, single importable module file 6. Select highest quality stream for download or streaming 7. Download video only (no audio) in m4v or webm format 8. Download audio only (no video) in ogg or m4a format 9. Retrieve playlists and playlist metadata 10. Works with Python 2.6+ and 3.3+ 
Installation In order to install pafy we use the command given below 
pip install pafy
Note : Pafy is optionally depends on youtube-dl so therefore for more stable usage it is recommended to install youtube-dl before installing pafy. Below is the command to install youtube-dl 
pip install youtube_dl
Example 1: Program to get the number of views on a video 
Python3
# importing pafyimport pafy   # url of videourl = "https://www.youtube.com / watch?v = mmjDZGSr7EA"   # instant createdvideo = pafy.new(url) # getting number of likescount = video.viewcount # showing likesprint("View Count : " + str(count))
Output : 
View Count : 287205
Example 2: Program to get the thumb image of a video 
Python3
# importing pafyimport pafy   # url of videourl = "https://www.youtube.com / watch?v = mmjDZGSr7EA"   # instant createdvideo = pafy.new(url) # getting thumb imagecount = video.thumb # showing likesprint("Thumb Image : " + str(count))
Output : 
Thumb Image : http://i.ytimg.com/vi/vG2PNdI8axo/default.jpg
Example 3: Program to get the title of a video 
Python3
# importing pafyimport pafy   # url of videourl = "https://www.youtube.com / watch?v = vG2PNdI8axo"   # instant createdvideo = pafy.new(url) # getting titlevalue = video.title # showing likesprint("Title : " + str(value))
Output : 
Title : DSA Self Paced Course | GeeksforGeeks
 
ruhelaa48
Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to call JavaScript function in HTML ?

06 Jun, 2022
In this article, we will see how to call JavaScript function in HTML with two approaches that are discussed below.
Approach 1: First, take a button by the input tag. After clicking the button, you can see a dialog box that pops up on the screen that has already been declared in the JavaScript function as an alert. The clickEvent() function allows executing the alert() when this button gets clicked by using onclick() method.
Example:
HTML
<!DOCTYPE html><html> <body>    <input type="button" onclick="clickEvent();"        value="button" />    <script>        function clickEvent() {            alert("Who!! You have discovered");        }    </script></body> </html>
Output:
Approach 2: By using the display() method in JavaScript, you can see the output GeeksForGeeks in the h1 tag.
Example:
HTML
<!DOCTYPE html><html> <head>    <title>Call JavaScript function in HTML</title></head> <body>    <script>        function display() {            document.write("<h1>GeeksForGeeks</h1>");        }        display();    </script></body> </html>
Output:
h1 tag
sumitgumber28
HTML-Questions
JavaScript-Methods
JavaScript-Questions
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scraping Reddit with Python and BeautifulSoup

30 May, 2021
In this article, we are going to see how to scrape Reddit with Python and BeautifulSoup. Here we will use Beautiful Soup and the request module to scrape the data.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import all the required modules.
Pass the URL in the getdata function(UDF) to that will request to a URL, it returns a response. We are using the GET method to retrieve information from the given server using a given URL.
Syntax: requests.get(url, args)
Now Parse the HTML content using bs4.
Syntax: soup = BeautifulSoup(r.content, ‘html5lib’)
Parameters:
r.content : It is the raw HTML content.
html.parser : Specifying the HTML parser we want to use.
Now filter the required data using soup.Find_all function.
Let’s see the stepwise execution of the script.
Step 1: Import all dependence
Python3
# import moduleimport requestsfrom bs4 import BeautifulSoup
Step 2: Create a URL get function
Python3
# user define function# Scrape the datadef getdata(url):    r = requests.get(url, headers = HEADERS)    return r.text
Step 3: Now take the URL and pass the URL into the getdata() function and Convert that data into HTML code.
Python3
url = "https://www.reddit.com/r/learnpython/comments/78qnze/web_scraping_in_20_lines_of_code_with/"  # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser')    # display html codeprint(soup)
Output:
Note: This is only HTML code or Raw data.
Now find authors with a div tag where class_ =”NAURX0ARMmhJ5eqxQrlQW”. We can open the webpage in the browser and inspect the relevant element by pressing right-click as shown in the figure.
Example:
Python3
# find the Html tag# with find()# and convert into stringdata_str = ""for item in soup.find_all("div", class_="NAURX0ARMmhJ5eqxQrlQW"):    data_str = data_str + item.get_text()        print(data_str)
Output:
kashaziz
Now find the article text, here we will follow the same methods as the above example.
Example:
Python3
# find the Html tag# with find()# and convert into stringdata_str = ""result = ""for item in soup.find_all("div", class_="_3xX726aBn29LDbsDtzr_6E _1Ap4F5maDtT1E1YuCiaO0r D3IL3FD0RFy_mkKLPwL4"):    data_str = data_str + item.get_text()print(data_str)
Output:
Now Scape the comments, here we will follow the same methods as the above example.
Python3
# find the Html tag# with find()# and convert into stringdata_str = ""  for item in soup.find_all("p", class_="_1qeIAgB0cPwnLhDF9XSiJM"):    data_str = data_str + item.get_text()print(data_str)
Output:
Picked
Python BeautifulSoup
Python web-scraping-exercises
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | math.cos() function

20 Mar, 2019
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.cos() function returns the cosine of value passed as argument. The value passed in this function should be in radians.
Syntax: math.cos(x)
Parameter:x : value to be passed to cos()
Returns: Returns the cosine of value passed as argument
Code #1:
# Python code to demonstrate the working of cos()     # importing "math" for mathematical operations import math     a = math.pi / 6     # returning the value of cosine of pi / 6 print ("The value of cosine of pi / 6 is : ", end ="") print (math.cos(a)) 
The value of cosine of pi/6 is : 0.8660254037844387

 Code #2:
# Python program showing # Graphical representation of # cos() function import mathimport numpy as npimport matplotlib.pyplot as plt   in_array = np.linspace(-(2 * np.pi), 2 * np.pi, 20)  out_array = []  for i in range(len(in_array)):    out_array.append(math.cos(in_array[i]))    i += 1     print("in_array : ", in_array) print("\nout_array : ", out_array)   # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = "o") plt.title("math.cos()") plt.xlabel("X") plt.ylabel("Y") plt.show() 
in_array : [-6.28318531 -5.62179738 -4.96040945 -4.29902153 -3.6376336 -2.97624567-2.31485774 -1.65346982 -0.99208189 -0.33069396 0.33069396 0.992081891.65346982 2.31485774 2.97624567 3.6376336 4.29902153 4.960409455.62179738 6.28318531]
out_array : [1.0, 0.7891405093963934, 0.2454854871407988, -0.40169542465296987, -0.8794737512064891, -0.9863613034027223, -0.6772815716257412, -0.08257934547233249, 0.5469481581224268, 0.9458172417006346, 0.9458172417006346, 0.5469481581224268, -0.0825793454723316, -0.6772815716257405, -0.9863613034027223, -0.8794737512064893, -0.40169542465296987, 0.2454854871407988, 0.7891405093963934, 1.0]
Python math-library-functions
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | Numpy np.cholesky() method

11 Nov, 2019
With the help of np.cholesky() method, we can get the cholesky decomposition by using np.cholesky() method.
Syntax : np.cholesky(matrix)Return : Return the cholesky decomposition.
Example #1 :In this example we can see that by using np.cholesky() method, we are able to get the cholesky decomposition in the form of matrix using this method.
# import numpyimport numpy as np  a = np.array([[2, -3j], [5j, 15]])# using np.cholesky() methodgfg = np.linalg.cholesky(a)  print(gfg)
Output :
[[1.41421356 + 0.j, 0. + 0.j][0. + 3.53553391j, 1.58113883 + 0.j]]
Example #2 :
# import numpyimport numpy as np  a = np.array([[12, -13j], [4j, 8]])# using np.cholesky() methodgfg = np.linalg.cholesky(a)  print(gfg)
Output :
[[3.46410162 + 0.j, 0. + 0.j][0. + 1.15470054j, 2.5819889 + 0.j]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISNUMERIC() Function in SQL Server

18 Jan, 2021
ISNUMERIC() function :This function in SQL Server is used to check if the stated expression is numeric or not.
Features :
This function is used to check if the given expression is numeric or not.
This function returns 1 if the given expression is in numerical form.
This function returns 0 if the given expression is not numeric.
This function comes under Advanced Functions.
This function accepts only one parameter namely expression.
Syntax :
ISNUMERIC(expression)

Parameter :This method accepts only one parameter as given below :
expression : Specified expression or the value which is to be checked if its numeric or not.
Returns :It returns 1 if the specified value is numeric form else it returns 0.
Example-1 :Using ISNUMERIC() function and getting the output.
SELECT ISNUMERIC(1352);

Output :
1
Here, 1 is returned as the stated value is numeric.
Example-2 :Using ISNUMERIC() function and getting the output.
SELECT ISNUMERIC('abd');

Output :
0
Here, 0 is returned as output as the stated expression is not numeric.
Example-3 :Using ISNUMERIC() function and getting the output using a variable.
DECLARE @exp INT;
SET @exp = 44;
SELECT ISNUMERIC(@exp);

Output :
1
Example-4 :Using ISNUMERIC() function and getting the output using multiplication operation and a variable as well.
DECLARE @exp INT;
SET @exp = 30*7;
SELECT ISNUMERIC(@exp);

Output :
1
Application :This function is used to test if the stated expression is numeric or not.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Seaborn.barplot() method in Python

16 Jun, 2021
Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well.
A barplot is basically used to aggregate the categorical data according to some methods and by default it’s the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x-axis and a numerical column for the y-axis, and we see that it creates a plot taking a mean per categorical column.
Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x000002BC3EB5C4C8>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=0.75, errcolor=’.26′, errwidth=None, capsize=None, dodge=True, ax=None, **kwargs,)  
Parameters :
Following steps are used :
Import Seaborn
Load Dataset from Seaborn as it contain good collection of datasets.
Plot Bar graph using seaborn.barplot() method.
Below is the implementation :
Example 1:
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # who v/s fare barplotsns.barplot(x = 'who',            y = 'fare',            data = df) # Show the plotplt.show()
Output:
Example 2:
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic')  # who v/s fare barplotsns.barplot(x = 'who',            y = 'fare',            hue = 'class',            data = df) # Show the plotplt.show()
Output:
Example 3:
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic')  # who v/s fare barplotsns.barplot(x = 'who',            y = 'fare',            hue = 'class',            data = df,            palette = "Blues") # Show the plotplt.show()
Output:
Example 4:
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic')  # who v/s fare barplotsns.barplot(x = 'who',            y = 'fare',            hue = 'class',            data = df,            estimator = np.median,            ci = 0) # Show the plotplt.show()
Output:
ankthon
abhishek0719kadiyan
Python-Seaborn
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method