code-rag-bench/online-tutorials huggingface dataset:
Different Input and Output Techniques in Python3

23 Jun, 2020
In this Article, we will learn some basic input-output techniques with the help of which we can easily follow the input and output format mentioned in the questions that we face in either daily coding life or in competitive programming.
1. Taking a single Input:  A single input in Python can be taken using the input() method.
Example:
Python3
# For integersn = int(input())  # For floating or decimal numbersn = float(input())  # For Stringsn = input()
2. Taking Multiple Input: Multiple inputs in Python can be taken with the help of map() and split() method. The split() method splits the space separated inputs and returns an iterable whereas when this function is used with the map() function it can convert the inputs to float and int accordingly.
Example:
Python3
# For Stringsx, y = input().split()  # For integers and floating point# numbersm, n = map(int, input().split()) m, n = map(float, input().split())
3. Taking variable number of input as list or tuple: For this the split() and map() functions can be used. As these functions return an iterable we can convert the given iterable to the list, tuple or set accordingly.
Example:
Python3
# For Input - 4 5 6 1 56 21 # (Space separated inputs)n = list(map(int, input().split()))print(n)
Output:
[4, 5, 6, 1, 56, 21]

4. Taking Fixed and variable number of input: 
Python3
# Input: geeksforgeeks 2 0 2 0str, *lst = input().split()lst = list(map(int, lst))  print(str, lst)
Output:
geeksforgeeks [2, 0, 2, 0]
1. Output on different line: print() method is used in python for printing to console.
Example:
Python3
lst = ['geeks', 'for', 'geeks']  for i in lst:    print(i)
Output:
geeks
for
geeks

2. Output on same line: end parameter in Python can be used to print on the same line.
Example 1:
Python3
lst = ['geeks', 'for', 'geeks']  for i in lst:    print(i, end='')
Output:
geeksforgeeks
Example 2: Printing with space.
Python3
lst = ['geeks', 'for', 'geeks']  for i in lst:    print(i,end=' ')
Output:
geeks for geeks

