code-rag-bench/online-tutorials huggingface dataset:
PHP date_create() Function

The date_create() function is an alias of the DateTime::__construct, a constructor of the DateTime class. Where, a DateTime class represents date and time in PHP. The date_create() function accepts a date time string and time zone (optional) as parameters and, creates a DateTime object accordingly.
By default, this function creates an object of the current date/time
date_create([$date_time, $timezone]);

date_time (Optional)
This is the date/time string (in supported formats) for which you need to create a DateTime object.
timezone (Optional)
 This represents the timezone of the given time.
PHP date_create() function returns the created DateTime object.
This function was first introduced in PHP Version 5.2.0 and, works with all the later versions.
Try out following example in here, we are creating a DateTime object, formatting it, and printing the result −
<?php
   //Date string
   $date_string = "25-09-1989";
   //Creating a DateTime object
   $date_time_Obj = date_create($date_string);
   //formatting the date to print it
   $format = date_format($date_time_Obj, "d-m-Y H:i:s");
   print($format);
?>
This will produce following result −
25-09-1989 00:00:00

Following example creates date formats it as date and time separately −
<?php
   $dateString = '11-06-2012 12:50 GMT';
   $dateTime = date_create($dateString);
   print("Date: ".$dateTime->format('d-m-y')); 
   print("\n");
   print("Time: ".$dateTime->format('H:i:s')); 
?>
This will produce following result −
Date: 11-06-12
Time: 12:50:00

Following example creates a DateTime object by specifying both date string and time zone −
<?php
   //Date string
   $date_string = "25-09-1989, 07:32:41 GMT";
   //Creating a DateTime object
   $tz = 'Indian/Mahe';   
   $date_time_Obj = date_create($date_string, new DateTimeZone($tz));
   //formatting the date to print it
   $format = date_format($date_time_Obj, "d-m-y H:i:s");
   print($format);
?>
This will produce following result −
Array
25-09-89 07:32:41

In the following example we are invoking the date_create() function without any parameters. It creates the object of the current time −
<?php
   //Creating a DateTime object
   $date_time_Obj = date_create();
   //formatting the date to print it
   print(date_format($date_time_Obj, "d-m-y H:i:s"));
?>
This produces the following result −
04-05-20 12:41:31


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How do we compare two dictionaries in Python?

dicts in python are also classes. These have the __eq__method overridden, so you can use the == operator to check if 2 dictionaries are equal or not. 
a = {'foo': 10, 'bar': 150}
b = {'foo': 10, 'bar': 150}
print(a == b)
This will give the output −
True
If you want a list of shared items in the 2 dictionaries, you can use sets and the & operator on them to get that. 
a = {'foo': 10, 'bar': 150}
b = {'foo': 10, 'baz': 50}

shared = set(a.items()) & set(b.items())
print(shared)
This will give the output −
{('foo', 10)}
Difference between Static Constructor and Instance Constructor in C#

A static constructor is a constructor declared using static modifier. It is the first block of code executed in a class. With that, a static constructor executes only once in the life cycle of class.
Instance constructor initializes instance data. Instance constructor is called when an object of class is created.
The following example shows the difference between static and instance constructor in C#.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Difference {
   class Demo {
      static int val1;
      int val2;
      static Demo() {
         Console.WriteLine("This is Static Constructor");
         val1 = 70;
      }
      public Demo(int val3) {
         Console.WriteLine("This is Instance Constructor");
         val2 = val3;
      }
      private void show() {
         Console.WriteLine("First Value = " + val1);
         Console.WriteLine("Second Value = " + val2);
      }
      static void Main(string[] args) {
         Demo d1 = new Demo(110);
         Demo d2 = new Demo(200);
         d1.show();
         d2.show();
         Console.ReadKey();
      }
   }
}
This is Static Constructor
This is Instance Constructor
This is Instance Constructor
First Value = 70
Second Value = 110
First Value = 70
Second Value = 200
Python | Pandas.apply()

03 Jul, 2018
Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. It comes as a huge improvement for the pandas library as this function helps to segregate data according to the conditions required due to which it is efficiently used in data science and machine learning.
Installation:Import the Pandas module into the python file using the following commands on the terminal:
pip install pandas

To read the csv file and squeezing it into a pandas series following commands are used:
import pandas as pd
s = pd.read_csv("stock.csv", squeeze=True)

Syntax:
s.apply(func, convert_dtype=True, args=())
Parameters:
func: .apply takes a function and applies it to all values of pandas series.convert_dtype: Convert dtype as per the function’s operation.args=(): Additional arguments to pass to function instead of series.Return Type: Pandas Series after applied function/operation.
For the dataset, click here to download.
Example #1:
The following example passes a function and checks the value of each element in series and returns low, normal or High accordingly.
import pandas as pd  # reading csvs = pd.read_csv("stock.csv", squeeze = True)  # defining function to check pricedef fun(num):      if num<200:        return "Low"      elif num>= 200 and num<400:        return "Normal"      else:        return "High"  # passing function to apply and storing returned series in newnew = s.apply(fun)  # printing first 3 elementprint(new.head(3))  # printing elements somewhere near the middle of seriesprint(new[1400], new[1500], new[1600])  # printing last 3 elementsprint(new.tail(3))
Output:
Example #2:
In the following example, a temporary anonymous function is made in .apply itself using lambda. It adds 5 to each value in series and returns a new series.
import pandas as pds = pd.read_csv("stock.csv", squeeze = True)  # adding 5 to each valuenew = s.apply(lambda num : num + 5)  # printing first 5 elements of old and new seriesprint(s.head(), '\n', new.head())  # printing last 5 elements of old and new seriesprint('\n\n', s.tail(), '\n', new.tail())
Output:
0    50.12
1    54.10
2    54.65
3    52.38
4    52.95
Name: Stock Price, dtype: float64 

0    55.12
1    59.10
2    59.65
3    57.38
4    57.95
Name: Stock Price, dtype: float64

3007    772.88
3008    771.07
3009    773.18
3010    771.61
3011    782.22
Name: Stock Price, dtype: float64
 
3007    777.88
3008    776.07
3009    778.18
3010    776.61
3011    787.22
Name: Stock Price, dtype: float64

As observed, New values = old values + 5
python-modules
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
random.gauss() function in Python

26 May, 2020
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
gauss() is an inbuilt method of the random module. It is used to return a random floating point number with gaussian distribution.
Syntax : random.gauss(mu, sigma)
Parameters :mu : meansigma : standard deviation
Returns : a random gaussian distribution floating number
Example 1:
# import the random moduleimport random  # determining the values of the parametersmu = 100sigma = 50  # using the gauss() methodprint(random.gauss(mu, sigma))
Output :
127.80261974806497
Example 2: We can generate the number multiple times and plot a graph to observe the gaussian distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a  # list nums = [] mu = 100sigma = 50    for i in range(100):     temp = random.gauss(mu, sigma)    nums.append(temp)         # plotting a graph plt.plot(nums) plt.show()
Output :
Example 3: We can create a histogram to observe the density of the gaussian distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a list nums = [] mu = 100sigma = 50    for i in range(10000):     temp = random.gauss(mu, sigma)     nums.append(temp)         # plotting a graph plt.hist(nums, bins = 200) plt.show()
Output :
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use a custom png image marker in a plot (Matplotlib)?

To use custome png or jpg i.e an image as a marker in a plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a paths list to store the directories of images.
Make a paths list to store the directories of images.
Make a list (x and y) of points.
Make a list (x and y) of points.
Using subplots() method, create a figure and a set of subplots.
Using subplots() method, create a figure and a set of subplots.
To plot images instead of points, iterate zipped x, y and paths.
To plot images instead of points, iterate zipped x, y and paths.
Instantiate AnnotationBbox() with image and (x, y) points.
Instantiate AnnotationBbox() with image and (x, y) points.
Put xticks and yticks on both the axes.
Put xticks and yticks on both the axes.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def getImage(path):
   return OffsetImage(plt.imread(path, format="jpg"), zoom=.1)

paths = ['globe.jpg', 'settings.jpg', 'settings.jpg', 'globe.jpg']
x = [8, 4, 3, 6]
y = [5, 3, 4, 7]
fig, ax = plt.subplots()
for x0, y0, path in zip(x, y, paths):
   ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)
   ax.add_artist(ab)
plt.xticks(range(10))
plt.yticks(range(10))
plt.show()
Perl seek Function

This function moves to a specified position in a file. You can move relative to the beginning of the file (WHENCE = 0), the current position (WHENCE = 1), or the end of the file (WHENCE = 2). This function is mainly used with fixed length records to randomly access specific records of the file.
For WHENCE you may use the constants SEEK_SET , SEEK_CUR , and SEEK_END (start of the file, current position, end of the file) from the Fcntl module.
This function is similar to Unix seek() system call.
Following is the simple syntax for this function −
seek FILEHANDLE,POSITION,WHENCE

This function

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
PostgreSQL – SMALLINT Integer Data Type

28 Aug, 2020
PostgreSQL allows a type of integer type namely SMALLINT. It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc.
Syntax: variable_name SMALLINT
Now let’s look into some examples of use cases of SMALLINT integer type.Example 1:In this example we will create a table that stores the number of pages in a book by using the below commands:
CREATE TABLE books (
    book_id SERIAL PRIMARY KEY,
    title VARCHAR (255) NOT NULL,
    pages SMALLINT NOT NULL CHECK (pages > 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO books(title, pages)
VALUES
    ('Jumanji', 600),
    ('Insurgent', 7530), 
    ('Nottingham', 8657),  
    ('Dracula', 3000);
Now let’s check our inserted data using the below commands:
SELECT * FROM books;
Output:
Example 2:In this example we will create a table that stores the ages of students by using the below commands:
CREATE TABLE student_age(
    student_id SERIAL PRIMARY KEY,
    first_name VARCHAR (255) NOT NULL,
    last_name VARCHAR (255) NOT NULL,
    age SMALLINT NOT NULL CHECK (age > 0)
);
Now let’s add some data to the table using the below command:
INSERT INTO student_age(first_name, last_name, age)
VALUES
    ('Raju', 'Kumar', 25),
    ('Nikhil', 'Aggarwal', 21), 
    ('Baccha', 'Yadav', 45),  
    ('Geeta', 'Devi', 30);
Now let’s check our inserted data using the below commands:
SELECT * FROM student_age;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - IF Statement
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - SELECT
PostgreSQL - REPLACE Function
PostgreSQL - GROUP BY clause
PostgreSQL - Create Database
PostgreSQL Tutorial
PostgreSQL - FETCH clause
PostgreSQL - INSERT
How to initialize a list in a single line in Java with a specified value?

16 Dec, 2019
Given a value N, the task is to create a List having this value N in a single line in Java.
Examples:
Input: N = 5
Output: [5]

Input: N = GeeksForGeeks
Output: [GeeksForGeeks]

Approach:
Get the value N
Create an array with this value N
Create a List with this array as an argument in the constructor
Below is the implementation of the above approach:
// Java program to initialize a list// in a single line with a specified value  import java.io.*;import java.util.*;  class GFG {      // Function to create a List    // with the specified value    public static <T> List<T> createList(T N)    {          // Currently only one value is taken        int size = 1;          // Create an array of size 1        T arr[] = (T[]) new Object[1];          // Add the specified value in the array        arr[0] = N;          // System.out.println(Arrays.toString(arr));        List<T> list = Arrays.asList(arr);          // return the created list        return list;    }      // Driver code    public static void main(String[] args)    {          int N = 1024;        System.out.println("List with element "                           + N + ": "                           + createList(N));          String str = "GeeksForGeeks";        System.out.println("List with element "                           + str + ": "                           + createList(str));    }}
Output:
List with element 1024: [1024]
List with element GeeksForGeeks: [GeeksForGeeks]

Java-List-Programs
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Remove first and last character of a string in Java
Program to print ASCII Value of a character
Iterate Over the Characters of a String in Java
Traverse Through a HashMap in Java
How to Convert Char to String in Java?
MongoDB – Greater than Operator $gt

27 Mar, 2020
MongoDB provides different types of comparison operators and greater than operator($gt) is one of them. This operator is used to select those documents where the value of the field is greater than(>) the given value. You can use this operator in methods (like, find, update, etc.) according to your requirements.
Syntax:
{field: {$gt: value}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs.
 Example #1:In this example, we are selecting those documents where the value of the salary field is greater than 35000.
 Example #2:In this example, we are selecting only those documents where the age of the employee is greater than 23. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.
 Example #3:In this example, we are selecting only those documents where the points array is greater than the specified array.
 Example #4:In this example, we are updating the salary of those employees whose experience year is greater than 2 years. Or in other words, set the value of the salary field to 49000 of those documents whose experienceYear field value is greater than 2.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Fuzzy Logic | Introduction
Mounting a Volume Inside Docker Container
GATE | GATE-CS-2016 (Set 1) | Question 56

07 Sep, 2021
Consider the following Syntax Directed Translation Scheme (SDTS), with non-terminals {S, A} and terminals {a, b}}.
Using the above SDTS, the output printed by a bottom-up parser, for the input aab is(A) 1 3 2(B) 2 2 3(C) 2 3 1(D) Syntax ErrorAnswer: (C)Explanation: Bottom up parser builds the parse tree from bottom to up, i.e from the given string to the starting symbol. The given string is aab and starting symbol is S.
so the process is to start from aab and reach S.
=>aab ( given string)=>aSb (after reduction by S->a, and hence print 2)=>aA (after reduction by A->Sb, and hence print 3)=>S (after reduction by S->aA, and hence print 1)
As we reach the starting symbol from the string, the string belongs to the language of the grammar.
Another way to do the same thing is :- bottom up parser does the parsing by RMD in reverse.
RMD is as follows:
=>S=> aA (hence, print 1)=> aSb (hence, print 3)=> aab (hence, print 2)
If we take in Reverse it will print : 231
PYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:50 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" 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
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating a Rainbow using Graphics Programming in C

13 Aug, 2019
In Turbo C graphics we use graphics.h functions to draw different shapes(like circle, rectangle etc), display text(any message) in different format(different fonts and colors). By using graphics.h we can make programs, animations and also games. These can be useful for beginners.
Functions Used :
delay(n): A function from dos.h header file is responsible for holding of the program for a while depending upon given value n.
setcolor(n): A function from graphics.h header file which set the color of pointer(cursor).
arc(x,y,a1,a2,r): A function from graphics.h header file which draw an arc with (x,y) as centre (a2-a1) as angle and r as radius.
Implementation:
// A C program to make a rainbow. This program would only// work in Turbo C compiler in DOS compatible machine#include<stdio.h>#include<graphics.h>#include<dos.h>  // function for making of rainbowvoid rainbow(){    // auto detection    int gdriver = DETECT,gmode;    int x, y, i;      // initialize graphics mode(passed three arguments to    // initgraph function)    // &gdriver is the address of gdriver variable, &gmode is    // the address of gmode and    //  "C:\\Turboc3\\BGI" is the directory path where BGI files are stored    initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI");      x = getmaxx() / 2;//finding centre x-ordinate of screen    y = getmaxy() / 2;//finding centre y-ordinate of screen      for (i=30; i<200; i++)    {        // delay function under dos.h for holding the        // function for some time        delay(100);          // selecting  color for making of rainbow        setcolor(i/10);          // making of arc with fixed centre and increasing radius        arc(x, y, 0, 180, i-10);    }}// driver programint main(){    rainbow();    return 0;}
Reference:http://www.xcnotes.com/graphics-in-c-language/draw-rainbow-in-c
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
MuhammedYasir
C-Library
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype?
GATE | GATE-IT-2004 | Question 8

19 Nov, 2018
What is the minimum number of NAND gates required to implement a 2-input EXCLUSIVE-OR function without using any other logic gate?(A) 3(B) 4(C) 5(D) 6Answer: (B)Explanation: 
Pic Courtesy: http://www.electronics-tutorials.ws/logic/logic_7.html
Other way around:
x XOR y = x’y+xy’ = x’y+xy’+xx’+yy’ = (x+y) (x’+y’)
Using NAND gates
F= (x+y)(xy)’ = x. (xy)’ + y. (xy)’
Taking compliment
F’= ( x. (xy)’ + y. (xy)’ )’ = (x. (xy)’)’. (y. (xy)’)
Compliment again
F=( (x. (xy)’)’. (y. (xy)’) )’
So Answer is BQuiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make a PyGame Window?

24 Feb, 2021
PyGame is a free and open-source cross-platform library for game development in Python. It was officially written by Pete Shinners to replace PySDL it is suitable for the creation of client-side applications and acts as standalone executables. In this article, we are going to see how to make Pygame window in Python.
Command to install pygame on Windows-based system :  
pip install pygame
Steps to make a pygame window:
Import pygame module
Create a pygame window object using pygame.display.set_mode() method. It requires two parameters that define the width and height of the window.
Window properties can be altered such as the title of the window can be set using the set_caption() method. The background color can be changed by filling the screen object using a 3 tuple of integers ranging from 0 to 255 and representing the RGB values respectively.
Display the window using the flip() method. Once this method is called, the code reaches its end and the program terminates.
To keep the window visible without terminating abruptly, an infinite loop can be added to the code. However, the program will not quit even if the user wants. The user has to forcibly end the program by using CTRL+C in the command line.
To display the window for as long as the user does not choose to close it, pygame.event.get() method is used. This method returns a list of events. To stop the window from displaying, one has to loop through and check whether the event has a type quit. If found, one can easily exit from the loop.
Example:
Python3
# import the pygame moduleimport pygame  # Define the background colour# using RGB color coding.background_colour = (234, 212, 252)  # Define the dimensions of# screen object(width,height)screen = pygame.display.set_mode((300, 300))  # Set the caption of the screenpygame.display.set_caption('Geeksforgeeks')  # Fill the background colour to the screenscreen.fill(background_colour)  # Update the display using flippygame.display.flip()  # Variable to keep our game loop runningrunning = True  # game loopwhile running:    # for loop through the event queue      for event in pygame.event.get():              # Check for QUIT event              if event.type == pygame.QUIT:            running = False
Output: 
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js band.bandwidth() Function

26 Jul, 2021
The band.bandwidth() function in d3.js is used to find the width of each band.
Syntax:
band.bandwidth()
Parameters: This function does not accept any parameter.
Return Values: This function returns the width of each band.
Example 1:
HTML
<!DOCTYPE html><html lang = "en"> <head>    <meta charset = "UTF-8" />    <meta name = "viewport"        path1tent = "width=device-width,        initial-scale = 1.0"/>    <script src =        "https://d3js.org/d3.v4.min.js">    </script></head>   <body>    <script>        // Creating the band scale with        // specified domain and range.        var A = d3.scaleBand()                    .domain([10, 20, 30, 40, 50])                    .range([0, 10]);             // Applying bandwidth() Function        let gfg = A.bandwidth();         // Printing the Output         console.log("Bandwidth Of A: ",gfg);             </script></body> </html>
Output:
Bandwidth Of A:  2
Example 2: 
HTML
<!DOCTYPE html><html lang = "en"> <head>    <meta charset = "UTF-8" />    <meta name = "viewport"        path1tent = "width=device-width,        initial-scale = 1.0"/>    <script src =        "https://d3js.org/d3.v4.min.js">    </script></head> <body>    <script>        // Creating the band scale with        // specified domain and range.        var B = d3.scaleBand()                    .domain(["one", "two", "three", "four"])                    .range([0, 60]);             // Applying bandwidth() Function        let gfg = B.bandwidth();         // Printing the Output         console.log("Bandwidth Of each band in B: ",gfg);    </script></body> </html>
  Output: 
Bandwidth Of each band in B:  15
surinderdawra388
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – How to add border on QLabel ?

26 Mar, 2020
When we create Label in PyQt5, we can see that there are no borders like there exist in Push Buttons, in this article we will see how to add border to the Label.
In order to add border to the Label we will use label.setStyleSheet() method, this will add the border to the label, also we can set the thickness as well as color of the border.
Syntax : label.setStyleSheet(“border: 1px solid black;”)
Argument : It takes string as a argument.
Action performed : This will create a border on label with thickness of 1px and color will be black.
 Below is the Python implementation –
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        # by default label will display at top left corner        self.label_1 = QLabel('It is Label 1', self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # creating a label widget        # by default label will display at top left corner        self.label_2 = QLabel('It is Label 2', self)          # moving position        self.label_2.move(100, 200)          # setting up border        self.label_2.setStyleSheet("border: 3px solid blue;")          # show all the widgets        self.show()      # 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
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
How to Print Specific date-time in Golang?

17 May, 2020
Golang supports time formatting and parsing via pattern-based layouts. In Go, the current time can be determined by using time.Now(), provided by the time package. Package time provides functionality for measuring and displaying the time.
To print Current date-time you need to import the “time” package in your Go program to work with date and time.
Example:
// Golang program to show// the use of time.Now() Functionpackage main  import "fmt"import "time"  func main() {    dt := time.Now()          // printing the time in string format    fmt.Println("Current date and time is: ", dt.String())}
Output :
Current date and time is:  2020-05-05 06:43:01.419199824 +0000 UTC m=+0.000076701
To print Specific date-time in Golang use format constants provided in the time package. The commonly used formats are:
const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)

Example:
// Golang program to print specific date and timepackage main  import "fmt"import "time"  func main() {      dt := time.Now()          // printing date and time in UnixDate format    fmt.Println("Specific date and time is: ", dt.Format(time.UnixDate))}
Output:
Specific date and time is:  Tue May  5 07:05:00 UTC 2020

Example:
// Golang program to print specific date and timepackage main  import "fmt"import "time"  func main() {    dt := time.Now()          // Format MM-DD-YYYY    fmt.Println(dt.Format("01-02-2006"))      // Format MM-DD-YYYY hh:mm:ss    fmt.Println(dt.Format("01-02-2006 15:04:05"))      // With short weekday (Mon)    fmt.Println(dt.Format("01-02-2006 15:04:05 Mon"))      // With weekday (Monday)    fmt.Println(dt.Format("01-02-2006 15:04:05 Monday"))      // Include micro seconds    fmt.Println(dt.Format("01-02-2006 15:04:05.000000"))}
Output:
11-10-2009
11-10-2009 23:00:00
11-10-2009 23:00:00 Tue
11-10-2009 23:00:00 Tuesday
11-10-2009 23:00:00.000000

Golang-Program
GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ASP Server.HTMLEncode() Method

05 Feb, 2021
The ASP Server.HTMLEncode() Method is used to convert an HTML code to a string. It is used to encode form data and other client request data before using it in the web application. When the string to be encoded is not a double-byte character set, this method will convert the characters as given below:
The less-than, greater-than, ampersand, and double-quote characters are converted to their respective entity names.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where the <number> portion is the ASCII character’s value.
When the string to be encoded is a double-byte character set, this method converts characters as given below:
All the extended characters are converted.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where <number> is the ASCII character value.
Syntax: 
Server.HTMLEncode( string )
Parameter Values: It contains a string value that specifies the HTML to be encoded as a string.
Example: The following code illustrates this method.
<%response.write(Server.HTMLEncode("The Bold tag: <b>"))%>
Output: The script produces the following output in the encoded form
The Bold tag: &lt;b&gt;
The Web Browser displays the HTML as normal
The Bold tag: <b>
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
REST API (Introduction)
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners
Python | Image blurring using OpenCV

17 Apr, 2019
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels.
Advantages of blurring:
It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise.
It helps in smoothing the image.
Low intensity edges are removed.
It helps in hiding the details when necessary. For e.g. in many cases police deliberately want to hide the face of the victim, in such cases blurring is required.
Important types of blurring:
Gaussian Blurring:Gaussian blur is the result of blurring an image by a Gaussian function. It is a widely used effect in graphics software, typically to reduce image noise and reduce detail. It is also used as a preprocessing stage before applying our machine learning or deep learning models.E.g. of a Gaussian kernel(3×3)
Median Blur: The Median Filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Median filtering is very widely used in digital image processing because, under certain conditions, it preserves edges while removing noise. It is one of the best algorithms to remove Salt and pepper noise.
Bilateral Blur: A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images. It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels. This weight can be based on a Gaussian distribution. Thus, sharp edges are preserved while discarding the weak ones.
Below is the Python code:
# importing librariesimport cv2import numpy as np  image = cv2.imread('C://Geeksforgeeks//image_processing//fruits.jpg')  cv2.imshow('Original Image', image)cv2.waitKey(0)  # Gaussian BlurGaussian = cv2.GaussianBlur(image, (7, 7), 0)cv2.imshow('Gaussian Blurring', Gaussian)cv2.waitKey(0)  # Median Blurmedian = cv2.medianBlur(image, 5)cv2.imshow('Median Blurring', median)cv2.waitKey(0)    # Bilateral Blurbilateral = cv2.bilateralFilter(image, 9, 75, 75)cv2.imshow('Bilateral Blurring', bilateral)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How does concatenation operator work on list in Python?

The concatenation operator creates a new list in Python using the initial lists in the order they were added in. This is not an inplace operation. 
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = list1 + list2
print(list3)
This will give the output −
[1, 2, 3, 'a', 'b']
There are other ways to concatenate 2 lists. Easiest is to use the extend function, if you want to extend the list in place. 
list1 = [1, 2, 3]
list2 = ['a', 'b']
list1.extend(list2)
print(list1)
This will give the output −
[1, 2, 3, 'a', 'b']
You can also use unpacking operator * to create list from 2 lists. This can be used only in Python 3.5+.
list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [*list1, *list2]
print(list3)
This will give the output −
[1, 2, 3, 'a', 'b']
How to convert byte array to string in C#?

In .Net, every string has a character set and encoding. A character encoding tells the computer how to interpret raw zeroes and ones into real characters. It usually does this by pairing numbers with characters. Actually, it is the process of transforming a set of Unicode characters into a sequence of bytes.
We can use Encoding.GetString Method (Byte[]) to decodes all the bytes in the specified byte array into a string. Several other decoding schemes are also available in Encoding class such as UTF8, Unicode, UTF32, ASCII etc. The Encoding class is available as part of System.Text namespace.
string result = Encoding.Default.GetString(byteArray);
 Live Demo
using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.Default.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.Default.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}
The output of the above code is
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: Hello World
It is important to note that we should use the same encoding for both directions. For example, if the byte array is encoded with ASCII and we are trying to get the string using UTF32, we won’t get the desired string.
 Live Demo
using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.ASCII.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.UTF32.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}
The output of the above code is
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: ???
Map remove() Method in Java with Examples

27 Aug, 2021
This method is used to remove the mapping for a key from this map if it is present in the map.  
Syntax:  
V remove(Object key)
Parameters: This method has the only argument key, whose mapping is to be removed from the map.Returns: This method returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.Below programs show the implementation of int remove() method.Program 1: 
Java
// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a Map of type HashMap        Map<Integer, String> map = new HashMap<>();        map.put(1, "One");        map.put(3, "Three");        map.put(5, "Five");        map.put(7, "Seven");        map.put(9, "Nine");        System.out.println(map);         map.remove(3);         System.out.println(map);         // If it doesn't exists, returns        // null and does not affects the map        map.remove(2);         System.out.println(map);    }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
 
Program 2: Below is the code to show implementation of put(). 
Java
// Java code to show the implementation of// remove method in Map interfaceimport java.util.*;public class GfG {     // Driver code    public static void main(String[] args)    {         // Initializing a Map of type HashMap        Map<String, String> map = new HashMap<>();        map.put("1", "One");        map.put("3", "Three");        map.put("5", "Five");        map.put("7", "Seven");        map.put("9", "Nine");        System.out.println(map);         map.remove("3");         System.out.println(map);    }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
 
Reference: Oracle Docs
sagar0719kumar
Java - util package
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python | Minimum value keys in Dictionary

11 Jul, 2019
Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the minimum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using min() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, minimum value is extracted using the min function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with min value.
# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using min() + list comprehension + values()  # initializing dictionarytest_dict = {'Gfg' : 11, 'for' : 2, 'CS' : 11, 'geeks':8, 'nerd':2}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using min() + list comprehension + values()# Finding min value keys in dictionarytemp = min(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp]  # printing result print("Keys with minimum values are : " + str(res))
The original dictionary is : {‘nerd’: 2, ‘Gfg’: 11, ‘geeks’: 8, ‘CS’: 11, ‘for’: 2}Keys with minimum values are : [‘nerd’, ‘for’]
 
Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are greater than values with keys and return the keys with smallest values using list comprehension.
# Python3 code to demonstrate working of# Finding min value keys in dictionary# Using all() + list comprehension  # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 1}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using all() + list comprehension# Finding min value keys in dictionaryres =  [key for key in test_dict if         all(test_dict[temp] >= test_dict[key]        for temp in test_dict)]  # printing result print("Keys with minimum values are : " + str(res))
The original dictionary is : {‘Gfg’: 1, ‘CS’: 1, ‘for’: 2}Keys with minimum values are : [‘Gfg’, ‘CS’]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – tensorflow.convert_to_tensor()

26 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
convert_to_tensor() is used to convert the given value to a Tensor
Syntax: tensorflow.convert_to_tensor( value, dtype, dtype_hint, name )
Parameters:
value: It is the value that needed to be converted to Tensor.
dtype(optional): It defines the type of the output Tensor.
dtype_hint(optional): It is used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to dtype_hint is not possible, this argument has no effect.
name(optiona): It defines the name for the operation.
Returns: It returns a Tensor.
Example 1: From Python list
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputl = [1, 2, 3, 4]  # Printing the inputprint('l: ', l)  # Calculating resultx = tf.convert_to_tensor(l)    # Printing the resultprint('x: ', x)
Output:
l:  [1, 2, 3, 4]
x:  tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)


Example 2: From Python tuple
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputl = (1, 2, 3, 4)  # Printing the inputprint('l: ', l)  # Calculating resultx = tf.convert_to_tensor(l, dtype = tf.float64)    # Printing the resultprint('x: ', x)
Output:
l:  (1, 2, 3, 4)
x:  tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)



Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Logistic Regression v/s Decision Tree Classification

25 Aug, 2021
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one’s superior performance is often credited to the nature of the data being worked upon. 
We can compare the two algorithms on different categories – 
As a simple experiment, we run the two models on the same dataset and compare their performances.
Step 1: Importing the required libraries 
Python3
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.tree import DecisionTreeClassifier
  Step 2: Reading and cleaning the Dataset
Python3
cd C:\Users\Dev\Desktop\Kaggle\Sinking Titanic# Changing the working location to the location of the filedf = pd.read_csv('_train.csv')y = df['Survived'] X = df.drop('Survived', axis = 1)X = X.drop(['Name', 'Ticket', 'Cabin', 'Embarked'], axis = 1) X = X.replace(['male', 'female'], [2, 3])# Hot-encoding the categorical variables X.fillna(method ='ffill', inplace = True)# Handling the missing values
  Step 3: Training and evaluating the Logistic Regression model
Python3
X_train, X_test, y_train, y_test = train_test_split(            X, y, test_size = 0.3, random_state = 0) lr = LogisticRegression()lr.fit(X_train, y_train)print(lr.score(X_test, y_test))
  Step 4: Training and evaluating the Decision Tree Classifier model
Python3
criteria = ['gini', 'entropy']scores = {} for c in criteria:    dt = DecisionTreeClassifier(criterion = c)    dt.fit(X_train, y_train)    test_score = dt.score(X_test, y_test)    scores = test_score print(scores)
On comparing the scores, we can see that the logistic regression model performed better on the current dataset but this might not be the case always. 
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe