code-rag-bench/online-tutorials huggingface dataset:
List all values of a certain field in MongoDB?

To get the list of all values of certain fields in MongoDB, you can use distinct(). The syntax is as follows −
db.yourCollectionName.distinct( "yourFieldName");
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fc89ed3c9d04998abf011")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,60]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fc8abd3c9d04998abf012")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fc8d7d3c9d04998abf013")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,70]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fc8e2d3c9d04998abf014")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.listAllValuesOfCeratinFieldsDemo.find().pretty();

The following is the output −
{
   "_id" : ObjectId("5c8fc89ed3c9d04998abf011"),
   "ListOfValues" : [
      10,
      20,
      30
   ]
}
{
   "_id" : ObjectId("5c8fc8abd3c9d04998abf012"),
   "ListOfValues" : [
      40,
      50,
      60
   ]
}
{
   "_id" : ObjectId("5c8fc8d7d3c9d04998abf013"),
   "ListOfValues" : [
      10,
      20,
      30
   ]
}
{
   "_id" : ObjectId("5c8fc8e2d3c9d04998abf014"),
   "ListOfValues" : [
      40,
      50,
      70
   ]
}
Here is the query to get the list all values of a certain field in MongoDB. We are displaying the record of the field ‘ListOfValues’ −
> db.listAllValuesOfCeratinFieldsDemo.distinct( "ListOfValues");
The following is the output −
[ 10, 20, 30, 40, 50, 60, 70 ]
Windows 10 Toast Notifications with Python

We can create a notifier for the events that occurred in Windows using Python. This is very simple with the win10toast module. If you are familiar with the Toast in Android then understanding the Toast notifications with Python is a piece of cake. We can generate notifications whenever an event occurs as a remainder. Let's see.
Run the following command in command-line to install win10toast module
pip install win10toast
If the module successfully installed then, you will get the following result when you run the command.
Collecting win10toast
Downloading https://files.pythonhosted.org/packages/d4/ba/95c0ea87d9bcad68b90d8cb130a313b939c88d8338a2fed7c11eaee972fe/win10toast-0.9-py2.py3-none-any.whl
Collecting pypiwin32 (from win10toast)
Downloading https://files.pythonhosted.org/packages/d0/1b/2f292bbd742e369a100c91faa0483172cd91a1a422a6692055ac920946c5/pypiwin32-223-py3-none-any.whl
Requirement already satisfied: setuptools in c:\users\hafeezulkareem\anaconda3\lib\site-packages (from win10toast) (40.8.0)
Requirement already satisfied: pywin32>=223 in c:\users\hafeezulkareem\anaconda3\lib\site-packages (from pypiwin32->win10toast) (223)
Installing collected packages: pypiwin32, win10toast
Successfully installed pypiwin32-223 win10toast-0.9
Import ToastNotifier class from the win10toast.
Import ToastNotifier class from the win10toast.
Instantiate the class.
Instantiate the class.
Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments.
Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments.
You will get True as output after notification duration complete, if successful.
You will get True as output after notification duration complete, if successful.
Let's see it with a simple example.
## program to generate a simple toast notifier
from win10toast import ToastNotifier
## instantiating the class
notifier = ToastNotifier()
## invoking the show_toast() method with required arguments notifier.show_toast("Sample Notification", "You are learning at Tutorialspoint", duration = 25, icon_path = "globe.ico")
If you run the above program, you will get the following results.
You can add this notification program when an event occurs on your system. If you have any doubts regarding the tutorial, please mention them in the comment section.
DateTime.FromOADate() Method in C#

28 Jan, 2019
DateTime.FromOADate(Double) Method is used to return a DateTime equivalent to the specified OLE Automation Date.
Syntax: public static DateTime FromOADate (double d);Here, it takes an OLE Automation Date value.
Return Value: This method returns an object that represents the same date and time as d.
Exception: This method will give ArgumentException if the date is not a valid OLE Automation Date value.
Below programs illustrate the use of DateTime.FromOADate(Double) Method:
Example 1:
// C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // converting 657435.0 OLE             // Automation Date value.            // into DateTime format            // using FromOADate() method            DateTime date2 = DateTime.FromOADate(657435.0);              // Display the date2            System.Console.WriteLine("DateTime "                       + ": {0:y} {0:dd}",date2);                                               }          catch (ArgumentException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
DateTime : 3699 December 28