3. Output Formatting: If you want to format your output then you can do it with {} and format() function. {} is a placeholder for a variable that is provided in the format() like we have %d in C programming.
Example:
Python3
print('I love {}'.format('geeksforgeeks.'))  print("I love {0} {1}".format('Python', 'programming.')
Output:
I love geeksforgeeks.
I love Python programming.

Note: For Formatting the integers or floating numbers the original method can be used in the {}. like ‘{%5.2f}’ or with the numbers we can write it as ‘{0:5.2f}’. We can also use string module ‘%’ operator to format our output.
nidhi_biet
python-basics
python-io
Python
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the plot line color from blue to black in Matplotlib?

To change the plot line color from blue to black, we can use setcolor() method−
Create x and y data points using numpy.
Plot line x and y using plot() method; store the returned value in line.
Set the color as black using set_color() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = 4 * x + 5
line, = plt.plot(x, y, c='b')
line.set_color('black')
plt.show()
Groovy - subString()

Returns a new String that is a substring of this String. This method has 2 different variants
String substring(int beginIndex) − Pad the String with the spaces appended to the right.
String substring(int beginIndex) − Pad the String with the spaces appended to the right.
Syntax
String substring(int beginIndex)

Parameters
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
Return Value − The specified substring.
String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.
String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.
Syntax
String substring(int beginIndex, int endIndex)

Parameters
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
endIndex − the end index, exclusive.
endIndex − the end index, exclusive.
Return Value − The specified substring.
Following is an example of the usage of both variants −
class Example { 
   static void main(String[] args) { 
      String a = "HelloWorld"; 
      println(a.substring(4)); 
      println(a.substring(4,8));
   }
}
When we run the above program, we will get the following result −
oWorld 
oWor


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Count square and non-square numbers before n in C++

We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N.
Traverse all numbers from 1 to N and check if it is a perfect square. If floor(sqrt(i))==ceil(sqrt(i)).
Then the number is a perfect square.
Perfect squares below N can be found using formula: floor(sqrt(N)).
Let’s understand with examples.
Input 
N=20
Output 
Count of square numbers: 4
Count of non-square numbers: 16
Explanation 
Square numbers are 1, 4, 9 and 16. Rest all are non-squares and less than 20.
Input 
N=40
Output 
Count of square numbers: 6
Count of non-square numbers: 34
Explanation 
Square numbers are 1, 4, 9, 16, 25, 36. Rest all are non-squares and less than 40.
We take integer N.
We take integer N.
Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares.
Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares.
Take the initial variable count as 0.
Take the initial variable count as 0.
Traverse using for loop from i=1 to i<=n
Traverse using for loop from i=1 to i<=n
If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count.
If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count.
At the end of all loops count will have a total number that are perfect squares.
At the end of all loops count will have a total number that are perfect squares.
N-squares will be numbers that are non squares
N-squares will be numbers that are non squares
 Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int squareNums(int n){
   int count = 0;
   for (int i = 1; i <= n; i++){
      if(floor(sqrt(i))==ceil(sqrt(i)))
         { count++; }
   }
   return count;
}
int main(){
   int N = 40;
   int squares=squareNums(N);
   cout <<endl<<"Count of squares numbers: "<<squares;
   cout <<endl<<"Count of non-squares numbers: "<<N-squares;
   return 0;
}
If we run the above code it will generate the following output −
Count of squares numbers: 6
Count of non-squares numbers: 34
We take integer N.
We take integer N.
Take variable squares = floor(sqrt(N)).
Take variable squares = floor(sqrt(N)).
Variable squares will have a number of perfect squares below N.
Variable squares will have a number of perfect squares below N.
N-squares will be the number of non-squares below N.
N-squares will be the number of non-squares below N.
 Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main(){
   int N = 40;
   int squares=floor(sqrt(N));
   cout <<endl<<"Count of squares numbers: "<<squares;
   cout <<endl<<"Count of non-squares numbers: "<<N-squares;
   return 0;
}
If we run the above code it will generate the following output −
Count of squares numbers: 6
Count of non-squares numbers: 34
Laravel - Retrieve Records

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table.
$query(string) − query to execute in database
$bindings(array) − values to bind with queries
Step 1 − Execute the below command to create a controller called StudViewController.
php artisan make:controller StudViewController --plain

Step 2 − After the successful execution of step 1, you will receive the following output −
Step 3 − Copy the following code to file
app/Http/Controllers/StudViewController.php
app/Http/Controllers/StudViewController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudViewController extends Controller {
   public function index() {
      $users = DB::select('select * from student');
      return view('stud_view',['users'=>$users]);
   }
}
Step 4 − Create a view file called resources/views/stud_view.blade.php and copy the following code in that file.
resources/views/ stud_view.blade.php
<html>
   
   <head>
      <title>View Student Records</title>
   </head>
   
   <body>
      <table border = 1>
         <tr>
            <td>ID</td>
            <td>Name</td>
         </tr>
         @foreach ($users as $user)
         <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
         </tr>
         @endforeach
      </table>
   </body>
</html>
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('view-records','StudViewController@index');

Step 6 − Visit the following URL to see records from database.
http://localhost:8000/view-records

Step 7 − The output will appear as shown in the following image.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
Difference between print() and println() in Java

As we know in Java these both methods are primarily used to display text from code to console. Both these methods are of PrintStream class and are called on static member 'out' of 'System' class which is a final type class.
The following are the important differences between print() and println().
JavaTester.java
import java.io.*;
class JavaTester {
   public static void main(String[] args){
      System.out.print("Hello");
      System.out.print("World");
   }
}
HelloWorld
JavaTester.java
import java.io.*;
class JavaTester {
   public static void main(String[] args){
      System.out.println("Hello");
      System.out.println("World");
   }
}
Hello
World
How to Install Python Pycharm on Linux? - GeeksforGeeks

06 Oct, 2021
Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python.
Installing Python: Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T
Now run the following command:For Python2
python --version

For Python3.x
python3.x --version

If Python is already installed, it will generate a message with the Python version available.
If Python is not present, go through How to install Python on Linux? and follow the instructions provided.
Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its Setup.
Begin setting up PyCharm:
Download the tar.gz file for PyCharm:
Extract Files to a Folder:
Extraction Process:
Extracted File for PyCharm:
Open Terminal in bin Folder:Go to home -> nikhil -> Documents -> pycharm-community-2019.3.1 -> bin and open Terminal Window
Command to Start PyCharm:In the terminal window, type the following command to start PyCharm../pycharm.sh
./pycharm.sh
Finished Setup:
how-to-install
python-basics
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Add hover color to a table with Bootstrap

To add hover color to table, use the table-hover class. You can try to run the following code to implement the table-hover class:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-hover table-bordered table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
               <th>Country</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Messi</td>
               <td>1</td>
               <td>Argentina</td>
            </tr>
            <tr>
               <td>Neymar</td>
               <td>2</td>
               <td>Brazil</td>
            </tr>
            <tr>
               <td>Ronaldo</td>
               <td>3</td>
               <td>Portugal</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
Python | Numpy np.fft() method - GeeksforGeeks

21 Nov, 2019
With the help of np.fft() method, we can get the 1-D Fourier Transform by using np.fft() method.
Syntax : np.fft(Array)Return : Return a series of fourier transformation.
Example #1 :In this example we can see that by using np.fft() method, we are able to get the series of fourier transformation by using this method.
# import numpyimport numpy as np  a = np.array([5, 4, 6, 3, 7])# using np.fft() methodgfg = np.fft.fft(a)  print(gfg)
Output :
[25. + 0.j 1.11803399 + 1.08981379j -1.11803399 + 4.61652531j-1.11803399 – 4.61652531j 1.11803399 – 1.08981379j]
Example #2 :
# import numpyimport numpy as np  a = np.array([-5.5, 4.4, -6.6, 3.3, -7.7])# using np.fft() methodgfg = np.fft.fft(a)  print(gfg)
Output :
[-12.1 + 0.j -3.85 – 5.68870985j -3.85 – 16.52766106j-3.85 + 16.52766106j -3.85 + 5.68870985j]
Python numpy-Matrix Function
Python-numpy
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
C# Average Method

To find the average of integers in C#, use the Queryable Average() method.
Let’s say the following is our integer array.
var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };
Now, use the Average() method to get the average of the elements.
double avg = Queryable.Average(arr.AsQueryable());
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };
      double avg = Queryable.Average(arr.AsQueryable());
      Console.WriteLine("Average = "+avg);
   }
}
Average = 38.375
R – NonLinear Least Square

