code-rag-bench/online-tutorials huggingface dataset:
What is Lexical scope and lexical closures in Dart - GeeksforGeeks

08 Jun, 2020
It is the term used in various programming languages (not just in dart), to describe a condition where the scope of the variable is not present when the control is out of the block of code where the scope was present. Dart is a lexically scoped language, i.e. you can find the scope of the variable by the help of the braces.
Example 1: Lexical Scope of a variable.
// Declaring a variable whose scope is globalvar outter_most;  void main() {// This variable is inside main and can be accessed within  var inside_main;    void geeksforgeeks() {// This variable is inside geeksforgeeks and can be accessed within    var inside_geeksforgeeks;      void geek() {// This variable is geek and can be accessed within      var inside_geek;      }  }}
The above code depicts, about the scope of the variable in dart function and how their scope 
ends outside braces.
In programming languages, a lexical closure, also called closure or function closure, is a way of implementing lexical scope name binding in a function. It is a function object that has access to variables in its lexical scope, even when the function is used outside the scope.
Example 2:
Function geeksforgeeks(num add) {  return (num i) => add + i;}  void main() {  // Create a function that adds 2.  var geek1 = geeksforgeeks(2);    // Create a function that adds 4.  var geek2 = geeksforgeeks(4);    print(geek1(3));  print(geek2(3));}
Output:
5
7
Note:
Functions can close over variables defined in surrounding scopes. In the following example,
geeksforgeeks() captures the variable addBy. Wherever the returned function goes, it remembers
"add" variable.

Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Flutter - Dialogs
Flutter - Positioned Widget
Flutter - Managing the MediaQuery Object
Format Dates in Flutter
What is widgets in Flutter?
Mean Encoding - Machine Learning - GeeksforGeeks

03 Jun, 2020
During Feature Engineering the task of converting categorical features into numerical is called Encoding.There are various ways to handle categorical features like OneHotEncoding and LabelEncoding, FrequencyEncoding or replacing by categorical features by their count. In similar way we can uses MeanEncoding.
Created a DataFrame having two features named subjects and Target and we can see that here one of the features (SubjectName) is Categorical, so we have converted it into the numerical feature by applying Mean Encoding.Code:
# importing librariesimport pandas as pd  # creating datasetdata={'SubjectName':['s1','s2','s3','s1','s4','s3','s2','s1','s2','s4','s1'],      'Target':[1,0,1,1,1,0,0,1,1,1,0]}  df = pd.DataFrame(data)  print(df)
Output:
     SubjectName  Target
0    s1    1
1    s2    0
2    s3    1
3    s1    1
4    s4    1
5    s3    0
6    s2    0
7    s1    1
8    s2    1
9    s4    1
10    s1    0

Code : Counting every datapoints in SubjectName
df.groupby(['SubjectName'])['Target'].count()
Output:
subjectName
 s1         4
 s2         3
 s3         2
 s4         2
Name: Target, dtype: int64

Code: groupby data with SubjectName with their mean according to their positive target value
df.groupby(['SubjectName'])['Target'].mean()
Output:
subjectName
s1         0.750000
s2         0.333333
s3         0.500000
s4         1.000000
Name: Target, dtype: float64

The output shows the mean mapped with data point in SubjectName with their positive target value (1-positive and 0-Negative).
Code : Finally assigning the mean value and map with df[‘SubjectName’]
Mean_encoded_subject = df.groupby(['SubjectName'])['Target'].mean().to_dict()  df['SubjectName'] =  df['SubjectName'].map(Mean_encoded_subject)  print(df)
Output : Mean Encoded Data
    SubjectName    Target
0    0.750000    1
1    0.333333    0
2    0.500000    1
3    0.750000    1
4    1.000000    1
5    0.500000    0
6    0.333333    0
7    0.750000    1
8    0.333333    1
9    1.000000    1
10    0.750000    0

Pros of MeanEncoding:
Capture information within the label, therefore rendering more predictive features
Creates a monotonic relationship between the variable and the target
Cons of MeanEncodig:
It may cause over-fitting in the model.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Assigning values to static final variables in Java

14 Sep, 2021
Assigning values to static final variables in Java: In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.For example, following program works fine.  
Java
class Test {     // i could be assigned a value here    // or constructor or init block also.    final int i;    Test()    {        i = 10;    }     // other stuff in the class}
If we make i as static final then we must assign value to i with the declaration.  
Java
class Test {     // Since i is static final,    // it must be assigned value here    // or inside static block .    static final int i;    static    {        i = 10;    }     // other stuff in the class}
Such behavior is obvious as static variables are shared among all the objects of a class; creating a new object would change the same static variable which is not allowed if the static variable is final.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
karthikthamilarasan
kk9826225
java-basics
Java-Output
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Set in Java
Stream In Java
Initializing a List in Java
Singleton Class in Java
String slicing in Python to rotate a string

16 Jun, 2022
Given a string of size n, write functions to perform following operations on string.
Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).
Left (Or anticlockwise) rotate the given string by d elements (where d <= n).
Right (Or clockwise) rotate the given string by d elements (where d <= n).
Examples:
Input : s = "GeeksforGeeks"
        d = 2
Output : Left Rotation  : "eksforGeeksGe" 
         Right Rotation : "ksGeeksforGee"  


Input : s = "qwertyu" 
        d = 2
Output : Left rotation : "ertyuqw"
         Right rotation : "yuqwert"
Method#1: We have existing solution for this problem please refer Left Rotation and Right Rotation of a String link. We will solve this problem quickly in python using String Slicing. Approach is very simple,
Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].Now concatenate these two parts second + first accordingly.
Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].
Now concatenate these two parts second + first accordingly.
Python3
# Function to rotate string left and right by d length def rotate(input,d):     # slice string in two parts for left and right    Lfirst = input[0 : d]    Lsecond = input[d :]    Rfirst = input[0 : len(input)-d]    Rsecond = input[len(input)-d : ]     # now concatenate two parts together    print ("Left Rotation : ", (Lsecond + Lfirst) )    print ("Right Rotation : ", (Rsecond + Rfirst)) # Driver programif __name__ == "__main__":    input = 'GeeksforGeeks'    d=2    rotate(input,d)
Output:
Left Rotation  : eksforGeeksGe 
Right Rotation : ksGeeksforGee
Method#2: We use extended string to rotate the string. We will solve this problem quickly in python by slicing extended string. Approach is very simple,
Use extended string Extend_str, for Left rotation Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n].Now print this string. 
Python3
# Function to rotate string left and right by d length def rotate(str1,n):     # Create the extended string and index of for rotation    temp = str1 + str1    l1 = len(str1)    l2 = len(temp)    Lfirst = temp[n  : l1+n]    Lfirst = temp[l1-n : l2-n]     # now printing the string    print ("Left Rotation : ", Lfirst)    print ("Right Rotation : ", Lfirst ) # Driver programif __name__ == "__main__":    input = 'GeeksforGeeks'    d=2    rotate(input,d)
Left Rotation :  ksGeeksforGee
Right Rotation :  ksGeeksforGee

