code-rag-bench/online-tutorials huggingface dataset:
Exercise v1.3

Create a variable called carName, assign the value "Volvo" to it, and display it.
Hint: Use the var keyword to create a variable.
<!DOCTYPE html>
<html>
<body>
​
<p id="demo">Display the result here.</p> 
​
<script>
// Create the variable here
</script>
​
</body>
</html>
​
xxxxxxxxxx
<!DOCTYPE html>
<html>
<body>
​
<p id="demo">Display the result here.</p> 
​
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
Optional property in a C# class

A property is optional if it is possible and valid for it to have null. A property whose CLR type cannot have null cannot be configured optional.
An example optional attribute usage −
[AttributeUsage(AttributeTargets.Property,
Inherited = false,
AllowMultiple = false)]
internal sealed class OptionalAttribute : Attribute { }

public class Employee {
   public string EmpName { get; set; }

   [Optional]
   public string AlternativeName { get; set; }
}
How to check multiple columns for a single value in MySQL?

You can check multiple columns for one value with the help of IN operator. The syntax is as follows −
select *from yourTableName where value IN(yourColumnName1, yourColumnName2,......N);
To understand the above concept, let us create a table with some columns. The query to create a table is as follows −
mysql> create table OneValueFromAllColumns
   −> (
   −> StudentId int,
   −> StudentFirstname varchar(200),
   −> StudentLastname varchar(200),
   −> StudentAge int
   −> );
Query OK, 0 rows affected (1.41 sec)
Insert some records in the table with the help of select statement. The query is as follows −
mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22);
Query OK, 1 row affected (0.18 sec)

mysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19);
Query OK, 1 row affected (0.16 sec)

mysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21);
Query OK, 1 row affected (0.22 sec)
Display all records which we have inserted above. The query to display all records from the table is as follows −
mysql> select *from OneValueFromAllColumns;
The following is the output −
+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstname | StudentLastname | StudentAge |
+-----------+------------------+-----------------+------------+
|          1 | John            | Smith           |         23 |
|          2 | Carol           | Taylor          |         22 |
|          3 | Maria           | Garcia          |         19 |
|          4 | Bob             | Wilson          |         21 |
+-----------+------------------+-----------------+------------+
4 rows in set (0.00 sec)
Here is the query to check multiple columns for single value. We are checking for the value “Taylor’ in multiple columns i.e. StudentId, StudentFirstname, StudentLastname and StudentAge.
The query is as follows −
mysql> select *from OneValueFromAllColumns where 'Taylor' IN(StudentId,StudentFirstname,StudentLastname,StudentAge);
The following is the output that displays the record with the value “Taylor” −
+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstname | StudentLastname | StudentAge |
+-----------+------------------+-----------------+------------+
|         2 | Carol            | Taylor          | 22         |
+-----------+------------------+-----------------+------------+
1 row in set, 4 warnings (0.03 sec)
How do you create a Tkinter GUI stop button to break an infinite loop?

Tkinter is a Python library which is used to create GUI-based application. Let us suppose that we have to create a functional application in which a particular function is defined in a loop. The recursive function will display some text in a Label widget for infinite times.
To stop this recursive function, we can define a function which changes the condition whenever a button is clicked. The condition can be changed by declaring a global variable which can be either True or False.
# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win= Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Define a function to print something inside infinite loop
run= True

def print_hello():
   if run:
      Label(win, text="Hello World", font= ('Helvetica 10 bold')).pack()
   # After 1 sec call the print_hello() again
   win.after(1000, print_hello)
def start():
   global run
   run= True

def stop():
   global run
   run= False

# Create buttons to trigger the starting and ending of the loop
start= Button(win, text= "Start", command= start)
start.pack(padx= 10)
stop= Button(win, text= "Stop", command= stop)
stop.pack(padx= 15)