22 Apr, 2020
In non-linear function, the points plotted on the graph are not linear and thus, do not give a curve or line on the graph. So, non-linear regression analysis is used to alter the parameters of the function to obtain a curve or regression line that is closed to your data.To perform this, Non-Linear Least Square approach is used to minimize the total sum of squares of residual values or error values i.e., the difference between vertical points on the graph from regression line and will fit the non-linear function accordingly.
Mathematical Formula:
where,
r is residual or error value between 2 points.
Above mathematical function to find minimum residual function can be performed in R using resid() function.
Regression analysis is widely used in all types of business issues to perform a smart decision or predicting the future by altering a factor of their business.In R language, Non-linear Least Square function is represented as –Syntax:
nls(formula, start)

where,
formula indicates the model formula i.e., non-linear functionstart is a list of starting estimates
Note: To know about more optional parameters of nls(), use below command in R console –
help("nls")

Example 1 :In this example, a non-linear function is taken and plotted on the graph as points.
# defining x and y coordinatesx <- seq(0, 10, 0.1)y <- rnorm(101, 5, 1)   # output to be present as PNG filepng(file ="nls.png")   # Taking the model to get fittedm <- nls(y~a * x ^ 3 + b * x + c,          start = list(a = 1, b = 2, c = 1))   # plot the graphplot(x, y, col.lab ="darkgreen",            col.axis ="darkgreen")   # plot the graph with new fitting line# or regression linelines(x, predict(m))   # saving the filedev.off()   # print minimum residual or error valueprint(sum(resid(m)^2))
Output :
[1] 106.4507
Example 2 :In this example, below code is accepting a non-linear function as shown:
Further plotting the points and regression line and also, finding out the goodness of fit also by using cor() method.
# creating sequence of 101 values from 0 to 100x <- seq(0, 100, 1)   y<-((runif(1, 10, 20)*x)/(runif(1, 0, 10) + x)) +                           rnorm(101, 0, 1)   # output to be present as PNG filepng(file ="nls2.png")   # using starting values in nls() function# to not get a warningm<-nls(y~a * x/(b + x), start = list(a = 1, b = 2))   # goodness of fitcor(y, predict(m))   # minimized residual valuesum(resid(m)^2)   # plotting points on graphplot(x, y)   # finding regression linelines(x, predict(m))   # saving the filedev.off()
Output :
[1] 0.9622681
[1] 108.1481

Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | thead bgcolor Attribute

31 Dec, 2019
The HTML thead bgcolor Attribute is used to specify the background color of a table head. It is not supported by HTML 5.
Syntax:
<thead bgcolor= "color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the text color by using the color name. For example “red”.
hex_number: It sets the text color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)”.
Example:
<!DOCTYPE html> <html>   <head>     <title>         HTML thead bgcolor Attribute     </title> </head>   <body>     <h1>GeeksforGeeks</h1>       <h2>HTML thead bgcolor Attribute</h2>       <table border="1"        width="500">         <thead bgcolor="red">             <tr>                 <th>NAME</th>                 <th>AGE</th>                 <th>BRANCH</th>             </tr>         </thead>           <tbody align="center" >             <tr>                 <td>BITTU</td>                 <td>22</td>                 <td>CSE</td>             </tr>         </tbody>     </table> </body>   </html> 
Output :
Supported Browsers: The browser supported by HTML <thead> bgcolor attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
Change Legend Size in Base R Plot

30 May, 2021
In this article, we will be looking at the approach to change the size of the legend in the plot in the R programming language.
To change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot.
Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
Parameters:
x and y: These are co-ordinates to be used to position the legend
legend: Text of the legend
fill: Colors to use for filling the boxes with legend text
col: Colors of lines
bg: It defines background color for the legend box
cex: Used for scaling
title: Legend title        (optional)
text.font: An integer specifying the font style of the legend (optional)
Returns: Legend plot
cex is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc. 
Example 1:
R
x1 <- c(1,8,5,3,8,7)                y1 <- c(4,6,3,8,2,7)plot(x1,y1,cex=.8,pch=1,col="red")  x2<-c(4,5,8,6,4)y2<-c(9,8,2,3,1)  x3<-c(2,1,6,7,4)y3<-c(7,9,1,5,2)  points(x2,y2,cex=.8,pch=2,col="blue")points(x3,y3,cex=.8,pch=3,col="green")  legend("topright",c("gfg1","gfg2","gfg3"),       cex=0.5,col=c("red","blue","green"),       pch=c(1,2,3))
Output:
Example 2:
R
gfg_data <- matrix(c(1,2,3,4,5,6,7,8,9,10), ncol = 5)  colnames(gfg_data) <- paste0("Gfg", 1:5)rownames(gfg_data) <- c('A','B')  gfg_data        barplot(gfg_data,                           col = 1:nrow(gfg_data))  legend("topright",       legend = rownames(gfg_data),       pch = 15,       col = 1:nrow(gfg_data),cex=2.5)
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
JavaScript String fromCharCode() Method

