code-rag-bench/online-tutorials huggingface dataset:
Import Only Selected Columns of Data from CSV in R - GeeksforGeeks

17 Jun, 2021
In this article, we will be looking at two different approaches to import selected columns of the Data from a CSV file in the R programming language.
In this method of only importing the selected columns of the CSV file data, the user needs to call the read.table() function, which is an in-built function of R programming language, and then passes the selected column in its arguments to import particular columns from the data. Here, the user has to pass the null value to the parameter, to avoid importing that particular column.
read.table() function reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file.
Syntax:
read.table(file, header, nrows, skip, colClasses, sep)
Parameters:
file: Specifies the name of the file.
header:The header is a logical flag indicating whether the first line is a header line contains data or not.
nrows: Specifies number of rows in the dataset.
skip: Helps in skipping of lines from the beginning.
colClasses: It is a character vector which indicates class of each column of the data set.
sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc.
Dataset in Use:
Example:
R
gfg_data <- read.table("gfg_data.csv", header = TRUE, sep = ",",                           colClasses = c("numeric", "NULL", "NULL",                                          "numeric", "NULL"))  gfg_data
Output:
In this approach to import only selected columns to the R programming language, the user first needs to install and import the data.table package in the R console and call the read() function which is the function of the data.table package, with the file location and the selected columns which are to be imported in the select argument of this function. Further, this will lead to importing of the selected columns  
fread() function is fast and more convenient to controls such as sep, colClasses, and nrows are automatically detected
Syntax:
fread(file, sep, colClasses, nrows)
Parameter:
file: Specifies the name of the file.
colClasses: It is a character vector which indicates class of each column of the data set.
sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc.
nrows: Specifies number of rows in the dataset.
Example:
R
library("data.table")     gfg_data <- fread("gfg_data.csv",                  select = c("A", "C", "E"))  gfg_data
Output: 
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
Plot mean and standard deviation using ggplot2 in R
Difference between const int*, const int * const, and int const *

22 Jun, 2022
int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn’t be changed. Const qualifier doesn’t affect the pointer in this scenario so the pointer is allowed to point to some other address. The first const keyword can go either side of data type, hence int const* is equivalent to const int*. 
C
#include <stdio.h> int main(){    const int q = 5;    int const* p = &q;     //Compilation error    *p = 7;     const int q2 = 7;     //Valid    p = &q2;         return 0;}
int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer. Effectively, this implies that the pointer shouldn’t point to some other address. Const qualifier doesn’t affect the value of integer in this scenario so the value being stored in the address is allowed to change. 
C
#include <stdio.h> int main(){    int q = 5;    int *const p = &q;     //Valid    *p = 7;     const int q2 = 7;     //Compilation error    p = &q2;     return 0;}
const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer. Effectively, this implies that a constant pointer is pointing to a constant value. Hence, neither the pointer should point to a new address nor the value being pointed to should be changed. The first const keyword can go either side of data type, hence const int* const is equivalent to int const* const. 
C
#include <stdio.h> int main(){    const int q = 5;     //Valid    const int* const p = &q;     //Compilation error    *p = 7;         const int q2 = 7;     //Compilation error    p = &q2;         return 0;}
One way to remember the syntax (according to Bjarne Stroustrup) is the spiral rule- The rule says, start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends.  The rule can also be seen as decoding the syntax from right to left.  Hence,
int const* is pointer to const int
int *const is const pointer to int
int const* const is const pointer to const int
Using this rule, even complex declarations can be decoded like,
int ** const is a const pointer to pointer to an int.
int * const * is a pointer to const pointer to an int.
int const ** is a pointer to a pointer to a const int.
int * const * const is a const pointer to a const pointer to an int.
RanaShaktiSingh
dcdschaudhary
needgyan
Picked
Pointers
C Language
C Programs
Difference Between
Programming Language
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
setlinestyle() function in C

25 Jan, 2018
The header file graphics.h contains setlinestyle() function which sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on.
Syntax :
void setlinestyle(int linestyle, unsigned upattern,
                                   int thickness);

Examples :
Input : x = 200, y = 100
Output : 

x and y are initialized as (200, 100). 
For every line, value of y increments 
by 25 to change the position. 
The line style keep changing corresponding
to value of first parameter(c). 

Explanation : linestyle specifies in which of several styles subsequent lines will be drawn (such as solid, dotted, centered, dashed).upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE (4). In that case, whenever a bit in the pattern word is 1, the corresponding pixel in the line is drawn in the current drawing color. A value for ‘upattern’ must always be supplied. It is simply ignored if ‘linestyle’ is not USERBIT_LINE (4).thickness specifies whether the width of subsequent lines drawn will be normal or thick.
Below is the implementation of setlinestyle() function :
// C Implementation for setlinestyle()#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // variable to change the    // line styles    int c;      // initial coordinate to     // draw line    int x = 200, y = 100;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // To keep track of lines    for ( c = 0 ; c < 5 ; c++ )   {       // setlinestyle function       setlinestyle(c, 0, 1);         // Drawing line       line(x, y, x+200, y);       y = y + 25;   }      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File.GetCreationTime() Method in C# with Examples

28 Apr, 2020
File.GetCreationTime(String) is an inbuilt File class method which is used to return the creation date and time of the specified file or directory.
Syntax:
public static DateTime GetCreationTime (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the specified file path whose creation date and time is going to be returned.
Exceptions:
UnauthorizedAccessException: The caller does not have the required permission.
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
NotSupportedException: The path is in an invalid format.
Return Value: Returns the creation date and time of the specified file or directory.
Below are the programs to illustrate the File.GetCreationTime(String) method.
Program 1: Before running the below code, a file file.txt is created with some contents shown below:
// C# program to illustrate the usage// of File.GetCreationTime(String) method  // Using System and System.IO namespacesusing System;using System.IO;  class GFG {    static void Main(string[] args)    {        // Calling the GetCreationTime() function        DateTime fileCreatedDate = File.GetCreationTime(@"file.txt");          // Printing the creation date and time of the        // specified file        Console.WriteLine("File created on: " + fileCreatedDate);    }}
Executing:
File created on: 4/19/2020 4:02:54 AM

Program 2: Before running the below code, two files were created shown below:
// C# program to illustrate the usage// of File.GetCreationTime(String) method  // Using System and System.IO namespacesusing System;using System.IO;  class GFG {    static void Main(string[] args)    {        // Calling the GetCreationTime() function        DateTime fileCreatedDate1 = File.GetCreationTime(@"file.txt");        DateTime fileCreatedDate2 = File.GetCreationTime(@"gfg.txt");          // Printing the creation date and time of the        // specified file        Console.WriteLine("File created on: " + fileCreatedDate1);        Console.WriteLine("File created on: " + fileCreatedDate2);    }}
Executing:
File created on: 4/19/2020 4:02:54 AM
File created on: 4/19/2020 4:07:02 AM

CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Replace() Method
How to convert value to string using $toString in MongoDB?

Let us see an example to understand the $toString in MongoDB. To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.objectidToStringDemo.insertOne({"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80036de59bd9de0639d")
}
> db.objectidToStringDemo.insertOne({"UserName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80436de59bd9de0639e")
}
> db.objectidToStringDemo.insertOne({"UserName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b80936de59bd9de0639f")
}
> db.objectidToStringDemo.insertOne({"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92b81836de59bd9de063a0")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.objectidToStringDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" }
Here is the query to convert ObjectId to a string value in MongoDB aggregate. The query is as follows −
> db.objectidToStringDemo.aggregate([
   ... {
      ... $project: {
         ... _id: {
            ... $toString: "$_id"
         ... }
      ... }
   ... }
... ]
... );
The following is the output −
{ "_id" : "5c92b80036de59bd9de0639d" }
{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }
In order to get the original ObjectId, use the $toObjectId operator −
> db.objectidToStringDemo.aggregate([ { $project: { _id: { $toObjectId: "$_id" } } } ] );
The following is the output −
{ "_id" : ObjectId("5c92b80036de59bd9de0639d") }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e") }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f") }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0") }
Python | Check if a list is contained in another list

21 Nov, 2019
Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A’s order.
Examples:
Input : A = [1, 2], B = [1, 2, 3, 1, 1, 2, 2]
Output : True