# Call the print_hello() function after 1 sec.
win.after(1000, print_hello)
win.mainloop()
Now, whenever we click the "Stop" button, it will stop calling the function.
Matplotlib.axes.Axes.set_position() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_position() function in axes module of matplotlib library is used to set the axes position.
Syntax: Axes.set_position(self)
Parameters: This method accepts the following parameters.
pos : This parameter is the new position of the in Figure coordinates.
which : This parameter is used to determines which position variables to change.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_position() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17,     16, 18, 20]y2 = [10, 11, 12, 13, 8, 10,       12, 14, 18, 19]  fig, ax = plt.subplots()  ax.plot(x, y, "go-", label ='Line 1', )ax.plot(x, y2, "o-", label ='Line 2')  chartBox = ax.get_position()ax.set_position([chartBox.x0, chartBox.y0,                 chartBox.width,                 chartBox.height * 0.6])  ax.legend(loc ='upper center',          bbox_to_anchor =(0.5, 1.45),          shadow = True, ncol = 1)   fig.suptitle('matplotlib.axes.Axes.set_position()\function Example', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm   Z = np.random.rand(6, 30)   fig, (ax, ax1) = plt.subplots(1, 2)   ax.pcolor(Z)ax1.pcolor(Z)  chartBox = ax1.get_position()ax1.set_position([chartBox.x0,                   chartBox.y0,                  chartBox.width,                  chartBox.height * 0.6])  ax.set_title("Original Window")ax1.set_title("Modified  Window")   fig.suptitle('matplotlib.axes.Axes.set_position()\function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | Pandas dataframe.count()

20 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.count() is used to count the no. of non-NA/null observations across the given axis. It works with non-floating type data as well.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiselevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFramenumeric_only : Include only float, int, boolean data
Returns: count : Series (or DataFrame if level specified)
Example #1: Use count() function to find the number of non-NA/null value across the row axis.
# importing pandas as pdimport pandas as pd  # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, None, 5, 3],                    "B":[-1, None, 6, 4, None, 3],                   "C:["sam", "haris", "alex", np.nan, "peter", "nathan"]})  # Printing the dataframedf
Now find the count of non-NA value across the row axis
# axis = 0 indicates rowdf.count(axis = 0)
Output : Example #2: Use count() function to find the number of non-NA/null value across the column.
# importing pandas as pdimport pandas as pd  # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, None, 5, 3],                   "B":[-1, None, 6, 4, None, 3],                    "C:["sam", "haris", "alex", np.nan, "peter", "nathan"]})  # Find count of non-NA across the columnsdf.count(axis = 1)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
java.net.URLConnection Class in Java

26 Aug, 2021
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL class. Secondly, with a URLConnection we can check the header sent by the server and respond accordingly, we can configure header fields used in client requests. We can also download binary files by using URLConnection.
Let us do discuss out major methods of this class
Implementation:
Example
Java
// Java Program to demonstrate URLConnection class // Importing input output classesimport java.io.*;// Importing java.net package// consisting of all network classesimport java.net.*; // Main class// URLConnectionExamplepublic class GFG {     // Main driver method    public static void main(String[] args) throws Exception    {        // Try block to check for exceptions        try {             // Creating an object of URL class             // Custom input URL is passed as an argument            URL u = new URL("www.geeksforgeeks.com");             // Creating an object of URLConnection class to            // communicate between application and URL            URLConnection urlconnect = u.openConnection();             // Creating an object of InputStream class            // for our application streams to be read            InputStream stream                = urlconnect.getInputStream();             // Declaring an integer variable            int i;             // Till the time URL is being read            while ((i = stream.read()) != -1) {                 // Continue printing the stream                System.out.print((char)i);            }        }         // Catch block to handle the exception        catch (Exception e) {             // Print the exception on the console            System.out.println(e);        }    }}
java.net.MalformedURLException: no protocol: www.geeksforgeeks.com
 
anikaseth98
adnanirshad158
sooda367
Java-Classes
Java-net-package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Decimal conjugate() method

05 Sep, 2019
Decimal#conjugate() : conjugate() is a Decimal class method which returns the self, this method is only to comply with the Decimal Specification
Syntax: 
Decimal.conjugate()

Parameter: 
Decimal values

Return: 
the self Decimal value


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


Decimal a with conjugate() method :  -1
Decimal b with conjugate() method :  0.142857


Code #2 : Example for conjugate() method
# Python Program explaining # conjugate() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.conjugate() methodprint ("\n\nDecimal a with conjugate() method : ", a.conjugate())  print ("Decimal b with conjugate() method : ", b.conjugate())
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with conjugate() method :  -3.14
Decimal b with conjugate() method :  3.21E+7

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
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 - Pandas dataframe.append()
Python | datetime.timedelta() function
PyQt5 – Change size of Push Button

22 Apr, 2020
In this article we will see how to change the size of push button. There are basically two ways in order to change the size of button i.e using resize method and setGeometry method.The main difference between them is resize method will only resize the push button. on the other hand setGeometry method will change the size and also set the position of the push button.
Method #1:
Syntax : button.setGeometry(left, top, width, height)
Argument : It takes four integer as argument, first two are the position and second two are the size.
Action performed : It sets the position and the size of push button.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 40)            # adding action to a button        button.clicked.connect(self.clickme)        # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output : 
Method #2:
Syntax : button.resize(width, height)
Argument : It takes two integer as argument i.e width and height.
Action performed : It sets the size of push button
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting size of button        button.resize(150, 50)            # adding action to a button        button.clicked.connect(self.clickme)        # action method    def clickme(self):          # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
std::advance in C++

26 Apr, 2022
std::advance advances the iterator ‘it’ by n element positions. Syntax :
template 
    void advance (InputIterator& it, Distance n);

it : Iterator to be advanced
n : Number of element positions to advance.
This shall only be negative for random-access and bidirectional iterators.

Return type :
None.
Motivation problem : A vector container is given. Task is to print alternate elements. Examples :
Input : 10 40 20 50 80 70
Output : 10 20 80
CPP
// C++ program to illustrate// using std::advance#include <bits/stdc++.h> // Driver codeint main(){    // Vector container    std::vector<int> vec;     // Initialising vector    for (int i = 0; i < 10; i++)        vec.push_back(i * 10);     // Printing the vector elements    for (int i = 0; i < 10; i++) {        std::cout << vec[i] << " ";    }     std::cout << std::endl;     // Declaring the vector iterator    std::vector<int>::iterator it = vec.begin();     // Printing alternate elements    while (it < vec.end()) {        std::cout << *it << " ";        std::advance(it, 2);    }}
Output:
0 10 20 30 40 50 60 70 80 90 
0 20 40 60 80
C++
#include <iostream>#include<bits/stdc++.h>using namespace std; int main() {     vector<int >vect(10);  //insert the ten element in the vector    for(int i=1;i<=10;i++)    {      vect[i-1]=i;    }    //iterator pointing to first element.    vector<int >::iterator it=vect.begin();        for(int i=1;i<=10;i++)     {       cout<<*it<<" ";       it++;             }   vector<int >::iterator it1=vect.begin();  //here it is pointing to the 3rd element.      advance(it1,2);//here second argument is the index base.       cout<<endl;     cout<<*it1;  //print it1 pointing to the 3rd position.    return 0;}/* This code is contributed by Sameer Hake/*
1 2 3 4 5 6 7 8 9 10 
3
This article is contributed by Rohit Thapliyal , Sameer Hake. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
sameerhakeentc2019
cpp-iterator
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
Addition in Nested Tuples in Python

When it is required to perform addition in nested tuples, the 'zip' method and the generator expression can be used.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = ((7, 8), (3, 4), (3, 2))
my_tuple_2 = ((9, 6), (8, 2), (1, 4))

print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)

