code-rag-bench/online-tutorials huggingface dataset:
Collections.UserString in Python

31 Aug, 2021
Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example:
Python3
# Python program to demonstrate# string # Creating a String # with single QuotesString1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ")print(String1)   # Creating a String# with double QuotesString1 = "I'm a Geek"print("\nString with the use of Double Quotes: ")print(String1)
Output:
String with the use of Single Quotes: 
Welcome to the Geeks World

String with the use of Double Quotes: 
I'm a Geek
Note: For more information, refer to Python String 
Python supports a String like a container called UserString present in the collections module. This class acts as a wrapper class around the string objects. This class is useful when one wants to create a string of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the string. This class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.Syntax: 
collections.UserString(seq)
Example 1:
Python3
# Python program to demonstrate# userstring  from collections import UserString  d = 12344 # Creating an UserDictuserS = UserString(d)print(userS.data)  # Creating an empty UserDictuserS = UserString("")print(userS.data)
Output: 
12344
Example 2:
Python3
# Python program to demonstrate# userstring   from collections import UserString   # Creating a Mutable Stringclass Mystring(UserString):         # Function to append to    # string    def append(self, s):        self.data += s             # Function to remove from    # string    def remove(self, s):        self.data = self.data.replace(s, "")     # Driver's codes1 = Mystring("Geeks")print("Original String:", s1.data) # Appending to strings1.append("s")print("String After Appending:", s1.data) # Removing from strings1.remove("e")print("String after Removing:", s1.data)
Output:
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
varshagumber28
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | Access-Control-Expose-Headers

19 Nov, 2019
The HTTP Access-Control-Expose-Headers header is a response header that is used to expose the headers that have been mentioned in it. By default 6 response headers are already exposed which are known as CORS-safelisted response headers. They are namely- Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma.
Syntax:
Access-Control-Expose-Headers: <header-name>
Access-Control-Expose-Headers: *
Note: Multiple headers can be used.
Directives:
<header-name>: It specifies the header that needs to be exposed other than the safe listed headers specified by CORS. If there are multiple headers in use we separate them using commas.
*(wildcard): It is used for requests without HTTP cookies or HTTP authentication information. It should be noted that the Authorization header cannot be wildcarded and needs explicit mentioning.
Examples:
In this example, the Accept-Language HTTP header is exposed. It can be noted that it is a non-CORS safe listed header.Access-Control-Expose-Headers: Accept-Language
Access-Control-Expose-Headers: Accept-Language
In this example, the Authorization HTTP header was needed to be mentioned explicitly as it can’t be wild-carded normally.Access-Control-Expose-Headers: *, Authorization
Access-Control-Expose-Headers: *, Authorization
Supported Browsers: The browsers are compatible with HTTP header Access-Control-Expose-Headers are listed below:
Google Chrome 4.0
Internet Explorer 12.0
Opera 12.0
Firefox 3.5
Safari 4.0
Note: *(wildcard) directive may not supported on Safari and Internet Explorer.
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Integer count in Mixed List

07 Feb, 2022
The lists in python can handle different type of data types in it. The manipulation of such lists is complicated. Sometimes we have a problem in which we need to find the count of integer values in which the list can contain string as a data type i.e heterogeneous. Let’s discuss certain ways in which this can be performed.Method #1 : Using list comprehension + len() + isinstance() This particular problem can be solved by filtering our search of len using the isinstance method, we can filter out the integer value and then can use len function to get required length value. 
Python3
# Python3 code to demonstrate# Integer count in Mixed List# using list comprehension + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension + len() + isinstance()# Integer count in Mixed Listres = len(list(i for i in test_list if isinstance(i, int))) # printing resultprint ("The length of integers in list is : " + str(res))
The original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
 
 Method #2 : Using lambda + map() + len() + isinstance() The above problem can also be solved using the lambda function as a map() in the len() along with the isinstance method which performs the task of checking for integer values. 
Python3
# Python3 code to demonstrate# Integer count in Mixed List# using lambda + map() + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint ("The original list is : " + str(test_list)) # using lambda + map() + len() + isinstance()# Integer count in Mixed Listtemp = list(map(lambda i: isinstance(i, int), test_list))res = len([ele for ele in temp if ele]) # printing resultprint ("The length of integers in list is : " + str(res))
The original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
 
