code-rag-bench/online-tutorials huggingface dataset:
std::is_enum Template in C++

19 Nov, 2018
The std::is_enum template of C++ STL is used to check whether the given type is enum or not. It returns a boolean value showing the same.
Syntax:
template <class T> struct is_enum;
Parameter: This template accepts single parameter T (Trait class) to check whether T is a enumeration type or not.
Return Value: This template returns a boolean value as shown below:
True: if the type is a enumeration.
False: if the type is a non-enumeration.
Below programs illustrate the std::is_enum template in C++:
Program 1::
// C++ program to illustrate// is_enum template  #include <iostream>#include <type_traits>using namespace std;  class GFG1 {};enum class GFG2 { var1,                  var2,                  var3,                  var4};  // Driver codeint main(){    cout << boolalpha;    cout << "is_enum:" << endl;    cout << "GFG1: "         << is_enum<GFG1>::value << endl;    cout << "GFG2: "         << is_enum<GFG2>::value << endl;      return 0;}
is_enum:
GFG1: false
GFG2: true

Program 2::
// C++ program to illustrate// is_enum template  #include <iostream>#include <type_traits>using namespace std;  class GFG1 {};  enum class GFG2 : int {};  // Driver codeint main(){    cout << boolalpha;    cout << "is_enum:" << endl;    cout << "GFG1: "         << is_enum<GFG1>::value << '\n';    cout << "GFG2: "         << is_enum<GFG2>::value << '\n';    cout << "int: "         << is_enum<int>::value << '\n';    return 0;}
is_enum:
GFG1: false
GFG2: true
int: false

C++-Templates
cpp-template
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a URL in a C++ program