satyam00so
Python string-programs
python-string
rotation
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy nanmedian() function

20 Jun, 2022
numpy.nanmedian() function can be used to calculate the median of array ignoring the NaN value. If array have NaN value and we can find out the median without effect of NaN value. Let’s see different type of examples about numpy.nanmedian() method. 
Syntax: numpy.nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=)Parameters: a: [arr_like] input array axis: we can use axis=1 means row wise or axis=0 means column wise. out: output array overwrite_input: If True, then allow use of memory of input array a for calculations. The input array will be modified by the call to median. keepdims: If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.Returns: It return median in ndarray.  
Example #1:
Python3
# Python code to demonstrate the# use of numpy.nanmedianimport numpy as np # create 2d array with nan value.arr = np.array([[12, 10, 34], [45, 23, np.nan]]) print("Shape of array is", arr.shape) print("Median of array without using nanmedian function:",                                           np.median(arr)) print("Using nanmedian function:", np.nanmedian(arr))
Output: 
Shape of array is (2, 3)
Median of array without using nanmedian function: nan
Using nanmedian function: 23.0
Example #2: 
Python3
# Python code to demonstrate the# use of numpy.nanmedian# with axisimport numpy as np # create 2d array with nan value.arr = np.array([[12, 10, 34], [45, 23, np.nan]]) print("Shape of array is", arr.shape) print("Median of array with axis = 0:",             np.median(arr, axis = 0)) print("Using nanmedian function:",      np.nanmedian(arr, axis = 0))
Output:  
Shape of array is (2, 3)
Median of array with axis = 0: [ 28.5  16.5   nan]
Using nanmedian function: [ 28.5  16.5  34. ]
Example #3: 
Python3
# Python code to demonstrate the# use of numpy.nanmedian# with axis = 1import numpy as np # create 2d matrix with nan valuearr = np.array([[12, 10, 34],                [45, 23, np.nan],                 [7, 8, np.nan]]) print("Shape of array is", arr.shape) print("Median of array with axis = 0:",             np.median(arr, axis = 1)) print("Using nanmedian function:",      np.nanmedian(arr, axis = 1))
Output: 
Shape of array is (3, 3)
Median of array with axis = 0: [ 12.  nan  nan]
Using nanmedian function: [ 12.   34.    7.5]
adnanirshad158
prachisoda1234
vinayedula
Python numpy-Statistics Functions
Python-numpy
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
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
TypeScript | String indexOf() Method