saurabh1990aror
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
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
How to Get a Comma Separated String From an Array in C#?

17 Jan, 2022
Given an array, now our task is to get a comma-separated string from the given array. So we can do this task using String.Join() method. This method concatenates the items of an array with the help of a comma separator between each item of the array.
Syntax:
String.Join(",", array_name)
Where array_name is the input array.
Example:
Input: {"sireesha", "priyank", "ojaswi", "gnanesh"}
Output: sireesha,priyank,ojaswi,gnanesh

Input: {"sireesha", "priyank"}
Output: sireesha,priyank
Approach 1:
Declare an array of strings.
Use the string join() function to get the comma separated strings.
String.Join(",", names)
Display the final result.
Example:
C#
// C# program to display the comma separated// string from an arrayusing System; class GFG{ public static void Main(){         // Creating an array of string elements    String[] names = { "sireesha", "priyank",                       "ojaswi", "gnanesh" };                            // Join the elements separated by comma    // Using Join() method    var str1 = String.Join(",", names);         // Display the final string    Console.WriteLine(str1);}}
 Output:
sireesha,priyank,ojaswi,gnanesh
Approach 2:
We can also find the command-separated string from the object array.
Create a class named MyEmployee with First_Name and Last_Name methods.
Declare object array of MyEmployee in the main method.
Use string join() function to get the comma separated strings.
String.Join(",", e.Select(m => m.First_Name));
Here, we only join the first name so we use the select method to select the First_Name of the employees.
Display the final result.
Example 2:
C#
// C# program to display the comma separated// string from an arrayusing System;using System.Linq; // MyEmployee classclass MyEmployee{    public string First_Name { get; set; }    public string Last_Name { get; set; }} class GFG{ public static void Main(){         // Creating object array of MyEmployee    MyEmployee[] e = {        new MyEmployee(){ First_Name = "Sumi", Last_Name = "Goyal" },        new MyEmployee(){ First_Name = "Mohan", Last_Name = "Priya" },        new MyEmployee(){ First_Name = "Sumit", Last_Name = "Singh" }    };         // Join the elements separated by comma    // Using Join() method    var res = String.Join(",", e.Select(m => m.First_Name));         // Display the final result    Console.WriteLine("Final String:" + res);}}
Output:
Final String:Sumi,Mohan,Sumit
saurabh1990aror
CSharp-Arrays-Programs
CSharp-Strings-Programs
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Printing list vertically

22 Jan, 2019
Printing the list has been dealt many times. But sometimes we need a different format to get the output of list. This also has application in getting a transpose of matrix. Printing list vertically also has application in web development. Lets discuss certain ways in which this task can be achieved.
Method #1 : Using Naive MethodThe naive method can be used to print the list vertically vis. using the loops and printing each index element of each list successively will help us achieve this task.
# Python3 code to demonstrate # Vertical list print # using naive method   # initializing list  test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]]  # printing original listprint ("The original list is : " + str(test_list))  # using naive method  # to print list verticallyfor i in range(len(test_list)):    for x in test_list:        print(x[i], end =' ')    print()
Output :
The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]
1 4 8 
4 6 3 
5 8 10 

Method #2 : Using zip()Using zip function, we map the elements at respective index to one other and after that print each of them. This performs the task of vertical printing.
# Python3 code to demonstrate # Vertical list print # using zip()  # initializing list  test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]]  # printing original listprint ("The original list is : " + str(test_list))  # using zip() # to print list verticallyfor x, y, z in zip(*test_list):    print(x, y, z)
Output :
The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]
1 4 8
4 6 3
5 8 10

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useParams Hook

17 Mar, 2021
In our React app sometimes we want to access the parameters of the current route in this case useParams hook comes into action. The react-router-dom package has useParams hooks that let you access the parameters of the current route.
Syntax:
useParams();
Creating React Application and Installing required modules:
Step 1: Create a React application using the following command.npx create-react-app useparams_react
Step 1: Create a React application using the following command.
npx create-react-app useparams_react
Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.cd useparams_react
Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.
cd useparams_react
Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.npm install --save react-router-dom react-dom
Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.
npm install --save react-router-dom react-dom
Project structure:
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";  import {  BrowserRouter as Router,  Switch,  Route,  useParams,} from "react-router-dom";  function BlogPost() {  let { id } = useParams();  return <div style={{ fontSize: "50px" }}>           Now showing post {id}         </div>;}  function Home() {  return <h3>home page </h3>;}  function App() {  return (    <Router>      <Switch>        <Route path="/page/:id">          <BlogPost />        </Route>        <Route path="/">          <Home />        </Route>      </Switch>    </Router>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. You can see what you have passed in the URL as “: id” is displayed on the screen. In this way, you can access the parameters of the current route’s URL.
React-Hooks
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
How to pass data from one component to other component in ReactJS ?
ReactJS setState()
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
C Quiz - 113 - GeeksforGeeks

16 Feb, 2016
 int A[100][100];
 int main()
 {
    for(int i=1; i < 100 ; i++)
        for(int j=1; j < 100;j++)
            A[i][j] = (i/j)*(j/i);
   return 0;
 }


Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
C++ Inheritance Quiz - GeeksQuiz

01 Jun, 2021
Base1's destructor
Base2's destructor
Derived's destructor
Derived's destructor
Base2's destructor
Base1's destructor

Derived's destructor
#include<iostream>
using namespace std;
 
class base {
  int arr[10];     
};
 
class b1: virtual public base { };
 
class b2: virtual public base { };
 
class derived: public b1, public b2 {};
 
int main(void)
{ 
  cout << sizeof(derived);
  return 0;
} 
This is Derived class
This is Base class
This is Base class
This is Derived class
This is Base class
This is Base class
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
Epam Interview Experience for Junior Software Engineer
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Construct a DFA that Start With aa or bb
Python Data Structures and Algorithms
Python - Maximum Consecutive Substring Occurrence - GeeksforGeeks

10 May, 2020
Sometimes, while working with python, we can have a problem in which we need to check for substrings occurring in consecutive repetition. This can have application in data domains. Lets discuss a way in which this task can be performed.
Method : Using max() + re.findall()The combination of above methods can be used to perform this task. In this, we extract the substrings repetitions using using findall() and extract the maximum of them using max().
# Python3 code to demonstrate working of # Maximum Consecutive Substring  Occurrence# Using max() + re.findall()import re  # initializing stringtest_str = 'geeksgeeks are geeks for all geeksgeeksgeeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing subs sub_str = 'geeks'  # Maximum Consecutive Substring  Occurrence# Using max() + re.findall()res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len)  # printing result print("The maximum run of Substring : " + res) 
The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
The maximum run of Substring : geeksgeeksgeeks

 
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Plotting cross-spectral density in Python using Matplotlib - GeeksforGeeks

24 Jan, 2022
Matplotlib is a comprehensive library consisting of modules that are used for Data Visualization just like MATLAB. Pyplot is a further module which makes functions and methods executable. 
The cross-spectral density compares two signals, each from different source taking into account both amplitude and phase difference of the two signals. In Python, this function is carried out using the Pyplot module’s method matplotlib.pyplot.csd()Syntax: 
matplotlib.pyplot.csd(x, y)
Here, x and y are 1-D arrays or a sequence having the data.Let us take two signals and plot their CSD: 
Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function.Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle.Taking these two signals, we plot their cross spectral density.
Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function.
Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle.
Taking these two signals, we plot their cross spectral density.
Example 1: Plotting Signal 1  
python3
import numpy as npimport matplotlib.pyplot as plt  time = np.arange(0, 1, 0.1)amp = np.sin(time) plt.plot(time, amp)plt.title("Signal 1") plt.show()
Output: 
Example 2: Plotting Signal 2 
Python3
import numpy as npimport matplotlib.pyplot as plt  t = np.arange(5, 10, 0.25)ampl = np.sin(t) plt.plot(t, ampl)plt.title("Signal 2") plt.show()
Output: 
Example 3: Plotting the cross-spectral density 
Python3
import numpy as npimport matplotlib.pyplot as plt  # Signal 1time = np.arange(0, 1, 0.1)amp = np.sin(time) # Signal 2t = np.arange(5, 10, 0.25)ampl = np.sin(t) # Cross-spectral densityplt.csd(amp, ampl) plt.show()
Output: 
Example 4: Using discrete lists or arrays  
Python3
import numpy as npimport matplotlib.pyplot as plt  a = np.arange(5)b = np.arange(10, 30) plt.csd(a, b)plt.show()
Output: 
 
varshagumber28
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
How to combine Groupby and Multiple Aggregate Functions in Pandas? - GeeksforGeeks

10 May, 2020
Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library.
Pandas dataframe.groupby() function is used to split the data in dataframe into groups based on a given condition.
Example 1:
# import libraryimport pandas as pd  # import csv filedf = pd.read_csv("https://bit.ly/drinksbycountry")  df.head()
Output:
Example 2:
# Find the average of each continent# by grouping the data  # based on the "continent".df.groupby(["continent"]).mean()
Output:
Pandas dataframe.agg() function is used to do one or more operations on data based on specified axis
Example:
# here sum, minimum and maximum of column # beer_servings is calculataddf.beer_servings.agg(["sum", "min", "max"])
Output:
Using These two functions together: We can find multiple aggregation functions of a particular column grouped by another column.
Example:
# find an aggregation of column "beer_servings"# by grouping the "continent" column.df.groupby(df["continent"]).beer_servings.agg(["min",                                               "max",                                               "sum",                                               "count",                                               "mean"])
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Remove the whitespaces from a string using replace() in JavaScript?

Let’s say the following is our string with whitespace −
var fullName=" John Smith ";
Use replace() and set Regex in it to remove whitespaces.
function removeSpacesAtTheBeginningAndTheEnd(name) {
   return name.toString().replace(/^\s+|\s+$/g,'');
}
var fullName=" John Smith ";
var
valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName)
console.log(valueAfterRemovingSpace);
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo208.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo208.js
John Smith
_Generic keyword in C - GeeksforGeeks

03 Jan, 2019
A major drawback of Macro in C/C++ is that the arguments are strongly typed checked i.e. a macro can operate on different types of variables(like char, int ,double,..) without type checking.
// C program to illustrate macro function.#include<stdio.h>#define INC(P) ++Pint main(){    char *p = "Geeks";    int x = 10;    printf("%s  ", INC(p));    printf("%d", INC(x));    return 0;}
Output:
eeks 11

Therefore we avoid to use Macro. But after the implementation of C11 standard in C programming, we can use Macro with the help of a new keyword i.e. “_Generic”. We can define MACRO for the different types of data types. For example, the following macro INC(x) translates to INCl(x), INC(x) or INCf(x) depending on the type of x:
#define INC(x) _Generic((x), long double: INCl, \
                              default: INC, \
                              float: INCf)(x)

Example:-
// C program to illustrate macro function.#include <stdio.h>int main(void){    // _Generic keyword acts as a switch that chooses     // operation based on data type of argument.    printf("%d\n", _Generic( 1.0L, float:1, double:2,                             long double:3, default:0));    printf("%d\n", _Generic( 1L, float:1, double:2,                             long double:3, default:0));    printf("%d\n", _Generic( 1.0L, float:1, double:2,                                        long double:3));    return 0;}
Output:Note: If you are running C11 compiler then the below mentioned output will be come.
3
0
3

// C program to illustrate macro function.#include <stdio.h>#define geeks(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0)int main(void){    // char returns ASCII value which is int type.     printf("%d\n", geeks('A'));        // Here A is a string.    printf("%d",geeks("A"));          return 0;}
Output:
2
0

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AJ04
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Converting Strings to Numbers in C/C++
Ruby | Array max() function

06 Dec, 2019
Array#max() : max() is a Array class method which returns the maximum value in this array.
Syntax: Array.max()
Parameter: Array
Return: the maximum value in this array.
Example #1 :
# Ruby code for max() method  # declaring arraya = %w[for geeks]    # max method exampleputs "max() method form : #{a.max()}\n\n"  puts "max() method form : #{a.max(2)}\n\n"
Output :
max() method form : geeks

max() method form : ["geeks", "for"]


Example #2 :
# Ruby code for max() method  # declaring arraya = %w[hi I can code for geeks]    # max method exampleputs "max() method form : #{a.max(4)}\n\n"  puts "max() method form : #{a.max(1)}\n\n"
Output :
max() method form : ["hi", "geeks", "for", "code"]

max() method form : ["hi"]

Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Data Types
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | unless Statement and unless Modifier
PyQt5 QListWidget – Setting Current Item

01 Aug, 2020
In this article we will see how we can set the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected.
In order to do this we will use setCurrentItem method with the list widget object.
Syntax : list_widget.setCurrentItem(item)
Argument : It takes QListWidgetItem as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting current item        list_widget.setCurrentItem(item2)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 300, 80)          # making label multi line        label.setWordWrap(True)        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
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
Set equals() method in Java with Examples

09 Aug, 2019
The equals() method of java.util.Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.
Syntax:
public boolean equals(Object o)
Parameters: This method takes the object o as a parameter to be compared for equality with this set.
Returns Value: This method returns true if the specified object is equal to this set.
Below are the examples to illustrate the equals() method.
Example 1:
// Java program to demonstrate equals()// method of Set  import java.util.*;  public class GFG {    public static void main(String[] argv)    {          // Creating object of Set        Set<String> arrset1 = new HashSet<String>();          // Populating arrset1        arrset1.add("A");        arrset1.add("B");        arrset1.add("C");        arrset1.add("D");        arrset1.add("E");          // print arrset1        System.out.println("First Set: "                           + arrset1);          // Creating another object of Set        Set<String> arrset2 = new HashSet<String>();          // Populating arrset2        arrset2.add("A");        arrset2.add("B");        arrset2.add("C");        arrset2.add("D");        arrset2.add("E");          // print arrset2        System.out.println("Second Set: "                           + arrset2);          // comparing first Set to another        // using equals() method        boolean value = arrset1.equals(arrset2);          // print the value        System.out.println("Are both set equal? "                           + value);    }}
First Set: [A, B, C, D, E]
Second Set: [A, B, C, D, E]
Are both set equal? true

Example 2:
// Java program to demonstrate equals()// method of Set  import java.util.*;  public class GFG1 {    public static void main(String[] argv)    {          // Creating object of Set        Set<Integer> arrset1 = new HashSet<Integer>();          // Populating arrset1        arrset1.add(10);        arrset1.add(20);        arrset1.add(30);        arrset1.add(40);        arrset1.add(50);          // print arrset1        System.out.println("First Set: " + arrset1);          // Creating another object of Set        Set<Integer> arrset2 = new HashSet<Integer>();          // Populating arrset2        arrset2.add(10);        arrset2.add(20);        arrset2.add(30);          // print arrset2        System.out.println("Second Set: " + arrset2);          // comparing first Set to another        // using equals() method        boolean value = arrset1.equals(arrset2);          // print the value        System.out.println("Are both set equal? "                           + value);    }}
First Set: [50, 20, 40, 10, 30]
Second Set: [20, 10, 30]
Are both set equal? false

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#equals(java.lang.Object)
sdkbnv
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java program to read all mobile numbers present in given file

24 Mar, 2018
Given the input text file, read all mobile numbers present and write to some output file.
Suppose we have a file names as input.txt and in that input file we have some Mobile Number which are mixed with some other data. Our task is to read the input file line by line and if we find any Number in that line we have to write that Mobile Number to an another file, which is output.txt file.
Example :
Mobile Number validation criteria :
The first digit should contain number between 7 to 9.
The rest 9 digit can contain any number between 0 to 9.
The mobile number can have 11 digits also by including 0at the starting.
The mobile number can be of 12 digits also by including 91at the starting
The number which satisfies the above criteria, is a valid mobile Number.
Approach : We use Regular expression, first we have to form a regular expression for Mobile Number. Whenever any Number in the input.txt file matches with that regular expression which we form for Mobile Number, that matched number will be written to output.txt file.
Below is Java implementation is above approach :
// Java program to read all mobile numbers// present in given fileimport java.util.regex.*;import java.io.*;  class MobileNumberExtraction {    public static void main(String[] args) throws IOException    {        // Write Mobile Numbers to output.txt file        PrintWriter pw = new PrintWriter("output.txt");          // Regular expression for mobile number        Pattern p = Pattern.compile("(0/91)?[7-9][0-9]{9}");          // BufferedReader for reading from input.txt file        BufferedReader br = new BufferedReader                                (new FileReader("input.txt"));        String line = br.readLine();                  while (line != null)         {            Matcher m = p.matcher(line);              while (m.find())             {                // Write the mobile number to output.txt file                pw.println(m.group());            }              line = br.readLine();        }        pw.flush();    }}
Output :
7873923408
7205435005

The above output is for this input.txt file :
Abstract classes may have some executable methods
and 7873923408 methods left unimplemented. Interfaces 
contain no implementation code. An abstract
class can have non abstract 7205435005 methods. 
All methods 1234 of an interface are abstract.
java-file-handling
Java-I/O
java-regular-expression
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Python | Decimal sqrt() method

05 Sep, 2019
Decimal#sqrt() : sqrt() is a Decimal class method which returns the Square root of a non-negative number to context precision.
Syntax: Decimal.sqrt()
Parameter: Decimal values
Return: the Square root of a non-negative number to context precision.
Code #1 : Example for sqrt() method
# Python Program explaining # sqrt() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(1)  b = Decimal(2)  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.sqrt() methodprint ("\n\nDecimal a with sqrt() method : ", a.sqrt())  print ("Decimal b with sqrt() method : ", b.sqrt())
Output :
Decimal value a :  1
Decimal value b :  2


Decimal a with sqrt() method :  1
Decimal b with sqrt() method :  1.414213562373095048801688724


Code #2 : Example for sqrt() method
# Python Program explaining # sqrt() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(300)  b = Decimal(15)    # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.sqrt() methodprint ("\n\nDecimal a with sqrt() method : ", a.sqrt())  print ("Decimal b with sqrt() method : ", b.sqrt())
Output :
Decimal value a :  300
Decimal value b :  15


Decimal a with sqrt() method :  17.32050807568877293527446342
Decimal b with sqrt() method :  3.872983346207416885179265400


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
Scala List isEmpty Operation with example

13 Aug, 2019
The isEmpty operation is utilized to check if the stated list is empty or not.Syntax:
m1.isEmpty
Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false.Example #1:
// Scala program of isEmpty()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(6, 8, 9, 12)                  // Applying isEmpty method        val result = m1.isEmpty                  // Displays output        println(result)          }}
false

Example #2:
// Scala program of isEmpty()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List()                  // Applying isEmpty method        val result = m1.isEmpty                  // Displays output        println(result)          }}
true

Scala
Scala-list
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects
How to send response from server to client using Node.js and Express.js ?

06 Oct, 2021
The following approach covers how to send responses from servers using node and express. Also, we are going to see different ways to send responses from the server to the client.
Prerequisite:
Node js: It is an open-source JavaScript Back-End technology.
Express.js: It is a node.js server framework.
Required Module: Install the express module using the following command:
npm install express
Methods to send response from server to client are:
Using send() function.Using json() function.
Using send() function.
Using json() function.
Example 1: Demonstrating the use of the status() function.
index.js
const express = require('express');const app = express();  app.get('/' , (req,res)=>{   // 200 status code means OK   res.status().send(200); })  // Server setupapp.listen(4000 , ()=>{    console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
Example 2: Sending some particular data to the client then you can use send() function.
index.js
const express = require('express');const app = express();  var computerSciencePortal = "GeeksforGeeks";  app.get('/' , (req,res)=>{   // Server will send GeeksforGeeks as response   res.send(computerSciencePortal); })  // Server setupapp.listen(4000 , ()=>{    console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
Example 3: Sending the JSON response from the server to the client using json() function.
index.js
const express = require('express');const app = express();  // Sample JSON datavar data = {    portal : "GeeksforGeeks",    knowledge : "unlimited",    location : "Noida"  }  app.get('/' , (req,res)=>{   // This will send the JSON data to the client.    res.json(data); })  // Server setupapp.listen(4000 , ()=>{    console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
So, These are the methods that you can use to send responses from server to client using node and express.
Node.js
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Integer byteValue() Method

06 May, 2022
The byteValue() method of Integer class of java.lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.  
The package view is as follows:
--> java.lang Package 
    --> Integer Class
        --> byteValue() Method 
Syntax :
public byte byteValue()
Return Type: Returns the numeric value represented by this object after conversion to byte type.
Note: It is compatible with Java 1.5 and onwards.
Example 1:
Java
// Java program to Illustrate byteValue() Method// Of Integer Class // Importing required classimport java.lang.Integer; // Main Classclass GFG {     // Main driver method    public static void main(String args[]) {         // Creating an Integer object and        // passing custom integer input        Integer a = new Integer(34);         // Converting integer number to byte value        // using byteValue() method        byte b = a.byteValue();         // Printing the corresponding byte value        System.out.println(b);    }}
34
Example 2:
Java
// Java Program to Illustrate byteValue() Method// of Integer Class // Importing required classesimport java.lang.*;import java.util.*; // Main Classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating a Byte object        Byte b = new Byte("01");         // Converting Byte to byte primitive        // using byteValue() method        Byte bp = b.byteValue();         // Display statement        System.out.println("Byte object : " + b);         // Primitive byte value of custom Byte passed above        String str            = "Primitive byte value of Byte object : " + bp;         // Printing byte primitive value        System.out.println(str);    }}
Byte object : 1
Primitive byte value of Byte object : 1
solankimayank
rkbhola5
Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Test Driver

Test Drivers are used during Bottom-up integration testing in order to simulate the behaviour of the upper level modules that are not yet integrated. Test Drivers are the modules that act as temporary replacement for a calling module and give the same output as that of the actual product.
Drivers are also used when the software needs to interact with an external system and are usually complex than stubs.
The above diagrams clearly states that Modules 4, 5, 6 and 7 are unavailable for integration, whereas, above modules are still under development that cannot be integrated at this point of time. Hence, drivers are used to test the modules. The order of Integration will be:
4,2
5,2
6,3
7,3
2,1
3,1
+ Firstly, the integration between the modules 4,5,6 and 7
+ Test the integration between the module 4 and 5 with Driver 2
+ Test the integration between the module 6 and 7 with Driver 3
Default Constructors in C++

Constructors are functions of a class that are executed when new objects of the class are created. The constructors have the same name as the class and no return type, not even void. They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors.
Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0.
A program that demonstrates default constructors is given as follows.
 Live Demo
#include <iostream>
using namespace std;
class DemoDC {
   private:
   int num1, num2 ;
   public:
   DemoDC() {
      num1 = 10;
      num2 = 20;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
int main() {
   DemoDC obj;
   obj.display();
   return 0;
}
num1 = 10
num2 = 20
In the above program, the class DemoDC contains a default constructor that initialises num1 and num2 as 10 and 20. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.
class DemoDC {
   private:
   int num1, num2
   public:
   DemoDC() {
      num1 = 10;
      num2 = 20;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
};
The function main() contains the object definition for an object of class type DemoDC. Then the function display() is called. This is shown below.
DemoDC obj;
obj.display();
How to change the color of bars in histogram for values that are greater than 0 or less than 0 in R?

Although, the histogram represents the distribution of a complete set of values but we might want to visualize that histogram based on the division of some threshold value. For example, we might want to visualize the histogram with different bars that have values greater than 1 or less than 1. This will help us to understand the distribution of the values in whole data set that lies above or below certain value. For this purpose, we can simply use hist function with col argument to change the color of the values that are greater than or less than a fixed value.
x<-rnorm(1000000)
hist(x,col=x>0)
hist(x,col=x<0)
Explain if-else statement in C language

If-else statement takes care of true as well as false conditions. ‘true block’ is executed, when the condition is true and ‘false block’ (or) ‘else block’ is executed, when the condition is false.
Refer the syntax given below −
if (condition){
   True block statement(s)
}else{
   False block statement(s)
}
In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block.
In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block.
If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block.
If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block.
Following is the C program to execute If and If Else conditional operators −
 Live Demo
#include<stdio.h>
void main (){
   int a=4;
   printf("Enter the value of a: \n");
   scanf("%d",&a);
   if(a%2==1){
      printf("a is odd number \n");
   }else{
      printf("a is even number");
   }
}
You will see the following output −
Run 1: Enter the value of a: 26
a is even number
Run 2: Enter the value of a: 53
a is odd number