Example 2: For ArgumentException
// C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // converting 657435.0 OLE            // Automation Date value.            // into DateTime format            // using FromOADate() method            DateTime date2 = DateTime.FromOADate(-657435.0);              // Display the date2            System.Console.WriteLine("DateTime "                      + ": {0:y} {0:dd}",date2);                                               }          catch (ArgumentException e)         {            Console.WriteLine("The date is not a valid "+                           "OLE Automation Date value.");            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The date is not a valid OLE Automation Date value.
Exception Thrown: System.ArgumentException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromoadate?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Generate QR Code using pyqrcode module

17 May, 2020
Let’s see how to generate QR code in Python using pyqrcode module.
pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in pyqrcode come directly from the standard.
Installation
$ pip install pyqrcode

 install an additional module pypng to save image in png format:
$ pip install pypng

 pyqrcode.create(content, error='H', version=None, mode=None, encoding=None) : When creating a QR code only the content to be encoded is required, all the other properties of the code will be guessed based on the contents given. This function will return a QRCode object.
One can specify all the properties of required QR code through the optional parameters of the pyqrcode.create() function. Below are some properties:
error: This parameter sets the error correction level of the code.version: This parameter specifies the size and data capacity of the code.mode: This parameter sets how the contents will be encoded.
Below is the code:
# Import QRCode from pyqrcodeimport pyqrcodeimport pngfrom pyqrcode import QRCode    # String which represents the QR codes = "www.geeksforgeeks.org"  # Generate QR codeurl = pyqrcode.create(s)  # Create and save the svg file naming "myqr.svg"url.svg("myqr.svg", scale = 8)  # Create and save the png file naming "myqr.png"url.png('myqr.png', scale = 6)
Output:
VarshaGS
shauryasheth95
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Microsoft Azure – Create Alert For Conditional Access Policy Changes

16 Dec, 2021
In this article, we will look into the process of creating an alert for Conditional Access Policy Changes. Conditional Access brings signals together, to make decisions, and enforce organizational policies. 
Creation of a New Conditional Access Policy,Deletion of a Conditional Access Policy,Changes to any current Conditional Access Policy.
Creation of a New Conditional Access Policy,
Deletion of a Conditional Access Policy,
Changes to any current Conditional Access Policy.
Log Analytics Workspace
Contributor Access on Subscription or Resource Group to create alerts.
Follow the below steps to enable alter on conditional policy changes:
Step 1: Login to Azure Portal
Step 2: Navigate to select Log Analytics Workspace >> from left menu select Logs >> Copy the below Search Query and Add Query (Copy the below Search Query) >> Click on Run (Refer Output Screenshot)
Search Query:
AuditLogs
| where Category == "Policy" and LoggedByService == "Conditional Access"
| project ActivityDateTime, InitiatedBy.user.userPrincipalName, TargetResources[0].displayName, ActivityDisplayName
Output:
Step 3: After running the Query, from top-right Click on + New alert rule. Then, click on Condition name and set up the required.
Alert Logic: Number of results
Operator: Greater than
Threshold value : 0
Period (in minutes) : 15
Frequency (in minutes) : 15
Now Click on “OK”
Step 4: Add Action Group and Configure Notification >> click on Add action group and fill in the following details.
Action Group:
Subscription: Provide the Select Subscription
Resource group: Provide Select Resource group
Action group name : Select Requested Action Group (for example: security-notification)
Display name : conditAccess
Notification:
Notification type : Email/SMS message/Push/Voice
Name: Email-Action
Select : Email >> security@domain.com
After filling up the required changes click on save changes.
Customize actions : Email Subject >> Add Subject line >> “Conditional Access Changes Detected – Alert”
Alert rule name: Conditional Access Changes Detected
Description:
This alert detects:
Creation of a New Conditional Access PolicyDeletion of a Conditional Access PolicyChanges to any current Conditional Access Policy
Creation of a New Conditional Access Policy
Deletion of a Conditional Access Policy
Changes to any current Conditional Access Policy
Resource group: Select same as Scope Resource Group
Severity: 2 Warning
Automatically resolve alerts: false
Suppress alerts: false
Step 5: Click on Review and Create. Once the alert is triggered, configured email user will be notified about the alert details.
That’s it, you are done. At this point, we have successfully enabled email alert whenever there are any conditional policy changes.
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript | Importing and Exporting Modules

