code-rag-bench/online-tutorials huggingface dataset:
Angular Material 7 - Toggle Button

The <mat-button-toggle>, an Angular Directive, is used to create a toggle or on/off button with material styling and animations. mat-button-toggle buttons can be configured to behave as radio buttons or checkboxes. Typically they are part of <mat-button-toggle-group>.
In this chapter, we will showcase the configuration required to draw a button toggle control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonToggleModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatButtonToggleModule, MatIconModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-selected-value {
   margin: 15px 0;
}
Following is the content of the modified HTML host file app.component.html.
<mat-button-toggle-group #group = "matButtonToggleGroup">
   <mat-button-toggle value = "left">
      <mat-icon>format_align_left</mat-icon>
   </mat-button-toggle>
   <mat-button-toggle value = "center">
      <mat-icon>format_align_center</mat-icon>
   </mat-button-toggle>
   <mat-button-toggle value = "right">
      <mat-icon>format_align_right</mat-icon>
   </mat-button-toggle>
   <mat-button-toggle value = "justify" disabled>
      <mat-icon>format_align_justify</mat-icon>
   </mat-button-toggle>
</mat-button-toggle-group>
<div class = "tp-selected-value">Selected value: {{group.value}}</div>
Verify the result.
As first, we've created a toggle button group using mat-button-toggle-group.
Then, we've added toggle buttons to the group using mat-button-toggle.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python Pandas – How to skip initial space from a DataFrame

To skip initial space from a Pandas DataFrame, use the skipinitialspace parameter of the read_csv() method. Set the parameter to True to remove extra space.
Let’s say the following is our csv file −
We should get the following output i.e. skipping initial whitespace and displaying the DataFrame from the CSV −
Following is the complete code −
import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# reading csv file and removing initial space
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv", skipinitialspace = True)
print("DataFrame...\n",dataFrame)
At first, read the CSV. Our CSV file is on the Desktop −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
While reading, you can set the skipinitialspace parameter and remove whitespace −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv", skipinitialspace = True)
This will produce the following output −
DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi         200
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai          60
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100
DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi         200
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai          60
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100
JavaScript TypeError - Cyclic object value - GeeksforGeeks

23 Aug, 2020
This JavaScript exception cyclic object value occurs if the references of objects were found in JSON. JSON.stringify() fails to solve them.
Message:
TypeError: cyclic object value (Firefox)
TypeError: Converting circular structure to JSON 
           (Chrome and Opera)
TypeError: Circular reference in value argument 
           not supported (Edge)

Error Type:
TypeError

Cause of error: If in the code references are found then JSON.stringify() fails to solve them.
Example 1: In this example, the circObj has a reference to itself, So the error has occurred.
HTML
<script>    var circObj = {1: "1"};    circObj.myself = circObj;    JSON.stringify(circObj);</script>
Output:
TypeError: Converting circular structure to JSON

Example 2: In this example, the GFG_Obj has a reference to itself, and JSON.stringify() fails to solve it. So the error has occurred.
HTML
<script>    var GFG_Obj = {property_1: "value_1"};    GFG_Obj.myself = GFG_Obj;    JSON.stringify(GFG_Obj);</script>
Output:
TypeError: Converting circular structure to JSON

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
Element Type Selector in CSS

The CSS element type selector is used to select all elements of a type. The syntax for CSS element type selector is as follows
element {
   /*declarations*/
}
The following examples illustrate CSS element type selector
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li {
   list-style: none;
   margin: 5px;
   border-bottom-style: dotted;
}
div {
   box-shadow: inset 0 0 8px plum;
   padding: 36px;
}
</style>
</head>
<body>
<div>
<pre> \(╪)(╪) /</pre>
<ul>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li {
   text-align: center;
   list-style: none;
   margin: 5px;
   padding: 5px;
   box-shadow: inset 0 0 15px yellowgreen;
}
div {
   box-shadow: inset 0 0 8px orange;
   padding: 36px;
   width: 30%;
   border-radius: 50%;
}
</style>
</head>
<body>
<div>
<ul>
<li>Hello</li>
<li>Guys</li>
</ul>
</div>
</body>
</html>
This gives the following output −
Can we iteratively import python modules inside a for loop?

Yes you can iteratively import python modules inside a for loop. You need to have a list of modules you want to import as strings. You can use the inbuilt importlib.import_module(module_name) to import the modules. For example,
>>> import importlib
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
...     globals()[lib] = importlib.import_module(lib)
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
AWT ActionEvent Class

