code-rag-bench/online-tutorials huggingface dataset:
Java Program to Count set bits in an integer - GeeksforGeeks

02 Jan, 2019
Write an efficient program to count number of 1s in binary representation of an integer.
Examples :
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits

1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.
Java
// Java program to Count set// bits in an integerimport java.io.*;  class countSetBits {    /* Function to get no of set     bits in binary representation     of positive integer n */    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            count += n & 1;            n >>= 1;        }        return count;    }      // driver program    public static void main(String args[])    {        int i = 9;        System.out.println(countSetBits(i));    }}  // This code is contributed by Anshika Goyal.
2

Recursive Approach :
Java
// Java implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer nimport java.io.*;  class GFG {      // recursive function to count set bits    public static int countSetBits(int n)    {          // base case        if (n == 0)            return 0;          else              // if last bit set add 1 else add 0            return (n & 1) + countSetBits(n >> 1);    }      // Driver code    public static void main(String[] args)    {          // get value from user        int n = 9;          // function calling        System.out.println(countSetBits(n));    }}  // This code is contributes by sunnysingh
2

Please refer complete article on Count set bits in an integer for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Modulo or Remainder Operator in Java
How to Iterate LinkedList in Java?
How to convert Date to String in Java
Java Program to Find Sum of Array Elements
Java Program to Convert String to String Array
How to Replace a Element in Java ArrayList?
Fill elements in a Java double array in a specified range

Elements can be filled in a Java double array in a specified range using the java.util.Arrays.fill() method. This method assigns the required double value in the specified range to the double array in Java.
The parameters required for the Arrays.fill() method are the array name, the index of the first element to be filled(inclusive), the index of the last element to be filled(exclusive) and the value that is to be stored in the array elements.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.Arrays;
public class Demo {
   public static void main(String[] argv) throws Exception {
      double[] doubleArray = new double[10];
      double doubleValue = 2.7;
      int indexStart = 3;
      int indexFinish = 8;
      Arrays.fill(doubleArray, indexStart, indexFinish, doubleValue);
      System.out.println("The double array content is: " + Arrays.toString(doubleArray));
   }
}
The double array content is: [0.0, 0.0, 0.0, 2.7, 2.7, 2.7, 2.7, 2.7, 0.0, 0.0]
Now let us understand the above program.
First the double array doubleArray[] is defined. Then the the Arrays.fill() method is used to fill the double array with value 2.7 from index 3(inclusive) to index 8(exclusive). Finally, the double array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −
double[] doubleArray = new double[10];
double doubleValue = 2.7;
int indexStart = 3;
int indexFinish = 8;
Arrays.fill(doubleArray, indexStart, indexFinish, doubleValue);
System.out.println("The double array content is: " + Arrays.toString(doubleArray));
File.ReadLines(String) Method in C# with Examples - GeeksforGeeks