my_result = tuple(tuple(a + b for a, b in zip(tup_1, tup_2))
   for tup_1, tup_2 in zip(my_tuple_1, my_tuple_2))
print("The tuple after summation is : ")
print(my_result)
The first tuple is :
((7, 8), (3, 4), (3, 2))
The second tuple is :
((9, 6), (8, 2), (1, 4))
The tuple after summation is :
((16, 14), (11, 6), (4, 6))
Two nested tuples/tuple of tuples are defined and are displayed on the console.
They are zipped, and iterated over, and every element in each of the nested tuple is added, and a new tuple of tuples is created.
This result is assigned to a variable.
It is displayed as output on the console.
Dart Programming - List.single Method

Checks if the list has only one element and returns it.
List.single 

void main() { 
   var lst = new List(); 
   lst.add(12);
   print("The list has only one element: ${lst.single}"); 
}  
It will produce the following output −
The list values in reverse order: (13, 12) 

It will produce the following output −
The list has only one element: 12 

This property throws an exception if the List has more than one element in it. The following example illustrates the same −
void main() { 
   var lst = new List(); 
   lst.add(12); 
   lst.add(10); 
   print(lst.single); 
}
If the list has more than one element, then the same code will throw the following exception −
Unhandled exception: 
Bad state: Too many elements 
#0 List.single (dart:core-patch/growable_array.dart:234) 
#1 main (file:///D:/Demos/Boolean.dart:6:13) 
#2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261) 
#3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to exit a Kivy application using a button ? - GeeksforGeeks