18 Jun, 2020
The indexOf() is an inbuilt function in TypeScript which is used to get the index within the calling String object of the first occurrence of the specified value. Syntax:
string.indexOf(searchValue[, fromIndex]) 
Parameter: This method accepts two parameter as mentioned above and described below . 
searchValue: This parameter is a string representing the value to search for.
fromIndex: This parameter is a location within the calling string to start the search from.
Return Value: This method returns the index of the found occurrence, otherwise -1 if not found.
Below example illustrate the  String indexOf() method in TypeScriptJS:Example 1: 
JavaScript
<script>    // Original strings    var str1 = new String('TypeScript | \String indexOf() Method with example');       // use of String indexOf() Method    console.log(str1.indexOf("String"));</script>
Output: 
13

Example 2: 
JavaScript
<script>    // Original strings    var str1 = new String('TypeScript | \    String indexOf() Method with example');       // use of String indexOf() Method    console.log(str1.indexOf("Geeks"));</script>
Output: 
-1

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – Change color of Push Button

22 Apr, 2020
In this article we will see how to change the color of button. By default, when we create a button it is of grey color although PyQt5 allows us to change this color. Below is the difference in default button and colored button.
 
In order to do this we will use setStyleSheet method.
Syntax : button.setStyleSheet(“background-color : yellow”)
Argument : It takes string as argument.
Action performed : It adds the color to button
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 40)          # changing color of button        button.setStyleSheet("background-color : yellow")          # adding action to a button        button.clicked.connect(self.clickme)        # action method    def clickme(self):            # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM cloneNode() Method

16 Jun, 2022
The DOM cloneNode() Method is used to copy or clone a node on which cloneNode() method is called. For example, a list item can be copied from one list to another using this method.Syntax:  
yourNode.cloneNode([deep])
The [deep] is an optional argument. We can set its value to “true” if we want to copy the node along with its attributes and child nodes and “false” if we want to copy the node and its attributes only.Note: If we do not specify any argument, then the value of [deep] is taken as true by default.Example-1:  
html
<!DOCTYPE html><html> <head>    <title>HTML|DOM cloneNode() Method</title>    <!-- Set CSS property to the element -->    <style>        h1,        h2 {            color: green;        }    </style></head> <body style="text-align: center;">    <div style="border:3px solid green">        <h1>           GeeksforGeeks        </h1>         <h2>          A computer science portal for geeks        </h2>    </div>     <button onclick="nClone()">        Click here to clone the above elements.    </button>     <!-- nClone() function is used to fetch our node     and apply cloneNode method on it     and cloning it with another element-->    <script>        function nClone() {            // accessing div attribute using a            //variable geek            var geek =                document.getElementsByTagName("DIV")[0];             // cloning geek variable into a variable           //named clone            var clone = geek.cloneNode(true);             // adding our clone variable to end             //of the document            document.body.appendChild(clone);        }    </script></body> </html>
Output:Before clicking the button: 
After clicking the button: 
Example-2:  
html
<!DOCTYPE html><html>          <head>        <title>HTML|DOM cloneNode() Method</title>        <!-- Set CSS property to the element -->        <style>        h1, h2 {                color: green;            }        </style>    </head>     <body><h1>GeeksforGeeks</h1><h2> A computer science portal for geeks</h2><ul id="list1"><li>Geek1</li><li>Geek2</li></ul><ul id="list2"><li>Geek3</li><li>Geek4</li></ul> <button onclick="clone()">Try it</button> <script>    function clone() {        // accessing list2 last item and storing it in a variable "geek"            var listItem = document.getElementById("list2").lastChild;                 // cloning listItem variable into a variable named clone        var clone = listItem.cloneNode(true);                     // adding our clone variable to end of the list1.        document.getElementById("list1").appendChild(clone);        }</script></body> </html>                   
Output:Before clicking the button: 
After clicking the button: 
Supported Browser: The browser supported by DOM cloneNode() Method are listed below:  
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 6 and above
Firefox 1 and above
Opera 7 and above
Safari 1.1 and above
 
Akanksha_Rai
shubham_singh
adnanirshad158
kumargaurav97520
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to Count Primes in Ranges - GeeksforGeeks

13 Jan, 2022
Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples:  
Input : Query 1 : L = 1, R = 10
        Query 2 : L = 5, R = 10
Output : 4
         2
Explanation
Primes in the range L = 1 to R = 10 are 
{2, 3, 5, 7}. Therefore for query, answer 
is 4 {2, 3, 5, 7}.
For the second query, answer is 2 {5, 7}.
 
A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1].  
C++
// CPP program to answer queries for count of// primes in given range.#include <bits/stdc++.h>using namespace std;  const int MAX = 10000;  // prefix[i] is going to store count of primes// till i (including i).int prefix[MAX + 1];  void buildPrefix(){    // Create a boolean array "prime[0..n]". A     // value in prime[i] will finally be false     // if i is Not a prime, else true.    bool prime[MAX + 1];    memset(prime, true, sizeof(prime));      for (int p = 2; p * p <= MAX; p++) {          // If prime[p] is not changed, then         // it is a prime        if (prime[p] == true) {              // Update all multiples of p            for (int i = p * 2; i <= MAX; i += p)                prime[i] = false;        }    }      // Build prefix array    prefix[0] = prefix[1] = 0;    for (int p = 2; p <= MAX; p++) {        prefix[p] = prefix[p - 1];        if (prime[p])            prefix[p]++;    }}  // Returns count of primes in range from L to// R (both inclusive).int query(int L, int R){    return prefix[R] - prefix[L - 1];}  // Driver codeint main(){    buildPrefix();      int L = 5, R = 10;    cout << query(L, R) << endl;      L = 1, R = 10;    cout << query(L, R) << endl;      return 0;}
Output:  
2
4
Please refer complete article on Count Primes in Ranges for more details!
array-range-queries
prefix-sum
Prime Number
sieve
C++
C++ Programs
Mathematical
prefix-sum
Mathematical
Prime Number
sieve
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Convert string to char array in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
PyQt5 – Get geometry of the Push button - GeeksforGeeks

22 Apr, 2020
We know we can set geometry of button using setGeometry method, geometry in PyQt5 refer to the location and size of the push button.
In order to get the geometry of any push button we will usegeometry method. This method will return the QRect object which tells the location and the size of push button also it is the argument of setGeometry method.
Syntax : button.geometry()
Argument : It takes no argument.
Return It returns QRect object.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 40)          # adding action to a button        button.clicked.connect(self.clickme)          # getting geometry        geo = button.geometry()                  # printing the geometry        print(geo)          # action method    def clickme(self):            # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
PyQt5.QtCore.QRect(200, 150, 100, 40)
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Tryit Editor v3.7

Tryit: Using letter-spacing
MySQL | PARTITION BY Clause

06 Mar, 2019
A PARTITION BY clause is used to partition rows of table into groups. It is useful when we have to perform a calculation on individual rows of a group using other rows of that group.
It is always used inside OVER() clause.
The partition formed by partition clause are also known as Window.
This clause works on windows functions only. Like- RANK(), LEAD(), LAG() etc.
If this clause is omitted in OVER() clause, then whole table is considered as a single partition.
Syntax:The syntax for Partition clause is-
Window_function ( expression ) 
       Over ( partition by expr [order_clause] [frame_clause] ) 

Here, order_clause and frame_clause are optional.
expr can be column names or built-in functions in MySQL.
But, standard SQL permits only column names in expr.
Examples:
Consider, a table “Hacker“:
We have to find the rank of hackers in each challenge. That means we have to list all participated hackers of a challenge along with their rank in that challenge.
Query:
select challenge_id, h_id, h_name, score, 
   dense_rank() over ( partition by challenge_id order by score desc ) 
       as "rank", from hacker;

Explanation:
In the above query, partition by clause will partition table into groups that are having same challenge_id.
order by will arrange the hackers of each partition in descending order by “scores”.
over() clause defines how to partition and order rows of table, which is to be processed by window function rank().
dense_rank() is a window function, which will assign rank in ordered partition of challenges. If two hackers have same scores then they will be assigned same rank.
Output:
Thus, we get list of all hackers along with their ranks in the individual challenges.
DBMS-SQL
mysql
SQL-Clauses
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Trigger | Student Database
SQL | Views
Introduction of ER Model
SQL Interview Questions
Types of Functional dependencies in DBMS
Difference between DELETE, DROP and TRUNCATE
PostgreSQL – Show Tables

28 Aug, 2020
PostgreSQL does not support the SHOW TABLES statement directly like MySQL does but provides users with an alternative. In this article, we will explore them in detail.
One way to list all the tables in a database is to use the below command after logging into the database:
Syntax: \dt
Example:
In this example, we will query for the list of all tables in the sample database, ie, dvdrental.
First, log in to the sample database using the below command:
\c dvdrental
Now use the below command to list the tables of the same:
\dt
Output:
Another way to show tables in PostgreSQL is to use the SELECT statement to query data from the PostgreSQL catalog as follows:
Syntax:
SELECT *
FROM pg_catalog.pg_tables
WHERE schemaname != 'pg_catalog' AND 
    schemaname != 'information_schema';
Example:
In this example, we will query for the list of all tables in the sample database, ie, dvdrental.
First, log in to the sample database using the below command:
\c dvdrental
Now runt the below command to list the tables in the database:
SELECT *
FROM pg_catalog.pg_tables
WHERE schemaname != 'pg_catalog' AND 
    schemaname != 'information_schema';
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Argument vs Parameter in Java

23 Feb, 2022
Argument
An argument is a value passed to a function when the function is called. Whenever any function is called during the execution of the program there are some values passed with the function. These values are called arguments. An argument when passed with a function replaces with those variables which were used during the function definition and the function is then executed with these values. Let’s look at some examples for easy understanding:Example: 
Java
public class Example {     public static int multiply(int a, int b)    {        return a * b;    }     public static void main(String[] args)    {        int x = 2;        int y = 5;         // the variables x and y are arguments        int product = multiply(x, y);         System.out.println("PRODUCT IS: " + product);    }}
Output:
PRODUCT IS: 10
In the above example 
in the function  
the variable x and y are the arguments
Parameters
A parameter is a variable used to define a particular value during a function definition. Whenever we define a function we introduce our compiler with some variables that are being used in the running of that function. These variables are often termed as Parameters. The parameters and arguments mostly have the same value but theoretically, are different from each other.Example: 
Java
public class Example {     // the variables a and b are parameters    public static int multiply(int a, int b)    {        return a * b;    }     public static void main(String[] args)    {        int x = 2;        int y = 5;         int product = multiply(x, y);         System.out.println("PRODUCT IS:" + product);    }}
Output:
PRODUCT IS: 10
In the above example 
in the function  
the variable a and b are the parameters
Difference between an Argument and a Parameter
ManasChhabra2
francisalvinbarretto
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Non-binary Counter in Digital Logic

23 Apr, 2020
A counter is a circuit that counts the number of occurrences of an input. The circuit consists of flip-flops which along with combinational elements are used for generation of control signals.
If M = Total number of states, and
   n = Total number of flip-flop
Then,      M <= 2n
If         M = 2n    ; Binary counter
and        M < 2n    ; Non-binary counter 
Block Diagram of Non-Binary Counter:Here is the block diagram of a mod-10 counter. Here, the total number of flip-flops required is 4 thus the number of used state is 10 and number of unused state is 6.
In order to design a non binary counter a logic gate is required which detects M stage. In mod-10 coounter 10 stages are detected from 0000 to 10001 and as soon as 1010 appears it clears all the flip-flops.
Making of Non-binary counter:For making non-binary counter,
If CLR is present and CLK is connected with output Q, then we use AND gate.
If CLR is present and CLK is connected with output Q’, then we use NOR gate.
If complement of CLR is present and CLK is connected with output Q, then we use NAND gate.
If complement of CLR is present and CLK is connected with output Q’, then we use OR gate.
Truth Table:
It is clear from truth table that as soon as 1010 appears, inputs to the AND gate becomes 11 which resets the flip-flop with CLR =1.
Output Frequency:The output frequency of mod-M counter,
= f / M 
If there is no feedback present at last output (i.e D) then the output frequency,
= f / (2n) 
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Double.GetHashCode() Method in C# - GeeksforGeeks

17 Mar, 2019
Double.GetHashCode() Method is used to return the hash code for this instance.
Syntax: public override int GetHashCode ();
Return Value: This method returns a 32-bit signed integer hash code.
Below programs illustrate the use of Double.GetHashCode() Method:
Example 1:
// C# program to demonstrate the// Double.GetHashCode() Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {          // Declaring and initializing value1        double value1 = 10d;          // getting the HashCode        // using GetHashCode() method        int value = value1.GetHashCode();          // Display the HashCode        Console.WriteLine("HashCode is {0}", value);    }}
HashCode is 1076101120

Example 2:
// C# program to demonstrate the// Double.Equals(Double)// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // calling get() method        get(5d);        get(5.5d);        get(10d);        get(7.5d);    }      // defining get() method    public static void get(double value1)    {          // getting the HashCode        // using GetHashCode() method        int value = value1.GetHashCode();          // Display the HashCode        Console.WriteLine("HashCode is {0}", value);    }}
HashCode is 1075052544
HashCode is 1075183616
HashCode is 1076101120
HashCode is 1075707904

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.double.gethashcode?view=netframework-4.7.2
CSharp-Double-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
PostgreSQL - CREATE TRIGGER - GeeksforGeeks

28 Aug, 2020
To create a new trigger in PostgreSQL, you follow these steps:
First, create a trigger function using CREATE FUNCTION statement.
Second, bind the trigger function to a table by using the CREATE TRIGGER statement.
A trigger function is similar to an ordinary function. However, a trigger function does not take any argument and has a return value with the type of trigger.
The following illustrates the syntax of creating a trigger function:
Syntax:
CREATE FUNCTION trigger_function() 
   RETURNS trigger AS

A trigger function receives data about its calling environment through a special structure called TriggerData, which contains a set of local variables. Once you define a trigger function, you can bind it to one or more triggers events such as INSERT, UPDATE, and DELETE.
Example:
Let’s take a look at an example of creating a new trigger. In this example, we will create a new table named COMPANY as follows:
CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

When the name of an employee changes, we log the changes in a separate table named AUDIT :
CREATE TABLE AUDIT(
   EMP_ID INT NOT NULL,
   ENTRY_DATE TEXT NOT NULL
);

First, define a new function called auditlog():
CREATE OR REPLACE FUNCTION auditlog() RETURNS TRIGGER AS $example_table$
   BEGIN
      INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
      RETURN NEW;
   END;
$example_table$ LANGUAGE plpgsql;

The function inserts the old last name into the AUDIT table including employee id, last name, and the time of change if the last name of an employee changes. Second, bind the trigger function to the employees table. The trigger name is name changes. Before the value of the name column is updated, the trigger function is automatically invoked to log the changes.
 CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY
FOR EACH ROW EXECUTE PROCEDURE auditlog();

Third, insert some sample data for testing. We insert two rows into the employees table.
INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY)
VALUES (1, 'Raju', 25, 'New-Delhi', 33000.00 );

To examine the employees table use the below query:
SELECT * FROM COMPANY;

Output:
postgreSQL-triggers
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Cursor
PostgreSQL - Copy Table
PostgreSQL - Record type variable
MongoEngine - Atomic Updates

Atomicity is one of the ACID transaction properties. A database transaction has to be indivisible and irreducible so that it either occurs completely or doesn’t occur at all. This property is called Atomicity. MongoDB supports Atomicity only on single documents and not on multi-document transactions.
MongoEngine provides the following methods for atomic updates on a queryset.
update_one() − Overwrites or adds first document matched by query.
update() − Performs atomic update on fields matched by query.
modify() − Update a document and return it.
Following modifiers may be used with these methods. (These modifiers come before the field, not after).
The following is an example of atomic update, we first create a Document class called tests and add a document in it.
from mongoengine import *
con=connect('newdb')

class tests (Document):
   name=StringField()
   attempts=IntField()
   scores=ListField(IntField())

t1=tests()
t1.name='XYZ'
t1.attempts=0
t1.scores=[]
t1.save()
Let us use update_one() method to update name field from XYZ to MongoDB.
tests.objects(name='XYZ').update_one(set__name='MongoDB')
The push modifier is used to add data in ListField (scores).
tests.objects(name='MongoDB').update_one(push__scores=50)
To increment attempts field by one, we can use inc modifier.
tests.objects(name='MongoDB').update_one(inc__attempts=1)
The updated document looks as follows −
{
"_id":{"$oid":"5ebcf8d353a48858e01ced04"},
"name":"MongoDB",
"attempts":{"$numberInt":"1"},
"scores":[{"$numberInt":"50"}]
}
 Print
 Add Notes
 Bookmark this page
How to use an update function to animate a NetworkX graph in Matplotlib?

To use an update function to animate a NetworkX graph in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Initialize a graph with edges, name, and graph attributes.
Add nodes to the graph using add_nodes_from() method.
Draw the graph G with Matplotlib.
Use FuncAnimation() class to make an animation by repeatedly calling a function, animate.
Function animate clears the current figure, generate two random numbers, and draws the edges between them.
To display the figure, use show() method.
from matplotlib import pyplot as plt, animation
import networkx as nx
import random

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

fig = plt.figure()

G = nx.DiGraph()
G.add_nodes_from([0, 1, 2, 3, 4])

nx.draw(G, with_labels=True)

def animate(frame):
   fig.clear()
   num1 = random.randint(0, 4)
   num2 = random.randint(0, 4)
   G.add_edges_from([(num1, num2)])
   nx.draw(G, with_labels=True)

ani = animation.FuncAnimation(fig, animate, frames=6, interval=1000, repeat=True)

plt.show()
Algorithms | Analysis of Algorithms (Recurrences) | Question 3 - GeeksforGeeks

28 Jun, 2021
What is the worst case time complexity of following implementation of subset sum problem.
// Returns true if there is a subset of set[] with sun equal to given sumbool isSubsetSum(int set[], int n, int sum){   // Base Cases   if (sum == 0)     return true;   if (n == 0 && sum != 0)     return false;      // If last element is greater than sum, then ignore it   if (set[n-1] > sum)     return isSubsetSum(set, n-1, sum);      /* else, check if sum can be obtained by any of the following      (a) including the last element      (b) excluding the last element   */   return isSubsetSum(set, n-1, sum) ||           isSubsetSum(set, n-1, sum-set[n-1]);}
(A) O(n * 2^n)(B) O(n^2)(C) O(n^2 * 2^n)(D) O(2^n)Answer: (D)Explanation: Following is the recurrence for given implementation of subset sum problem
T(n) = 2T(n-1) + C1T(0) = C1
Where C1 and C2 are some machine specific constants.
The solution of recurrence is O(2^n)
We can see it with the help of recurrence tree method
           C1
       /       \
    T(n-1)     T(n-1) 


                    C1
                /       \
              C1           C1
           /     \        /    \
      T(n-2)  T(n-2)   T(n-2)  T(n-2)

                    C1
                /       \
              C1           C1
           /     \        /    \
          C1     C1      C1     C1
        /   \   /  \    /  \   /  \

       
If we sum the above tree level by level, we get the following series
T(n) = C1 + 2C1 + 4C1 + 8C1 + ...
The above series is Geometrical progression and there will be n terms in it.
So T(n) = O(2^n)    

Quiz of this Question
Algorithms-Analysis of Algorithms (Recurrences)
Analysis of Algorithms (Recurrences)
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Graph Traversals | Question 2
Algorithms | Graph Traversals | Question 12
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Sorting | Question 5
Algorithms | Recursion | Question 2
Algorithms | Sorting | Question 7
Algorithms | Recursion | Question 5
Algorithms | Recursion | Question 9
C library Macro - ERANGE

As mentioned above, the C library macro ERANGE represents a range error, which occurs if an input argument is outside the range, over which the mathematical function is defined and errno is set to ERANGE.
Following is the declaration for ERANGE Macro.
#define ERANGE some_value
NA
NA
NA
NA
The following example shows the usage of ERANGE Macro.
#include <stdio.h>
#include <errno.h>
#include <math.h>

int main () {
   double x;
   double value;

   x = 2.000000;
   value = log(x);
   
   if( errno == ERANGE ) {
      printf("Log(%f) is out of range\n", x);
   } else {
      printf("Log(%f) = %f\n", x, value);
   }

   x = 1.000000;
   value = log(x);
   
   if( errno == ERANGE ) {
      printf("Log(%f) is out of range\n", x);
   } else {
      printf("Log(%f) = %f\n", x, value);
   }
   
   x = 0.000000;
   value = log(x);
   
   if( errno == ERANGE ) {
      printf("Log(%f) is out of range\n", x);
   } else {
      printf("Log(%f) = %f\n", x, value);
   }
   
   return 0;
}
Let us compile and run the above program that will produce the following result −
Log(2.000000) = 0.693147                                      
Log(1.000000) = 0.000000                                      
Log(0.000000) is out of range


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
LISP - When Construct

The when macro is followed by a test clause that evaluates to t or nil. If the test clause is evaluated to nil, then no form is evaluated and nil is returned, however the test result is t, then the action following the test clause is executed.
Syntax for when macro −
(when (test-clause) (<action1) )

Create a new source code file named main.lisp and type the following code in it.
(setq a 100)
(when (> a 20)
   (format t "~% a is greater than 20"))
(format t "~% value of a is ~d " a)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
a is greater than 20
value of a is 100 


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Find the number of rows and columns of a given matrix using NumPy - GeeksforGeeks

29 Aug, 2020
In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix.
Syntax:
shape()
Return: The number of rows and columns.
Example:
Python
import numpy as np    matrix= np.arange(1,9).reshape((3, 3))  # Original matrixprint(matrix)  # Number of rows and columns of the said matrixprint(matrix.shape)
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
(3,3)

Example :
Python
import numpy as np    matrix= np.arange(10,15).reshape((3, 2))  # Original matrix:print(matrix)  # Number of rows and columns of the said matrixprint(matrix.shape)
Output
[[10 11]
[12 13]
[14 15]]
(3,2)

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
MongoEngine - Indexes

An indexed collection results in faster processing of queries. By default, every collection is automatically indexed on _id field. In addition, you can create index on one or more fields.
Using Compass, we can build index very easily. Click on CREATE INDEX button on Indexes tab as shown in figure below−
A dialog box appears as shown. Choose name of index, field on which to index, order of index (ascending or descending) and other options.
While using MongoEngine, indexes are created by specifying ‘indexes’ key in meta dictionary of definition of Document class.
Value of indexes property is a list of fields. In the following example, we ask documents in student collection be indexed according to name field.
from mongoengine import *
con=connect('mydata')
class student(Document):
   name=StringField(required=True)
   course=StringField()
   meta = {'indexes':['name']}
   
s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
By default, indexing order is ascending. Order may be specified by prepending ‘+’ for ascending or ‘-‘ for descending order.
To create compound index, use a tuple of field names, optionally having + or – symbol attached to indicate sort order.
In the following example, student document class contains definition of compound index on name and course (note - symbol prefixed to course field which means index is built namewise ascending and coursewise descending order.
from mongoengine import *
con=connect('mydata')

class student(Document):
   name=StringField(required=True)
   course=StringField()
   meta = {'indexes':[('name','-course')]}

s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
MongoDB Compass will show indexes as below −
Value of ‘indexes’ may be a dictionary of various options as below −
Following example creates index on name field that expires after 3600 seconds.
from mongoengine import *
con=connect('mydata')

class student(Document):
   name=StringField(required=True)
   course=StringField()
   meta = {'indexes':[{
            'fields': ['name'],
            'expireAfterSeconds': 3600
           }
    ]
}

To specify text index, prefix field name with ‘$’ sign and for hashed index, use ‘#’ as prefix.
Indexes so specified are created automatically as documents are added in the collection. To disable automatic creation, set ‘auto_create_index’ to False in meta attribute.
We have list_indexes() method with Document class that displays list of available indexes.
print (student.list_indexes())

[[('name', 1)], [('_id', 1)]]

To create index on a field not in the meta dictionary, use create_index() method. The following code will create index on course field −
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[{
          'fields': ['name'],
          'expireAfterSeconds': 3600
        }
]}
student.create_index(['course'])

 Print
 Add Notes
 Bookmark this page