01 Jun, 2020
File.ReadLines(String) is an inbuilt File class method that is used to read the lines of a file.
Syntax:
public static System.Collections.Generic.IEnumerable ReadLines (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the specified file for reading.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method.
ArgumentNullException: The path is null.
DirectoryNotFoundException: The path is invalid.
FileNotFoundException: The file specified by the path was not found.
IOException: An I/O error occurred while opening the file.
PathTooLongException: The path exceeds the system-defined maximum length.
SecurityException: The caller does not have the required permission.
UnauthorizedAccessException: The path specifies a file that is read-only. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission.
Return Value: Returns all the lines of the specified file.
Below are the programs to illustrate the File.ReadLines(String) method.
Program 1: Initially, a file file.txt is created with some contents shown below-
// C# program to illustrate the usage// of File.ReadLines(String) method  // Using System and System.IO namespacesusing System;using System.IO;  public class GFG {    public static void Main(String[] argv)    {        // Calling the ReadLines(String) function        foreach(string line in File.ReadLines(@"file.txt"))        {            // Printing the file contents            Console.WriteLine(line);        }    }}
Output:
GFG
gfg
Geeks
GeeksforGeeks
geeksforgeeks

Program 2: Initially, a file file.txt is created with some contents shown below-
Below code filter some contents from the file and prints them back.
// C# program to illustrate the usage// of File.ReadLines(String) method  // Using System and System.IO namespacesusing System;using System.IO;  public class GFG {    public static void Main(String[] argv)    {        // Calling the ReadLines(String) function        foreach(string line in File.ReadLines(@"file.txt"))        {            // Filtering the file contents and printing            if (line.Contains("GFG")) {                Console.WriteLine(line);            }        }    }}
Output:
GFG

CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
Difference between Ref and Out keywords in C#
Destructors in C#
Extension Method in C#
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
C# | Data Types
How to change Input box borders after filling the box using JavaScript ? - GeeksforGeeks

29 Jul, 2020
In this article, we will change the input border after filling the text on the input text field. The onchange event attribute works when the value of the element changes and select the new value from the list.
Approach: Whenever the input value is changed with some value by the user, the onchange event attribute is triggered. After the event is fired, the value is checked if it is not null. If the user value exists, then the bottom border of the input control is changed to dotted red color by using inline styling.
Syntax:
<element onchange = "script">
Example: In this example, we will change the border bottom style when the user type some text in the field.
<!DOCTYPE html><html>  <body style="text-align: center;">    <h2>GeeksForGeeks</h2>      <h2>        How to Change Input         borders after filling?    </h2>      <form>        <label> NAME</label>        <input type="text" id="fname"                 name="fname" value="">        <input type="submit" value="submit">    </form>      <script>        var gfg = document.getElementById("fname");        gfg.onchange = function (e) {            if (gfg.value != '') {                e.target.style.borderBottom                         = "4px dotted red";            }        };    </script></body>  </html>
Output:
Before filling the text:
After filling the text:
Supported Browsers:
Google Chrome
Internet Explorer
Opera
Safari
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Difference between Grant and Revoke - GeeksforGeeks

22 Jul, 2021
Data Controlling Language (DCL) helps users to retrieve and modify the data stored in the database with some specified queries. Grant and Revoke belong to these types of commands of the Data controlling Language. DCL is a component of SQL commands. 
1. Grant : SQL Grant command is specifically used to provide privileges to database objects for a user. This command also allows users to grant permissions to other users too. 
Syntax: 
grant privilege_name on object_name
to {user_name | public | role_name} 
Here privilege_name is which permission has to be granted, object_name is the name of the database object, user_name is the user to which access should be provided, the public is used to permit access to all the users. 
2. Revoke : Revoke command withdraw user privileges on database objects if any granted. It does operations opposite to the Grant command. When a privilege is revoked from a particular user U, then the privileges granted to all other users by user U will be revoked. 
Syntax: 
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:  
grant insert, 
select on accounts to Ram
By the above command user ram has granted permissions on accounts database object like he can query or insert into accounts. 
revoke insert, 
select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts database object has been removed. 
 
To know the exact syntax and how are they used click here. 
Differences between Grant and Revoke commands:  
kalrap615
DBMS-SQL
Picked
DBMS
Difference Between
SQL
DBMS
SQL
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 == and .equals() Method in Java
What is the difference between compile time errors and run time errors in Java?

Compile time errors are syntactical errors in the code which hinders it from being compiled.
public class Test{
   public static void main(String args[]){
      System.out.println("Hello")
   }
}
C:\Sample>Javac Test.java
Test.java:3: error: ';' expected
   System.out.println("Hello")

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {
   public static void main(String args[]) {
      File file = new File("E://file.txt");
      FileReader fr = new FileReader(file);
   }
}
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
   FileReader fr = new FileReader(file);
                   ^
1 error
CSS text-shadow Property - GeeksforGeeks

22 Oct, 2021
The text-shadow property in CSS is used to add shadows to the text. This property accepts a list of shadows that are to be applied to the text, separated by the comma. The default value of the text-shadow property is none.
Syntax:
text-shadow: h-shadow v-shadow blur-radius color|none|initial|
inherit;
Property values: 
h-shadow: This property is required & used to specify the position of horizontal shadow. It accepts the negative values.
v-shadow: This property is required & used to specify the position of vertical shadow. It also accepts the negative values.
blur-radius: It is used to set the blur radius. Its default value is 0 & is optional.
none: It represents no shadow added to the text, this is the default value.
color: It is used to set the color of the shadow. It is optional.
initial: It is used to set text-shadow to its default value.
inherit: This property is inherited from its parent element.
Example: This example shows the use of the text-shadow property with specific values assigned in pixels.
HTML
<!DOCTYPE html><html><head>    <title> CSS | text-shadow Property </title>    <style>    h1 {        text-shadow: 5px 5px 8px #00FF00;    }    </style></head> <body>    <h1> GeeksforGeeks </h1></body></html>
Output:
Supported Browsers: The browsers supported by the text-shadow property are listed below:
Google Chrome 4.0
Internet Explorer 10.0
Microsoft Edge 12.0
Firefox 3.5
Opera 9.6
Safari 4.0
arorakashish0911
bhaskargeeksforgeeks
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to create the tabbing order of an element in HTML?

Use the tabindex attribute in HTML to set the tab order of an element. It gives you the authority to change the order of your TAB usage on the keyboard.
You can try to run the following code to create tabbing order of an element in HTML −
<!DOCTYPE html>
<html>
   <body>
      <a href="https://www.tutorialspoint.com/current_affairs/index.htm" tabindex="1">Current Affairs</a><br>
      <a href="https://www.tutorialspoint.com/codingground.htm" tabindex="2">Coding Ground</a><br>
      <a href="https://www.tutorialspoint.com/verbal_ability/index.htm" tabindex="4">Verbal Ability</a><br>
      <a href="https://www.tutorialspoint.com/quantitative_aptitude/index.htm" tabindex="3">Quantitative Aptitude</a><br>
     
      <p>We have changed the tab order above. Use TAB on keyboard to view the changes.</p>
   </body>
</html>
Stack two Pandas series vertically and horizontally

18 Aug, 2020
In this article we’ll see how we can stack two Pandas series both vertically and horizontally. We stack these lists to combine some data in a DataFrame for a better visualization of the data, combining different data, etc. Now let’s see with the help of examples how we can do this.
Stacking Horizontally : We can stack 2 Pandas series horizontally by passing them in the pandas.concat() with the parameter axis = 1.Example :
# importing the moduleimport pandas as pd  # creating the seriesseries1 = pd.Series(['g', 'e', 'e', 'k', 's'])print("Series 1:")print(series1)series2 = pd.Series([9, 8, 7, 6, 5])print("Series 2:")print(series2)   # stacking the series horizontallydf = pd.concat([series1, series2], axis = 1)print("\nStack two series horizontally:")display(df)
Output :
Stacking Vertically : We can stack 2 Pandas series vertically by passing them in the pandas.concat() with the parameter axis = 0.Example :
# importing the moduleimport pandas as pd  # creating the seriesseries1 = pd.Series(['g', 'e', 'e', 'k', 's'])print("Series 1:")print(series1)series2 = pd.Series([9, 8, 7, 6, 5])print("Series 2:")print(series2)   # stacking the series verticallydf = pd.concat([series1, series2], axis = 0)print("\nStack two series vertically:")display(df)
Output :
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Swap two numbers in PL/SQL

17 May, 2018
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements.In declare part, we declare variables and between begin and end part, we perform the operations.
Basic structure of pl/sql block
declare
-- declare all the variables

begin  -- for start block
-- make a program here

end -- for end block
You have given two numbers num1 and num2 the your task is to swap the value of given numbers.
Examples:
Input : num1  = 1000 num2 = 2000
Output : num1  = 2000 num2 = 1000

Input : num1  = 40 num2 = 20
Output : num1  = 20 num2 = 40

declare  -- declare variable num1, num2 -- and temp of datatype number    num1 number;    num2 number;    temp number;     begin    num1:=1000;    num2:=2000;          -- print result before swapping    dbms_output.put_line('before');    dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);          -- swapping of numbers num1 and num2    temp := num1;    num1 := num2;    num2 := temp;         -- print result after swapping    dbms_output.put_line('after');    dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);      end;
Output:
before
num1  = 1000 num2 = 2000
after
num1  = 2000 num2 = 1000
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Cubes Product in list