05 Oct, 2021
Below is the example of the String.fromCharCode() Method.
Example:<script> function func() {     var str = String.fromCharCode(71, 70, 71);     document.write(str); } func(); </script> 
<script> function func() {     var str = String.fromCharCode(71, 70, 71);     document.write(str); } func(); </script> 
Output:GFG

GFG

String.fromCharCode() method is used to create a string from the given sequence of UTF-16 code units.
Syntax:
String.fromCharCode(n1, n2, ..., nX)

Arguments:The method takes the UTF-16 Unicode sequences as its argument. The number of arguments to this method depends upon the number of characters to be joined as a string. The range of the numbers is between 0 and 65535
Return value:The return value of this method is a string containing the characters whose UTF-16 codes were passed to the method as arguments.
Examples for the above method are provided below:
Example 1:
print(String.fromCharCode(65, 66, 67));  

Output:
ABC

In this example the method fromCharCode() converts the UTF-16 codes into their equivalent characters and returns the string containing them as the answer. In this case the answer is ABC.
Example 2:
String.fromCharCode(0x12014);

Output:
—

In this example the method fromCharCode() converts the UTF-16 code into its equivalent character and returns the string containing it as the answer. In this case the answer is —.
Codes for the above method are provided below:
Program 1:
<script>// JavaScript to illustrate fromCharCode() methodfunction func() {      // UTF-16 codes to be converted into characters    var str = String.fromCharCode(65, 66, 67);    document.write(str);}  func();</script>
Output:
ABC

Program 2:
<script>// JavaScript to illustrate fromCharCode() methodfunction func() {      // UTF-16 code to be converted into character    var str = String.fromCharCode(0x12014);    document.write(str); }  func();</script>
Output:
—

Supported Browsers:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 4 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Shallow and Deep copy of a class

16 Nov, 2020
Shallow Copy: Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can have pointers that reference constant underlying knowledge.
Deep Copy: Deep repetition truly clones the underlying data. It is not shared between the first and therefore the copy.
Below is the tabular Difference between the Shallow Copy and Deep Copy: 
 
Below is the program to explain the shallow and deep copy of the class.
 
Python3
# Python3 implementation of the Deep# copy and Shallow Copyfrom copy import copy, deepcopy # Class of Carclass Car:  def __init__(self, name, colors):          self.name = name     self.colors = colors     honda = Car("Honda", ["Red", "Blue"]) # Deepcopy of Hondadeepcopy_honda = deepcopy(honda)deepcopy_honda.colors.append("Green")print(deepcopy_honda.colors, \      honda.colors) # Shallow Copy of Hondacopy_honda = copy(honda) copy_honda.colors.append("Green")print(copy_honda.colors, \      honda.colors)
['Red', 'Blue', 'Green'] ['Red', 'Blue']
['Red', 'Blue', 'Green'] ['Red', 'Blue', 'Green']



 
pulkitagarwal03pulkit
python
Difference Between
Programming Language
Python
python
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
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Decorators with parameters in Python
C# | Data Types
Groupon Archives - GeeksforGeeks

Longest Palindromic Substring | Set 1
Longest Palindromic Substring | Set 2
Search in a row wise and column wise sorted matrix
Groupon Interview Experience | Set 4 (SDE2 for Experienced)
Groupon Interview | Set 1 (SDE Profile - Fresher)
Git - Difference Between Git Fetch and Git Pull
Unit Testing in Spring Boot Project using Mockito and Junit
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
Create a Date object using the Calendar class in Java

For using Calendar class, import the following package.
import java.util.Calendar;
Now, let us create an object of Calendar class.
Calendar calendar = Calendar.getInstance();
Set the date, month and year.
calendar.set(Calendar.YEAR, 2018);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DATE, 18);
Create a Date object using Calendar class.
java.util.Date dt = calendar.getTime();
The following is an example.
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      // Set year, month and date
      calendar.set(Calendar.YEAR, 2018);
      calendar.set(Calendar.MONTH, 11);
      calendar.set(Calendar.DATE, 18);
      // util date object
      java.util.Date dt = calendar.getTime();
      System.out.println("Date: "+dt);
   }
}
Date: Tue Dec 18 08:29:51 UTC 2018
PHP - Function MySQLi Fetch Array

mysqli_fetch_array(result,resulttype);

It is used to fetchs a result row as an associative array
It returns an array of strings that corresponds to the fetched row.
result
It specifies the result set identifier
resulttype
It specifies what type of array that should be produced
Try out the following example
<?php
   $connection_mysql = mysqli_connect("localhost","username","password","db");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   $sql = "SELECT name,age FROM emp";
   $result = mysqli_query($connection_mysql,$sql);
   $row = mysqli_fetch_array($result,MYSQLI_NUM);
   
   print $row[0];
   print "\n";
   print $row[1];
   
   $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
   print $row["name"];
   print "\n";
   print $row["age"];
   
   mysqli_free_result($result);
   mysqli_close($connection_mysql);
?>

    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
Adding a scatter of points to a boxplot using Matplotlib

To add a scatter of points to a boxplot using matplotlib, we can use boxplot() method and enumerate the Pandas dataframe to get the x and y data points to plot the scatter points.
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 dataframe using DataFrame class with the keys, Box1 and Box2.
Make a dataframe using DataFrame class with the keys, Box1 and Box2.
Make boxplots from the dataframe.
Make boxplots from the dataframe.
Find x and y for the scatter plot using data (Step 1).
Find x and y for the scatter plot using data (Step 1).
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = pd.DataFrame({"Box1": np.random.rand(10), "Box2": np.random.rand(10)})
data.boxplot()
for i, d in enumerate(data):
   y = data[d]
   x = np.random.normal(i + 1, 0.04, len(y))
   plt.scatter(x, y)
plt.show()
DAX Information - ISNUMBER function

Checks whether a value is a number, and returns TRUE or FALSE.
ISNUMBER (<value>) 

value
The value you want to test.
TRUE or FALSE.
= ISNUMBER (5.0): The DAX formula returns TRUE. 
= ISNUMBER("AB"): This DAX formula returns FALSE. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to write :hover condition for a:before and a:after in CSS?

18 May, 2022
The :before and :after selectors in CSS is used to add content before and after an element. The :hover is pseudo-class and :before & :after are pseudo-elements. In CSS, pseudo-elements are written after pseudo-class. 
Syntax: 
a:hover::before {
    // CSS Property
}
a:hover::after {
    // CSS Property
}
In CSS3 double colon(::) is used to denote pseudo-element. For IE8 or older use a single colon (CSS2 syntax) is used. 
Example 1: This example uses :hover condition for a:before and a:after in an element. 
html
<!DOCTYPE html><html>   <head>       <title>           :hover condition for a:before           and a:after       </title>      <!-- Style to add hover condition -->      <style>         a:hover::before {            content: "Before -";         }         a:hover::after {            content: "-after";         }      </style>   </head>       <body>      <a href="#" > Hover here </a>   </body></html>
Output:
HTML Before Mouse move over: 
   
After Mouse move over:
  
Example 2: This example uses :hover condition for a:before and a:after in an element. 
html
<!DOCTYPE html><html>    <head>        <title>            :hover condition for a:before            and a:after        </title>                <style>            a:hover::before {                content: "Before -";                background-color: green;            }            a:hover::after{                content: "-after";                background-color: green;            }        </style>    </head>        <body>        <a href="#" > GeeksForGeeks </a>    </body></html>
Output:
HTML Before Mouse move over:
  
After Mouse move over :
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
hardikkoriintern
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to count the number of occurrences of a specific value in a column with a single MySQL query?