21 Jun, 2022
Writing URLs in programming code doesn’t affect the program and the compiler will not throw any error. Here, we will how to use Url in various languages without any errors.
The full form of URL is  Uniform Resource Locators. URLs are unique they store the address of a particular web application.
C++
Java
PHP
C#
Javascript
// C++ program to demonstrate URL in code#include <iostream>using namespace std; int main(){    https://www.geeksforgeeks.org/     for (int i = 0; i < 5; i++)    {        cout << "This code is error free" << endl ;         // Uncommenting below goto statement causes        // infinite loop        // goto http;    }     return 0;}
/*package whatever //do not write package name here */import java.io.*; class GFG {    public static void main (String[] args)    {         https://www.geeksforgeeks.org/        for(int i = 0; i < 5; i++){             System.out.println("This code is error free");        }    }}
<?php// PHP program to demonstrate// URL in code https://www.geeksforgeeks.org/ for ($i = 0; $i < 5; $i++){    echo "This code is error " .                 "free" , "\n" ;     // Uncommenting below    // goto statement causes    // infinite loop         // goto https;} // This code is contributed// by m_kit?>
using System;class Demo {  static void Main() {    string input = "https://www.geeksforgeeks.org";         // See if input matches one of these starts.    for (int i = 0; i < 5; i++)       Console.WriteLine("This code is error");  }} // This code is contributed by aayushcoding100.
<script>//new URL(url, [base])let mainUrl = new URL('https://www.geeksforgeeks.org');alert(mainUrl);for (let i = 0; i < 5; i++) {        document.write("This code is error");} // This code is contributed by aayushcoding100.</script>
Output:  
 
Explanation:  
Any identifier followed by a : becomes a (goto) labels in a Program.A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore:
Any identifier followed by a : becomes a (goto) labels in a Program.
A single line comment begins with a // and so in https://www.geeksforgeeks.org/ and so it is a comment. And therefore:
label- http: 
comment- www.geeksforgeeks.org/
Time complexity : O(1) Auxiliary Space : O(1)
jit_t
akshitsaxenaa09
ayushcoding100
sagartomar9927
mahendrabagul569
cpp-puzzle
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
How to use while True in Python

22 Nov, 2021
In this article, we will discuss how to use while True in Python.
While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.
Python3
# Python program to demonstrate# while loop with True  while True:    pass
If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement explicitly.
Let’s consider the below example, where we want to find the sum of the first N numbers. Let’s see the below code for better understanding.
Python3
# Python program to demonstrate# while loop with True  N = 10Sum = 0  # This loop will run foreverwhile True:    Sum += N    N -= 1          # the below condition will tell    # the loop to stop    if N == 0:        break          print(f"Sum of First 10 Numbers is {Sum}")
Sum of First 10 Numbers is 55
In the above example, we have used the while True statement to run the while loop and we have added an if statement that will stop the execution of the loop when the value of N becomes 0 If we do not write this if statement then the loop will run forever and will start adding the negative values of N to the sum.
prachisoda1234
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python – Filter all uppercase characters Tuples from given list of tuples

02 Sep, 2020
Given a Tuple list, filter tuples which contains all uppercase characters.
Input : test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : [(‘GFG’, ‘IS’, ‘BEST’)]Explanation : Only 1 tuple has all uppercase Strings.
Input : test_list = [(“GFG”, “iS”, “BEST”), (“GFg”, “AVERAGE”), (“GfG”, ), (“Gfg”, “CS”)]Output : []Explanation : No has all uppercase Strings.
Method #1 : Using loop
In this, we iterate for each tuple, and check if every string is uppercase, if no, that tuple is omitted from new tuple. 
Python3
# Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using loop  # initializing listtest_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")]  # printing original listprint("The original list is : " + str(test_list))  res_list = []for sub in test_list:    res = True     for ele in sub:                  # checking for uppercase        if not ele.isupper():            res = False             break    if res:        res_list.append(sub)  # printing resultsprint("Filtered Tuples : " + str(res_list))
The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]
Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]

Method #2 : Using list comprehension + all() + isupper()
In this, we check for all strings uppercase using all(), and list comprehension provides compact solution of problem. isupper() is used to check for uppercase.
Python3
# Python3 code to demonstrate working of # Filter uppercase characters Tuples# Using list comprehension + all() + isupper()  # initializing listtest_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")]  # printing original listprint("The original list is : " + str(test_list))  # all() returns true only when all strings are uppercaseres = [sub for sub in test_list if all(ele.isupper() for ele in sub)]  # printing resultsprint("Filtered Tuples : " + str(res))
The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]
Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python sympy | Matrix.rref() method

13 Aug, 2019
With the help of sympy.Matrix().rref() method, we can put a matrix into reduced Row echelon form. Matrix().rref() returns a tuple of two elements. The first is the reduced row echelon form, and the second is a tuple of indices of the pivot columns.
Syntax: Matrix().rref()
Returns: Returns a tuple of which first element is of type Matrix and second one is of type tuple.
Example #1:
# import sympy from sympy import *   M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])print("Matrix : {} ".format(M))   # Use sympy.rref() method M_rref = M.rref()        print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref))  
Output:
Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]]) 
The Row echelon form of matrix M and the pivot columns : (Matrix([
[1, 0,   1,   3],
[0, 1, 2/3, 1/3],
[0, 0,   0,   0]]), (0, 1))

Example #2:
# import sympy from sympy import *   M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])print("Matrix : {} ".format(M))   # Use sympy.rref() method M_rref = M.rref()        print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref))  
Output:
Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]]) 
The Row echelon form of matrix M and the pivot columns : (Matrix([
[1, 0, 0, 1405/4254],
[0, 1, 0,    10/709],
[0, 0, 1, -314/2127]]), (0, 1, 2))

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | How to shorten long URLs using Bitly API

22 Oct, 2018
Bitly is used to shorten, brand, share, or retrieve data from links programmatically.
In this article, we’ll see how to shorten URLs using Bitly API. Below is a working example to shorten a URL using Bitly API.
Step #1: Install Bitly API using gitgit clone https://github.com/bitly/bitly-api-python.git
Go inside the folder using:cd bitly-api-python
Note: In case installation with pip command is not working:
File "/usr/local/lib/python3.5/dist-packages/bitly_api/__init__.py", line 1, in from bitly_api import Connection, BitlyError, Error  ImportError: cannot import name 'Connection'
Uninstall bitly-api in case already installed using pip:
pip uninstall bitly_api
 
Step #2: Install in Python’s folder for modules:
python setup.py install
Note: Delete the source code using (since we don’t need it for now) :
cd../
rmdir bitly-api-python-master
 Step #3: To get “Bitly username and API Key” login to account on bit.ly and then go here and get it. In case of further assistance, one can go here.
 Step #4: Now create a file shorturl.py and write this code:
import bitly_api  API_USER = "your_username"API_KEY = "your_API_Key"  b = bitly_api.Connection(API_USER, API_KEY)  # Replace this with your Long URL Herelongurl = www.google.com    response = b.shorten(uri = longurl)  # Now let us print the Bitly URLprint(response)
Step #5: Run the file ‘shorturl.py’.
 Reference: https://dev.bitly.com/v4_documentation.html
Technical Scripter 2018
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
How to setup cron jobs in Ubuntu
Top Programming Languages for Android App Development
How to Add External JAR File to an IntelliJ IDEA Project?
'dd' command in Linux
How to Delete Temporary Files in Windows 10?
Stream builder() in Java with Examples

06 Dec, 2018
Stream builder() returns a builder for a Stream.
Syntax :
static <T> Stream.Builder<T> builder()

where, T is the type of elements.

Return Value : A stream builder.
Example 1 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Using Stream builder()        Stream.Builder<String> builder = Stream.builder();          // Adding elements in the stream of Strings        Stream<String> stream = builder.add("Geeks").build();          // Displaying the elements in the stream        stream.forEach(System.out::println);    }}
Output :
Geeks

Example 2 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Using Stream builder()        Stream.Builder<String> builder = Stream.builder();          // Adding elements in the stream of Strings        Stream<String> stream = builder.add("Geeks")                                    .add("for")                                    .add("Geeks")                                    .add("GeeksQuiz")                                    .build();          // Displaying the elements in the stream        stream.forEach(System.out::println);    }}
Output :
Geeks
for
Geeks
GeeksQuiz

Example 3 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors;  class GFG {      // Driver code    public static void main(String[] args)    {        // Using Stream builder()        Stream.Builder<String> builder = Stream.builder();          // Adding elements in the stream of Strings        Stream<String> stream = builder.add("GEEKS")                                    .add("for")                                    .add("Geeks")                                    .add("GeEKSQuiz")                                    .build();          // Converting elements to Lower Case        // and storing them in List list        List<String> list = stream.map(String::toLowerCase)                                .collect(Collectors.toList());          // Displaying the elements in list        System.out.println(list);    }}
Output :
[geeks, for, geeks, geeksquiz]

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Using findOneAndUpdate () to update in MongoDB?

The findOneAndUpdate() is used to update a single document based on the filter and sort criteria i.e. −
db.collection.findOneAndUpdate(filter, update, options)
Let us create a collection with documents −
> db.demo328.insertOne({Name:"Chris",Marks:67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b19f8647eb59e56207a")
}
> db.demo328.insertOne({Name:"David",Marks:78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b24f8647eb59e56207b")
}
> db.demo328.insertOne({Name:"Bob",Marks:97});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b2bf8647eb59e56207c")
}
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
Following is the query to update with findOneAndUpdate(). Here, we are incrementing a specific document’s field Marks −
> db.demo328.findOneAndUpdate({Name:"David"},{ $inc: { "Marks" : 10} });
{
   "_id" : ObjectId("5e516b24f8647eb59e56207b"),
   "Name" : "David",
   "Marks" : 78
}
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 88 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
Python 3 - List index() Method

The index() method returns the lowest index in list that obj appears.
Following is the syntax for index() method −
list.index(obj)

obj − This is the object to be find out.
This method returns index of the found object otherwise raise an exception indicating that value does not find.
The following example shows the usage of index() method.
#!/usr/bin/python3

list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))
When we run above program, it produces the following result −
Index of chemistry 1
Traceback (most recent call last):
   File "test.py", line 3, in <module>
      print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Perl pos Function

This function is used to find the offset or position of the last matched substring. If SCALAR is specified, it will return the offset of the last match on that scalar variable.
You can also assign a value to this function (for example, pos($foo) = 20;) in order to change the starting point of the next match operation.
Offset is counter starting from zeroth position.
Following is the simple syntax for this function −
pos EXPR

pos

This function returns Integer in Scalar context and then positions of all the matches within the regular expression in List context.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$name = "This is alpha beta gamma";
$name =~ m/alpha/g;

print("pos() ", pos($name), "\n");
When above code is executed, it produces the following result −
pos() 13


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Find records from one MySQL table which don't exist in another?

To find the records from one MySQL table which don’t exist in another table we can use the
subquery for the table which does not have the records. This can be better understood using the
given steps −
First a table is created using the create command. The table name is ‘PresentHistory’ and it has
two columns. This is given as follows −
mysql> CREATE table PresentHistory
-> (
-> HisID int,
-> HisName varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)
After creating the table, some records are inserted that will be present in the second table as
well. This is done with the help of the insert command as follows −
mysql> INSERT into PresentHistory values(1,'John');
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into PresentHistory values(2,'Bob');
Query OK, 1 row affected (0.15 sec)
After inserting the records successfully, they are displayed with the select statement as follows −
mysql> SELECT * from PresentHistory;

After executing the above query, the output obtained is.
+-------+---------+
| HisID | HisName |
+-------+---------+
| 1     | John    |
| 2     | Bob     |
+-------+---------+
2 rows in set (0.00 sec)
Now, a second table is created using the create command. This table is named ‘PastHistory’
and contains two columns as given below.
mysql> CREATE table PastHistory
-> (
-> PastId int,
-> PastName varchar(100)
-> );
Query OK, 0 rows affected (0.74 sec)
After creating the table, some records which are present in first table and some records which
are not present in first table are inserted in PastHistory table.
mysql> INSERT into PastHistory values(1,'John');
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into PastHistory values(2,'Bob');
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into PastHistory values(3,'Carol');
Query OK, 1 row affected (0.17 sec)

mysql> INSERT into PastHistory values(4,'Jason');
Query OK, 1 row affected (0.16 sec)
Now, there are 4 records in the second table. Out of these, 2 records are from the first table and
2 records are different in second table.
The records in the second table are seen with the help of the select statement as follows −
mysql> SELECT * from PastHistory;

The output of the above query is
+--------+----------+
| PastId | PastName |
+--------+----------+
| 1      | John     |
| 2      | Bob      |
| 3      | Carol    |
| 4      | Jason    |
+--------+----------+
4 rows in set (0.00 sec)
The syntax to check the records from one table that don’t exist in the second table is given as
follows −
SELECT * from yourSecondTableName where columnNamefromSecondtable NOT IN
(SELECT columnNamefromfirsttable from yourFirstTableName);
The given query is used to get the records that are distinct in the second table −
mysql> SELECT * from PastHistory where PastName not in (select HisName from
PresentHistory);
The output of the above query is as follows −
+--------+----------+
| PastId | PastName |
+--------+----------+
| 3      | Carol    |
| 4      | Jason    |
+--------+----------+
2 rows in set (0.00 sec)
From the above output it is clear that we have found two records which are not present in the
first table.
LTrim() and RTrim() Function in MS Access - GeeksforGeeks

02 Sep, 2020
1. LTrim() Function :In MS Access LTrim() function remove all the leading spaces from the given string. In LTrim() function a string will be pass as a parameter and it will return the string with no leading spaces.
Syntax :
LTrim(string)
Example-1 :
SELECT LTrim("    GEEKSFORGEEKS") AS LeftTrimmedString;
Output –
Example-2 :
SELECT LTrim("    GFG") AS LeftTrimmedString;
Output –
2. RTrim() Function :It works same like LTrim() function but it will remove all trailing spaces from a string.
Syntax :
RTrim(string)
Example-1 :
SELECT RTrim("GEEKSFORGEEKS    ") AS RightTrimmedString;
Output –
Example-2 :
SELECT RTrim("GFG    ") AS RightTrimmedString;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
Python 3 - File truncate() Method

The method truncate() truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.
The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size, the result is platform-dependent.
Note − This method would not work in case file is opened in read-only mode.
Following is the syntax for truncate() method −
fileObject.truncate( [ size ])

size − If this optional argument is present, the file is truncated to (at most) that size.
This method does not return any value.
The following example shows the usage of truncate() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python3

fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readline()
print ("Read Line: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt
Read Line: This is 1s
Read Line: []


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C library function - fread()

The C library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr.
Following is the declaration for fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
size − This is the size in bytes of each element to be read.
size − This is the size in bytes of each element to be read.
nmemb − This is the number of elements, each one with a size of size bytes.
nmemb − This is the number of elements, each one with a size of size bytes.
stream − This is the pointer to a FILE object that specifies an input stream.
stream − This is the pointer to a FILE object that specifies an input stream.
The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.
The following example shows the usage of fread() function.
#include <stdio.h>
#include <string.h>

int main () {
   FILE *fp;
   char c[] = "this is tutorialspoint";
   char buffer[100];

   /* Open file for both reading and writing */
   fp = fopen("file.txt", "w+");

   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);

   /* Seek to the beginning of the file */
   fseek(fp, 0, SEEK_SET);

   /* Read and display data */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);
   
   return(0);
}
Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −
this is tutorialspoint


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Read a character from standard input without waiting for a newline in C++

A portable solution doesn't exist for doing this. On windows, you can use the getch() function from the conio(Console I/O) library to get characters pressed.
#include<iostream>
#include<conio.h>
using namespace std;
int main() {
    char c;
    while(1){ // infinite loop
        c = getch();
        cout << c;
    }
}
This will output whatever character you input to the terminal. Note that this will only work on windows as the conio library exists only on windows. On UNIX, you can achieve this by entering in system raw mode. 
#include<iostream>
#include<stdio.h>
int main() {
    char c;
   // Set the terminal to raw mode
    system("stty raw");
    while(1) {
        c = getchar();
        // terminate when "." is pressed
        if(c == '.') {
            system("stty cooked");
            exit(0);
        }  
        std::cout << c << " was pressed."<< std::endl;
    }
}
GATE | GATE CS 2013 | Question 28 - GeeksforGeeks

19 Nov, 2018
Consider the following sequence of micro-operations.
     MBR ← PC 
     MAR ← X  
     PC ← Y  
     Memory ← MBR
Which one of the following is a possible operation performed by this sequence?(A) Instruction fetch(B) Operand fetch(C) Conditional branch(D) Initiation of interrupt serviceAnswer: (D)Explanation: MBR – Memory Buffer Register ( that stores the data being transferred to and from the immediate access store)
MAR – Memory Address Register ( that holds the memory location of data that needs to be accessed.)
PC – Program Counter ( It contains the address of the instruction being executed at the current time )
The 1st instruction places the value of PC into MBR
The 2nd instruction places an address X into MAR.
The 3rd instruction places an address Y into PC.
The 4th instruction places the value of MBR ( which was the old PC value) into Memory.
Now it can be seen from the 1st and the 4th instructions, that the control flow was not sequential and the value of PC was stored in the memory, so that the control can again come back to the address where it left the execution.
This behavior is seen in the case of interrupt handling. And here X can be the address of the location in the memory which contains the beginning address of Interrupt service routine.And Y can be the beginning address of Interrupt service routine.
In case of conditional branch (as for option C ) only PC is updated with the target address and there is no need to store the old PC value into the memory.
And in the case of Instruction fetch and operand fetch ( as for option A and B), PC value is not stored anywhere else.
Hence option D.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
Groovy - Lists get()

Returns the element at the specified position in this List.
Object get(int index)

Index – The index at which the value needs to be returned.
The value at the index position in the list.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      def lst = [11, 12, 13, 14];
      println(lst.get(0));
      println(lst.get(2));
   } 
}
When we run the above program, we will get the following result −
11 
13


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Performing regex Queries with PyMongo?

PyMongo is a Python distribution containing tools for working with MongoDB. To perform regex queries with PyMongo, the syntax is as follows −
db.yourCollectionName.find({'yourCollectionName':{'$regex':'^yourWords'}}).pretty();
The above syntax will give all those documents that start from a specific word.
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
   "Folder 1","Folder 2","Folder 3","Folder 4","Folder 5"], "MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a8b186cea1f28b7aa07f2")
}
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
   "ClientFolder 1","ClientFolder 2","ClientFolder 3","ClientFolder 4","ClientFolder 5"],
   "MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a8b1d6cea1f28b7aa07f3")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.performRegex.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "Folder 1",
      "Folder 2",
      "Folder 3",
      "Folder 4",
      "Folder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
{
   "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "ClientFolder 1",
      "ClientFolder 2",
      "ClientFolder 3",
      "ClientFolder 4",
      "ClientFolder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
Here is the query to perform regex.
Case 1 − The below query gives all documents which starts from the word ‘ClientFolder’ −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^ClientFolder'}}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "ClientFolder 1",
      "ClientFolder 2",
      "ClientFolder 3",
      "ClientFolder 4",
      "ClientFolder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
Case 2 − The below query gives all documents which starts from word ‘Folder’ −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^Folder'}}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
   "ClientName" : "Larry",
   "ClientFolderInformation" : [
      "Folder 1",
      "Folder 2",
      "Folder 3",
      "Folder 4",
      "Folder 5"
   ],
   "MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
Explain the logical operators in DBMS

Logical operators are used to specify conditions in the structured query language (SQL) statement. They are also used to serve as conjunctions for multiple conditions in a statement.
The different logical operators are shown below −
ALL − It is used to compare a value with every value in a list or returned by a query. Must be preceded by =, !=, >, < ,<=, or >= evaluates.
For example,
select * from emp where salary>= ALL(1500,4000);
AND − Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE; otherwise returns UNKNOWN.
For example,
select * from emp where job=’manager’ AND deptno=20;
OR − Return TRUE if either component condition is TRUE. Return FALSE if both are FALSE. Otherwise, return UNKNOWN.
For example,
select * from emp where job=’manager’ OR deptno=20;
IN − It is equivalent to any test. Equivalent to = ANY, The In operator is used to compare a value to a list of literal values that have been specified.
For example,
select * from emp where ename IN (‘bhanu’,’ward’);

NOT − Returns TRUE if the condition is FALSE. Returns FALSE, if it is TRUE. If it is UNKNOWN, it remains UNKNOWN.
For example,
select * from emp where NOT (job is NULL)
select * from emp where NOT(salary between 2000 AND 5000);
BETWEEN − It is used to define range limits.
For example,
If we want to find all employees whose age is in between 40 and 50 the query is as follows −
Select * from employee E where E.age between 40 AND 50;
LIKE − It is used to compare values to a list of literal values that are specified. “%” character is used to match any substring and “_” character is used to match any character. It expresses a pattern by using the ‘like’ comparison operator.
For example,
To display all names whose second letter is ‘b’, use the below mentioned command −
select * from emp where ename LIKE ‘_b%’;
To display a person details whose first letter is ‘A’ and third letter is ‘d’, use the command given below −
Select * from emp where ename LIKE ‘A_d_’;
Python – Check Similar elements in Matrix rows

08 Dec, 2020
Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of List.
Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.
Input : test_list = [[1, 1, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : False Explanation : All rows don’t have same elements.  
Method #1 : Using loop 
In this, we iterate through each row and check for its similar number in the list, if all the elements in a row are the same as an ith element in the List, true is returned, else false.
Python3
# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using loop  # initializing Matrixtest_list = [[1, 1, 1], [4, 4],             [3, 3, 3], [5, 5, 5, 5]]               # printing original listprint("The original list is : " + str(test_list))  # initializing tar_list tar_list = [1, 4, 3, 5]  res = Trueflag = 0for idx in range(len(test_list)):    for ele in test_list[idx]:                  # checking for row index         # equal to list index elements         if ele != tar_list[idx]:            res = False             flag = 1            break                  if flag:        break      # printing resultprint("Are row index element similar\       to list index element ? : " + str(res))
 Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True
Method #2 : Using all() + generator expression
In this, we check for all elements to be equal using all(), and check for all elements follow this pattern using all() again. The iteration of elements and rows is done using generator expression.
 
Python3
# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using all() + generator expression  # initializing Matrixtest_list = [[1, 1, 1], [4, 4],             [3, 3, 3], [5, 5, 5, 5]]               # printing original listprint("The original list is : " + str(test_list))  # initializing tar_list tar_list = [1, 4, 3, 5]  # nested all() used to check each element and rowsres = all(all(ele == tar_list[idx] for ele in test_list[idx])          for idx in range(len(test_list)) )      # printing resultprint("Are row index element\    similar to list index element ? : " + str(res))
Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementing ANDNOT Gate using Adaline Network

18 Jun, 2019
ADALINE (Adaptive Linear Neuron or later Adaptive Linear Element) is an early single-layer artificial neural network and the name of the physical device that implemented this network. The problem here is to implement AND-NOT using Adaline network. Here we perform 5 epochs of training and calculate total mean error in each case, the total mean error decreases after each epochs and later becomes nearly constant.
The Truth Table for AND-NOT Gate is as follows:
 x1  x2  t
 1   1  -1
 1  -1   1
-1   1  -1
-1  -1  -1

#include <iostream>using namespace std;int main(){    // input array    int arr[4][2] = { { 1, 1 },        { 1, -1 },        { -1, 1 },        { -1, -1 }    };          // target array    int t[4] = { -1, 1, -1, -1 }, i, j;    float yi, dif, dw1, dw2, db, w1 = 0.2, w2 = 0.2, b = 0.2, err[4];      // taking bias in each case as 1    // Calculation upto 5 epochs    // consider learning rate = 0.2      for (i = 0; i < 5; i++)    {        float avg = 0;                  cout << "EPOCH " << i + 1 << " Errors" << endl             << endl;        for (j = 0; j < 4; j++)        {            // calculating net input            yi = arr[j][0] * w1 + arr[j][1] * w2 + 1 * b;            dif = t[j] - yi;                          // updated weights            w1 += 0.2 * dif * arr[j][0];            w2 += 0.2 * dif * arr[j][1];            b += 0.2 * dif * 1;            err[j] = dif * dif;            cout << err[j] << " ";            avg += err[j];        }        cout << endl             << "Total Mean Error :" << avg << endl             << endl             << endl;    }    return 0;}
EPOCH 1 Errors

2.56 1.2544 0.430336 1.47088 
Total Mean Error :5.71562


EPOCH 2 Errors

0.951327 0.569168 0.106353 0.803357 
Total Mean Error :2.43021


EPOCH 3 Errors

0.617033 0.494715 0.369035 0.604961 
Total Mean Error :2.08574


EPOCH 4 Errors

0.535726 0.496723 0.470452 0.541166 
Total Mean Error :2.04407


EPOCH 5 Errors

0.515577 0.503857 0.499932 0.520188 
Total Mean Error :2.03955

Neural Network
C++ Programs
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to check if a given String is Palindrome or not
How to find the minimum and maximum element of a Vector using STL in C++?
Shallow Copy and Deep Copy in C++
C Program to Swap two Numbers
Enumerated Types or Enums in C++
Naive Bayes Classifiers
Reinforcement learning
Agents in Artificial Intelligence
Search Algorithms in AI
Markov Decision Process
Pandas.cut() method in Python

13 Jul, 2021
Pandas cut() function is used to separate the array elements into different bins . The cut function is mainly used to perform statistical analysis on scalar data.  
Syntax: cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates=”raise”,)
Parameters:
x: The input array to be binned. Must be 1-dimensional.
bins: defines the bin edges for the segmentation.
right : (bool, default True )  Indicates whether bins includes the rightmost edge or not. If right == True (the default), then the bins [1, 2, 3, 4] indicate (1,2], (2,3], (3,4]. 
labels : (array or bool, optional)  Specifies the labels for the returned bins. Must be the same length as the resulting bins. If False, returns only integer indicators of the bins. 
retbins : (bool, default False) Whether to return the bins or not. Useful when bins is provided as a scalar.
Example 1: Let’s say we have an array of 10 random numbers from 1 to 100 and we wish to separate data into 5 bins of (1,20] , (20,40] , (40,60] ,  (60,80] , (80,100] .
Python3
import pandas as pdimport numpy as np  df= pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60,                                          80, 100])print(df) # We can check the frequency of each binprint(df['bins'].unique())
 
 
Output:
 
 
Example 2: We can also add labels to our bins, for example let’s look at the previous example and  add some labels to it
 
Python3
import pandas as pdimport numpy as np df = pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60, 80, 100],                    labels=['1 to 20', '21 to 40', '41 to 60',                            '61 to 80', '81 to 100']) print(df) # We can check the frequency of each binprint(df['bins'].unique())
Output:
rajeev0719singh
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript(ES6) | Object Literal Enhancement

10 May, 2020
Object literal enhancement is used to group variables from the global scope and form them into javascript objects. It is the process of restructuring or putting back together.
Example 1:
<script>// variable declarationvar name = "Duke";var color = "Brown";var age = 5;  // Using Object Literal Enhancement// Combines all variables into a dog objectvar dog = {name, color, age};console.log(dog);</script>
Output : The name, color and age are now keys of dog object.
{
    name:"Duke",
    color:"Brown",
    age:5
}

Example 2: We can also create object methods with object literal enhancement.
<script>// variable declarationvar name = "Tike";var color = "Black";var age = 7;  // function declarationvar bark = function(){    console.log("Woof Woof!!");}  // Using Object Literal Enhancement// combines all variables into an anotherDog objectvar anotherDog = {name, color, age, bark};anotherDog.bark();</script>
Output:
Woof Woof!!
Example 3: We can also use “this” keyword to access the object keys.
<script>    // Variable declaration    var name = "Lilly";    var color = "White";    var age = 3;      // function declaration     // using "this" keyword to access the object keys.    var barkWithName = function(){        console.log('Woof Woof!!, I am '        +this.name+' and I am a '        +this.age+' years old, '        +this.color+ ' coloured dog.Woof Woof!!');    }      // Using Object Literal Enhancement    // combines all variables into a yetAnotherDog object    var yetAnotherDog = {name, color, age, barkWithName};    yetAnotherDog.barkWithName();</script>                    
Output :
Woof Woof!!, I am lilly and I am a 3 years old,
white coloured dog.Woof Woof!!
Example 4: When defining object methods, it is no longer necessary to use the function keyword. Object literal enhancement allows us to pull global variables into objects and reduces typing by making the function keyword unnecessary.
<script>// Old syntaxvar driver1 = {    name: "John",    speed: 50,    car:"Ferrari",    speedUp: function(speedup){         this.speed = this.speed + speedup;         console.log("new speed = "+ this.speed)    }}  // New syntax without function keywordconst driver2 = {    name: "Jane",    speed: 60,    car:"McLaren",    speedUp(speedup){         this.speed = this.speed + speedup;         console.log("new speed = "+ this.speed)    }}</script>
ES6
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ulong type in C#

The Ulong type in C# is an alias to the System.UInt64 type. It is an Unsigned integer.
Set the Ulong type −
ulong val = 7712059531;
To get the minimum and maximum value for Ulong type −
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(ulong.MinValue);
Here is the complete code −
 Live Demo
using System;
using System.Threading;
using System.Diagnostics;
public class Demo {
   public static void Main() {
      ulong val = 7712059531;
      Console.WriteLine(val);
      // Max and Min values
      Console.WriteLine(ulong.MaxValue);
      Console.WriteLine(ulong.MinValue);
      // typeof
      Console.WriteLine(typeof(ulong));
   }
}
7712059531
18446744073709551615
0
System.UInt64
Can you extend a static inner class in Java?

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
You can extend static inner class with another inner class.
 Live Demo
public class SampleClass {
   static abstract class Test{
      int num = 300;
      public abstract void display();
   }
   class DemoClass extends Test{
      public void display() {
         System.out.println("Hi how are you");
      }
   }
   public static void main(String args[]){
      SampleClass obj = new SampleClass();
      obj.new DemoClass().display();
   }
}
Hi how are you