code-rag-bench/online-tutorials huggingface dataset:
How to Convert Bytes to String in Python ? - GeeksforGeeks

11 Dec, 2020
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
We can convert bytes to string using the below methods:
Method #1: Using decode() method
This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode.
Python3
# Program for converting bytes # to string using decode()  data = b'GeeksForGeeks'  # display inputprint('\nInput:')print(data)print(type(data))  # convertingoutput = data.decode()  # display outputprint('\nOutput:')print(output)print(type(output))
Output:
Input:
b'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>
Method #2: Using str() function
The str() function of Python returns the string version of the object.
Python3
# Program for converting bytes to string using decode()data = b'GeeksForGeeks'  # display inputprint('\nInput:')print(data)print(type(data))  # convertingoutput = str(data, 'UTF-8')  # display outputprint('\nOutput:')print(output)print(type(output))
Output:
Input:
b'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>
Method #3: Using codecs.decode() method
This method is used to decode the binary string into normal form.
Python3
# Program for converting bytes to string using decode()  # import required moduleimport codecs  data = b'GeeksForGeeks'  # display inputprint('\nInput:')print(data)print(type(data))  # convertingoutput = codecs.decode(data)  # display outputprint('\nOutput:')print(output)print(type(output))
Output:
Input:
b'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>
python-basics
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.swapaxes() - GeeksforGeeks

23 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.swapaxes() function interchange axes and swap values axes appropriately. The function takes the name of the axes to be interchanged with as parameter. Based on the axes, it accordingly changes the data as well.
Syntax: DataFrame.swapaxes(axis1, axis2, copy=True)
Parameters :axis1 : name of the first axes { string}axis2 : name of the second axes { string}
Returns : y : same as input
Example #1: Use swapaxes() function to swap the axes of the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[10, 11, 7, 8, 5],                   "B":[21, 5, 32, 4, 6],                   "C":[11, 21, 23, 7, 9],                   "D":[1, 5, 3, 8, 6]},                    index =["A1", "A2", "A3", "A4", "A5"])  # Print the dataframedf
# interchange the index and columns axisdf.swapaxes("index", "columns")
Output : Example #2: Use swapaxes() function to swap the index and column axes with each other. The dataframe has some missing values.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[1, 5 + 1j, 3+.2j, 4 + 1j, None],                   "B":[3, 2, 4, 3, 4],                   "C":["brook", "daniela", "samantha", "hayden", "nathan"],                   "D":[None, 3, 6, None, 7]},                   index =["A1", "A2", "A3", "A4", "A5"])  # Print the dataframedf
# interchange the columns and index axis  df.swapaxes("index", "columns")
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
sum() function in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Convert integer to string in Python
jQuery toggleClass() with Examples

The toggleClass() method in jQuery is used to toggle between adding or removing one or more classes from selected elements.
The syntax is as follows −
$(selector).toggleClass(classname,func(index,currentclass),switch)
Above, class name specifies one or more class names to add or remove, whereas func is a function that returns one or more class names to add or remove.
Let us now see an example to implement the jQuery toggleClass() method −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         $("p").toggleClass("demo");
      });
   });
</script>
<style>
.demo {
   background-color: orange;
   color: white;
   border: 1px solid blue;
}
</style>
</head>
<body>
<h2>Exam Info</h2>
<p>Examination begins on 24th December. The students are requested to submit project report before 15th December.</p>
<button>Toggle</button>
</body>
</html>
This will produce the following output −
On clicking Toggle, the appearance of the above text will change −
On clicking Toggle again, the appearance gets back to the initial stage −
Comparing Timestamp in Python – Pandas

To compare timestamps, we can use index operator i.e. the square brackets. At first, import the required library −
import pandas as pd
Create a DataFrame with 3 columns −
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
      ],
      "Date_of_Service": [
          pd.Timestamp("2021-11-10"),
          pd.Timestamp("2021-12-11"),
          pd.Timestamp("2021-11-25"),
          pd.Timestamp("2021-11-29"),
          pd.Timestamp("2021-08-20"),
      ]
   })


Let us now compare some timestamps from both the date columns −
timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0])
timestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1])
Compare all the timestamps −
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
Following is the complete code −
import pandas as pd