This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Following is the declaration for java.awt.event.ActionEvent class:
public class ActionEvent
   extends AWTEvent
Following are the fields for java.awt.event.ActionEvent class:
static int ACTION_FIRST -- The first number in the range of ids used for action events.
static int ACTION_FIRST -- The first number in the range of ids used for action events.
static int ACTION_LAST  -- The last number in the range of ids used for action events.
static int ACTION_LAST  -- The last number in the range of ids used for action events.
static int ACTION_PERFORMED  -- This event id indicates that a meaningful action occured.
static int ACTION_PERFORMED  -- This event id indicates that a meaningful action occured.
static int ALT_MASK  -- The alt modifier.
static int ALT_MASK  -- The alt modifier.
static int CTRL_MASK  -- The control modifier.
static int CTRL_MASK  -- The control modifier.
static int META_MASK  -- The meta modifier.
static int META_MASK  -- The meta modifier.
static int SHIFT_MASK  -- The shift modifier.
static int SHIFT_MASK  -- The shift modifier.
ActionEvent(java.lang.Object source, int id, java.lang.String command)
Constructs an ActionEvent object.
ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)
Constructs an ActionEvent object with modifier keys.
ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)
Constructs an ActionEvent object with the specified modifier keys and timestamp.
java.lang.String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
long getWhen()
Returns the timestamp of when this event occurred.
java.lang.String paramString()
Returns a parameter string identifying this action event.
This class inherits methods from the following classes:
java.awt.AWTEvent
java.awt.AWTEvent
java.util.EventObject
java.util.EventObject
java.lang.Object
java.lang.Object

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
Python program to replace every Nth character in String - GeeksforGeeks

21 Apr, 2021
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K.
Examples:
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘$’, N = 5
Output : geeks$orge$ks i$ bes$ for$all $eeks
Explanation : Every 5th character is converted to $.
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘*’, N = 5
Output : geeks*orge*ks i* bes* for*all *eeks
Explanation : Every 5th occurrence is converted to *.
Method 1 : Using loop and enumerate()
In this, we perform an iteration of each character and check if its Nth by performing modulo, i.e finding remainder by N. If its Nth occurrence, the character is replaced by K.
Example
Python3
# initializing stringtest_str = "geeksforgeeks is best for all geeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing KK = '$'  # initializing NN = 5  res = ''for idx, ele in enumerate(test_str):      # add K if idx is multiple of N    if idx % N == 0 and idx != 0:        res = res + K    else:        res = res + ele  # printing resultprint("String after replacement : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Method 2 : Using generator expression, join() and enumerate()
In this, the construction of string happens using join(). The enumerate(), helps to get required indices. The generator expression provides a shorthand approach to this problem.
Example
Python3
# initializing stringtest_str = "geeksforgeeks is best for all geeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing KK = '$'  # initializing NN = 5  res = ''.join(ele if idx % N or idx == 0 else K for idx,              ele in enumerate(test_str))  # printing resultprint("String after replacement : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to create a Titleless and Borderless JFrame in Java?

To create a Titleless and Borderless JFrame, use the setUndecorated() method and set it to TRUE −
JFrame frame = new JFrame("Register!");
frame.setUndecorated(true);
The following is an example to create a titleless and borderless JFrame −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField age = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(age);
      frame.add(passwd);
      frame.setUndecorated(true);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
Execute both if and else statements simultaneously in C/C++

In this section we will see how to execute the if and else section simultaneously in a C or C++ code. This solution is little bit tricky.
When the if and else are executed one after another then it is like executing statements where if-else are not present. But here we will see if they are present how to execute them one after another.
#include <iostream>
using namespace std;
int main() {
   int x = 10;
   if(x > 5)   {
      lebel_1: cout << "This is inside if statement" <<endl;
      goto lebel_2;
   }else{
      lebel_2: cout << "This is inside else statement" <<endl;
      goto lebel_1;
   }
}
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
....
....
....
This program will act as an infinite loop, but here the, if block and else block, are executing simultaneously. After the first check the condition checking is not really effect on the output.
Note: Here we are using goto statement to forcefully send the control from if block to else and else to if. But the using of goto statement is not good. It makes difficult to trace the control flow of a program.
How to set the border color of the dots in matplotlib's scatterplots?

To set the border color of the dots in matplotlib scatterplots, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable "N" to store the number of sample data.
Create x and y data points using numpy.
Plot the x and y data points using scatter() method. To set the border color of the dots, use the edgecolors parameter in the scatter() method. Here, we have used "red" as the border color of the dots by using edgecolors='red'.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

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

N = 10

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, s=500, c=np.random.rand(N),
   edgecolors='red', linewidth=3)

plt.show()
It will produce the following output
HTML | <meta> charset Attribute - GeeksforGeeks

29 Jan, 2020
The HTML charset Attribute is used to specify the character encoding for the HTML document. The charset attribute could be overridden by using the lang attribute of any element.
Syntax:
<meta charset="character_set">
Attribute Values: It contains the value i.e character_set which specify the character encoding for the HTML document.Values:
UTF-8: It specify the character encoding for Unicode.
ISO-8859-1: It specify the character encoding for the Latin alphabet.
Example: This Example illustrates the use of charset Attribute in Meta Element.
<!DOCTYPE html><html>  <head>    <title>      HTML charset Attribute  </title>    <meta name="keywords"           charset="UTF-8"          content="Meta Tags, Metadata" /></head>  <body style="text-align:center">    <H1>Hello GeeksforGeeks!</H1>    <h2>      HTML charset Attribute in Meta Element  </h2></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <meta> Charset Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
mittalaman307
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Bringing Colab to a Jupyter Notebook near you... | by Robert Dargavel Smith | Towards Data Science

When programming in Python, it can be quite overwhelming when you hit an error deep down in a stack of nested function calls. One of the advantages of Python is that it has an enormous amount of high quality libraries available and for which the source code is readily available. Sometimes, it is useful just to be able to dig in to it in order to be able to understand what is going on.
To help you do just this, Google Colab automatically displays clickable links to the source files in the stack trace, as well as a handy button that searches for the error in Stack Overflow. Wouldn’t it be nice if Jupyter Notebook could do the same? That’s what I thought, so I decided to create a Notebook Extension that does exactly that.
If you have not already installed Jupyter Notebook extensions, you can do this by typing
pip install jupyter_contrib_nbextensions
Download the Goto Error code from GitHub with
git clone git://github.com/teticio/nbextension-gotoerror
install it like so
jupyter nbextension install nbextension-gotoerror
and finally, enable it thusly
jupyter nbextension enable nbextension-gotoerror/main
If all goes to plan, you should be able to configure the Goto Error extension in the nbextensions tab of Jupyter Notebook.
As the Jupyter server is only able to access files in the directory in which it is run or a subdirectory, for the notebook to be able to open the source files it is necessary to provide a soft link to the source file directory. For example, if you don’t use virtual environments, make soft link in the Jupyter launch directory to the site-packages directory of your Python installation (e.g. ~/lib/python3.6/site-packages) and call this site-packages. Then set the prefix parameter in the nbextension configuration to ~/lib/python3.6.
If you do use virtual environments, then point the soft link to the envs directory and set the prefix parameter accordingly.
To make a soft link in Linux:
ln -s ~/.local/lib/python3.6/site-packages site-packages
To make a soft link in Windows:
mklink -d envs C:\users\teticio\Anaconda\python\envs
It should now work just like the following example.
Google Colab has some other great features (apart from free access to GPUs and TPUs!). For example, if you add a #@param comment to the end of a line, it will automatically create a form which allows the user to input a value. For example
fred = 123 #@param {type : 'number'}
pops up a form with ‘fred’ and the number 123. If you change the number in the form to 456, say, the code is changed to
fred = 456 #@param {type : 'number'}
I’d like to develop an extension for Jupyter Notebook that does the same thing and, while I’m at it, port both of these extensions to Jupyter Lab. Please let me know if this is something that you would use.
Optimization techniques for Gradient Descent

20 Jun, 2022
Gradient Descent is an iterative optimization algorithm, used to find the minimum value for a function. The general idea is to initialize the parameters to random values, and then take small steps in the direction of the “slope” at each iteration. Gradient descent is highly used in supervised learning to minimize the error function and find the optimal values for the parameters. Various extensions have been designed for the gradient descent algorithms. Some of them are discussed below:
Momentum method: This method is used to accelerate the gradient descent algorithm by taking into consideration the exponentially weighted average of the gradients. Using averages makes the algorithm converge towards the minima in a faster way, as the gradients towards the uncommon directions are canceled out. The pseudocode for the momentum method is given below.
V = 0
for each iteration i:
    compute dW
    V = β V + (1 - β) dW
    W = W - α V