15 Mar, 2021
Kivy is a graphical user interface open-source Python library that allows you to develop multi-platform applications on Windows, macOS, Android, iOS, Linux, and Raspberry-Pi. In addition to the regular mouse and keyboard inputs, it also supports multitouch events. The applications made using Kivy will similar across all the platforms, but it also means that the application’s feel or look will differ from any native application.
In this article, we will develop a GUI window using kivy framework of python, and we will add a single button on the window which will close kivy application on click
Import kivy button
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the implementation.
Python3
# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import Appfrom kivy.core.window import Window  # importing builder from kivyfrom kivy.lang import Builder    # this is the main class which # will render the whole applicationclass uiApp(App):      # method which will render our application    def close_application(self):        # closing application        App.get_running_app().stop()        # removing window        Window.close()      def build(self):        return Builder.load_string("""  #:import C kivy.utils.get_color_from_hexButton:     # text which will appear on first button     text:"Close App"   on_release: app.close_application()                                        """)    # running the applicationuiApp().run()
Output:
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Difference between Selection and Projection in DBMS - GeeksforGeeks

12 Jun, 2020
Prerequisite – Relational Algebra1. Selection :This operation chooses the subset of tuples from the relation that satisfies the given condition mentioned in the syntax of selection.
Notation –
σc (R)
Here, ‘c’ is selection condition and ‘σ (sigma)’ is used to denote Select Operator.
2. Projection :This operation selects certain required attributes, while discarding other attributes.
Notation –
πA (R)
where ‘A’ is the attribute list, it is the desired set of attributes from the attributes of relation(R),symbol ‘π(pi)’  is used to denote the Project operator,R is generally a relational algebra expression, which results in a relation.
Difference between Selection and Projection in DBMS
DBMS-Relational Algebra
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Seaborn - Histogram

Histograms represent the data distribution by forming bins along the range of the data and then drawing bars to show the number of observations that fall in each bin.
Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets.
Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.distplot(df['petal_length'],kde = False)
plt.show()

Here, kde flag is set to False. As a result, the representation of the kernel estimation plot will be removed and only histogram is plotted.

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    11 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
Pascal - Bit Operators

The Bitwise operators supported by Pascal are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Please note that different implementations of Pascal differ in bitwise operators. Free Pascal, the compiler we used here, however, supports the following bitwise operators −
The following example illustrates the concept −
program beBitwise;
var
a, b, c: integer;

begin
   a := 60;	(* 60 = 0011 1100 *)  
   b := 13;	(* 13 = 0000 1101 *)
   c := 0;           

   c := a and b;       (* 12 = 0000 1100 *)
   writeln('Line 1 - Value of c is  ', c );

   c := a or b;       (* 61 = 0011 1101 *)
   writeln('Line 2 - Value of c is  ', c );

   c := not a;          (* -61 = 1100 0011 *)
   writeln('Line 3 - Value of c is  ', c );

   c := a << 2;     (* 240 = 1111 0000 *)
   writeln('Line 4 - Value of c is  ', c );

   c := a >> 2;     (* 15 = 0000 1111 *)
   writeln('Line 5 - Value of c is  ', c );