# create a dataframe with 3 columns
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
      ],
      "Date_of_Service": [
         pd.Timestamp("2021-11-10"),
         pd.Timestamp("2021-12-11"),
         pd.Timestamp("2021-11-25"),
         pd.Timestamp("2021-11-29"),
         pd.Timestamp("2021-08-20"),
      ]
   })

print"DataFrame...\n", dataFrame

# compare specific timestamps
timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0])
timestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1])
print"\nDifference between Car 1 Date of Purchase and Service \n",timestamp1_diff
print"\nDifference between Car 2 Date of Purchase and Service \n",timestamp2_diff

# compare all timestamps by finding difference
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
print"\nDifference between two Timestamps: \n",timestamp_diff
This will produce the following output −
DataFrame...
        Car   Date_of_Purchase   Date_of_Service
0      Audi         2021-06-10        2021-11-10
1     Lexus         2021-07-11        2021-12-11
2     Tesla         2021-06-25        2021-11-25
3  Mercedes         2021-06-29        2021-11-29
4       BMW         2021-03-20        2021-08-20

Difference between Car 1 Date of Purchase and Service
153 days 00:00:00

Difference between Car 2 Date of Purchase and Service
153 days 00:00:00

Difference between two Timestamps:
0   153 days
1   153 days
2   153 days
3   153 days
4   153 days
dtype: timedelta64[ns]
Faulty calculator using Python - GeeksforGeeks

01 Jul, 2021
A faulty calculator is simply a calculator which operates simple tasks, but in some cases (set by the programmer) it gives the wrong output. You all must be wondering why do we need a faulty calculator? This type of calculator is not needed unless you want to prank someone or prove them wrong in case of some maths problem.
Approach:
First, we take input from the user that what he/she wants to do
Then we write the code of Addition, Subtraction, Multiplication, and Division
And lastly, we insert those cases that we want wrong results.
Implementation:
Python
print("what type of arithmetic operation you want to do?\n"      "type + for addition\n"      "type - for subtraction\n"      "type / for division\n"      "type* for multiplication\n")  # taking inputtype_of_calculation = input() print("enter the first number")A = int(input()) print("enter the second number\n")B = int(input()) b = "+"c = "-"d = "*"e = "/"  # setting normal and false condition for calculatorif type_of_calculation == b:    # for addition    if (A == 53 and B == 9) or (A == 90 and B == 52):        print(97)    else:        print(A+B)elif type_of_calculation == c:       # for subtraction    print(A-B)elif type_of_calculation == d:       # for multiplication    if A == 45 and B == 3 or A == 4 and B == 67:        print(575)    else:        print(A*B)elif type_of_calculation == e:       # for division    if A == 5 and B == 63:        print(40)    else:        print(A/B)
Output:
For normal condition
For false condition
anikaseth98
school-programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to read all excel files under a directory as a Pandas DataFrame ? - GeeksforGeeks

21 Apr, 2021
In this article, we will see how to read all Excel files in a folder into single Pandas dataframe. The task can be performed by first finding all excel files in a particular folder using glob() method and then reading the file by using pandas.read_excel() method and then displaying the content.
Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’Loop over the list of excel files, read that file using pandas.read_excel().Convert each excel file into a dataframe.Display its location, name, and content.
Import necessary python packages like pandas, glob, and os.
Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’
Loop over the list of excel files, read that file using pandas.read_excel().
Convert each excel file into a dataframe.
Display its location, name, and content.
Below is the implementation.
Python3
# import necessary librariesimport pandas as pdimport osimport glob    # use glob to get all the csv files# in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, "*.xlsx"))    # loop over the list of csv filesfor f in csv_files:        # read the csv file    df = pd.read_excel(f)          # print the location and filename    print('Location:', f)    print('File Name:', f.split("\\")[-1])          # print the content    print('Content:')    display(df)    print()
Output :
Note: The program reads all Excel files in the folder in which the program itself is present.
Picked
Python-excel
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Sum of the Series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... in C++


In this problem, we are given a number n which is the nth term of the series 1/(1*2) + 1/(2*3) +...+ 1/(n*(n+1)). Our task is to create a program to find the sum of the series.
Input 
n = 3
Output 
0.75
Explanation − sum = 1/(1*2) + 1/(2*3) + 1/(3*4) = 1⁄2 + 1⁄6+ 1/12 = (6+2+1)/12 = 9/12 = 3⁄4 = 0.75
A simple solution to the problem is using the loop. And commuting value for each element of the series. Then add them to the sum value.
Initialize sum = 0
Step 1: Iterate from i = 1 to n. And follow :
   Step 1.1: Update sum, sum += 1/ ( i*(i+1) )
Step 2: Print sum.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   double sum = 0.0;
   for (int i = 1; i <= n; i++)
   sum += ((double)1/(i*(i+1)));
   return sum;
}
int main() {
   int n = 5;
   cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333
This solution is not much effective as it uses loops.
An effective approach to solve the problem is using the general formula for the sum of series.
The series is 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...
n-th terms is 1/n(n+1).
an = 1/n(n+1)
an = ((n+1) - n) /n(n+1)
an = (n+1)/n(n+1) - n/ n(n+1)
an = 1/n - 1/(n+1)
sum of the series is
sum = 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ...
Changing each term as in above formula,
sum = 1/1 - 1⁄2 + 1⁄2 - 1⁄3 + 1⁄3 - 1⁄4 + 1⁄4 -1⁄5 + .... 1/n - 1/(n+1)
sum = 1 - 1/(n+1)
sum = (n+1 -1) / (n+1) = n/(n+1)
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   return ((double)n/ (n+1));
}
int main() {
   int n = 5;
   cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333
PHP Exercises With Solutions

Theory of Computation
$str1 = "00004";
$str2 = "008";
$str3 = "00007-STR";
$a = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';

[
	{
	"name" : "John Garg",
	"age"  : "15",
	"school" : "Ahlcon Public school"
	},
	{
	"name" : "Smith Soy",
	"age"  : "16",
	"school" : "St. Marie school"
	},
	{
	"name" : "Charle Rena",
	"age"  : "16",
	"school" : "St. Columba school"
	}
]

$a = array('one' => 'I', 'two' => 'II', 'three' =>'III', 'four' => 'IV');
$quantity1 = 70;
$quantity2 = 100;
$price1 = 35;
$price2 = 30;
How to validate a form using jQuery?

At first you have to make a html form like.
<html>
<body>
<h2>Validation of a form</h2>
<form id="form" method="post" action="">
First name:<br>
<input type="text" name="firstname" value="john">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br>
Email:<br>
<input type="email" name="u_email" value="johndoe@gmail.com">
<br>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now use jQuery validation plugin to validate forms' data in easier way.
first,add jQuery library in your file.
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
then add javascript code:
$(document).ready(function() {
   $("#form").validate();
});
</script>
Then to define rules use simple syntax.
jQuery(document).ready(function() {
   jQuery("#forms).validate({
      rules: {
         firstname: 'required',
         lastname: 'required',
         u_email: {
            required: true,
            email: true,//add an email rule that will ensure the value entered is valid email id.
            maxlength: 255,
         },
      }
   });
});
To define error messages.
messages: {
   firstname: 'This field is required',
   lastname: 'This field is required',
   u_email: 'Enter a valid email',
},
Now finally to submit the form.
submitHandler: function(form) {
   form.submit();
}
How to open a file in append mode with Python?

To open files in append mode, specify 'a' as the mode(a=append). For example,
f = open('my_file.txt', 'a')
file_content = f.read()
f.write('Hello World')
f.close()
Above code opens my_file.txt in append mode and appends the file to contain "Hello World" at the end.
How to multiply two Arrays in JavaScript?