For this, you can use GROUP BY clause along with IN(). Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Chris |
|  3 | David |
|  4 | Chris |
|  5 | Chris |
|  6 | John  |
|  7 | Carol |
|  8 | Sam   |
+----+-------+
8 rows in set (0.00 sec)
Now, count the number of occurrences of a specific value in a column with a single query −
mysql> select Name,count(*) AS Occurrences from DemoTable
   -> where Name in('John','Chris') group by Name;
This will produce the following output −
+-------+-------------+
| Name  | Occurrences |
+-------+-------------+
| John  |           2 |
| Chris |           3 |
+-------+-------------+
2 rows in set (0.00 sec)
HTML | DOM onblur Event

28 Jun, 2019
The HTML DOM onblur event occurs when an object loses focus. The onblur event is the opposite of the onfocus event.The onblur event is mostly used with form validation code (e.g. when the user leaves a form field).
Syntax:
In HTML:
<element onblur="myScript">
In JavaScript:
object.onblur = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("blur", myScript);
Example: Using HTML
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onblur event</h2> Email:        <input type="email" id="email" onblur="myFunction()">          <script>            function myFunction() {                alert("Focus lost");            }        </script>    </center></body>  </html>
Output:
Example: In JavaScript:
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onblur event</h2>        <input type="email" id="email">          <script>            document.getElementById("email").onblur = function() {                myFunction()            };              function myFunction() {                alert("Input field lost focus.");            }        </script>    </center></body>  </html>
Output:
Example: In JavaScript, using the addEventListener() method
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onblur event</h2>        <input type="email" id="email">          <script>            document.getElementById(              "email").addEventListener("blur", myFunction);              function myFunction() {                alert("Input field lost focus.");            }        </script>    </center></body>  </html>
Output:
Supported Browsers: The browsers supported by HTML DOM onblur Event are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Design a web page using HTML and CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Python | Button Action in Kivy

29 Jun, 2021
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. 
???????? Kivy Tutorial – Learn Kivy with Examples.
Now in this article, we will learn how to build a button in kivy by using the kv file, just like the button we use in calculators and many more places.Buttons : The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). To bind the action of button when it pressed we have the function on_press. Basic Approach for the button Actions using .kv file:  
1) Import kivy
2) Import kivy app
3) Import Box layout
4) create .kv with label and button
5) Bind button to a method
6) create method
Now let’s code the .py file. 
Python3
# import kivy moduleimport kivy   # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1")   # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # BoxLayout arranges children# in a vertical or horizontal box.from kivy.uix.boxlayout import BoxLayout # class in which we are defining action on clickclass RootWidget(BoxLayout):     def btn_clk(self):        self.lbl.text = "You have been pressed"  # creating action class and calling# Rootwidget by returning itclass ActionApp(App):     def build(self):        return RootWidget() # creating the myApp root for ActionApp() class myApp = ActionApp() # run function runs the whole program# i.e run() method which calls the# target function passed to the constructor.myApp.run()
  .kv file of the above code [action.kv] :Must be saved with the name of the ActionApp class. i.e action.kv.  
Python3
# Base widget from Rootwidget class in .py file<RootWidget>:     # used to change the label text    # as in rootwidget class    lbl:my_label     # child that is an instance of the BoxLayout    BoxLayout:        orientation: 'vertical'        size: [1, .25]     Button:        text:'Click Me'        font_size:"50sp"        color: [0, 255, 255, .67]        on_press: root.btn_clk()     Label:        # id is limited in scope to the rule        # it is declared in. An id is a weakref        # to the widget and not the widget itself.        id: my_label        text: 'No click Yet'        color: [0, 84, 80, 19]
Output: 
 
Video explaining output:  
Note: BoxLayout arranges widgets in either in a vertical fashion that is one on top of another or in a horizontal fashion that is one after another. 
rajeev0719singh
Python-gui
Python-kivy
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
ML | Label Encoding of datasets in Python