V and dW are analogous to velocity and acceleration respectively. α is the learning rate, and β is analogous to momentum normally kept at 0.9. Physics interpretation is that the velocity of a ball rolling downhill builds up momentum according to the direction of slope(gradient) of the hill and therefore helps in better arrival of the ball at a minimum value (in our case – at a minimum loss).
RMSprop: RMSprop was proposed by the University of Toronto’s Geoffrey Hinton. The intuition is to apply an exponentially weighted average method to the second moment of the gradients (dW2). The pseudocode for this is as follows:
S = 0
for each iteration i
    compute dW
    S = β S + (1 - β) dW2
    W = W - α dW⁄√S + ε
Adam Optimization: Adam optimization algorithm incorporates the momentum method and RMSprop, along with bias correction. The pseudocode for this approach is as follows:
V = 0
S = 0
for each iteration i
    compute dW
    V = β1 S + (1 - β1) dW
    S = β2 S + (1 - β2) dW2
    V = V⁄{1 - β1i}
    S = S⁄{1 - β2i}
    W = W - α V⁄√S + ε
Kingma and Ba, the proposers of Adam, recommended the following values for the hyperparameters.
α = 0.001
β1 = 0.9
β2 = 0.999
ε = 10-8
vaibhav29498
darsu2000sharma
jatingrg2399
Advanced Computer Subject
Machine Learning
Mathematical
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
Markov Decision Process
Agents in Artificial Intelligence
Search Algorithms in AI
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
PyQt5 | How to create colorful border of Push Button ?

22 Apr, 2020
In this article we will see how to create colorful border of Push button. By default, push button have a button but we can also change the border color and size as well. PyQt5 allows us to change the color of push button with the help of style sheet.
Syntax :
button.setStyleSheet("border :5px solid ;"
                     "border-top-color : red; "
                     "border-left-color :pink;"
                     "border-right-color :yellow;"
                     "border-bottom-color : green")

Argument : It takes string as argument.
Action performed : It will set different color to different sides.
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)          # creating colorful border        button.setStyleSheet("border :5px solid ;"                             "border-top-color : red; "                             "border-left-color :pink;"                             "border-right-color :yellow;"                             "border-bottom-color : green")          # 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.
Mongoose | exists() Function

21 May, 2020
The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  User.exists({name:'Gourav'}, function (err, doc) {    if (err){        console.log(err)    }else{        console.log("Result :", doc) // false    }});  User.exists({name:'Amit'}, function (err, doc) {    if (err){        console.log(err)    }else{        console.log("Result :", doc) // true    }});
Steps to run the program:
The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js
The project structure will look like this:
Make sure you have install mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
So this is how you can use the mongoose exists() function which returns true if at least one document exists in the database that matches the given filter, and false otherwise.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
Upsert in MongoDB
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Ulimit, Soft Limits and Hard Limits in Linux

26 Nov, 2020
ulimit is admin access required Linux shell command which is used to see, set, or limit the resource usage of the current user. It is used to return the number of open file descriptors for each process. It is also used to set restrictions on the resources used by a process.
Syntax:
To check the ulimit value use the following command:
ulimit -a
Working with ulimit commands:
1. To display maximum users process or for showing maximum user process limit for the logged-in user.
ulimit -u
2. For showing the maximum file size a user can have.
ulimit -f
3. For showing maximum memory size for the current user.
ulimit -m
4. For showing maximum memory size limit.
ulimit -v
What are Soft limits and Hard limits in Linux? 
The soft limits are the limits which are allocated for actual processing of application or users while the Hard limits are nothing but an upper bound to the values of soft limits. Hence,  
(soft limits <= hard limit)
Working with Hard and Soft limit values:
1. For displaying the Hard limit. Hard limits are a restriction to the maximum value of soft limits
ulimit -Hn
2. For displaying Soft Limit. The soft limits are the limits that are there for processing.
ulimit -Sn
3. To change Soft Limit values:
sysctl -w fs.file-max=<value>
Note: Replace <value> with the value you want to set for the soft limit and also remember size can not exceed the Hard Limit!
4. Displaying current Values for opened files
cat /proc/sys/fs/file-max
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
chown command in Linux with Examples
touch command in Linux with Examples
Difference between Tuple Relational Calculus (TRC) and Domain Relational Calculus (DRC)

07 Jun, 2022
1. Tuple Relational Calculus (TRC) : A tuple relational calculus is a non-procedural query language that specifies to select of the tuples in a relation. It can select the tuples with a range of values or tuples for certain attribute values etc. The resulting relation can have one or more tuples. 
Notation :
{T | P (T)}   or {T | Condition (T)}  
where T is the resulting tuples and P(T) is a condition used to fetch T. 
Example : 
{T | EMPLOYEE (T) AND T.DEPT_ID = 10} 
This selects all the tuples of employee names who work for Department 10. 
2. Domain Relational Calculus (DRC) : A domain relational calculus uses the list of attributes to be selected from the relation based on the condition. It is the same as TRC but differs by selecting the attributes rather than selecting whole tuples.  
Notation :
{ a1, a2, a3, ..., an | P (a1, a2, a3, ..., an) } 
Where a1, a2, a3, ... an are attributes of the relation and P is the condition. 
Example : 
{ |  < EMPLOYEE > DEPT_ID = 10 } 
select EMP_ID and EMP_NAME of employees who work for department 10. 
itskawal2000
annieahujaweb2020
Picked
DBMS
Difference Between
GATE CS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between OLAP and OLTP in DBMS
Difference between Where and Having Clause in SQL
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Introduction to NSE Tools Module in Python

03 Aug, 2021
NSE National Stock Exchange of India Limited is the leading stock exchange of India, located in Mumbai, Maharashtra. NSE was established in 1992 as the first dematerialized electronic exchange in the country.nsetools is a library for collecting real time data from National Stock Exchange of India. It can be used in various types of projects which requires fetching live quotes for a given stock or index or building large data sets for further data analytics. We can also build command line interface applications which can provide us live market details at a blazing fast speeds, much faster than any browser. The accuracy of data is only as correct as provided on http://www.nseindia.comIn order to install nse tools we have to use the command given below  
pip install nsetools
Creating a Nse object  
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # printing Nse objectprint(nse)
Output :  
Driver Class for National Stock Exchange (NSE)
Getting Information  
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing buy priceprint("Buy Price : " + str(quote['buyPrice1']))
Output :  
State Bank of India
Buy Price : 191.45
 
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing average priceprint("Average Price : " + str(quote['averagePrice']))
Output :  
State Bank of India
Average Price : 193.9
 
kapoorsagar226
Python NseTools-library
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
turtle.forward() method in Python-Turtle

16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.forward() method is used to move the turtle forward by the value of the argument that it takes. It gives a line on moving to another position or direction. 
turtle.forward(distance)

The argument it takes is distance { a number (integer or float) }. So, it moves the turtle forward by the specified distance, in the direction the turtle is headed.
Below is the implementation of above method with some examples :
Example 1:
Python3
# importing packagesimport turtle  # move turtle forward with # distance = 100turtle.forward(100)
Output :
Example 2:
Python3
# importing packageimport turtle    # move the turtle forward by 50turtle.forward(50)  # change the directionturtle.right(90)  # move the turtle forward by 50 againturtle.forward(50)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Tryit Editor v3.7

Tryit: Using pseudo-element and HTML class
Java default Keyword

❮ Java Keywords

Specify some code to run if there is no case match in a switch block:
int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
/ Outputs "Looking forward to the Weekend"


Try it Yourself »

The default keyword the default block of code in a switch statement.
The default keyword specifies some code to run if there is no case match in the switch.
Note: if the default keyword is used 
as the last statement in a switch block, it does not need a break.
Read more about the switch statement in our Java Switch Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions - GeeksforGeeks

23 Jun, 2020
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution.
It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles.
Syntax:dbeta(vec, shape1, shape2)
Parameter:vec: Vector to be usedshape1, shape2: beta density of input values
Returns: beta density values for a vector of quantiles
Example :
# R program to illustrate the use of # dbeta() function  # Creating a vectorx_beta <- seq(0, 1.5, by = 0.025 )    # Apply beta function          y_beta <- dbeta(x_beta, shape1 = 2, shape2 = 4.5)    # Plot beta valuesplot(y_beta)                                       
Output:
It is used to create cumulative distribution function of the beta distribution.
Syntax:pbeta(vec, shape1, shape2)
Parameter:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
# Specify x-values for pbeta functionx_pbeta <- seq(0, 1, by = 0.025)        # Apply pbeta() functiony_pbeta <- pbeta(x_pbeta, shape1 = 1, shape2 = 4)    # Plot pbeta valuesplot(y_pbeta)
Output:
It is known as beta quantile function and used t return quantile values of the function.
Syntax:qbeta(vec, shape1, shape2)
Parameters:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
    # Specify x-values for qbeta() functionx_qbeta <- seq(0, 1, by = 0.025)  # Apply qbeta() functiony_qbeta <- qbeta(x_qbeta, shape1 = 1, shape2 = 4)    # Plot qbeta() valuesplot(y_qbeta) 
Output:
It is defined as a random number generator that is used to set seed and specify sample size.
Syntax:rbeta(N, shape1, shape2 )
Parameters:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
# Set seed for reproducibilityset.seed(13579)  # Specify sample sizeN <- 10000    # Draw N beta distributed valuesy_rbeta <- rbeta(N, shape1 = 1, shape2 = 5)   y_rbeta  # Plot of randomly drawn beta densityplot(density(y_rbeta),      main = "beta Distribution in R")
Output:
R Math-Function
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Java Generics - Classes

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
public class Box<T> {
   private T t;
}

Where
Box − Box is a generic class.
Box − Box is a generic class.
T − The generic type parameter passed to generic class. It can take any Object.
T − The generic type parameter passed to generic class. It can take any Object.
t − Instance of generic type T.
t − Instance of generic type T.
The T is a type parameter passed to the generic class Box and should be passed when a Box object is created.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();
      Box<String> stringBox = new Box<String>();

      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));

      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
   }
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }   
}
This will produce the following result.
Integer Value :10
String Value :Hello World


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Private and Protected Members in C++

A class in C++ has public, private and protected sections which contain the corresponding class members.
The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default.
The protected members in a class are similar to private members but they can be accessed by derived classes or child classes while private members cannot.
A program that demonstrates private and protected members in a class is given as follows −
 Live Demo
#include <iostream>
using namespace std;
class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};
class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};
int main() {
   Derived obj;
   obj.func();
   return 0;
}
The output of the above program is as follows.
The value of a : 8
The value of b : 10
Now, let us understand the above program.
In the class Base, the data members are a, b and c which are public, protected and private respectively. The code snippet for this is given as follows.
class Base {
   public :
   int a = 8;
   protected :
   int b = 10;
   private :
   int c = 20;
};
The class Derived inherits the class Base. The function func() prints the values of a and b. It cannot print the value of c as that is private to class Base and cannot be accessed in class Derived. The code snippet for this is given as follows.
class Derived : public Base {
   public :
   void func() {
      cout << "The value of a : " << a;
      cout << "\nThe value of b : " << b;
   }
};
In the function main(), the object obj of class Derived is created. Then the function func() is called. The code snippet for this is given as follows.
int main() {
   Derived obj;
   obj.func();
   return 0;
}
Python | Pandas dataframe.sum() - GeeksforGeeks

22 Oct, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column. It also provides support to skip the missing values in the dataframe while calculating the sum in the dataframe.
Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.
Returns : sum : Series or DataFrame (if level specified)
For link to the CSV file used in the code, click here
Example #1: Use sum() function to find the sum of all the values over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
Now find the sum of all values along the index axis. We are going to skip the NaN values in the calculation of the sum.
# finding sum over index axis# By default the axis is set to 0df.sum(axis = 0, skipna = True)
Output : Example #2: Use sum() function to find the sum of all the values over the column axis.
Now we will find the sum along the column axis. We are going to set skipna to be true. If we do not skip the NaN values then it will result in NaN values.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # sum over the column axis.df.sum(axis = 1, skipna = True)
Output :
Akanksha_Rai
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
isupper(), islower(), lower(), upper() in Python and their applications
Set Button on Image with CSS

You can try to run the following code to set button on an image:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .box {
            position: relative;
            width: 100%;
            max-width: 250px;
         }
         .box img {
            width: 100%;
            height: auto;
         }
         .box .btn {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
         }
      </style>
   </head>
   <body>
      <div class = "box">
         <img src = "https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg" alt = "Current Affairs">
         <button class = "btn">Button</button>
      </div>
   </body>
</html>