Following is the code to multiply two arrays in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Multiply two Arrays in JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to multiply the above two arrays</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 2, 3, 4, 5];
   let arr1 = [11, 12, 13, 14, 15, 22];
   let multArray = [];
   sampleEle.innerHTML = arr + "<br>" + arr1 + "<br>";
   BtnEle.addEventListener("click", () => {
      for (let i = 0; i < Math.min(arr.length, arr1.length); i++) {
         multArray[i] = arr[i] * arr1[i];
      }
      resEle.innerHTML = "Multiplied array = " + multArray;
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Django Models | Set – 1

21 Jun, 2019
Prerequisites : Django Creating apps
According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
The basics:
Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
With all of this, Django gives you an automatically-generated database-access API.
Django models are used as a structure to define fields and their types which will be saved in the database. Whatever changes we want to make in the database and want to store them in the database permanently are done using Django Models. A table for a phone in the database can be imagined as:
We need to create a new app named product so that we can define all properties of phone described in the above-provided image. Open your terminal and run following command:
python manage.py startapp product
Now, our directory will be:After creating the app, don’t forget to mention it in geeks_site/settings.py under INSTALLED_APPS.
Also, register it with admin by adding following line of code to product/admin.py. By registering it with admin, you make sure that admin of the site will be aware that new table schema for database has been prepared.
   from django.contrib import admin  # Register your models here.from product.models import Phone  admin.site.register(Phone)
Now, navigate to product/models.py. You will see a file with following lines:
   from django.db import models  # Create your models here.
We use a python class to define models which inherit parent class named Model defined in django.db.models package.
Add the following lines of code to this file:
     from django.db import models  # Create your models here.class Phone(models.Model):    Price = models.IntegerField()    RAM = models.IntegerField()    ROM = models.IntegerField()    Front_camera = models.IntegerField()    Rear_camera = models.IntegerField()    Battery = models.IntegerField()    Screen_size = models.DecimalField(max_digits = 2, decimal_places = 1)    Color = models.CharField(max_length = 120)    Quantity = models.IntegerField()
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas DataFrame.values

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.values attribute return a Numpy representation of the given DataFrame.
Syntax: DataFrame.values
Parameter : None
Returns : array
Example #1: Use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# return the numpy representation of # this dataframeresult = df.values  # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame. Example #2: Use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.values attribute to return the numpy representation of the given DataFrame.
# return the numpy representation of # this dataframeresult = df.values  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.values attribute has successfully returned the numpy representation of the given DataFrame.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to open web cam in JavaScript ?

31 Mar, 2021
In this article, we will see how to open a webcam and show a live video using JavaScript. For this we are going to use Navigator media Devices.
Navigator Media Devices: It is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like camera and microphone.
Syntax :
var mediaDevices = navigator.mediaDevices;
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta http-equiv="X-UA-Compatible" content="IE=edge" />    <meta name="viewport"           content="width=device-width, initial-scale=1.0" />    <title>Web Cam</title>    <script>      document.addEventListener("DOMContentLoaded", () => {        var but = document.getElementById("but");        var video = document.getElementById("vid");        var mediaDevices = navigator.mediaDevices;        vid.muted = true;        but.addEventListener("click", () => {            // Accessing the user camera and video.          mediaDevices            .getUserMedia({              video: true,              audio: true,            })            .then((stream) => {                // Changing the source of video to current stream.              video.srcObject = stream;              video.addEventListener("loadedmetadata", () => {                video.play();              });            })            .catch(alert);        });      });    </script>  </head>    <style>    div {      width: 500px;      height: 400px;      border: 2px solid black;      position: relative;    }    video {      width: 500px;      height: 400px;      object-fit: cover;    }  </style>    <body>    <center>      <div>        <video id="vid"></video>      </div>      <br />      <button id="but" autoplay>        Open WebCam      </button>    </center>  </body></html>
Output :
Before clicking the button : 
Before clicking the button : 
After clicking the button : 
After clicking the button : 
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
B and B+ Trees - GeeksforGeeks

22 Aug, 2021
Insertion of 3 keys
10 20 30

Insertion of 4th key (1st split)
     30
   /   \
10*20   40


Insertion of 5th key no split 
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 5
      30
   /     \
5*10*20   40


Insertion of 6th key (2nd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 6
      8*30
   /   |   \
5    10*20   40 


Insertion of 7th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 15
        8*30
   /     |    \
5    10*15*20   40 



Insertion of 8th key (3rd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 12
      8*12*30
   /   /   \  \
 5   10 15*20  40 


Insertion of 9th key 
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 17
      8*12*30
   /  /   \   \
5  10 15*17*20 40 

Insertion of 10th key (4th and 5th Splits)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 13
          12
       /      \
      8       15*30
   /   \     /  |  \  
  5    10  13 17*20   40 

  Disk Block size = 1024 bytes
  
  Data Record Pointer size, r = 7 bytes
  Value size, V = 9 bytes
  Disk Block ptr, P = 6 bytes 
A) 

B) 

C) 

D) None of the above

Size of 1 record = 8 + 4 = 12

Let the order be N.

No. of index values per block = N - 1

(N - 1) 12 + 4 = 512

12N - 12 + 4 = 512

16N = 1009

N = 43.3333
We can get all values in range from 7 to 59 by accessing 5 nodes.  
1) First search 7 in a leaf node.
2) Once 7 is found, linearly traverse till 15 is found.

See following diagram 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
How to draw an SVG file on an HTML5 canvas?

To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas.
You can try the following code to draw an SVG file on an HTML canvas
<!DOCTYPE html>
<html>
   <head>
      <title>SVG file on HTML Canvas </title>
   </head>
   <body>
      <canvas id="myCanvas" style="border:2px solid green;" width="300" height="300"></canvas>
      <script>
         var canvas = document.getElementById('myCanvas');
         var ctx = canvas.getContext('2d');
         var data = '<svg xmlns="http://www.w3.org/2000/svg" width="300"
         height="200">' +
            '<foreignObject width="100%" height="100%">' +
               '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:50px">' +
                  'Simply Easy ' +
                  '<span style="color:blue;">' +
                  'Learning</span>' +
               '</div>' +
            '</foreignObject>' +
         '</svg>';
         var DOMURL = window.URL || window.webkitURL || window;
         var img1 = new Image();
         var svg = new Blob([data], {type: 'image/svg+xml'});
         var url = DOMURL.createObjectURL(svg);
         img1.onload = function() {
            ctx.drawImage(img1, 25, 70);
            DOMURL.revokeObjectURL(url);
         }
         img1.src = url;
      </script>
   </body>
</html>
PyQt5 – How to make Round Radio Button ?

22 Apr, 2020
In this article we will see how to create round radio button. By default the shape of radio button is rectangular although if we set width equal to the height it become square. Below is the representation of normal bordered radio button vs the radio button round in shape. 
In order to do this we have to do the following :
1. Create a radio button.2. Set its width equal to height to make it square3. Add border to it with the help of setStyleSheet method.4. Set border radius to half of width.
Style sheet code to do this –
QRadioButton
{
border : 3px solid black;
border-radius : 60px;
}

Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a radio button        self.radio_button = QRadioButton(self)          # setting geometry of radio button        self.radio_button.setGeometry(200, 150, 120, 120)          # setting text to radio button        self.radio_button.setText("Radio Button")          # changing style sheet code of radio button setting border to        # radio button and changing radius to half of width        self.radio_button.setStyleSheet("QRadioButton"                                        "{"                                        "border : 3px solid black;"                                        "border-radius : 60px;"                                        "}")    # 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.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Local variables in Java

Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Here, age is a local variable. This is defined inside pupAge()method and its scope is limited to only this method.
Live Demo
public class Test {
   public void pupAge() {
      int age = 0;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
Puppy age is: 7
PyQt - QCheckBox Widget

A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. Its common use is in a scenario when the user is asked to choose one or more of the available options.
Unlike Radio buttons, check boxes are not mutually exclusive by default. In order to restrict the choice to one of the available items, the check boxes must be added to QButtonGroup.
The following table lists commonly used QCheckBox class methods −
setChecked()
Changes the state of checkbox button
setText()
Sets the label associated with the button
text()
Retrieves the caption of the button
isChecked()
Checks if the button is selected
setTriState()
Provides no change state to checkbox
Each time a checkbox is either checked or cleared, the object emits stateChanged() signal.
Here, two QCheckBox objects are added to a horizontal layout. Their stateChanged() signal is connected to btnstate() function. The source object of signal is passed to the function using lambda.
self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))
self.b2.toggled.connect(lambda:self.btnstate(self.b2))

The isChecked() function is used to check if the button is checked or not.
if b.text() == "Button1":
   if b.isChecked() == True:
      print b.text()+" is selected"
   else:
      print b.text()+" is deselected"
The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class checkdemo(QWidget):
   def __init__(self, parent = None):
      super(checkdemo, self).__init__(parent)
      
      layout = QHBoxLayout()
      self.b1 = QCheckBox("Button1")
      self.b1.setChecked(True)
      self.b1.stateChanged.connect(lambda:self.btnstate(self.b1))
      layout.addWidget(self.b1)
		
      self.b2 = QCheckBox("Button2")
      self.b2.toggled.connect(lambda:self.btnstate(self.b2))

      layout.addWidget(self.b2)
      self.setLayout(layout)
      self.setWindowTitle("checkbox demo")

   def btnstate(self,b):
      if b.text() == "Button1":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
      if b.text() == "Button2":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
def main():

   app = QApplication(sys.argv)
   ex = checkdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
As mentioned earlier, checkBox buttons can be made mutually exclusive by adding them in the QButtonGroup object.
self.bg = QButtonGroup()
self.bg.addButton(self.b1,1)
self.bg.addButton(self.b2,2)
QButtonGroup object, provides abstract container for buttons and doesn’t have a visual representation. It emits buttonCliked() signal and sends Button object’s reference to the slot function btngroup().
self.bg.buttonClicked[QAbstractButton].connect(self.btngroup)

The btngroup() function displays the caption of the clicked checkbox.
def btngroup(self,btn):
   print btn.text()+" is selected"

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Node.js indexOf() function - GeeksforGeeks

13 Oct, 2021
The indexOf() function is a string function from Node.js which is used to find a string with another string.
Syntax:
str1.indexOf( str2 )
Parameter: This function uses two parameters as mentioned above and described below:
str1: It holds the string content where another string to be search.
str2: It holds the search string.
Return Value: The function returns the index of the passed parameter.
Below programs demonstrate the working of indexOf() function:
Program 1:
function findIndex(str) {    var index = str.indexOf("awesome");    console.log(index);}  var str = "gfg is awesome";  findIndex(str);
Output:
7
Program 2:
function findIndex(str1, str2) {          var index = str1.indexOf(str2);          console.log(index);}  var str1 = "Welcome to GeeksforGeeks";var str2 = "to"  findIndex(str1, str2);
Output:
8
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Mongoose Populate() Method
Mongoose find() Function
Express.js req.params Property
Mongoose | findOneAndDelete() Function
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
In MySQL, what is the difference between SERIAL and AUTO_INCREMENT?

In MySQL, both SERIAL and AUTO_INCREMENT are used to define a sequence as a default value for a field. But they are technically different from each other.
The AUTO_INCREMENT attribute is supported by all numeric data types except for BIT and DECIMAL. There can only be one AUTO_INCREMENT field per table and the sequence generated by an AUTO_INCREMENT field in one table cannot be used in any other table. 
This attribute requires that a UNIQUE index exists on the field to ensure the sequence has no duplicates. The sequence would start by default from 1 and increment by 1 for every insert.
mysql> Create Table Student(Student_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.18 sec)
The query above declares Student_id AUTO_INCREMENT.
mysql> Insert Into Student(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student;
+------------+-------+
| Student_id | Name  |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student\G
*************************** 1. row ***************************
      Table: Student
Create Table: CREATE TABLE `student` (
   `Student_id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   PRIMARY KEY (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
On the other hand, SERIAL DEFAULT VALUE is shorthand for NOT NULL AUTO_INCREMENT UNIQUE KEY. The interger numeric type like TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT supports the SERIAL DEFAULT VALUE keyword.
mysql> Create Table Student_serial(Student_id SERIAL, Name VArchar(20));
Query OK, 0 rows affected (0.17 sec)

mysql> Insert into Student_serial(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student_serial;
+------------+-------+
| Student_id | Name |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student_serial\G
*************************** 1. row ***************************
      Table: Student_serial
Create Table: CREATE TABLE `student_serial` (
   `Student_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   UNIQUE KEY `Student_id` (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
How to select all columns except one in a Pandas DataFrame?

To select all columns except one column in Pandas DataFrame, we can use df.loc[:, df.columns != <column name>].
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Print the input DataFrame, df.
Initialize a variable col with column name that you want to exclude.
Initialize a variable col with column name that you want to exclude.
Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column.
Use df.loc[:, df.columns != col] to create another DataFrame excluding a particular column.
Print the DataFrame without col column.
Print the DataFrame without col column.
 Live Demo
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print("Input DataFrame is:\n", df)

col = "y"
df1 = df.loc[:, df.columns != col]

print "DataFrame without Column-y: \n", df1
Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

DataFrame without Column-y:
   x  z
0  5  4
1  2  1
2  1  5
3  9  0
Find records on or after a specific date in MongoDB?

To find records on or after a date, use $gte i.e., greater than equal. Let us create a collection with documents −
> db.demo91.insertOne({"ArrivalDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d49fd79799acab037af66")
}
> db.demo91.insertOne({"ArrivalDate":new ISODate("2019-12-14")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d4a0679799acab037af67")
}
Display all documents from a collection with the help of find() method −
> db.demo91.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d49fd79799acab037af66"), "ArrivalDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e2d4a0679799acab037af67"), "ArrivalDate" : ISODate("2019-12-14T00:00:00Z") }
Following is the query to find records on or after a specific date in MongoDB −
> db.demo91.find({ArrivalDate: { $gte: ISODate('2020-01-10') } });
This will produce the following output −
{ "_id" : ObjectId("5e2d49fd79799acab037af66"), "ArrivalDate" : ISODate("2020-01-10T00:00:00Z") }
DAX Date & Time - EOMONTH function

Returns the date in datetime format of the last day of the month, before or after a specified number of months.
EOMONTH (<start_date>, <months>) 

start_date
A date that represents the start date.
It can be in datetime or text format.
months
A whole number that represents the number of months before or after start_date.
If months is not an integer, rounded up or down to the nearest integer.
A date in datetime format.
You can use EOMONTH to calculate the maturity dates or due dates that fall on the last day of the month.
DAX works with dates in datetime format. Dates stored in other formats are converted implicitly.
If start_date is not a valid date, EOMONTH returns an error.
If start_date is not a valid date, EOMONTH returns an error.
If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid.
If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and after December 31st of 9999 are invalid.
DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,

If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.


DAX EOMONTH function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. For example,
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Month/Day/Year, then the string, "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.
If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016.
If the text representation of the date cannot be correctly converted to a datetime value, the function returns an error.
= EOMONTH (DATE (2016,4,5),5) returns 9/30/2016 12:00:00 AM 
= EOMONTH (DATE (2016,4,5),4.5) also returns 9/30/2016 12:00:00 AM, as 4.5 will be rounded up to 5. 

    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
Python program to convert a list of characters into a string

Python requires this kind of conversion a lot. For example, such conversions are useful for serialization purposes. An example of such a conversion would be −
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] to "hello world"
Python has a join method that can be used for such conversions. It can be applied on a delimiter string that'll be used to concatenate the objects together. In this case, we need an empty delimiter string. We can implement it as follows −
 Live Demo
letters = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
sentence = ''.join(letters)
print(sentence)
This will give the output −
hello world
C library function - getenv()

The C library function char *getenv(const char *name) searches for the environment string pointed to by name and returns the associated value to the string.
Following is the declaration for getenv() function.
char *getenv(const char *name)
name − This is the C string containing the name of the requested variable.
name − This is the C string containing the name of the requested variable.
This function returns a null-terminated string with the value of the requested environment variable, or NULL if that environment variable does not exist.
The following example shows the usage of getenv() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   printf("PATH : %s\n", getenv("PATH"));
   printf("HOME : %s\n", getenv("HOME"));
   printf("ROOT : %s\n", getenv("ROOT"));

   return(0);
}
Let us compile and run the above program that will produce the following result −
PATH : /sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
HOME : /
ROOT : (null)


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to get the first day of next month in MySQL?

With the help of following MySQL query, we can get the first day of next month −
mysql> SELECT DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH,'%Y-%m-01') AS
'FIRST DAY OF NEXT MONTH';
+-------------------------+
| FIRST DAY OF NEXT MONTH |
+-------------------------+
| 2017-11-01              |
+-------------------------+
1 row in set (0.00 sec)
MomentJS - Time from now

This method will tell the length of time from now. Suppose for example if you pass a date to this method it will display the difference if it is in years, months, hours, minutes, or seconds.
moment().fromNow();
moment().fromNow(Boolean);

var changeddate = moment([2018, 0, 1]).fromNow();
Observe that the date given to the moment is 01/01/2018, the difference till date is 4 months, so the output is given as 4 months ago.
Observe the following example to check the output when no inputs are given to the moment −
var changeddate = moment().fromNow();
Note that in the above shown output, it has the ago keyword appended at the end. In case you do not need it, pass true to fromNow(true) method as shown below −
var changeddate = moment([2015, 10, 01]).fromNow();
var changeddate1 = moment([2015, 10, 01]).fromNow(true);
 Print
 Add Notes
 Bookmark this page