14 Feb, 2019
JavaScript Modules are basically libraries which are included in the given program. They are used for connecting two JavaScript programs together to call the functions written in one program without writing the body of the functions itself in another program.
Importing a library: It means include a library in a program so that use the function is defined in that library. For this, use ‘require’ function in which pass the library name with its relative path.Example: Suppose a library is made in the same folder with file name library.js, then include the file by using require function:
const lib = require('./library') 
which will return reference to that library. Now if there is area function defined in the library, then use it as lib.area().
Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module (program), this object will be exposed. Therefore, all those functions that need to be exposed or need to be available so that it can used in some other file, defined in module.exports.
Expample : Write two different programs and then see how to use functions defined in the library (Module) in given program. Define two simple functions in the library for calculating and printing area and perimeter of a rectangle when provided with length and breadth. Then export the functions so that other programs can import them if needed and can use them.
Exporting Module Example : library.js
<script>// Area functionlet area = function (length, breadth) {    let a = length * breadth;    console.log('Area of the rectangle is ' + a + ' square unit');}  // Perimeter functionlet perimeter = function (length, breadth) {    let p = 2 * (length + breadth);    console.log('Perimeter of the rectangle is ' + p + ' unit');}  // Making all functions available in this// module to exports that we have made// so that we can import this module and// use these functions whenever we want.module.exports = {    area,    perimeter}</script>
Importing Module Example
For importing any module, use a function called ‘Require’ which takes in the module name and if its user defined module then its relative path as argument and returns its reference.
The script.js contains the above JavaScript module (library.js).
Script.js
<script>// Importing the module library containing// area and perimeter functions.// " ./ " is used if both the files are in the same folder.const lib =  require('./library');  let length = 10;let breadth = 5;  // Calling the functions // defined in the lib modulelib.area(length, breadth);lib.perimeter(length, breadth);</script>
Output:
Area of the rectangle is 50 square unit
Perimeter of the rectangle is 30 unit
Note: To run the script first make both files in the same folder and then run script.js using NodeJs interpreter in terminal.
javascript-basics
Technical Scripter 2018
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array Size in Perl

The size of an array in Perl can be determined using the scalar context on the array - the returned value will be the number of elements in the array −
@array = (1,2,3);
print "Size: ",scalar @array,"\n";
The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows −
 Live Demo
#!/usr/bin/perl
@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;

print "Size: $size\n";
print "Max Index: $max_index\n";
This will produce the following result −
Size: 51
Max Index: 50
There are only four elements in the array that contains information, but the array is 51 elements long, with the highest index of 50.
Yii - Installation

The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool.
Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command.
curl -sS https://getcomposer.org/installer | php

Step 2 − Then move this archive to the bin directory.
mv composer.phar /usr/local/bin/composer

Step 3 − With the Composer installed, you can install Yii2 basic application template. Run these commands.
composer global require "fxp/composer-asset-plugin:~1.1.1" 
composer create-project --prefer-dist yiisoft/yii2-app-basic helloworld 

The first command installs the composer asset plugin, which manages npm and bower dependencies. The second command installs Yii2 basic application template in a directory called helloworld.
Step 4 − Now open the helloworld directory and launch the web server built into PHP.
php -S localhost:8080 -t web

Step 5 − Then open http://localhost:8080 in your browser. You can see the welcome page.
 Print
 Add Notes
 Bookmark this page
Make all column names lower case in MySQL with a single query

Let us first create a −
mysql> create table DemoTable1
   -> (
   -> StudentFirstName varchar(20),
   -> StudentLastName varchar(20),
   -> StudentAge int,
   -> StudentCountryName varchar(20)
   -> );
Query OK, 0 rows affected (4.20 sec)
Let us now make all column names lower case in MySQL −
mysql> select concat('alter table ', table_name, ' change `', column_name, '` `',
   -> lower(column_name), '` ', column_type, ';')
   -> from information_schema.columns  where table_schema = 'demo';
This will produce the following output −
+-----------------------------------------------------------------------------------------------------------------+
| concat('alter table ', table_name, ' change `', column_name, '` `', lower(column_name), '` ', column_type, ';') |
+-----------------------------------------------------------------------------------------------------------------+
| alter table demotable1 change `StudentFirstName` `studentfirstname` varchar(20);                                |
| alter table demotable1 change `StudentLastName` `studentlastname` varchar(20);                                  |
| alter table demotable1 change `StudentAge` `studentage` int(11);                                                |
| alter table demotable1 change `StudentCountryName` `studentcountryname` varchar(20);                            |
| alter table mytable change `MyEuroColumn` `myeurocolumn` varchar(5);                                            |
+-----------------------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)
How to add the entry in the windows host file using PowerShell?

To add the content to the host file, we need to first retrieve the content using the Get-Content command and the need to set the content to the host file after adding the entry. The Code is shown below. We need to add the global entry to it.
$file = "C:\Windows\System32\drivers\etc\hosts"
$hostfile = Get-Content $file
$hostfile += "8.8.8.8   Google.com"
Set-Content -Path $file -Value $hostfile -Force
Once you check the host file entry  "8.8.8.8          Google.com" will be added to the host file.
To add the entry on the remote computer, you just need to point that file location to the host file of the remote server and the rest of the content will be the same.
$file = \\Comptuter1\C$\Windows\System32\drivers\etc\hosts
$hostfile = Get-Content $file
$hostfile += "8.8.8.8   Google.com"
Set-Content -Path $file -Value $hostfile -Force
Python | numpy.datetime64() method

05 Sep, 2019
With the help of numpy.datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy.datetime64() method.
Syntax : numpy.datetime64(date)Return : Return the date in a format ‘yyyy-mm-dd’.
Example #1 :In this example we can see that by using numpy.datetime64() method, we are able to get the date in the particular format i.e yyyy-mm-dd.
# import numpyimport numpy as np  # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08-26'))  print(gfg)
Output :
array(‘2019-08-26′, dtype=’datetime64[D]’)
Example #2 :
# import numpyimport numpy as np  # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08', 'D'))  print(gfg)
Output :
array(‘2019-08-01′, dtype=’datetime64[D]’)
Python numpy-DataType
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
response.cookies – Python requests

01 Mar, 2020
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.cookies out of a response object. response.cookies returns a CookieJar object with the cookies sent back from the server.
To illustrate use of response.cookies, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
import requests  # Making a get requestresponse = requests.get('https://api.github.com')  # printing request cookiesprint(response.cookies)
Save above file as request.py and run using
Python request.py

Check that at the start of output, it means the reference to a cookies object.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Pandas.DataFrame.iterrows() function in Python

23 May, 2022
Pandas DataFrame.iterrows() is used to iterate over a pandas Data frame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in form of series.   
Syntax: DataFrame.iterrows() Yields: index- The index of the row. A tuple for a MultiIndex data- The data of the row as a Series Returns: it: A generator that iterates over the rows of the frame
Example 1: 
Sometimes we need to iter over the data frame rows and columns without using any loops, in this situation Pandas DataFrame.iterrows() plays a crucial role.
Python3
import pandas as pd # Creating a data frame along with column namedf = pd.DataFrame([[2, 2.5, 100, 4.5, 8.8, 95]], columns=[                  'int', 'float', 'int', 'float', 'float', 'int']) # Iter over the data frame rows# # using df.iterrows()itr = next(df.iterrows())[1]itr
Output:
In the above example, we use Pandas DataFrame.iterrows() to iter over numeric data frame rows.
Example 2:
Python3
import pandas as pd # Creating a data framedf = pd.DataFrame([['Animal', 'Baby', 'Cat', 'Dog',                    'Elephant', 'Frog', 'Gragor']]) # Iterating over the data frame rows# using df.iterrows()itr = next(df.iterrows())[1]itr
Output :
In the above example, we iter over the data frame having no column names using Pandas DataFrame.iterrows()
Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows.
sumitgumber28
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
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Node.js This Binding