Input : A = ['x', 'y', 'z'], B = ['x', 'a', 'y', 'x', 'b', 'z']
Output : False

 Approach #1 : Naive Approach
A simple naive approach is to use two for loops and check if the whole list A is contained within list B or not. If such a position is met in list A, then break the loop and return true, otherwise false
# Python3 program to Check if a list is # contained in another list without breaking order  def removeElements(A, B):    for i in range(len(B)-len(A)+1):        for j in range(len(A)):            if B[i + j] != A[j]:                break        else:            return True    return False  # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B))
True

 Approach #2 : List comprehension
A more efficient approach is to use List comprehension. We first initialize ‘n’ with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not.
# Python3 program to Remove elements of # list that repeated less than k times  def removeElements(A, B):    n = len(A)    return any(A == B[i:i + n] for i in range(len(B)-n + 1))                    # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B))
True

 Approach #3 : Using join and map module
Here we use join to join both lists to strings and then use in operator to check if list A is contained in B or not.
# Python3 program to Remove elements of # list that repeated less than k times    def removeElements(A, B):    return ', '.join(map(str, A)) in ', '.join(map(str, B))              # Driver codeA = ['x', 'y', 'z']B = ['x', 'a', 'y', 'x', 'b', 'z']print(removeElements(A, B))
False

ManasChhabra2
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 ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
HSQLDB - Connect

In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming).
Take a look at the following program, which will start the server and create a connection between the Java application and the database.
import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectDatabase {
   public static void main(String[] args) {
      Connection con = null;
      
      try {
         //Registering the HSQLDB JDBC driver
         Class.forName("org.hsqldb.jdbc.JDBCDriver");
         //Creating the connection with HSQLDB
         con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
         if (con!= null){
            System.out.println("Connection created successfully");
            
         }else{
            System.out.println("Problem with creating connection");
         }
      
      }  catch (Exception e) {
         e.printStackTrace(System.out);
      }
   }
}
Save this code into ConnectDatabase.java file. You will have to start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb

You can use the following command to compile and execute the code.
\>javac ConnectDatabase.java
\>java ConnectDatabase

After execution of the above command, you will receive the following output −
Connection created successfully

 Print
 Add Notes
 Bookmark this page
How to Join Computer to the AD domain using PowerShell?

To join any workgroup computer in the domain using PowerShell, we can use the Add-Computer command but before that, there are a few Windows prerequisite that DNS must be configured properly and the domain controller should be reachable and others should suffice then only PowerShell can use the command to join computer into a domain.
Add-Computer -ComputerName Test1-win2k16 `
             -DomainCredential Labdomain\Administrator `
             -DomainName Labdomain.local -Restart -Force -PassThru
Once you run the above command, it will ask you for the credential for the user you entered. In the above example, we are joining a remote computer to the domain LabDomain.Local and it will restart the remote system. If the users are logged in on the remote system, it might not restart but the system will connect to the domain. You can restart later forcefully.
We need to make sure that the username used in the -DomainCredential parameter, should have proper privileges like DomainAdmin, EnterpriseAdmin.
To Join the computer in the Different OU, you need to provide the OU path
Add-Computer -ComputerName Test1-win2k16 `
             -DomainCredential Labdomain\Administrator `
             -DomainName Labdomain.local `
             -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' `
             -Restart -Force -PassThru
Here the computer Name parameter is String[] so you can use multiple computers.  For example,
Add-Computer -ComputerName Test1-win2k16, Test1-Win2k12, Test2-Win2k12 `
             -DomainCredential Labdomain\Administrator `
             -DomainName Labdomain.local `
             -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' `
             -Restart -Force -PassThru
You can also use the foreach loop and the list of computers from the CSV file to join multiple computers if the OU path is different.
DateTime.AddDays() Method in C#

The DateTime.AddDays() method in C# is used to add the specified number of days to the value of this instance. This method returns a new DateTime.
Following is the syntax −
public DateTime AddDays (double days);
Above, the parameter days are the number of days to be added. To subtract, add a negative value.
Let us now see an example to implement the DateTime.AddDays() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 2, 8, 0, 15);
      DateTime d2 = d1.AddDays(25);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("\nNew DateTime (After adding days) = {0:y} {0:dd}", d2);
   }
}
This will produce the following output −
Initial DateTime = November 2019 02
New DateTime (After adding days) = November 2019 27
Let us now see another example to implement the DateTime.AddDays() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = DateTime.MinValue;
      DateTime d2 = d1.AddDays(150);
      System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1);
      System.Console.WriteLine("\nNew DateTime (After adding days) = {0:y} {0:dd}", d2);
   }
}
This will produce the following output −
Initial DateTime = January 0001 01
New DateTime (After adding days) = May 0001 31
Check if a large number is divisible by 8 or not in C++

Here we will see how to check a number is divisible by 8 or not. In this case the number is very large number. So we put the number as string.
A number will be divisible by 8, if the number formed by last three digits are divisible by 8.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isDiv8(string num){
   int n = num.length();
   int last_three_digit_val = (num[n-3] - '0') * 100 + (num[n-2] - '0') * 10 + ((num[n-1] - '0'));
   if(last_three_digit_val % 8 == 0)
      return true;
      return false;
}
int main() {
   string num = "1754586672360";
   if(isDiv8(num)){
      cout << "Divisible";
   }else{
      cout << "Not Divisible";
   }
}
Divisible
How can I scroll a web page using selenium webdriver in python?

Sometimes we need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element.
Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript.
Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium.
Code Implementation with Javascript Executor.
import time
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element
l= driver.find_element_by_xpath("//*[text()='About Us']")
# Javascript Executor
driver.execute_script("arguments[0].scrollIntoView(true);", l)
time.sleep(0.4)
driver.close
While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element.
Code Implementation with Actions.
from selenium.webdriver import ActionChains
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element
I=driver.find_element_by_xpath("//*[text()='About Us']")
# action object creation to scroll
a = ActionChains(driver)
a.move_to_element(l).perform()
Sum of the sequence 2, 22, 222, .........

15 Jun, 2022
Find the sum of the following sequence : 2, 22, 222, ......... to n terms. Examples :  
Input : 2
Output: 1.9926

Input : 3
Output: 23.9112
 
A simple solution is to compute terms one by one and add to the result.The above problem can be efficiently solved using the following formula: 
 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find sum of series// 2, 22, 222, ..#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){    return 0.0246 * (pow(10, n) - 1 - (9 * n));} // driver codeint main(){    int n = 3;    cout << sumOfSeries(n);    return 0;}
// JAVA Code for Sum of the// sequence 2, 22, 222,...import java.util.*; class GFG {         // function which return the    // the sum of series    static double sumOfSeries(int n)    {        return 0.0246 * (Math.pow(10, n)                            - 1 - (9 * n));    }         /* Driver program */    public static void main(String[] args)    {         int n = 3;         System.out.println(sumOfSeries(n));    }} // This code is contributed by Arnav Kr. Mandal.
# Python3 code to find# sum of series# 2, 22, 222, ..import math # function which return# the sum of seriesdef sumOfSeries( n ):    return 0.0246 * (math.pow(10, n) - 1 - (9 * n))     # driver coden = 3print( sumOfSeries(n)) # This code is contributed by "Sharad_Bhardwaj".
// C# Code for Sum of the// sequence 2, 22, 222,...using System; class GFG {         // Function which return the    // the sum of series    static double sumOfSeries(int n)    {        return 0.0246 * (Math.Pow(10, n)                           - 1 - (9 * n));    }         // Driver Code    public static void Main()    {        int n = 3;        Console.Write(sumOfSeries(n));    }} // This code is contributed by vt_m.
<?php// PHP program to find sum// of series 2, 22, 222, .. // function which return the// the sum of seriesfunction sumOfSeries($n){    return 0.0246 * (pow(10, $n) -                     1 - (9 * $n));} // Driver Code$n = 3;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program for Sum of the// sequence 2, 22, 222,...     // function which return the    // the sum of series    function sumOfSeries(n)    {        return 0.0246 * (Math.pow(10, n)                            - 1 - (9 * n));    } // Driver code                     let n = 3;        document.write(sumOfSeries(n));             </script>
Output : 
23.9112
Time complexity: O(log n) since using inbuilt power function. Auxiliary Space: O(1)
jit_t
splevel62
technophpfij
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Fizz Buzz Implementation
Count ways to reach the n'th stair
Product of Array except itself
Median of two sorted arrays of same size
Find Union and Intersection of two unsorted arrays
How to remove all items in a Qlistwidget in PyQt5?

25 Feb, 2021
Prerequisite:
PyQt5
QListWidget
There are so many options provided by Python to develop GUI applications and PyQt5 is one of them. PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.
In this article, we will learn how to remove all items from QlistWidget in PyQt5. To achieve the required functionality i.e. to cleaning the window or deleting all elements using Qlistwidget in Python, its clear() method is used.
Syntax:
clear()
Import module
Create QListWidget
Add title and button
Add mechanism to delete all items of the list when the button is pressed
Display window
Program:
Python3
# Import Moduleimport sysfrom PyQt5.QtWidgets import *    class ListBox(QWidget):      def __init__(self):        super().__init__()          self.initUI()      def initUI(self):        # Vertical box layout        vbox = QVBoxLayout(self)          # Horizontal box layout        hbox = QHBoxLayout()          # Create QlistWidget Object        self.listWidget = QListWidget(self)          # Add Items to QlistWidget        self.listWidget.addItems(            ['python', 'c++', 'java', 'pyqt5', 'javascript', 'geeksforgeeks'])          # Add Push Button        clear_btn = QPushButton('Clear', self)        clear_btn.clicked.connect(self.clearListWidget)          vbox.addWidget(self.listWidget)        hbox.addWidget(clear_btn)        vbox.addLayout(hbox)          self.setLayout(vbox)          # Set geometry        self.setGeometry(300, 300, 350, 250)          # Set window title        self.setWindowTitle('QListWidget')          # Display QlistWidget        self.show()      def clearListWidget(self):        self.listWidget.clear()    if __name__ == '__main__':    app = QApplication(sys.argv)      # Call ListBox Class    ex = ListBox()      # Close the window    sys.exit(app.exec_())
Output:
Picked
PyQt5-Widget
Python-gui
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
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
response.iter_content() – Python requests

01 Mar, 2020
response.iter_content() iterates over the response.content. 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.iter_content() out of a response object.
To illustrate use of response.iter_content(), let’s ping geeksforgeeks.org. 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 moduleimport requests  # Making a get requestresponse = requests.get('https://geeksforgeeks.org')  # print responseprint(response)  # print iter_content dataprint(response.iter_content())  # iterates over the listfor i in response.iter_content():    print(i)
Save above file as request.py and run using
Python request.py

Check that iterator object and iterators at the start of the output, it shows the iterator object and iteration elements in bytes respectively.
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.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Mongoose | findOneAndRemove() Function

20 May, 2020
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true,    useFindAndModify: false});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  // Find only one document matching the// condition(age>=5) and remove itUser.findOneAndRemove({age: {$gte:5} },                function (err, docs) {    if (err){        console.log(err)    }    else{        console.log("Removed User : ", docs);    }});
Steps to run the program:
The project structure will look like this:Make sure you have installed mongoose module using the following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below:
The project structure will look like this:
Make sure you have installed mongoose module using the following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
After the function is executed, You can see the database as shown below:
So this is how you can use the mongoose findOneAndRemove() function which finds the document according to the condition and then removes the first matched document.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are the differences between printStackTrace() method and getMessage() method in Java?

There are two ways to find the details of the exception, one is the printStackTrace() method and another is the getMessage() method.
This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class.
This method will display the name of the exception and nature of the message and line number where an exception has occurred.
public class PrintStackTraceMethod {
   public static void main(String[] args) {
      try {
         int a[]= new int[5];
         a[5]=20;
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
java.lang.ArrayIndexOutOfBoundsException: 5
        at PrintStackTraceMethod.main(PrintStackTraceMethod.java:5)
This is a method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error and java.lang.Exception classes.
This method will display the only exception message.
public class GetMessageMethod {
   public static void main(String[] args) {
      try {
         int x=1/0;
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}
/ by zero
cin get() in C++ with Examples - GeeksforGeeks

17 Jan, 2020
cin.get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found. However, cin.get() reads a string with the whitespace.
Syntax:
cin.get(string_name, size);
Example 1:
// C++ program to demonstrate cin.get()  #include <iostream>using namespace std;  int main(){    char name[25];    cin.get(name, 25);    cout << name;      return 0;}
Input:
Geeks for Geeks
Output:
Geeks for Geeks
Example 2:
// C++ program to demonstrate cin.get()  #include <iostream>using namespace std;  int main(){    char name[100];    cin.get(name, 3);    cout << name;      return 0;}
Input:
GFG
Output:
GF
CPP-Functions
C++
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Classes and Objects
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Copy Constructor in C++
Templates in C++ with Examples
C++ Data Types
unordered_map in C++ STL
How to insert an item into a C# list by using an index?

Firstly, set a list −
List<int> list = new List<int>();
list.Add(456);
list.Add(321);
list.Add(123);
list.Add(877);
list.Add(588);
list.Add(459);
Now, to add an item at index 5, let say; for that, use the Insert() method −
list.Insert(5, 999);
Let us see the complete example −
using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         List<int> list = new List<int>();
         list.Add(456);
         list.Add(321);
         list.Add(123);
         list.Add(877);
         list.Add(588);
         list.Add(459);
         Console.Write("List: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("\nCount: {0}", list.Count);

         // inserting element at index 5
         list.Insert(5, 999);
         Console.Write("\nList after inserting a new element: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("\nCount: {0}", list.Count);
      }
   }
}
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

const Header = () => {
  return (
    <>
      <h1 style={{color: "red"}}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>

    <div id="root"></div>

  </body>
</html>


Add a little style!
Count Triplets such that one of the numbers can be written as sum of the other two in C++

We are given an array Arr[] of integers with length n. The goal is to find the number of triplets
(Arr[i],Arr[j],Arr[k]) such that the sum of any two numbers is equal to the third number.
a+b=c, where a,b,c are elements of Arr[] with indexes i,j,k such that 0<=i<j<k<n
We will do this by using three for loops. Increment count if arr[x]+arr[y]=arr[z] and x!=y!=z.
Let’s understand with examples.
arr[]= { 1,2,2,3,4 }, N=5
Number of triplets: 4
Triplets with arr[x]+arr[y]=arr[z].
Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3
Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3
Arr{}=[ 1,2,2,3,4 ] =(1,3,4) → 1+3=4
Arr{}=[ 1,2,2,3,4 ] =(2,2,4) → 2+2=4
Total triplets: 4
arr[]= {2,2,2,2,2}, N=5
Number of triplets: 0
Every two numbers have sum=4 which is not equal to third=2.
Total triplets: 0
We take an integer array Arr[] initialized with random numbers.
We take an integer array Arr[] initialized with random numbers.
Variable N stores the length of Arr[].
Variable N stores the length of Arr[].
Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in
which one of the numbers can be written as sum of the other two
Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in
which one of the numbers can be written as sum of the other two
Take the initial variable count as 0 for the number of triplets.
Take the initial variable count as 0 for the number of triplets.
Traverse array using three for loops for each element of the triplet.
Traverse array using three for loops for each element of the triplet.
Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n.
Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n.
Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then
increment count.
Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then
increment count.
At the end of all loops count will have a total number of triplets that meet the condition.
At the end of all loops count will have a total number of triplets that meet the condition.
Return the count as result.
Return the count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[], int n){
   int count = 0;
   for (int i = 0; i < n-2; i++){
      for (int j = i+1; j < n-1; j++){
         for (int k = j+1; k < n; k++){
            if(arr[i]+arr[j]==arr[k] || arr[j]+arr[k]==arr[i] || arr[k]+arr[i]==arr[j]){                   count++;
             }
         }
      }
   }
   return count;
}
int main(){
   int Arr[]={ 1,2,2,3,4 };
   int N=5; //length of array
   cout <<endl<< "Number of triplets : "<<countTriplets(Arr,N);
   return 0;
}
Number of triplets : 4
send_keys() element method – Selenium Python

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use send_keys method in Selenium. send_keys method is used to send text to any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser.
element.send_keys("some text")
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
To enter text into a field, for example,
element.send_keys("some text")
One can simulate pressing the arrow keys by using the “Keys” class:
element.send_keys(" and some", Keys.ARROW_DOWN)
Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method:
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python. Here we get element of search and enter “Arrays” in the same.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_id("gsc-i-id2")  # send keys element.send_keys("Arrays")
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Index specific cyclic iteration in list

21 Feb, 2019
The problem of cyclic iteration is quite common, but sometimes, we come through the issue in which we require to process the list in a way in which it is cyclic iterated that too starting from a specific index. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using % operator + loopThe % operator can be used to cycle the out of bound index value to begin from the beginning of list to form a cycle and hence help in the cyclic iteration.
# Python3 code to demonstrate # cyclic iteration in list # using % operator and loop  # initializing tuple list test_list = [5, 4, 2, 3, 7]  # printing original listprint ("The original list is : " + str(test_list))  # starting index K = 3  # using % operator and loop# cyclic iteration in list res = []for i in range(len(test_list)):    res.append(test_list[K % len(test_list)])    K = K + 1  # printing result print ("The cycled list is : " +  str(res))
The original list is : [5, 4, 2, 3, 7]
The cycled list is : [3, 7, 5, 4, 2]

 Method #2 : Using itertools.cycle() + itertools.islice() + itertools.dropwhile()The itertools library has built in functions that can help achieve to the solution of this particular problem. The cycle function performs the cycling part, dropwhile function brings the cycle to begin of list and islice function specifies the cycle size.
# Python3 code to demonstrate # cyclic iteration in list using itertoolsfrom itertools import cycle, islice, dropwhile  # initializing tuple list test_list = [5, 4, 2, 3, 7]  # printing original listprint ("The original list is : " + str(test_list))  # starting index K = 3  # using itertools methods for# cyclic iteration in list cycling = cycle(test_list)  skipping = dropwhile(lambda x: x != K, cycling) slicing = islice(skipping, None, len(test_list))slicing = list(slicing)  # printing result print ("The cycled list is : " +  str(slicing))
The original list is : [5, 4, 2, 3, 7]
The cycled list is : [3, 7, 5, 4, 2]

Marketing
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | ne operator

07 May, 2019
‘ne‘ operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise not equal to the string to its right.
Syntax: String1 ne String2
Returns: 1 if left argument is not equal to the right argument
Example 1:
#!/usr/local/bin/perl  # Initializing Strings$a = "Welcome";$b = "Geeks";  # Comparing the strings using ne operator$c = $a ne $b;  if($c == 1){    print"String1 is not equal to String2";}else{    print"String1 is equal to String2";}
String1 is not equal to String2

Example 2:
#!/usr/local/bin/perl  # Initializing Strings$a = "Geeks";$b = "Geeks";  # Comparing the strings using ne operator$c = $a ne $b;  if($c == 1){    print"String1 is not equal to String2";}else{    print"String1 is equal to String2";}
String1 is equal to String2

perl-operators
Perl-String-Operators
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install Boost Library in C++ on Linux?

16 Oct, 2021
Boost is a set of libraries for the C++ programming language. It contains 164 individual libraries. It was initially released on September 1, 1999. Furthermore, it provides support for many tasks such as pseudo-random number generation, linear algebra, multithreading, image processing, regular expressions, and unit testing. In this article, we are going to learn how we can install a boost library in C++ on Linux.
To install the boost library on your Linux, run the following command in your Linux terminal.
sudo apt-get install libboost-all-dev
installing the boost library
Confirm the installation by pressing y from the keyword. This will confirm that the user wants to install the above-listed packages.
In this sample program, we are going to create an array using the boost library. For that, we have to include the boost’s array header file into our CPP program.
Code:
C++
#include <boost/array.hpp>#include <iostream>  using namespace std;int main(){    boost::array<int, 10> arr        = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };    for (int i = 0; i < 10; i++) {        cout << "Geek Rank is :" << arr[i] << "*"             << "\n";    }    return 0;}
Geek Rank is :1*
Geek Rank is :2*
Geek Rank is :3*
Geek Rank is :4*
Geek Rank is :5*
Geek Rank is :6*
Geek Rank is :7*
Geek Rank is :8*
Geek Rank is :9*
Geek Rank is :10*
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.