end.
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
PyQt5 - QDock Widget

A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. This area is around the central widget.
A dock window can be moved inside the main window, or they can be undocked to be moved into a new area by the user. These properties are controlled by the following QDockWidget class methods −
setWidget()
Sets any QWidget in the dock window’s area
setFloating()
If set to true, the dock window can float
setAllowedAreas()
Sets the areas to which the window can be docked
setFeatures()
Sets the features of dock window
In the following example, top level window is a QMainWindow object. A QTextEdit object is its central widget.
self.setCentralWidget(QTextEdit())

A dockable window is first created.
self.items = QDockWidget("Dockable", self)

A QListWidget object is added as a dock window.
self.listWidget = QListWidget()
self.listWidget.addItem("item1")
self.listWidget.addItem("item2")
self.listWidget.addItem("item3")
self.items.setWidget(self.listWidget)

Dockable object is placed towards the right side of the central widget.
self.addDockWidget(Qt.RightDockWidgetArea, self.items)

The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class dockdemo(QMainWindow):
   def __init__(self, parent = None):
      super(dockdemo, self).__init__(parent)
		
      layout = QHBoxLayout()
      bar = self.menuBar()
      file = bar.addMenu("File")
      file.addAction("New")
      file.addAction("save")
      file.addAction("quit")
		
      self.items = QDockWidget("Dockable", self)
      self.listWidget = QListWidget()
      self.listWidget.addItem("item1")
      self.listWidget.addItem("item2")
      self.listWidget.addItem("item3")
		
      self.items.setWidget(self.listWidget)
      self.items.setFloating(False)
      self.setCentralWidget(QTextEdit())
      self.addDockWidget(Qt.RightDockWidgetArea, self.items)
      self.setLayout(layout)
      self.setWindowTitle("Dock demo")
		
def main():
   app = QApplication(sys.argv)
   ex = dockdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output. Click on Dock icon to undock the ListWidget window. Double click to dock again −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
How to remove onClickListener for a view in android?

In some situations, We should not allow onClickListener for a view. This example demonstrates how to remove onClickListener for a view in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/acitivity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "28sp"
      android:textAlignment = "center"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view, In this example, we should remove onClickListner for this text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textview;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textview = findViewById(R.id.text);
      textview.setText("There is no Click listner for text view");
      textview.setOnClickListener(null);
   }
}
In the above example, we are passing a null value to setOnClickListener(), so it will don't perform any action when a user clicks on the text view.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above screen click on text view, it will show nothing because we have sent a null value for setOnClickListener().
Avoid duplicate entries in MongoDB?