18 May, 2022
In machine learning, we usually deal with datasets that contain multiple labels in one or more than one columns. These labels can be in the form of words or numbers. To make the data understandable or in human-readable form, the training data is often labelled in words. 
Label Encoding refers to converting the labels into a numeric form so as to convert them into the machine-readable form. Machine learning algorithms can then decide in a better way how those labels must be operated. It is an important pre-processing step for the structured dataset in supervised learning.
Example : Suppose we have a column Height in some dataset. 
After applying label encoding, the Height column is converted into: 
where 0 is the label for tall, 1 is the label for medium, and 2 is a label for short height.
We apply Label Encoding on iris dataset on the target column which is Species. It contains three species Iris-setosa, Iris-versicolor, Iris-virginica. 
Python3
# Import libraries import numpy as npimport pandas as pd  # Import datasetdf = pd.read_csv('../../data/Iris.csv')  df['species'].unique()
Output: 
array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)
After applying Label Encoding – 
Python3
# Import label encoderfrom sklearn import preprocessing  # label_encoder object knows how to understand word labels.label_encoder = preprocessing.LabelEncoder()  # Encode labels in column 'species'.df['species']= label_encoder.fit_transform(df['species'])  df['species'].unique()
Output: 
array([0, 1, 2], dtype=int64)
Limitation of label Encoding Label encoding converts the data in machine-readable form, but it assigns a unique number(starting from 0) to each class of data. This may lead to the generation of priority issues in the training of data sets. A label with a high value may be considered to have high priority than a label having a lower value.
ExampleAn attribute having output classes Mexico, Paris, Dubai. On Label Encoding, this column lets Mexico is replaced with 0, Paris is replaced with 1, and Dubai is replaced with 2. With this, it can be interpreted that Dubai has high priority than Mexico and Paris while training the model, But actually, there is no such priority relation between these cities here. 
deepak_jain
tanwarsinghvaibhav
akshaysingh98088
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Checking if structure is empty or not in Golang - GeeksforGeeks

04 May, 2020
If the structure is empty means that there is no field present inside that particular structure. In Golang, the size of an empty structure is zero. Whenever the user wants to know if the created structure is empty or not, he can access the structure in the main function through a variable. If there doesn’t exist any field inside the structure, he can simply display that the structure is empty.
Syntax:
type structure_name struct {
    }

There are different ways to find out whether a structure is empty or not as shown below.
1) To check if the structure is empty:
package main  import (    "fmt")  type Book struct {}  func main() {    var bk Book    if (Book{} == bk) {        fmt.Println("It is an empty structure.")    } else {        fmt.Println("It is not an empty structure.")    }}
Output:
It is an empty structure.
Explanation: In the above example, we have created a structure named “Book” in which there is no existing field. In the main function, we created a variable to access our structure. Since there are no fields specified in the structure, it will print that it is an empty structure. Now, if there are fields present in the structure, it will return the message that it is not an empty structure as shown below:
package main  import (    "fmt")  type Book struct {    qty int}  func main() {    var bk Book    if (Book{500} == bk) {        fmt.Println("It is an empty structure.")    } else {        fmt.Println("It is not an empty structure.")    }}
Output:
It is not an empty structure.
Explanation: In the above example, we have created a structure named “Book” in which we have declared a field named “qty” of data type int. In the main function, we created a variable to access our structure. Since there is a field present in the structure, it will print that it is not an empty structure.
2) Using switch case:
package main  import (    "fmt")  type articles struct {}  func main() {    x := articles{}      switch {    case x == articles{}:        fmt.Println("Structure is empty.")    default:        fmt.Println("Structure is not empty.")    }}
Output:
Structure is empty.
Explanation: In this example, we created a structure named “articles” in which no fields are declared. Inside the main function, we created a variable “x” and used a switch case to access our structure. Since there are no fields present in the structure, the program will display that the structure is empty.
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to convert a string in lower case in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
How to Parse JSON in Golang?
Different Ways to Find the Type of Variable in Golang