08 Oct, 2021
Arrow functions don’t bind their own ‘this’ value. Instead, the ‘this’ value of the scope in which it was defined is accessible. This makes arrow functions bad candidates for methods, as this won’t be a reference to the object the method is defined on.
For methods, ES6 provides a new method definition syntax. You can see this in the definition of the printGuestList method below. That function is a standard function, just with a shorthand syntax which allows for the removal of the colon and the function keyword.
Because arrow functions don’t bind this, they work well for everything except methods. As shown below, the arrow function passed to forEach is able to access this.name correctly, as it’s defined as an arrow function and doesn’t have this binding of its own. That code wouldn’t work if you swapped out the arrow function for a standard function.
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
Filename: index.js
// 'This' in Arrow functionconst eventOne = {    name: 'Birthday Party',    guestList: ['Gourav', 'Vijay'],    printGuestList() {        console.log('Guest list for ' + this.name);        this.guestList.forEach((guest) => {            console.log(guest + ' is attending ' + this.name)        });    }}  // 'This' in normal functionconst eventTwo = {    name: 'Birthday Party',    guestList: ['Gourav', 'Vijay'],    printGuestList() {        console.log('Guest list for ' + this.name);        this.guestList.forEach(function (guest) {            console.log(guest + ' is attending ' + this.name)        });    }}  eventOne.printGuestList();console.log('---------------------');eventTwo.printGuestList();
Steps to run the program:
Run index.js file using the following command:node index.js
node index.js
So this is how ‘this’ binding works on arrow functions and normal functions.
Node.js-Basics
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS htmlFor Attribute

25 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component.
In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
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 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';   // Defining our App Componentconst App = () => {     // Function to demonstrate htmlFor attribute  function printHtmlForValue() {    var element = document.getElementById('abc');       // Printing element    console.log(element)  }     // Returning our JSX code  return <>    <div>      <h1>GeeksforGeeks</h1>      <div id='abc'>        ReactJS htmlFor Attribute      </div>      <button onClick={printHtmlForValue}>        click      </button>    </div>  </>;}   // Exporting your Default App Componentexport 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:
Reference:https://reactjs.org/docs/dom-elements.html#htmlfor
ReactJS Attributes
ReactJS DOM Elements
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
goto statement in C/C++

The goto statement is a jump statement. Within a function, it is used to jump from one statement to another. The use of this statement is highly discouraged. It makes the program complex and difficult to trace the control flow of program. It makes hard to modify the program.
Here is the syntax of goto statement in C language,
goto label;
.
.
.
label: statement;
Here is an example of goto statement in C language,
 Live Demo
#include <stdio.h>
int main () {
   int a = 10;
   LOOP:do {  
      if( a == 12) {
         a = a + 1;
         goto LOOP;
      }
      printf("Value of a: %d\n", a);
      a++;
   }while( a < 15 );
   return 0;
}
Value of a: 10
value of a: 11
value of a: 13
value of a: 14
PostgreSQL - DELETE USING - GeeksforGeeks

28 Aug, 2020
PostgreSQL has various techniques to delete duplicate rows. One of them is using the DELETE USING statement.
Syntax: DELETE FROM table_name row1 USING table_name row2 WHERE condition;


For the purpose of demonstration let’s set up a sample table(say, basket) that stores fruits as follows:
CREATE TABLE basket(
    id SERIAL PRIMARY KEY,
    fruit VARCHAR(50) NOT NULL
);


Now let’s add some data to the newly created basket table.
INSERT INTO basket(fruit) values('apple');
INSERT INTO basket(fruit) values('apple');