27 Feb, 2020
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding product of cubes of list in just one line. Let’s discuss certain ways in which this can be performed.
Method #1 : Using reduce() + lambdaThe power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2.
# Python code to demonstrate # Cubes Product in list# using reduce() + lambda  # initializing listtest_list = [3, 5, 7, 9, 11]  # printing original list print ("The original list is : " + str(test_list))  # using reduce() + lambda# Cubes Product in listres = reduce(lambda i, j: i * j*j * j, [test_list[:1][0]**3]+test_list[1:])  # printing resultprint ("The product of cubes of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The product of cubes of list is : 1123242379875

 
Method #2 : Using map() + loopThe similar solution can also be obtained using the map function to integrate and external product function to perform the product of the cubed number.
# Python3 code to demonstrate # Cubes Product in list# using loop + max()  # getting Product def prod(val) :     res = 1    for ele in val:         res *= ele     return res   # initializing listtest_list = [3, 5, 7, 9, 11]  # printing original list print ("The original list is : " + str(test_list))  # using loop + max()# Cubes Product in listres = prod(map(lambda i : i * i * i, test_list))  # printing resultprint ("The product of cubes of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The product of cubes of list is : 1123242379875

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
iconphoto() method in Tkinter | Python

24 Nov, 2021
iconphoto() method is used to set the titlebar icon of any tkinter/toplevel window. But to set any image as the icon of titlebar, image should be the object of PhotoImage class.Syntax:  
iconphoto(self, default = False, *args)
Steps to set icon image –  
from tkinter import Tk
master = Tk()