To avoid duplicate entries in MongoDB, you can use createIndex(). The syntax is as follows −
db.yourCollectionName.createIndex({"yourFieldName":1},{unique:true});
Let us implement the above syntax. The query to avoid duplicate entries in MongoDB is a follows −
> db.avoidDuplicateEntriesDemo.createIndex({"UserName":1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
Now insert some records in the above collection. The query to insert record is as follows −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90e1824afe5c1d2279d697")
}
Here is the error whenever you try to insert the same record once again −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"});
2019-03-19T18:03:08.465+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : "John" } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : \"John\" }",
   "op" : {
      "_id" : ObjectId("5c90e1844afe5c1d2279d698"),
      "UserName" : "John"
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
Let us insert another record. The query is as follows −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90e18d4afe5c1d2279d699")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.avoidDuplicateEntriesDemo.find();
The following is the output −
{ "_id" : ObjectId("5c90e1824afe5c1d2279d697"), "UserName" : "John" }
{ "_id" : ObjectId("5c90e18d4afe5c1d2279d699"), "UserName" : "Carol" }
Visualizing Tiff File Using Matplotlib and GDAL using Python - GeeksforGeeks

12 Nov, 2020
Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation
To install this module run this command into your terminal. 
pip install GDAL

To visualize a tiff file we need matplotlib and GDAL modules in python. 
Import the moduleCount the number of bands.Fetch all the raster bands from the tiff file.Read the bands into NumPy arrays.Pass the arrays into Matplotlib’s imshow() to visualize.
Import the module
Count the number of bands.
Fetch all the raster bands from the tiff file.
Read the bands into NumPy arrays.
Pass the arrays into Matplotlib’s imshow() to visualize.
The tiff file can be downloaded from here.
Step 1: Import the modules and open the file.
Python3
from osgeo import gdalimport matplotlib.pyplot as plt    dataset = gdal.Open(r'land_shallow_topo_2048.tif')
Step 2: Count the number of bands.
Python3
print(dataset.RasterCount)
Output:
3

Step 3: Fetch the bands,
To fetch the bands we use GDAL’s GetRasterBand(int). Note that the value of int we pass will always start from 1 (indexing of bands starts from 1), 
Python3
# since there are 3 bands# we store in 3 different variablesband1 = dataset.GetRasterBand(1) # Red channelband2 = dataset.GetRasterBand(2) # Green channelband3 = dataset.GetRasterBand(3) # Blue channel
Step 4: Read the bands as Numpy arrays.
 GDAL provides ReadAsArray() method that converts the bands into numpy arrays and returns them. 
Python3
b1 = band1.ReadAsArray()b2 = band2.ReadAsArray()b3 = band3.ReadAsArray()
Step 5: Plotting the arrays using imshow().
To plot the three arrays we will stack them in sequence. 
Python3
img = np.dstack((b1, b2, b3))f = plt.figure()plt.imshow(img)plt.savefig('Tiff.png')plt.show()
Output:
Data Visualization
Python-matplotlib
Python
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
ByteArrayOutputStream toByteArray() method in Java with Examples - GeeksforGeeks

28 May, 2020
The toByteArray() method of ByteArrayOutputStream class in Java is used to create a newly allocated byte array. The size of the newly allocated byte array is equal to the current size of this output stream. This method copies valid contents of the buffer into it.
Syntax:
public byte[] toByteArray()

Parameters: This method does not accept any parameter.
Return value: The method returns newly allocated byte array which has the valid contents of this output stream.
Exceptions: This method does not throw any exception.
Below programs illustrate toByteArray() method in ByteArrayOutputStream class in IO package:
Program 1:
// Java program to illustrate// ByteArrayOutputStream toByteArray() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws Exception    {          // Create byteArrayOutputStream        ByteArrayOutputStream byteArrayOutStr            = new ByteArrayOutputStream();          // Create byte array        byte[] buf = { 71, 69, 69, 75, 83 };          // Write byte array        // to byteArrayOutputStream        byteArrayOutStr.write(buf);          for (byte b : byteArrayOutStr                          .toByteArray()) {              // Print the byte            System.out.println((char)b);        }    }}
G
E
E
K
S

Program 2:
// Java program to illustrate// ByteArrayOutputStream toByteArray() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws Exception    {          // Create byteArrayOutputStream        ByteArrayOutputStream byteArrayOutStr            = new ByteArrayOutputStream();          // Create byte array        byte[] buf = { 71, 69, 69, 75, 83,                       70, 79, 82, 71, 69,                       69, 75, 83 };          // Write byte array        // to byteArrayOutputStream        byteArrayOutStr.write(buf);          for (byte b : byteArrayOutStr                          .toByteArray()) {              // Print the byte            System.out.println((char)b);        }    }}
G
E
E
K
S
F
O
R
G
E
E
K
S

References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! - GeeksforGeeks

02 Nov, 2021
You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term.Examples:  
Input :n = 5
Output : 2.70833

Input :n = 7
Output : 2.71806
 
 
Java
// Java program to print the sum of series import java.io.*;import java.lang.*; class GFG {    public static double sumOfSeries(double num)    {        double res = 0, fact = 1;        for (int i = 1; i <= num; i++) {            /*fact variable store factorial of the i.*/            fact = fact * i;             res = res + (i / fact);        }        return (res);    }     public static void main(String[] args)    {        double n = 5;        System.out.println("Sum: " + sumOfSeries(n));    }} // Code contributed by Mohit Gupta_OMG <(0_o)>
Sum: 2.708333333333333
 
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! for more details! 
subhammahato348
Java Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
AngularJS | ng-app Directive - GeeksforGeeks

28 Mar, 2019
The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS Application.
Syntax:
<element ng-app=""> Contents... </element>
Example 1: This example uses ng-app Directive to define a default AngularJS application.
<html>      <head>    <title>AngularJS ng-app Directive</title>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head>  <body style="text-align:center">          <h2 style = "color:green">ng-app directive</h2>          <div ng-app="" ng-init="name='GeeksforGeeks'">        <p>{{ name }} is the portal for geeks.</p>    </div></body>  </html>
Output:
Example 2: This example uses ng-app Directive to define a default AngularJS application.
<html>      <head>    <title>AngularJS ng-app Directive</title>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head>  <body ng-app="" style="text-align: center">      <h1 style="color:green">GeeksforGeeks</h1>    <h2>ng-app Directive</h2>          <div>        <p>Name: <input type="text" ng-model="name"></p>        <p>You entered: <span ng-bind="name"></span></p>    </div></body>  </html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to find the sum of elements of a Vector using STL in C++? - GeeksforGeeks

08 Jul, 2021
Given a vector, find the sum of the elements of this vector using STL in C++.Example:  
Input: vec = {1, 45, 54, 71, 76, 12}
Output: 259

Input: vec = {1, 7, 5, 4, 6, 12}
Output: 35
 
Approach: Sum can be found with the help of accumulate() function provided in STL.Syntax:  
accumulate(first_index, last_index, initial value of sum);
Time Complexity: It is linear in the distance between first_index and last_index i.e if your your vector contains n number of elements between two given indices , the time complexity will be O(n). 
CPP
// C++ program to find the sum// of Array using accumulate() in STL #include <bits/stdc++.h>using namespace std; int main(){    // Get the vector    vector<int> a = { 1, 45, 54, 71, 76, 12 };     // Print the vector    cout << "Vector: ";    for (int i = 0; i < a.size(); i++)        cout << a[i] << " ";    cout << endl;     // Find the sum of the vector    cout << "\nSum = "         << accumulate(a.begin(), a.end(), 0);    return 0;}
Vector: 1 45 54 71 76 12 

Sum = 259
 
shriyanshi2017
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
Polymorphism in C++
Count the number of Documents in MongoDB using Python - GeeksforGeeks

08 Jun, 2020
Mongodb is a document-oriented NoSQL database which is non-relational DB. Mongodb is a schema-free database which is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in mongodb are schema-less.
PyMongo is one of the MongoDB drivers or client libraries. Using the PyMongo module we can send requests and receive responses from
Method 1: Using count()
The total number of documents present in the collection can be retrieved by using count() method.
Syntax :
db.collection.count()
Example : Count the number of documents (my_data) in the collection using count().
Sample Database:
from pymongo import MongoClient    Client = MongoClient()myclient = MongoClient('localhost', 27017)  my_database = myclient["GFG"]  my_collection = my_database["Student"]   # number of documents in the collectionmydoc = my_collection.find().count()print("The number of documents in collection : ", mydoc) 
Output :
The number of documents in collection :  8
Method 2: count_documents()
Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection.
Syntax :
db.collection.count_documents({query, option})
Example : Retrieves the documents present in the collection and the count of the documents using count_documents().
from pymongo import MongoClient    Client = MongoClient()myclient = MongoClient('localhost', 27017)  my_database = myclient["GFG"]  my_collection = my_database["Student"]   # number of documents in the collectiontotal_count = my_collection.count_documents({})print("Total number of documents : ", total_count)
Output :
Total number of documents :  8
soniyanagaraj30
Python-mongoDB
Python
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()