INSERT INTO basket(fruit) values('orange');
INSERT INTO basket(fruit) values('orange');
INSERT INTO basket(fruit) values('orange');

INSERT INTO basket(fruit) values('banana');


Now let’s verify the basket table using the below statement:
SELECT * FROM basket;


This should result into below:
Now that we have set up the sample table, we will query for the duplicates using the following:
SELECT
    fruit,
    COUNT( fruit )
FROM
    basket
GROUP BY
    fruit
HAVING
    COUNT( fruit )> 1
ORDER BY
    fruit;


This should lead to the following results:
Now that we know the duplicate rows we can use the DELETE USING statement to remove duplicate rows as follows:
DELETE FROM
    basket a
        USING basket b
WHERE
    a.id < b.id
    AND a.fruit = b.fruit;


This should remove all duplicate from the table basket, and to verify so use the below query:
SELECT
    fruit,
    COUNT( fruit )
FROM
    basket
GROUP BY
    fruit
HAVING
    COUNT( fruit )> 1
ORDER BY
    fruit;


This should result in the following:
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Interval Data Type
PostgreSQL - Rename Table
PostgreSQL - LEFT JOIN
PostgreSQL - TEXT Data Type
PostgreSQL - TIME Data Type
PostgreSQL - Record type variable
PostgreSQL - CREATE PROCEDURE
How to join two Vectors using STL in C++? - GeeksforGeeks

28 May, 2021
Given two vectors, join these two vectors using STL in C++.Example:  
Input: vec1 = {1, 45, 54, 71, 76, 12}, vec2 = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76}Input: vec1 = {1, 7, 5, 4, 6, 12}, vec2 = {10, 12, 11} Output: {1, 4, 5, 6, 7, 10, 11, 12}  
Approach: Joining can be done with the help of set_union() function provided in STL.Syntax:  
set_union (InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, InputIterator2 last2,
           OutputIterator result);
CPP
// C++ program to join two Vectors// using set_union() in STL #include <bits/stdc++.h>using namespace std; int main(){    // Get the vector    vector<int> vector1 = { 1, 45, 54, 71, 76, 12 };    vector<int> vector2 = { 1, 7, 5, 4, 6, 12 };     // Sort the vector    sort(vector1.begin(), vector1.end());    sort(vector2.begin(), vector2.end());     // Print the vector    cout << "First Vector: ";    for (int i = 0; i < vector1.size(); i++)        cout << vector1[i] << " ";    cout << endl;     cout << "Second Vector: ";    for (int i = 0; i < vector2.size(); i++)        cout << vector2[i] << " ";    cout << endl;     // Initialise a vector    // to store the common values    // and an iterator    // to traverse this vector    vector<int> v(vector1.size() + vector2.size());    vector<int>::iterator it, st;     it = set_union(vector1.begin(),                   vector1.end(),                   vector2.begin(),                   vector2.end(),                   v.begin());     cout << "\nAfter joining:\n";    for (st = v.begin(); st != it; ++st)        cout << *st << ", ";    cout << '\n';     return 0;}
First Vector: 1 12 45 54 71 76 
Second Vector: 1 4 5 6 7 12 

After joining:
1, 4, 5, 6, 7, 12, 45, 54, 71, 76,
 
Note that the vector should not contain 1 element twice:
In case you enter same elements, the set_union function will only consider 1 instance of the element, and default rest to 0.
Kaustubh_Gupta
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Socket Programming in C/C++
Constructors in C++
Virtual Function in C++
Templates in C++ with Examples
Copy Constructor in C++
How to hide axes and gridlines in Matplotlib?

To hide axes (X and Y) and gridlines, we can take the following steps −
Create x and y points using numpy.
Create x and y points using numpy.
Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels.
Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels.
Plot x and y points using the plot() method with linestyle, labels.
Plot x and y points using the plot() method with linestyle, labels.
To hide the grid, use plt.grid(False).
To hide the grid, use plt.grid(False).
To hide the axes, use plt.axis('off')
To hide the axes, use plt.axis('off')
To activate the labels' legend, use the legend() method.
To activate the labels' legend, use the legend() method.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 50)
y = np.sin(x)
plt.axhline(y=0, c="green", linestyle="dashdot", label="y=0")
plt.plot(x, y, c="red", lw=5, linestyle="dashdot", label="y=sin(x)")
plt.grid(False)
plt.axis('off')
plt.legend()
plt.show()
Prolog - Conjunctions & Disjunctions