photo = PhotoImage(file = "Any image file")
master.iconphoto(False, photo)
Set the titlebar icon for this window based on the named photo images passed through args. If default is True, this is applied to all future created toplevels as well. The data in the images is taken as a snapshot at the time of invocation. If the images are later changed, this is not reflected in the titlebar icons. The function also scales provided icons to an appropriate size.Code #1: When PhotoImage is provided.  
Python3
# Importing Tkinter modulefrom tkinter import *from tkinter.ttk import *  # Creating master Tkinter windowmaster = Tk()  # Creating object of photoimage class# Image should be in the same folder# in which script is savedp1 = PhotoImage(file = 'info.png')  # Setting icon of master windowmaster.iconphoto(False, p1)  # Creating buttonb = Button(master, text = 'Click me !')b.pack(side = TOP)  # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop()
Output:  
Exception: If you provide an image directly instead of PhotoImage object then it will show the following error.Code #2: When PhotoImage object is not provided.  
Python3
# Importing Tkinter modulefrom tkinter import *from tkinter.ttk import *  # Creating master Tkinter windowmaster = Tk()  # Setting icon of master windowmaster.iconphoto(False, 'info.png')  # Creating buttonb = Button(master, text = 'Click me !')b.pack(side = TOP)  # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop()
Output:  
Traceback (most recent call last):
  File "C:\Users\Admin\Documents\GUI_python\geeks.py", line 14, in 
    master.iconphoto(False, 'info.png')
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1910, in wm_iconphoto
    self.tk.call('wm', 'iconphoto', self._w, *args)
_tkinter.TclError: can't use "info.png" as iconphoto: not a photo image
 
delaliamina
masam
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
Write a C# program to find GCD and LCM?

GCD is the largest positive integer that divides each of the integers.
LCM of two numbers is the smallest integer divisible by both the numbers.
The following is an example to calculate the GCD and LCM. Here, we are calculating the LCM and GCD of 10 and 16 −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class Program {
      static void Main(string[] args) {

         int val1, val2, n1, n2, x;
         int resLCM, resGCD;
         val1 = 10;
         val2 = 16;

         n1 = val1;
         n2 = val2;
         while (n2 != 0) {
            x = n2;
            n2 = n1 % n2;
            n1 = x;
         }

         resGCD = n1;
         resLCM = (val1 * val2) / resGCD;

         Console.WriteLine("LCM: ", val1, val2, resLCM);
         Console.WriteLine("GCD: ", val1, val2, resGCD);
         Console.ReadKey();
      }
   }
}
LCM:
GCD:
What is a dictionary in C#?

Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace.
To declare and initialize a Dictionary −
IDictionary<int, int> d = new Dictionary<int, int>();
Above, types of key and value are set while declaring a dictionary object. An int is a type of key and string is a type of value. Both will get stored in a dictionary object named d.
Let us now see an example −
using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      IDictionary<int, int> d = new Dictionary<int, int>();
      d.Add(1,97);
      d.Add(2,89);
      d.Add(3,77);
      d.Add(4,88);

      // Dictionary elements
      Console.WriteLine("Dictionaly elements: "+d.Count);
   }
}
Socket.IO - Logging & Debugging

