code-rag-bench/online-tutorials huggingface dataset:
C# Decimal ("D") Format Specifier

The "D" (or decimal) format specifier works for integer type. It converts a number to a string of decimal digits (0-9).
Let’say the following is our number.
int val = 467;
Now to return the result as 0467, use the following decimal format specifier.
val.ToString("D4")
Let us see another example.
 Live Demo
using System;
using System.Globalization;
class Demo {
   static void Main() {
      int val;
      val = 877;
      Console.WriteLine(val.ToString("D"));
      Console.WriteLine(val.ToString("D4"));
      Console.WriteLine(val.ToString("D8"));
   }
}
877
0877
00000877
Python 3 - Number seed() Method

The seed() method initializes the basic random number generator. Call this function before calling any other random module function.
Following is the syntax for seed() method:
seed ([x], [y])

Note − This function initializes the basic random number generator.
x − This is the seed for the next random number. If omitted, then it takes system time to generate the next random number. If x is an int, it is used directly.
y − This is version number (default is 2). str, byte or byte array object gets converted in int. Version 1 used hash() of x.
This method does not return any value.
The following example shows the usage of seed() method.
#!/usr/bin/python3
import random

random.seed()
print ("random number with default seed", random.random())

random.seed(10)
print ("random number with int seed", random.random())

random.seed("hello",2)
print ("random number with string seed", random.random())
When we run above program, it produces the following result −
random number with default seed 0.2524977842762465
random number with int seed 0.5714025946899135
random number with string seed 0.3537754404730722


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
SAP HANA - SQL Stored Procedures

A procedure allows you to group the SQL statement into a single block. Stored Procedures are used to achieve certain result across applications. The set of SQL statements and the logic that is used to perform some specific task are stored in SQL Stored Procedures. These stored procedures are executed by applications to perform that task.
Stored Procedures can return data in the form of output parameters (integer or character) or a cursor variable. It can also result in set of Select statements, which are used by other Stored Procedures.
Stored Procedures are also used for performance optimization as it contains series of SQL statements and results from one set of statement determines next set of statements to be executed. Stored procedures prevent users to see the complexity and details of tables in a database. As Stored procedures contain certain business logic, so users need to execute or call the procedure name.
No need to keep reissuing the individual statements but can refer to the database procedure.
Create procedure prc_name (in inp integer, out opt "EFASION"."ARTICLE_LOOKUP")
as
begin
opt = select * from "EFASION"."ARTICLE_LOOKUP" where article_id = :inp ;
end;

    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How do I begin auto increment from a specific point in MySQL?

To begin auto increment from a specific point, use ALTER command. The syntax is as follows −
ALTER TABLE yourTableName auto_increment = anySpecificPoint;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table AutoIncrementSpecificPoint
   −> (
   −> BookId int auto_increment not null,
   −> Primary key(BookId)
   −> );
Query OK, 0 rows affected (0.56 sec)
Now you can insert records using insert command.
The query is as follows −
mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.17 sec)

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.17 sec)

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.10 sec)
The above insert command begins the value from 1 and adds 1 to the next value. Now you can check all records from table using select statement.
The query is as follows −
mysql> select *from AutoIncrementSpecificPoint;
The following is the output −
+--------+
| BookId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
+--------+
4 rows in set (0.00 sec)
Look at the above sample output, the auto_increment starts from 1.
Now to change the auto_increment to begin from a specific point, you can use ALTER command. The query is as follows −
mysql> alter table AutoIncrementSpecificPoint auto_increment = 100;
Query OK, 0 rows affected (0.25 sec)
Records: 0 Duplicates: 0 Warnings: 0
In the above query I have set the auto increment to 100. Let us now insert records once again in the table using insert command. The query is as follows −
mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.25 sec)

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from AutoIncrementSpecificPoint;
The following is the output displaying the other values set for auto increment i.e. beginning from 100 −
+--------+
| BookId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|    100 |
|    101 |
|    102 |
+--------+
7 rows in set (0.00 sec)
How can I dynamically update my Matplotlib figure as the data file changes?

To update a Matplotlib figure as the data file changes, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize variables m and n, to get a set of subplots.
Create a list of colors, to plot color dynamically.
Plot dynamic data points using plot() method with random data points.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import random

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

m = 2
n = 4

fix, axes = plt.subplots(nrows=m, ncols=n)
hexadecimal_alphabets = '0123456789ABCDEF'

color = ["#" + ''.join([random.choice(hexadecimal_alphabets)
                        for j in range(6)]) for i in range(m*n)]

for i in range(m):
   for j in range(n):
      axes[i][j].clear()
      axes[i][j].plot(np.random.rand(10), np.random.rand(10),
                     color=color[100 % np.random.randint(1, len(color))])
      plt.pause(0.1)

plt.show()
How to count total number of documents in MongoDB Collection using Node.js ? - GeeksforGeeks

12 Feb, 2021
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. 
Installing module: You can install mongodb module using the following command.
node install mongodb
Project Structure:
Running the server on Local IP: Data is the directory where the MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB Database:
Database:GFG
Collection:aayush
Following is the sample data stored in your database for this example.
Filename: index.js
Java
// Requiring moduleconst MongoClient = require("mongodb"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = "GFG";  MongoClient.connect(url).then((client) => {  const connect = client.db(databasename);   // Connect to collection  const collection = connect.collection("aayush");   // Count the total documents  collection.countDocuments().then((count_documents) => {    console.log(count_documents);  }).catch((err) => {    console.log(err.Message);  })      }).catch((err) => {  // Printing the error message  console.log(err.Message);})</div>
Run index.js file using the following command:
node index.js
Output:
mridulmanochagfg
MongoDB-method
Node.js-Misc
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
The globals(), locals() and reload() Functions in Python

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.
When the module is imported into a script, the code in the top-level portion of a module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −
reload(hello)
HTML5 Canvas - Drawing Bezier Curves

We need the following methods to draw Bezier curves on the canvas −
beginPath()
This method resets the current path.
moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
This method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points.
The x and y parameters in bezierCurveTo() method are the coordinates of the end point. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point.
Following is a simple example which makes use of above mentioned methods to draw a Bezier curves.
<!DOCTYPE HTML>

<html>
   <head>
      
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         function drawShape() {
            
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
            
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               
               ctx.beginPath();
               ctx.moveTo(75,40);
               
               ctx.bezierCurveTo(75,37,70,25,50,25);
               ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
               
               ctx.bezierCurveTo(20,80,40,102,75,120);
               ctx.bezierCurveTo(110,102,130,80,130,62.5);
               
               ctx.bezierCurveTo(130,62.5,130,25,100,25);
               ctx.bezierCurveTo(85,25,75,37,75,40);
               
               ctx.fill();
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
   
</html>
The above example would draw the following shape −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Clojure - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Clojure has the following types of operators −
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Note − In Clojure, operators and operands work in the following syntax manner.
(operator operand1 operand2 operandn)

For example,
(+ 1 2)
The above example does an arithmetic operation on the numbers 1 and 2.
Clojure language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available in Clojure.
Show Examples
Relational operators allow comparison of objects. Following are the relational operators available in Clojure.
Show Examples
Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy.
Show Examples
The following code snippet shows how the various operators can be used.
Clojure provides four bitwise operators. Following are the bitwise operators available in Clojure.
Show Examples
bit-and
This is the bitwise “and” operator
bit-or
This is the bitwise “or” operator
bit-xor
This is the bitwise “xor” or Exclusive ‘or’ operator
bit-not
This is the bitwise negation operator
Following is the truth table showcasing these operators.
As is the case with LISPs in general, there is no need to worry about operator precedence. This is one of the benefits of S-Expressions and prefix notation. All functions evaluate left to right and inside out. The operators in Clojure are just functions, and everything is fully parenthesized.
 Print
 Add Notes
 Bookmark this page
Print objects of a class in Python - GeeksforGeeks

29 Dec, 2019
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
Refer to the below articles to get the idea about classes and objects in Python.
Python Classes and Objects
Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users.
Example:
# Python program to demonstrate# object printing    # Defining a classclass Test:     def __init__(self, a, b):         self.a = a         self.b = b           def __repr__(self):         return "Test a:% s b:% s" % (self.a, self.b)         def __str__(self):         return "From str method of Test: a is % s, " \               "b is % s" % (self.a, self.b)   # Driver Code         t = Test(1234, 5678)   # This calls __str__() print(t)   # This calls __repr__() print([t])
Output:
From str method of Test: a is 1234, b is 5678
[Test a:1234 b:5678]

Important Points about Printing:
Python uses __repr__ method if there is no __str__ method.Example:class Test:     def __init__(self, a, b):         self.a = a         self.b = b         def __repr__(self):         return "Test a:% s b:% s" % (self.a, self.b)     # Driver Code         t = Test(1234, 5678) print(t)Output:Test a:1234 b:5678

Example:
class Test:     def __init__(self, a, b):         self.a = a         self.b = b         def __repr__(self):         return "Test a:% s b:% s" % (self.a, self.b)     # Driver Code         t = Test(1234, 5678) print(t)
Output:
Test a:1234 b:5678

If no __repr__ method is defined then the default is used.Example:class Test:     def __init__(self, a, b):         self.a = a         self.b = b     # Driver Code         t = Test(1234, 5678) print(t)  Output:<__main__.Test object at 0x7f9b5738c550>

Example:
class Test:     def __init__(self, a, b):         self.a = a         self.b = b     # Driver Code         t = Test(1234, 5678) print(t)  
Output:
<__main__.Test object at 0x7f9b5738c550>

Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Java Program to Convert a Stack Trace to a String

The Java.io.StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect.
The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream.
Using these two classes you can convert a Stack Trace to a String.
Live Demo
import java.io.PrintWriter;
import java.io.StringWriter;

public class StackTraceToString {
   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         StringWriter writer = new StringWriter();
         e.printStackTrace(new PrintWriter(writer));

         String myString = writer.toString();
         System.out.println("Stack trace message ::"+myString);
      }
   }
}
Stack trace message ::java.lang.ArrayIndexOutOfBoundsException: 3
   at lastRound.StackTraceToString.main(StackTraceToString.java:10)
How to convert a list to string in C#?

Declare a list.
List < string > l = new List < string > ();
Now, add elements to the list.
// elements
l.Add("Accessories");
l.Add("Footwear");
l.Add("Watches");
Now convert it into a string.
string str = string.Join(" ", l.ToArray());
Let us see the final code to convert a list to string in C# −
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List < string > l = new List < string > ();
      // elements
      l.Add("Accessories");
      l.Add("Footwear");
      l.Add("Watches");
      string str = string.Join(" ", l.ToArray());
      Console.WriteLine(str);
   }
}
Python-Quizzes | Python List Quiz | Question 5 - GeeksforGeeks

17 Sep, 2020
Question: 5 Find the output of the following program:
check1 = ['Learn', 'Quiz', 'Practice', 'Contribute'] check2 = check1 check3 = check1[:]   check2[0] = 'Code'check3[1] = 'Mcq'  count = 0for c in (check1, check2, check3):     if c[0] == 'Code':         count += 1    if c[1] == 'Mcq':         count += 10  print (count) 
(A) 4(B) 5(C) 11(D) 12Answer: (D)Explanation: When assigning check1 to check2, we create a second reference to the same list. Changes to check2 affect check1. When assigning the slice of all elements in check1 to check3, we are creating a full copy of check1 which can be modified independently (i.e, any change in check3 will not affect check1).So, while checking check1 ‘Code’ gets matched and the count increases to 1, but Mcq doest gets matched since its available only in check3.Now checking check2 here also ‘Code’ gets matched resulting in a count value to 2.Finally while checking check3 which is separate from both check1 and check2 here only Mcq gets matched and the count becomes 12.Quiz of this Question
Python-Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python-Quizzes | Python Dictionary Quiz | Question 25
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Miscellaneous | Question 1
Python-Quizzes | Miscellaneous | Question 9
Python-Quizzes | Miscellaneous | Question 7
Python-Quizzes | Miscellaneous | Question 10
Output of Python Program - Dictionary (set 25)
Python | Miscellaneous | Question 5
Python-Quizzes | Python Tuples Quiz | Question 10
Python | Miscellaneous | Question 4
C++ Vector Library - clear() Function

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
Following is the declaration for std::vector::clear() function form std::vector header.
void clear();

void clear() noexcept;

None
None.
This member function never throws excpetion.
Linear i.e. O(n)
The following example shows the usage of std::vector::clear() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   auto ilist = {1, 2, 3, 4, 5};
   vector<int> v(ilist);

   cout << "Initial size of vector     = " << v.size() << endl;
   /* destroy vector */
   v.clear();
   cout << "Size of vector after clear = " << v.size() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial size of vector     = 5
Size of vector after clear = 0

 Print
 Add Notes
 Bookmark this page
Python String endswith() Method

Python string method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end.
str.endswith(suffix[, start[, end]])

suffix − This could be a string or could also be a tuple of suffixes to look for.
suffix − This could be a string or could also be a tuple of suffixes to look for.
start − The slice begins from here.
start − The slice begins from here.
end − The slice ends here.
end − The slice ends here.
TRUE if the string ends with the specified suffix, otherwise FALSE.
#!/usr/bin/python

str = "this is string example....wow!!!";

suffix = "wow!!!";
print str.endswith(suffix)
print str.endswith(suffix,20)

suffix = "is";
print str.endswith(suffix, 2, 4)
print str.endswith(suffix, 2, 6)
True
True
True
False


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Lua - while Loop

A while loop statement in Lua programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in Lua programming language is as follows −
while(condition)
do
   statement(s)
end

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Here, the key point to note is that the while loop might not be executed at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
a = 10

while( a < 20 )
do
   print("value of a:", a)
   a = a+1
end
When the above code is built and executed, it produces the following result −
value of a:	10
value of a:	11
value of a:	12
value of a:	13
value of a:	14
value of a:	15
value of a:	16
value of a:	17
value of a:	18
value of a:	19


    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
Matplotlib - Histogram

A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. It is a kind of bar graph.
To construct a histogram, follow these steps −
Bin the range of values.
Divide the entire range of values into a series of intervals.
Count how many values fall into each interval.
The bins are usually specified as consecutive, non-overlapping intervals of a variable.
The matplotlib.pyplot.hist() function plots a histogram. It computes and draws the histogram of x.
The following table lists down the parameters for a histogram −
‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.
‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.
‘step’ generates a lineplot that is by default unfilled.
‘stepfilled’ generates a lineplot that is by default filled.
Following example plots a histogram of marks obtained by students in a class. Four bins, 0-25, 26-50, 51-75, and 76-100 are defined. The Histogram shows number of students falling in this range.
from matplotlib import pyplot as plt
import numpy as np
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a, bins = [0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
The plot appears as shown below −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Python Program to find out the determinant of a given special matrix

Suppose, we have a tree with n vertices, where each vertex is labeled from 1 to n. The root of the tree has the label 1, and each vertex weights wi. Now a nxn matrix A is formed where A(x,y) = Wf(x, y) where f(x, y) is the least common predecessor of vertex x and y. We have to find out the determinant of matrix A. The edges of the matrix, weights, and the total number of vertices are given to us as input.
So, if the input is like input_array = [[1, 2], [1, 3], [1, 4], [1, 5]], weights = [1, 2, 3, 4, 5], vertices = 5, then the output will be 24.
The matrix A is given as =
the determinant of this matrix is 24.
To solve this, we will follow these steps −
w := an empty list
for i in range 0 to vertices, doadd weights[i] and a new list to w
add weights[i] and a new list to w
for each i, item in enumerate(input_array), dop := item[0]q := item[1]insert q - 1 at the end of w[p - 1, 1]insert p - 1 at the end of w[q - 1, 1]
p := item[0]
q := item[1]
insert q - 1 at the end of w[p - 1, 1]
insert p - 1 at the end of w[q - 1, 1]
det := 1
stack := a stack containing a tuple (0, 0)
while stack is not empty, doi, weights := delete top element from stackdet := (det * (w[i, 0] - weights)) mod (10^9 + 7)for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1]
i, weights := delete top element from stack
det := (det * (w[i, 0] - weights)) mod (10^9 + 7)
for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1]
add tuple containing (t,w[i,0]) to the stack
for each t in w[i][1], dodelete i from w[t,1]
delete i from w[t,1]
return det
Let us see the following implementation to get better understanding −
 Live Demo
def solve(input_array, weights, vertices):
   w = [[weights[i],[]] for i in range(vertices)]
   for i, item in enumerate(input_array):
      p,q = item[0], item[1]
      w[p - 1][1].append(q - 1)
      w[q - 1][1].append(p - 1)
   det = 1
   stack = [(0,0)]
   while stack:
      i, weights = stack.pop()
      det = (det * (w[i][0] - weights)) % (10**9 + 7)
      stack += [(t,w[i][0]) for t in w[i][1]]
      for t in w[i][1]:
         w[t][1].remove(i)
   return det
print(solve([[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5))
[[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5
24
HTML - <center> Tag

The HTML <center> tag is used for centering the content enclosed with this tag. This tag is depreciated.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML center Tag</title>
   </head>

   <body>
      <center>This text is centered</center>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Calculate average value in MongoDB

To calculate average value in MongoDB, use aggregate() along with $avg. Let us create a collection with documents −
> db.demo159.insertOne({"Score":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557b2fdf09dd6d0853a01")
}
> db.demo159.insertOne({"Score":70});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557b6fdf09dd6d0853a02")
}
> db.demo159.insertOne({"Score":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557c4fdf09dd6d0853a03")
}
Display all documents from a collection with the help of find() method −
> db.demo159.find();
This will produce the following output −
{ "_id" : ObjectId("5e3557b2fdf09dd6d0853a01"), "Score" : 50 }
{ "_id" : ObjectId("5e3557b6fdf09dd6d0853a02"), "Score" : 70 }
{ "_id" : ObjectId("5e3557c4fdf09dd6d0853a03"), "Score" : 60 }
Following is the query to calculate $avg value −
> db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:"$Score"} } }])
This will produce the following output −
{ "_id" : null, "AverageValue" : 60 }
How can I set the location of minor ticks in Matplotlib?

To set the location of the minor ticks in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create a figure and a set of subplots.
Plot x and y data points using plot() method.
To locate minor ticks, use set_minor_locator() method.
To show the minor ticks, use grid(which='minor').
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator

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

x = np.linspace(1, 10, 100)
y = np.log(x)

fig, ax = plt.subplots()
ax.plot(x, y)
minor_locator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator)
plt.grid(which='minor')

plt.show()
What is the meaning of prepended double colon “::” in C++?

The prepended double colon is also known as the scope resolution operator. Some of the uses of this operator are given as follows.
The scope resolution operator can be used to define a function outside a class. A program that demonstrates this is given as follows.
 Live Demo
#include<iostream>
using namespace std;
class Example {
   int num;
   public:
   Example() {
      num = 10;
   }
   void display();
};
void Example::display() {
   cout << "The value of num is: "<<num;;
}
int main() {
   Example obj;
   obj.display();
   return 0;
}
The output of the above program is as follows.
The value of num is: 10
The scope resolution operator can be used to access a global variable when there is also a local variable with the same name. A program that demonstrates this is given as follows.
 Live Demo
#include<iostream>
using namespace std;
int num = 7;
int main() {
   int num = 3;
   cout << "Value of local variable num is: " << num;
   cout << "\nValue of global variable num is: " << ::num;
   return 0;
}
The output of the above program is as follows.
Value of local variable num is: 3
Value of global variable num is: 7
Pandas Groupby - Sort within groups - GeeksforGeeks

29 Aug, 2020
Pandas Groupby is used in situations where we want to split data and set into groups so that we can do various operations on those groups like – Aggregation of data, Transformation through some group computations or Filtration according to specific conditions applied on the groups.
In similar ways, we can perform sorting within these groups.
Example 1: Let’s take an example of a dataframe:
df = pd.DataFrame({'X': ['B', 'B', 'A', 'A'],                   'Y': [1, 2, 3, 4]})  # using groupby functiondf.groupby('X').sum()
Output:
Let’s pass the sort parameter as False.
# using groupby function # with sortdf.groupby('X', sort = False).sum()
Output:
Here, we see a dataframe with sorted values within the groups.
Example 2:Now, let’s take an example of a dataframe with ages of different people. Using sort along with groupby function will arrange the transformed dataframe on the basis of keys passes, for potential speedups.
data = {'Name':['Elle', 'Chloe', 'Noah', 'Marco',                   'Lee', 'Elle', 'Rachel', 'Noah'],          'Age':[17, 19, 18, 17,                 22, 18, 21, 20]}     df = pd.DataFrame(data) df
Output:
Let’s group the above dataframe according to the name
# using groupby without sortdf.groupby(['Name']).sum()
Output:
Passing the sort parameter as False
# using groupby function # with sortdf.groupby(['Name'], sort = False).sum()
Output:
Example 3:Let’s take another example of a dataframe that consists top speeds of various cars and bikes.We’ll try to get the top speeds sorted within the groups of vehicle type.
import pandas as pd    df = pd.DataFrame([('Bike', 'Kawasaki', 186),                   ('Bike', 'Ducati Panigale', 202),                   ('Car', 'Bugatti Chiron', 304),                    ('Car', 'Jaguar XJ220', 210),                   ('Bike', 'Lightning LS-218', 218),                    ('Car', 'Hennessey Venom GT', 270),                   ('Bike', 'BMW S1000RR', 188)],                   columns =('Type', 'Name', 'top_speed(mph)'))  df
Output:
After Using the groupby function
# Using groupby functiongrouped = df.groupby(['Type'])['top_speed(mph)'].nlargest()  # using nlargest() function will get the # largest values of top_speed(mph) within# groups createdprint(grouped)
Output:
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Double doubleToLongBits() method in Java with examples - GeeksforGeeks

26 Oct, 2018
The java.lang.Double.doubleToLongBits() method of Java Double class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout.
Syntax:
public static long doubleToLongBits(double val)

Parameter: The method accepts only one parameter val which specifies a double precision floating-point number.
Return Values: The function returns the bits that represent the floating-point number. Below are the special cases:
If the argument is positive infinity, the result is 7ff0000000000000L.
If the argument is negative infinity, the result is 0xfff0000000000000L.
If the argument is NaN, the result is 0x7ff8000000000000L.
Below programs illustrates the use of java.lang.Double.doubleToLongBits() method:
Program 1:
// Java program to demonstrate// Double.doubleToLongBits() method  import java.lang.*;  class Gfg1 {      public static void main(String args[])    {          double val = 1.5d;          // function call        long answer = Double.doubleToLongBits(val);          // print        System.out.println(val + " in long bits: "                           + answer);    }}
1.5 in long bits: 4609434218613702656

Program 2:
// Java program to demonstrate// Double.doubleToLongBits() method  import java.lang.*;  class Gfg1 {      public static void main(String args[])    {          double val = Double.POSITIVE_INFINITY;        double val1 = Double.NEGATIVE_INFINITY;        double val2 = Double.NaN;          // function call        long answer = Double.doubleToLongBits(val);          // print        System.out.println(val + " in long bits: "                           + answer);          // function call        answer = Double.doubleToLongBits(val1);          // print        System.out.println(val1 + " in long bits: "                           + answer);          // function call        answer = Double.doubleToLongBits(val2);          // print        System.out.println(val2 + " in long bits: "                           + answer);    }}
Infinity in long bits: 9218868437227405312
-Infinity in long bits: -4503599627370496
NaN in long bits: 9221120237041090560

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToLongBits(double)
java-basics
Java-Double
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
LinkedList in Java
Display all the numbers from a range of start and end value in JavaScript?

Let’s say the following is our start value −
var startValue=10;
Let’s say the following is our end value −
var endValue=20;
Use the for loop to fetch numbers between the start and end value −
var startValue=10;
var endValue=20;
var total='';
function printAllValues(startValue,endValue){
   for(var start=startValue;start < endValue ;start++){
      total=total+start+",";
   }
}
printAllValues(startValue,endValue)
var allSequences = total.slice(0, -1);
console.log(allSequences);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo87.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo87.js
10,11,12,13,14,15,16,17,18,19
Python 3 - List min() Method

The min() method returns the elements from the list with minimum value.
Following is the syntax for min() method −
min(list)

list − This is a list from which min valued element to be returned.
This method returns the elements from the list with minimum value.
The following example shows the usage of min() method.
#!/usr/bin/python3

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
When we run above program, it produces the following result −
min value element :  C++
min value element :  200


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Extract decimal numbers from a string in Python 



Using RegEx module is the fastest way.
>>> import re
Assuming that the string contains integer and floating point numbers as well as below −
>>> s='my age is 25. I have 55.50 percent marks and 9764135408 is my number'
the findall() function returns a list of numbers matching given pattern which includes digit before and after decimal point
>>> re.findall('\d*\.?\d+',s)
Result is a list object of all numbers
['25', '55.50', '9764135408']
HTML - <spacer> Tag

The HTML <spacer> tag specifies a whitespace.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML spacer Tag</title>
   </head>

   <body>
      Create some space <spacer type = "block" width = "50" /> here.
   </body>

</html>
<spacer> tag is available in Netscape 4 and higher version only. This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <object> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
This tag is available in Netscape 4 and higher version only.

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to use GridList in ReactJS? - GeeksforGeeks

22 Jan, 2021
Grid lists display a collection of images in an organized grid. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridList component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile';  const App = () => {  return (    <div style={{ width: 300, margin: 'auto' }}>      <h3>Grid List ReactJS</h3>      <GridList cellHeight={50} cols={3}>        <GridListTile rows={6} cols={3}>          <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"            alt="pic" />        </GridListTile>        <GridListTile cols={1}>          <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"            alt="pic" />        </GridListTile>        <GridListTile cols={3}>          <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"            alt="pic" />        </GridListTile>      </GridList>    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
Data Hiding in Python

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.
 Live Demo
#!/usr/bin/python
class JustCounter:
   __secretCount = 0
   def count(self):
      self.__secretCount += 1
      print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the following result −
1
2
Traceback (most recent call last):
   File "test.py", line 12, in <module>
      print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −
.........................
print counter._JustCounter__secretCount
When the above code is executed, it produces the following result −
1
2
2
How to create a unique ID for each object in JavaScript?

Following is the code to create a unique ID for each object −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Create a unique ID for each object</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button&g;
<h3>Click on the above button to check if id generated are unique or not</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = {
      id: Symbol("UID"),
      a: 22,
      b: 44,
   };
   let obj1 = {
      id: Symbol("UID"),
      a: 12,
      b: 41,
   };
   BtnEle.addEventListener("click", () => {
      if (obj.id === obj1.id) {
         resEle.innerHTML = "The id generated are not unique <br>";
      }
      else {
         resEle.innerHTML = "The id generated is unique for each object";
      }
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
java.time.ZoneId.systemDefault() Method Example

The java.time.ZoneId.systemDefault() method gets the system default time-zone.
Following is the declaration for java.time.ZoneId.systemDefault() method.
public static ZoneId systemDefault()

the zone ID, not null.
DateTimeException − if the converted zone ID has an invalid format.
DateTimeException − if the converted zone ID has an invalid format.
ZoneRulesException − if the converted zone region ID cannot be found.
ZoneRulesException − if the converted zone region ID cannot be found.
The following example shows the usage of java.time.ZoneId.systemDefault() method.
package com.tutorialspoint;

import java.time.ZoneId;

public class ZoneIdDemo {
   public static void main(String[] args) {
 
      System.out.println(ZoneId.systemDefault());  
   }
}
Let us compile and run the above program, this will produce the following result −
Asia/Calcutta

 Print
 Add Notes
 Bookmark this page