In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax.
Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male.
Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true.
parent(jhon,bob).
parent(lili,bob).

male(jhon).
female(lili).

% Conjunction Logic
father(X,Y) :- parent(X,Y),male(X).
mother(X,Y) :- parent(X,Y),female(X).

% Disjunction Logic
child_of(X,Y) :- father(X,Y);mother(X,Y).
| ?- [conj_disj].
compiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code...
D:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read - 1513 bytes written, 24 ms

yes
| ?- father(jhon,bob).

yes
| ?- child_of(jhon,bob).

true ?

yes
| ?- child_of(lili,bob).

yes
| ?-


    65 Lectures 
     5 hours 

 Arnab Chakraborty

    78 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Create Python Datetime from string - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to create a python DateTime object from a given string.
For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user.
Syntax: datetime.strptime(date_string, format)
Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this.
Python3
from datetime import datetime  input_str = '21/01/24 11:04:19'  dt_object = datetime.strptime(  input_str, '%d/%m/%y %H:%M:%S')  print("The type of the input date string now is: ",       type(dt_object))  print("The date is", dt_object)
Output: 
The type of the input date string now is:  <class ‘datetime.datetime’>
The date is 2024-01-21 11:04:19
The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done:
Python3
from datetime import datetime  time_str = 'May 17 2019  11:33PM'dt_object = datetime.strptime(  time_str, '%b %d %Y %I:%M%p')  print(dt_object)
Output: 
2019-05-17 23:33:00
DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused:
Python3
from datetime import datetime  time_str = '201123101455'  dt_obj = datetime.strptime(time_str, '%y%m%d%H%M%S')dt_obj2 = datetime.strptime(time_str, '%d%m%y%H%S%M')  print ("1st interpretation of date from string is: ",dt_obj) print ("2nd interpretation of date from same string is", dt_obj2)
Output : 
1st interpretation of date from string is:  2020-11-23 10:14:55
2nd interpretation of date from same string is 2023-11-20 10:55:14
The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier.
Python3
from datetime import datetime  time_str = '220917 114519'dt_obj = datetime.strptime(time_str, '%d/%m/%y %H:%M:%S')  print ("The type is", type(dt_obj))print ("The date is", date_time_obj)
Output:
ValueError(“time data %r does not match format %r” %(data_string, format))
The format specifiers are mostly the same as for strftime() method. These specifiers are:
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Font Awesome Icons

Font Awesome icons library provides 519 free scalable vector icons. This library is completely free for both personal and commercial use. Originally designed for Bootstrap, these icons can be customized easily.
To load the Font Awesome library, copy and paste the following line in the <head> section of the webpage.
<head>
   <link rel = "stylesheet" href = "http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
Font Awesome provides several icons. Choose one of them and add the name of the icon class to any HTML element within the <body> tag. In the following example, we have used the icon of the Indian currency.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
   </head>
	
   <body>
      <i class = "fa fa-inr"></i>
   </body>
	
</html>
It will produce the following output −
You can increase or decrease the size of an icon by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have declared the size as 6 em.
<html>
   <head>
      <link rel = "stylesheet" href = "http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
		
      <style>
         i.mysize {font-size: 10em;}
      </style>
		
   </head>
	
   <body>
      <i class = "fa fa-inr mysize"></i>
   </body>
	
</html>
It will produce the following output −
Just like size, you can define the color of the icons using CSS. The following example shows how to change the color of the Indian currency icon.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
		
      <style>
         i.custom {font-size: 6em; color: red;}
      </style>
		
   </head>
	
   <body>
      <i class = "fa fa-inr custom"></i>
   </body>
	
</html>
Font Awesome provides 519 icons in the following categories −
Web Application Icons
Hand Icons
Transportation Icons
Gender Icons
File Type Icons
Spinner Icons
Form Control Icons
Payment Icons
Chart Icons
Currency Icons
Text editor Icons
Directional Icons
Video Player Icons
Brand Icons
To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Font Awesome), we have explained category-wise the usage and the respective outputs of various Font Awesome icons.

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Encapsulation in C++

Encapsulation brings together the data and the methods that manipulate the data into a single component and protects them from outside interference. In essence, encapsulation involves bundling the data as well as the functions that use the data. Data encapsulation in lead to the very important concept of data hiding.
Encapsulation in C++ is implemented using classes that are user defined data types. These classes contain data types as well as methods that are bound together.
A program that represents encapsulation in C++ using classes is given as follows.
 Live Demo
#include <iostream>
using namespace std;
class EncapsulationDemo {
   private:
   int length, breath, height;
   public:
   void setValues(int l, int b,int h) {
      length = l;
      breath = b;
      height = h;
   }
   void calcVolume() {
      cout<<"Length = " << length << endl;
      cout<<"Breath = " << breath << endl;
      cout<<"Height = " << height << endl;
      cout<<"Volume = " << length*breath*height << endl;
   }
};
int main() {
   EncapsulationDemo obj;
   obj.setValues(5, 3, 2);
   obj.calcVolume();
   return 0;
}
Length = 5
Breath = 3
Height = 2
Volume = 30
In the above program, the variables and methods are wrapped in a single unit i.e the class Encapsulation. So, this program demonstrates the concept of encapsulation.
The length, breadth and height in class Encapsulation are private variables. There are public functions that initialize these variables and also calculate the volume by multiplying length, breadth and height. The code snippet for this is as follows.
class Encapsulation {
   private:
   int length, breadth, height;
   public:
   void setValues(int l, int b,int h) {
      length = l;
      breadth = b;
      height = h;
   }
   void calcVolume() {
      cout<<"Length = " << length << endl;
      cout<<"Breadth = " << breadth << endl;
      cout<<"Height = " << height << endl;
      cout<<"Volume = " << length*breadth*height << endl;
   }
};
In the function main(), first an object of type Encapsulation is defined. Then the function setValues() is called with the values 5, 3 and 2. Finally, these values and the volume are displayed using the function calcVolume(). The code snippet for this is as follows.
Encapsulation obj;
obj.setValues(5, 3, 2);
obj.calcVolume();
PostgreSQL - NULLIF() Function - GeeksforGeeks

28 Aug, 2020
PostgreSQL has a NULLIF function to handle null values. The NULLIF function is one of the most common conditional expressions provided by PostgreSQL.
Syntax:NULLIF(argument_1,argument_2);


The NULLIF function returns a null value if argument_1 equals to argument_2, otherwise it returns argument_1.
Example :
First, we create a table named posts as follows:
CREATE TABLE posts (
  id serial primary key,
    title VARCHAR (255) NOT NULL,
    excerpt VARCHAR (150),
    body TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP
);


Now we insert some sample data to the table as follows:
INSERT INTO posts (title, excerpt, body)
VALUES
      ('test post 1','test post excerpt 1','test post body 1'),
      ('test post 2','','test post body 2'),
      ('test post 3', null ,'test post body 3');


Our aim is to display the posts overview page that shows the title and excerpt of each post. In case the excerpt is not provided, we use the first 40 characters of the post body. We can simply use the following query to get all rows in the posts table.
SELECT
    ID,
    title,
    excerpt
FROM
    posts;


This leads to the following:
The null value in the excerpt column. To substitute this null value, we can use the COALESCE function as follows:
SELECT
    id,
    title,
    COALESCE (excerpt, LEFT(body, 40))
FROM
    posts;


This will result in the following:
Unfortunately, there is a mix between null value and ” (empty) in the excerpt column. This is why we need to use the NULLIF function:
SELECT
    id,
    title,
    COALESCE (
        NULLIF (excerpt, ''),
        LEFT (body, 40)
    )
FROM
    posts;


Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column