Socket.IO uses a very famous debugging module developed by ExpresJS's main author, called debug. Earlier Socket.IO used to log everything to the console making it quite difficult to debug the problem. After the v1.0 release, you can specify what you want to log.
The best way to see what information is available is to use the * −
DEBUG=* node app.js

This will colorize and output everything that happens to your server console. For example, we can consider the following screenshot.
Paste this to console, click enter and refresh your page. This will again output everything related to Socket.io to your console.
localStorage.debug = '*';

You can limit the output to get the debug info with incoming data from the socket using the following command.
localStorage.debug = 'socket.io-client:socket';

You can see the result like the following screenshot, if you use the second statement to log the info −
There is a very good blog post related to socket.io debugging here.

    35 Lectures 
     2.5 hours 

 Nicholas Lever
 Print
 Add Notes
 Bookmark this page
Find records in MongoDB that does NOT match a condition?

To find records that does not match a condition, use $ne. Let us create a collection with documents −
> db.demo148.insertOne({"Message":"Hello"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32fb37fdf09dd6d08539c0")
}
> db.demo148.insertOne({"Message":"Good"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32fb3efdf09dd6d08539c1")
}
> db.demo148.insertOne({"Message":"Bye"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32fb42fdf09dd6d08539c2")
}
Display all documents from a collection with the help of find() method −
> db.demo148.find();
This will produce the following output −
{ "_id" : ObjectId("5e32fb37fdf09dd6d08539c0"), "Message" : "Hello" }
{ "_id" : ObjectId("5e32fb3efdf09dd6d08539c1"), "Message" : "Good" }
{ "_id" : ObjectId("5e32fb42fdf09dd6d08539c2"), "Message" : "Bye" }
Following is the query to find records in MongoDB that does not match a condition −
> db.demo148.find({'Message' : {'$ne' : 'Good'}}).toArray(function(err, output)
... {
...    console.log(output);
... });
This will produce the following output −
[
   {
      "_id" : ObjectId("5e32fb37fdf09dd6d08539c0"),
      "Message" : "Hello"
   },
   {
      "_id" : ObjectId("5e32fb42fdf09dd6d08539c2"),
      "Message" : "Bye"
   }
]
Aptitude | GATE CS 1998 | Question 5 - GeeksforGeeks

11 Oct, 2021
What is the converse of the following assertion?
I stay only if you go.
(A) I stay if you go(B) If I stay then you go(C) If you do not go then I do not stay(D) If I do not stay then you goAnswer: (A)Explanation:
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersIntroduction to Propositional Logic (continued) with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0012:58 / 37:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=VgHVtJ-mYq4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
System.getProperty() in Java

The getProperty(String key) method in Java is used to returns the system property denoted by the specified key passed as its argument.It is a method of the java.lang.System Class.
Declaration − The java.lang.System.getProperty(String key) is declared as follows −
public static String getProperty(String key)
where key is the name of the System property.
Some values of the key are as follows −
file.separator
java.specification.version
java.vm.version
java.class.path
java.vendor
java.class.version
os.arch
java.compiler
line.separator
java.version
java.vendor.url
os.name
Let us see a program showing the use of getProperty() method in Java −
 Live Demo
public class Example {
   public static void main(String[] args) {
      System.out.println("System property: " + System.getProperty("user.dir"));
      System.out.println("Operating System: " + System.getProperty("os.name"));
      System.out.println("Java runtime version: " + System.getProperty("java.runtime.version" ));
   }
}
System property: /home/cg/root/5182567
Operating System: Linux
Java runtime version: 1.8.0_141-b16
Deep Learning with Keras - Training the Model

The model training is done in one single method call called fit that takes few parameters as seen in the code below −
history = model.fit(X_train, Y_train,
   batch_size=128, epochs=20,
   verbose=2,
   validation_data=(X_test, Y_test)))
The first two parameters to the fit method specify the features and the output of the training dataset.
The epochs is set to 20; we assume that the training will converge in max 20 epochs - the iterations. The trained model is validated on the test data as specified in the last parameter.
The partial output of running the above command is shown here −
Train on 60000 samples, validate on 10000 samples
Epoch 1/20
- 9s - loss: 0.2488 - acc: 0.9252 - val_loss: 0.1059 - val_acc: 0.9665
Epoch 2/20
- 9s - loss: 0.1004 - acc: 0.9688 - val_loss: 0.0850 - val_acc: 0.9715
Epoch 3/20
- 9s - loss: 0.0723 - acc: 0.9773 - val_loss: 0.0717 - val_acc: 0.9765
Epoch 4/20
- 9s - loss: 0.0532 - acc: 0.9826 - val_loss: 0.0665 - val_acc: 0.9795
Epoch 5/20
- 9s - loss: 0.0457 - acc: 0.9856 - val_loss: 0.0695 - val_acc: 0.9792
The screenshot of the output is given below for your quick reference −
Now, as the model is trained on our training data, we will evaluate its performance.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    106 Lectures 
     13.5 hours 

 Abhilash Nelson

    28 Lectures 
     4 hours 

 Abhilash Nelson

    58 Lectures 
     8 hours 

 Soumyadeep Dey

    59 Lectures 
     2.5 hours 

 Mike West

    128 Lectures 
     5.5 hours 

 TELCOMA Global
 Print
 Add Notes
 Bookmark this page
Python | Numpy matrix.fill() - GeeksforGeeks

12 Apr, 2019
With the help of Numpy matrix.fill() method, we are able to fill a scalar value in a given matrix and gives output as matrix having scalar values.
Syntax : matrix.fill(value)
Return : Return a matrix having scalar value
Example #1 :In this example we can see that with the help of matrix.fill() method we are able to fill the given matrix with a scalar value.
# import the important module in pythonimport numpy as np         # make matrix with numpygfg = np.matrix('[6, 2, 3]')         # applying matrix.fill() methodgfg.fill(0)   print(gfg)
[[0 0 0]]

Example #2 :
# import the important module in pythonimport numpy as np         # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6]')         # applying matrix.fill() methodgfg.fill(1)   print(gfg)
[[1 1 1]
 [1 1 1]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
PyQt5 QSpinBox - Setting range - GeeksforGeeks

06 May, 2020
In this article we will see how we can set range to the spin box, by default when we create a spin box it range varies from 0 to 99 i.e minimum value(lower bound) is 0 and maximum value(maximum bound) is 99 although we can change this range.
In order to do this we will use setRange method.
Syntax : spin_box.setRange(min_value, max_value)
Argument : It takes two integer i.e minimum and maximum value as argument
Return : 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, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 150, 40)          # setting range        self.spin.setRange(-1, 1)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to convert Dictionary to Pandas Dataframe? - GeeksforGeeks

10 Jul, 2020
Let’s discuss how to convert Python Dictionary to Pandas Dataframe. We can convert a dictionary to a pandas dataframe by using the pd.DataFrame.from_dict() class-method.
Example 1: Passing the key value as a list.
import pandas as pd    data = {'name': ['nick', 'david', 'joe', 'ross'],        'age': ['5', '10', '7', '6']} new = pd.DataFrame.from_dict(data)  new
Example 2
import pandas as pd    data = [{'area': 'new-hills', 'rainfall': 100, 'temperature': 20},         {'area': 'cape-town',  'rainfall': 70, 'temperature': 25},         {'area': 'mumbai',  'rainfall': 200,  'temperature': 39 }]  df = pd.DataFrame.from_dict(data)  df
Example 3: Using the orient parameter to change the orientation of the dataframe from column to index
import pandas as pd  data ={'area': ['new-hills', 'cape-town', 'mumbai'],       'rainfall':[100, 70, 200],       'temperature':[20, 25, 39]}  df = pd.DataFrame.from_dict(data, orient ='index') dfprint(df)
Python pandas-dataFrame
Python-pandas
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()
How to export promises from one module to another module node.js ? - GeeksforGeeks

26 May, 2021
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime, but the main problem with the callback function is the callback hell problem. The solution of callback hell is using the promises in this article we will discuss how to export from one module to another module. 
Project Structure: It will look like this.
FirstModule.js
function check(number) {  return new Promise((Resolve, reject) => {    if (number % 2 == 0) {      Resolve("The number is even")    }    else {      reject("The number is odd")    }  })}  // Exporting check functionmodule.exports = {  check: check};
SecondModule.js
// Importing check functionconst promise = require("./FirstModule.js")  // Promise handlingpromise.check(8).then((msg) => {  console.log(msg)}).catch((msg) => {  console.log(msg)})
Run SecondModule.js file using the below command:
node SecondModule.js
Output:
The number is even
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python PIL | getpixel() Method - GeeksforGeeks

19 May, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The PixelAccess class provides read and write access to PIL.Image data at a pixel level. Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API. getpixel() Returns the pixel at x, y. The pixel is returned as a single 
Syntax: getpixel(self, xy)Parameters:xy :The pixel coordinate, given as (x, y).Returns: a pixel value for single band images, a tuple of pixel values for multiband images. 
Image Used:  
 
Python3
# Importing Image from PIL packagefrom PIL import Image # creating a image objectim = Image.open(r"C:\Users\System-Pc\Desktop\leave.jpg")px = im.load()print (px[4, 4])px[4, 4] = (0, 0, 0)print (px[4, 4])coordinate = x, y = 150, 59 # using getpixel methodprint (im.getpixel(coordinate));
Output:  
(130, 105, 49)
(0, 0, 0)
(75, 19, 0)
Another example:Here we change the coordinate value. Image Used  
 
Python3
# Importing Image from PIL packagefrom PIL import Image # creating a image objectim = Image.open(r"C:\Users\System-Pc\Desktop\leave.jpg")px = im.load()print (px[4, 4])px[4, 4] = (0, 0, 0)print (px[4, 4])coordinate = x, y = 180, 79 # using getpixel methodprint (im.getpixel(coordinate));
Output:  
(130, 105, 49)
(0, 0, 0)
(22, 168, 25)
 
sumitgumber28
Python-pil
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Java Program to Print Boundary Elements of the Matrix - GeeksforGeeks

04 Jan, 2021
Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column.
Example:
Input :
         1 2 3
         4 5 6
         7 8 9
Output:  
        1 2 3
        4   6
        7 8 9
Approach:
Take the matrix as input from the user of N × M dimension.Print the border elements of the matrix using for loop.
Take the matrix as input from the user of N × M dimension.
Print the border elements of the matrix using for loop.
Below is the implementation of the problem statement:
Java
// Java Program to Print Boundary// Elements of the Matrix  import java.util.*;  public class GFG {      public void Boundary_Elements(int mat[][])    {        // Printing Input Matrix;        System.out.println("Input Matrix is : ");          for (int i = 0; i < mat.length; i++) {            for (int j = 0; j < mat[i].length; j++) {                  System.out.print(mat[i][j]);            }              System.out.println();        }          // Printing Boundary Values of Matrix        System.out.println("Resultant Matrix is :");          for (int i = 0; i < mat.length; i++) {            for (int j = 0; j < mat[i].length; j++) {                  if (i == 0 || j == 0 || i == mat.length - 1                    || j == mat[i].length - 1) {                    System.out.print(mat[i][j]);                }                else {                    // Printing Space if element                    // is not at Boundary                    System.out.print(" ");                }            }              System.out.println();        }    }    public static void main(String[] args)    {        // Input Matrix        int mat[][] = new int[][] { { 1, 2, 3 },                                    { 4, 5, 6 },                                    { 7, 8, 9 } };          GFG B_Values = new GFG();          B_Values.Boundary_Elements(mat);    }}
Input Matrix is : 
123
456
789
Resultant Matrix is :
123
4 6
789

Time Complexity: O(N × M), where n and m are the dimensions of the matrix.
Space Complexity: O(N × M).
Picked
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
Python - Tkinter Choose color Dialog - GeeksforGeeks

22 Jan, 2021
Python provides many options for GUI (Graphical User Interface ) development. tkinter is the most commonly used method options apart from all other available alternatives. It is a standard method for developing GUI applications using Tk GUI toolkit. 
The steps involved in developing a basic Tkinter app are:
Importing the Tkinter module.Creating the main window or the container.Insert as many widgets as you want to the main window.Apply the event Trigger on all the widgets.
Importing the Tkinter module.
Creating the main window or the container.
Insert as many widgets as you want to the main window.
Apply the event Trigger on all the widgets.
The process of importing the Tkinter module is the same as importing any other module in Python.
import tkinter
The Tkinter module has a package in it named colorchooser. This package of the Tkinter module helps in developing the color chooser dialog box. This package has a function named askcolor() that plays a major role. 
This function belongs to the colorchooser package of Tkinter module. The function helps in creating a color chooser dialog box. As soon as the function is called, it makes the color chooser dialogue box pop up. The function returns the hexadecimal code of the color selected by the user.Syntax: 
colorchooser.askcolor()
Example: 
Python3
# Python program to create color chooser dialog box # importing tkinter modulefrom tkinter import * # importing the choosecolor packagefrom tkinter import colorchooser # Function that will be invoked when the# button will be clicked in the main windowdef choose_color():     # variable to store hexadecimal code of color    color_code = colorchooser.askcolor(title ="Choose color")    print(color_code) root = Tk()button = Button(root, text = "Select color",                   command = choose_color)button.pack()root.geometry("300x300")root.mainloop()
Output: 
 
Note: The color chooser dialog box may vary for different operating systems. 
eikdahms
Picked
Python-gui
Python-tkinter
Python
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 ?
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python | Convert list of tuples into list - GeeksforGeeks

18 Feb, 2019
Given a list of tuples, write a Python program to convert it into list.
Examples:
Input: [(11, 20), (13, 40), (55, 16)]
Output:[11, 20, 13, 40, 55, 16]

Input: [('Geeks', 2), ('For', 4), ('geek', '6')]
Output: ['Geeks', 2, 'For', 4, 'geek', '6']

Below are methods to convert list of tuples into list.
Method #1 : Using list comprehension
# Python code to convert list of tuples into list  # List of tuple initializationlt = [('Geeks', 2), ('For', 4), ('geek', '6')]  # using list comprehensionout = [item for t in lt for item in t]  # printing outputprint(out)
['Geeks', 2, 'For', 4, 'geek', '6']

 Method #2 : Using itertools
# Python code to convert list of tuple into list  # Importingimport itertools  # List of tuple initializationtuple = [(1, 2), (3, 4), (5, 6)]  # Using itertoolsout = list(itertools.chain(*tuple))  # printing outputprint(out)
[1, 2, 3, 4, 5, 6]

 Method #3 : Using iteration
# Python code to convert list of tuple into list  # List of tuple initializationtup = [(1, 2), (3, 4), (5, 6)]  # result list initializationresult = []  for t in tup:    for x in t:        result.append(x)  # printing outputprint(result)
[1, 2, 3, 4, 5, 6]

 Method #4 : Using sum
# Python code to convert list of tuple into list  # List of tuple initializationtup = [(1, 2), (3, 4), (5, 6)]  # using sum function()out = list(sum(tup, ()))  # printing outputprint(out)
[1, 2, 3, 4, 5, 6]

 Method #5 : Using operator and reduce
# Python code to convert list of tuple into list  import operatorfrom functools import reduce  # List of tuple initializationtup = [(1, 2), (3, 4), (5, 6)]  # printing outputprint(list(reduce(operator.concat, tup)))
[1, 2, 3, 4, 5, 6]

 Method #6 : Using lambda
# Python code to convert list of tuple into list    # List of tuple initializationtup = [(1, 2), (3, 4), (5, 6)]  # Using map for 0 indexb = map(lambda x: x[0], tup)  # Using map for 1 indexc = map(lambda x: x[1], tup)  # converting to listb = list(b)c = list(c)  # Combining outputout = b + c  # printing outputprint(out)
[1, 3, 5, 2, 4, 6]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary