code-rag-bench/online-tutorials huggingface dataset:
What are the differences between an Integer and an int in Java?

The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type.
An int is a data type that stores 32-bit signed two’s complement integer whereas an Integer is a class that wraps a primitive type int in an object.
An Integer can be used as an argument to a method that requires an object, whereas int can be used as an argument to a method that requires an integer value, that can be used for arithmetic expression.
An int datatype helps to store integer values in memory whereas Integer helps to convert int into an object and to convert an object into an int.
The variable of int type is mutable unless it is marked as final and the Integer class contains one int value and is immutable.
Live Demo
public class PrimitiveDataTypeTest {
   public static void main(String []args) {
      // Declaration of int
      int a = 20;
      int b = 40;
      int result = a+b;
      System.out.println("Result is: " + result);
   }
}
Result is: 60
Live Demo
public class WrapperClassTest {
   public static void main(String []args) {
      int a = 20;
      Integer b = Integer.valueOf(a);
      System.out.println("Converted Value of b is: " + b);
      Integer c = new Integer(30);
      int d = c.intValue();
      System.out.println("Converted Value of d is: " + d);
   }
}
Converted Value of b is: 20
Converted Value of d is: 30
How to add delay in a loop in JavaScript?

To add delay in a loop, use the setTimeout() metod in JavaScript. Following is the code for
adding delay in a loop −
 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 {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Adding delay in a loop in JavaScript</h1>
<div class="result"></div>
<button class="Btn">Start</button>
<h3>Click on the above button to start the loop</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   BtnEle.addEventListener("click", () => {
      for (let i = 0; i < 10; i++) {
         setTimeout(function () {
            resEle.innerHTML += "i = " + i + "<br>";
         }, 2000 * i);
      }
   });
</script>
</body>
</html>
On clicking the ‘START’ button, 3
there will be delay after each iteration −
PyTorch - Introduction to Convents

Convents is all about building the CNN model from scratch. The network architecture will contain a combination of following steps −
Conv2d
MaxPool2d
Rectified Linear Unit
View
Linear Layer
Training the model is the same process like image classification problems. The following code snippet completes the procedure of a training model on the provided dataset −
def fit(epoch,model,data_loader,phase 
= 'training',volatile = False):
   if phase == 'training':
      model.train()
   if phase == 'training':
      model.train()
   if phase == 'validation':
      model.eval()
   volatile=True
   running_loss = 0.0
   running_correct = 0
   for batch_idx , (data,target) in enumerate(data_loader):
      if is_cuda:
         data,target = data.cuda(),target.cuda()
         data , target = Variable(data,volatile),Variable(target)
      if phase == 'training':
         optimizer.zero_grad()
         output = model(data)
         loss = F.nll_loss(output,target)
         running_loss + = 
         F.nll_loss(output,target,size_average = 
         False).data[0]
         preds = output.data.max(dim = 1,keepdim = True)[1]
         running_correct + = 
         preds.eq(target.data.view_as(preds)).cpu().sum()
         if phase == 'training':
            loss.backward()
            optimizer.step()
   loss = running_loss/len(data_loader.dataset)
   accuracy = 100. * running_correct/len(data_loader.dataset)
   print(f'{phase} loss is {loss:{5}.{2}} and {phase} accuracy is {running_correct}/{len(data_loader.dataset)}{accuracy:{return loss,accuracy}})
The method includes different logic for training and validation. There are two primary reasons for using different modes −
In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase.
In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase.
For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases.
For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases.
 Print
 Add Notes
 Bookmark this page
Python program to print Pascal’s Triangle

04 Jun, 2021
Pascal’s triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal’s triangle.
Example:
Input: N = 5
Output:
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
Method 1: Using nCr formula i.e. n!/(n-r)!r!
After using nCr formula, the pictorial representation becomes:
          0C0
       1C0   1C1
    2C0   2C1   2C2
 3C0   3C1   3C2    3C3
Algorithm:
Take a number of rows to be printed, lets assume it to be n
Make outer iteration i from 0 to n times to print the rows.
Make inner iteration for j from 0 to (N – 1).
Print single blank space ” “.
Close inner loop (j loop) //its needed for left spacing.
Make inner iteration for j from 0 to i.
Print nCr of i and j.
Close inner loop.
Print newline character (\n) after each inner iteration.
Implementation:
Python3
# Print Pascal's Triangle in Pythonfrom math import factorial # input nn = 5for i in range(n):    for j in range(n-i+1):         # for left spacing        print(end=" ")     for j in range(i+1):         # nCr = n!/((n-r)!*r!)        print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")     # for new line    print()
Output:
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
Time complexity: O(N2)
Method 2: We can optimize the above code by the following concept of a Binomial Coefficient, the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1).
C(line, i) = C(line, i-1) * (line - i + 1) / i
Implementations:
Python3
# Print Pascal's Triangle in Python # input nn = 5 for i in range(1, n+1):    for j in range(0, n-i+1):        print(' ', end='')     # first element is always 1    C = 1    for j in range(1, i+1):         # first value in a line is always 1        print(' ', C, sep='', end='')         # using Binomial Coefficient        C = C * (i - j) // j    print()
Output:
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
Time complexity: O(N2)
Method 3: This is the most optimized approach to print Pascal’s triangle, this approach is based on powers of 11.
11**0 = 1
11**1 = 11
11**2 = 121
11**3 = 1331
Implementation:
Python3
# Print Pascal's Triangle in Python # input nn = 5 # iterarte upto nfor i in range(n):    # adjust space    print(' '*(n-i), end='')     # compute power of 11    print(' '.join(map(str, str(11**i))))
Output:
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
Time Complexity: O(N)
However, this approach is applicable up to n=5 only.
Vishank Shah
pattern-printing
Python Pattern-printing
Technical Scripter 2020
Python
Python Programs
Technical Scripter
pattern-printing
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
Python | Pandas Index.tolist()

24 Dec, 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 Index.tolist() function return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period).
Syntax: Index.tolist()
Parameters : None
Returns : list
Example #1: Use Index.tolist() function to convert the index into a list.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'],                                  name ='Student')  # Print the Indexprint(idx)
Output :
Let’s convert the index into a List.
# convert the index into a listidx.tolist()
Output :
 Example #2: Use Index.tolist() function to convert the index into a python list.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['2000-01-02', '2000-02-05', '2000-05-11',                            '2001-02-11', '2005-11-12'])  # Print the Indexprint(idx)
Output :
Let’s convert the index into a List.
# convert the index into a listidx.tolist()
Output :
Python pandas-indexing
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
std::equal_to in C++ with Examples

16 Jul, 2021
The std::equal_to allows the equality comparison to be used as a function, which means that it can be passed as an argument to templates and functions. This is not possible with the equality operator == since operators cannot be passed as parameters.Header File:  
#include <functional.h>
Template Class:  
template struct equal_to : binary_function
{
 
  // Declaration of the equal operation
  bool operator() (const T& x,
                   const T& y) 
       const 
  { 
     return x==y;
  }

  // Type of first parameter
  typedef T first_argument_type;

  // Type of second parameter
  typedef T second_argument_type;

  // The result is returned
  // as bool type
  typedef bool result_type;
}
Syntax:  
std::equal_to <int> ()
Parameter: This function accepts the type of the arguments T, as the parameter, to be compared by the functional call.Return Type: It return a boolean value depending upon condition(let a & b are 2 element):  
True: If a is equals to b.
False: If a is not equals to b.
Below is the illustration of std::equal_to in C++:Program 1:  
CPP
// C++ code to illustrate std::equal_to#include <algorithm>#include <functional>#include <iostream>#include <vector>using namespace std; // Driver Codeint main(){    // Initialise vectors    vector<int> v1 = { 50, 55, 60,                       65, 70 };    vector<int> v2 = { 50, 55, 85,                       65, 70 };     // Declaring pointer of pairs    pair<vector<int>::iterator,         vector<int>::iterator>        pairs1;     // Use mismatch() function to    // search first mismatch between    // v1 and v2    pairs1 = mismatch(v1.begin(), v1.end(),                      v2.begin(),                      equal_to<int>());     // Print the mismatch pair    cout << "The 1st mismatch element"         << " of 1st container : ";    cout << *pairs1.first << endl;     cout << "The 1st mismatch element"         << " of 2nd container : ";    cout << *pairs1.second << endl;     return 0;}
The 1st mismatch element of 1st container : 60
The 1st mismatch element of 2nd container : 85
 
Program 2:  
CPP
// C++ program to illustrate std::equals_to#include <algorithm>#include <functional>#include <iostream>using namespace std; // Templatetemplate <typename A, typename B,          typename U = std::equal_to<int> > // Function to check if a = b or notbool f(A a, B b, U u = U()){    return u(a, b);} // Driver Codeint main(){    int X = 1, Y = 2;     // If X is equals to Y or not    cout << std::boolalpha;    cout << f(X, Y) << '\n';     X = -1, Y = -1;     // If X is equals to Y or not    cout << f(X, Y) << '\n';     return 0;}
false
true
 
Reference: http://www.cplusplus.com/reference/functional/equal_to/ 
sagartomar9927
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C program to swap adjacent characters of a String

09 Jun, 2022
Given a string str, the task is to swap adjacent characters of this string in C. Examples:
Input: str = "geeks"
Output: NA
Not possible as the string length is odd

Input: str = "geek"
Output: egke
Approach:
Check if the length of the string is even or odd.If the length is odd, swapping cannot be done.If the length is even, take each character of the string one by one and swap it with the adjacent character.
Check if the length of the string is even or odd.
If the length is odd, swapping cannot be done.
If the length is even, take each character of the string one by one and swap it with the adjacent character.
Below is the implementation of the above approach: 
C
// C program to swap// adjacent characters of a String #include <stdio.h>#include <string.h> // Function to swap adjacent charactersvoid swap(char* str){     char c = 0;    int length = 0, i = 0;     // Find the length of the string    length = strlen(str);     // Check if the length of the string    // is even or odd    if (length % 2 == 0) {         // swap the characters with        // the adjacent character        for (i = 0; i < length; i += 2) {            c = str[i];            str[i] = str[i + 1];            str[i + 1] = c;        }         // Print the swapped character string        printf("%s\n", str);    }    else {         // Print NA as the string length is odd        printf("NA\n");    }} // Driver codeint main(){     // Get the string    char str1[] = "Geek";    char str2[] = "Geeks";     swap(str1);    swap(str2);     return 0;}
eGke
NA
Time complexity: O(length(str))
Auxiliary space: O(1)
kabitac45
hasani
Swap-Program
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
How to generate a vector with random values in C++?

24 Nov, 2020
Vectors are dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. It can also be created with random value using the generate function and rand() function.
Below is the template of both the STL functions:
Syntax:
int rand(void): It returns a pseudo-random number in the range of 0 to RAND_MAX.RAND_MAX: is a constant whose default value that may vary between implementations but it is granted to be at least 32767.
void generate(ForwardIterator first, ForwardIterator last, Generator gen)
where,
first: Forward iterator pointing to the first element of the container.
last: Forward iterator pointing to the last element of the container.
gen: A generator function, based upon which values will be assigned.
Returns Value: Since, it has a void return type, so it does not return any value.
In order to have different random vectors each time, run this program, the idea is to use srand() function. Otherwise, the output vector will be the same after each compilation.
Syntax:
void srand(unsigned seed): This function seeds the pseudo-random number generator used by rand() with the value seed.
Below is the implementation of the above approach:
C++
// C++ program to generate the vector// with random values#include <bits/stdc++.h>using namespace std;  // Driver Codeint main(){    // Size of vector    int size = 5;      // Initialize the vector with    // initial values as 0    vector<int> V(size, 0);      // use srand() for different outputs    srand(time(0));      // Generate value using generate    // function    generate(V.begin(), V.end(), rand);      cout << "The elements of vector are:\n";      // Print the values in the vector    for (int i = 0; i < size; i++) {        cout << V[i] << " ";    }      return 0;}
The elements of vector are:
995552582 698831766 2088692742 1348138651 64302615

cpp-random
cpp-vector
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Java program to swap first and last characters of words in a sentence

26 Dec, 2017
Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example?
Examples:
Input : geeks for geeks
Output :seekg rof seekg

Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is.
First we will create an Char array of given String by using toCharArray() method.
Now we iterate the char array by using for loop.
In for loop, we declare a variable whose value is dependent on i.
Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space.
class SwapFirstLastCharacters {    static String count(String str)    {        // Create an equivalent char array        // of given string        char[] ch = str.toCharArray();        for (int i = 0; i < ch.length; i++) {              // k stores index of first character            // and i is going to store index of last             // character.             int k = i;            while (i < ch.length && ch[i] != ' ')                 i++;                          // Swapping            char temp = ch[k];            ch[k] = ch[i - 1];            ch[i - 1] = temp;              // We assume that there is only one space            // between two words.        }        return new String(ch);    }    public static void main(String[] args)    {        String str = "geeks for geeks";        System.out.println(count(str));    }}
Output:
seekg rof seekg

Java-Strings
Java Programs
Strings
Java-Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Tabbed panel in kivy

18 Oct, 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 Desktops applications
 Kivy Tutorial – Learn Kivy with Examples.
The TabbedPanel widget manages different widgets in tabs, with a header area for the actual tab buttons and a content area for showing the current tab content.
The TabbedPanel provides one default tab.
To use it must import :from kivy.uix.tabbedpanel import TabbedPanel
Basic Approach:
1) import kivy
2) import kivy App
3) import floatlayout
4) import tabbedpanel
5) set minimum version(optional)
6) Create Tabbed panel class
7) create the App class
8) create .kv file:
       # create multiple tabs in it.
       # Do there functioning also.
9) return the widget/layout etc class
10) Run an instance of the class

Implementation Of Approach:
.py file
# Program to explain how to create tabbed panel App in kivy         # import kivy module     import kivy            # base Class of your App inherits from the App class.     # app:always refers to the instance of your application    from kivy.app import App         # this restrict the kivy version i.e   # below this kivy version you cannot   # use the app or software   kivy.require('1.9.0')    # to  use this must have to import itfrom kivy.uix.tabbedpanel import TabbedPanel  # Floatlayout allows us to place the elements# relatively based on the current window# size and height especially in mobilesfrom kivy.uix.floatlayout import FloatLayout  # Create Tabbed class class Tab(TabbedPanel):    pass   # create App classclass TabbedPanelApp(App):    def build(self):        return Tab()  # run the Appif __name__ == '__main__':    TabbedPanelApp().run()
.kv file
# .kv file of tabbed panel  <Tab>:      # creating the size    # and the alignment of the tab     size_hint: .5, .5    pos_hint: {'center_x': .5, 'center_y': .5}    do_default_tab: False      # Create tab 1    TabbedPanelItem:        text: 'Tab 1'        Label:            text: "First tab"      # Create 2nd tab    TabbedPanelItem:        text: 'Tab 2'        BoxLayout:            Label:                text: 'Press button'            Button:                text: 'Click it'      # Create 3rd tab    TabbedPanelItem:        text: 'Tab 3'        RstDocument:            text: '\n'.join(("How are you GFG's???"))
Output:
Tab 1:
Tab 2:
Tab 3:
saurabh1990aror
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..

30 Oct, 2015
What is the time complexity of below code?
void fun(int n){   int j = 1, i = 0;   while (i < n)   {       // Some O(1) task       i = i + j;       j++;   }}
The loop variable ‘i’ is incremented by 1, 2, 3, 4, ... until i becomes greater than or equal to n.
The value of i is x(x+1)/2 after x iterations. So if loop runs x times, then x(x+1)/2 < n. Therefore time complexity can be written as Θ(√n).
This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Analysis
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Analysis of Algorithms | Set 4 (Analysis of Loops)
Analysis of different sorting techniques
Time complexities of different data structures
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Time Complexity and Space Complexity
SQL Interview Questions
How to draw an arc on a tkinter canvas?

The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas.
To draw an arc on a tkinter Canvas, we will use the create_arc() method of the Canvas and supply it with a set of coordinates to draw the arc. We can use create_arc() to create an arc item, which can be a chord, a pieslice, or a simple arc.
Import the required libraries and create an instance of tkinter frame.
Import the required libraries and create an instance of tkinter frame.
Set the size of the frame using root.geometry method.
Set the size of the frame using root.geometry method.
Create a Canvas widget and set its height and width. Also, set its background color with bg="blue".
Create a Canvas widget and set its height and width. Also, set its background color with bg="blue".
Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150.
Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import the required libraries
from tkinter import *

# Create an instance of Tkinter Frame
root = Tk()

# Set the geometry
root.geometry("700x350")

# Create a Canvas with a background color
C = Canvas(root, bg="blue", height=250, width=600)

# Coordinates for the arc
coord = 100, 50, 500, 300

# Create the arc with extent=150
arc = C.create_arc(coord, start=0, extent=150, fill="red")

C.pack(side=TOP, padx=50, pady=50)

root.mainloop()
On execution, it will produce the following output −
How can we run MySQL statements in batch mode?

We need to create a .sql file for running MySQL in batch mode. This file will contain the MySQL statements. Suppose I have hh.sql file in which I have written the statement select * from hh. With the help of the following command, we can run this file in batch mode −
C:\Program Files\MySQL\bin>mysql -u root -p gaurav < hh.sql
Enter password: *****
id
1
2
Here Gaurav is the database name that contains the table hh. Whenever you’ll run this command it will ask for the password and then give the output.
DirectX - Creating App

This chapter involves the process of creating new application with DirectX using Visual Studio Code Editor. Following steps should be followed for creating an app in DirectX −
Here we will start by constructing a DirectX project with a walk through of the basic steps to get a working application.
To create a DirectX “non-desktop” application, a special type of project called a “DirectX App” is used. This step involves opening a Visual Studio 2013, select File → New Project and select as “DirectX App” which comes under category of “Visual C++”, “Store App”, “Universal App”.
Once the project is created, you will see a lot of files being populated. This is clearly visible in snapshot mentioned below −
User can delete various files to make up a sample app and explore the features to see how a fully-functioning DirectX app is set up as per the attributes required.
As mentioned in the snapshot above, a file is created named “App.cpp”.
#include <stdio.h> // include the standard input/output header file
int main(void) { // our program starts here
   printf("Hello World!"); // print "Hello World!" into the console
   return 0; // return 0 to windows
}

The function main() marks the start of the application and works with Windows Operating System.
The function main() marks the start of the application and works with Windows Operating System.
main() function should be included where the program usually starts.
main() function should be included where the program usually starts.
Windows can feed the required parameters to get things done smoothly.
Windows can feed the required parameters to get things done smoothly.
There are specific parameters which can be included usually considered as secondary parameters.
There are specific parameters which can be included usually considered as secondary parameters.
 Print
 Add Notes
 Bookmark this page
Python - Draw Star Using Turtle Graphics - GeeksforGeeks

16 Oct, 2020
In this article, we will learn how to make a Star using Turtle Graphics in Python. For that let’s first know what is Turtle Graphics.
Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways.
Some commonly used methods are:
forward(length): moves the pen in the forward direction by x unit.
backward(length): moves the pen in the backward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
First import turtle module in the idle or editor you are using.
import turtle

Get a screen board on which turtle will draw.
ws=turtle.Screen()

A screen like this will appear:-
Define an instance for turtle.
For a drawing, a Star executes a loop 5 times.
In every iteration move the turtle 100 units forward and move it right 144 degrees.
This will make up an angle 36 degrees inside a star.
5 iterations will make up a Star perfectly.
Below is the python implementation of the above approach.
First way :
Python3
# import for turtleimport turtle # Starting a Working Screenws = turtle.Screen() # initializing a turtle instancegeekyTurtle = turtle.Turtle() # executing loop 5 times for a starfor i in range(5):         # moving turtle 100 units forward        geekyTurtle.forward(100)         # rotating turtle 144 degree right        geekyTurtle.right(144)
  
Turtle Making A Star
Alternate Approach:
Python3
#import turtleimport turtle # set screenScreen = turtle.Turtle() # decide colorscir= ['red','green','blue','yellow','purple'] # decide pensizeturtle.pensize(4) # Draw star patternturtle.penup()turtle.setpos(-90,30)turtle.pendown()for i in range(5):    turtle.pencolor(cir[i])    turtle.forward(200)    turtle.right(144) turtle.penup()turtle.setpos(80,-140)turtle.pendown() # choose pen colorturtle.pencolor("Black")turtle.done()
Output:-
 
anshitaagarwal
Python-turtle
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert String to bytes - GeeksforGeeks

22 May, 2019
Inter conversions are as usual quite popular, but conversion between a string to bytes is more common these days due to the fact that for handling files or Machine Learning ( Pickle File ), we extensively require the strings to be converted to bytes. Let’s discuss certain ways in which this can be performed.
Method #1 : Using bytes(str, enc)
String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to specified encoding.
# Python code to demonstrate# convert string to byte # Using bytes(str, enc)  # initializing string test_string = "GFG is best"  # printing original string print("The original string : " + str(test_string))  # Using bytes(str, enc)# convert string to byte res = bytes(test_string, 'utf-8')  # print resultprint("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))
The original string : GFG is best
The byte converted string is  : b'GFG is best', type : <class 'bytes'>

 
Method #2 : Using encode(enc)
The most recommended method to perform this particular task, using the encode function to get the conversion done, as it reduces one extra linking to a particular library, this function directly calls it.
# Python code to demonstrate# convert string to byte # Using encode(enc)  # initializing string test_string = "GFG is best"  # printing original string print("The original string : " + str(test_string))  # Using encode(enc)# convert string to byte res = test_string.encode('utf-8')  # print resultprint("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))
The original string : GFG is best
The byte converted string is  : b'GFG is best', type : <class 'bytes'>

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Check if a prime number can be expressed as sum of two Prime Numbers in Python

Suppose we have a prime number n. we have to check whether we can express n as x + y where x and y are also two prime numbers.
So, if the input is like n = 19, then the output will be True as we can express it like 19 = 17 + 2
To solve this, we will follow these steps −
Define a function isPrime() . This will take number
if number <= 1, thenreturn False
return False
if number is same as 2, thenreturn True
return True
if number is even, thenreturn False
return False
for i in range 3 to integer part of ((square root of number) + 1), increase by 2, doif number is divisible by i, thenreturn False
if number is divisible by i, thenreturn False
return False
return True
From the main method do the following −
if isPrime(number) and isPrime(number - 2) both are true, thenreturn True
return True
otherwise,return False
return False
Let us see the following implementation to get better understanding −
 Live Demo
from math import sqrt
def isPrime(number):
   if number <= 1:
      return False
   if number == 2:
      return True
   if number % 2 == 0:
      return False
   for i in range(3, int(sqrt(number))+1, 2):
      if number%i == 0:
         return False
   return True
def solve(number):
   if isPrime(number) and isPrime(number - 2):
      return True
   else:
      return False
n = 19
print(solve(n))
19
True
Grant MySQL table and column permissions using Python - GeeksforGeeks

20 May, 2021
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such as PyMySQL, mysql.connector, etc. 
In this article, we are going to grant permissions to a user in accessing a database and its MySQL tables. The CREATE USER statement creates a user account with no privileges. The statement for creating a user in MySQL is given below.
CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'password';
The above user can log in into MySQL Server, but cannot do anything such as querying data and selecting a database from tables. In our case,  user_name is geeksforgeeks and password for login is 1234. 
To change the user in MySQL client, use the below command:
SYSTEM MYSQL -u geeksforgeeks -p1234;
To check the current user, one can use the below command:
SELECT user();
The above statement could be used to know the permissions of the user. 
SHOW GRANTS FOR user_name@localhost;
See the below example:
Default Privileges
Note: To grant permissions to the user geeksforgeesks you must be logged into root account. Users can’t grant permissions to themselves. 
Below is the python program to add table and column permissions to the user geeksforgeeks:
Python3
# import required moduleimport pymysql  # establish connection to MySQLconnection = pymysql.connect(       # specify host    host='localhost',       # specify root account    user='root',         # specify password for root account    password='1234',         # default port number is 3306 fro MySQL    port=3306)  # make a cursor to run sql queriesmycursor = connection.cursor() # granting all permissions on all databases and their# tables of geeksforgeeks user permission also includes# table and column grantsmycursor.execute("Grant all on *.* to geeksforgeeks@localhost") # print all privileges of geeksforgeeks usermycursor.execute("Show grants for geeksforgeeks@localhost")result = mycursor.fetchall()print(result) # commit privilegesmycursor.execute("Flush Privileges") # close connection to MySQLconnection.close()
Output
Python Output
MySQL Terminal
MySQL output
We could see that permissions to CREATE and ALTER MySQL tables have been provided to user geeksforgeeks.
akshaysingh98088
Python-mySQL
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
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Visualizing image in different color spaces

OpenCV-Python is a library of Python bindings designed to solve computer vision problems. OpenCV-Python makes use of Numpy, which is a highly optimized library for numerical operations with a MATLAB-style syntax. All the OpenCV array structures are converted to and from Numpy arrays.
# read image as RGB
# Importing cv2 and matplotlib module
import cv2
import matplotlib.pyplot as plt
# reads image as RGB
img = cv2.imread('download.png')
# shows the image
plt.imshow(img)
# read image as GrayScale
# Importing cv2 module
import cv2
# Reads image as gray scale
img = cv2.imread('download.png', 0)
# We can alternatively convert
# image by using cv2color
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Shows the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# read image as YCrCb color space
# Import cv2 module
import cv2
# Reads the image
img = cv2.imread('download.png')
# Convert to YCrCb color space
img = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
# Shows the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# read image as HSV color space
# Importing cv2 module
import cv2
# Reads the image
img = cv2.imread('download.png')
# Converts to HSV color space
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Shows the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Heat map of image
# Importing matplotlib and cv2
import matplotlib.pyplot as plt
import cv2
# reads the image
img = cv2.imread('download.png')
# plot heat map image
plt.imshow(img, cmap ='hot')
# Spectral map of image
# Importing matplotlib and cv2
import matplotlib.pyplot as plt
import cv2
img = cv2.imread('download.png')
plt.imshow(img, cmap ='nipy_spectral')
How to switch to new window in Selenium for Python?

Selenium can switch to new windows when there are multiple windows opened. There may be scenarios when filling a date field in a form opens to a new window or clicking a link, button or an advertisement opens a new tab.
Selenium uses the current_window_handle and window_handles methods to work with new windows. The window_handles method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String].
The current_window_handle method is used to store the window handle id of the present active window. Finally to switch to a particular window, switch_to_window() method is used. The handle id of the window where we want to switch is passed as an argument to that method.
The steps to be followed to implement the above concept −
After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method.
After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method.
We shall iterate through all the window handle ids till we get our desired window handle id.
We shall iterate through all the window handle ids till we get our desired window handle id.
Let us then grab the current window handle id with the help of current_window_handle method.
Let us then grab the current window handle id with the help of current_window_handle method.
Then switch to that window with switch_to_window() method.
Then switch to that window with switch_to_window() method.
Code Implementation.
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://accounts.google.com/signup")
driver.find_element_by_link_text("Help").click()
#prints parent window title
print("Parent window title: " + driver.title)
#get current window handle
p = driver.current_window_handle
#get first child window
chwnd = driver.window_handles
for w in chwnd:
   #switch focus to child window
   if(w!=p):
   driver.switch_to.window(w)
   break
time.sleep(0.9)
print("Child window title: " + driver.title)
driver.quit()
Get data inside a button tag using BeautifulSoup - GeeksforGeeks

26 Mar, 2021
Sometimes while working with BeautifulSoup, are you stuck at the point where you have to get data inside a button tag? Don’t worry. Just read the article and get to know how you can do the same.
For instance, consider this simple page source having a button tag.
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Apple</title></head><body>  <button id="enjoy" onclick="gfg.html">      Click Me!  </button></body></html>
Once you have created the button in the HTML code, you can get the text inside a button tag using:
btn_text=btn.text
print(btn_text)
Also, you can find the onclick link of the button inside a button tag using:
btn_onclick=btn['onclick']
print(btn_onclick)
Step 1: First, import the libraries Beautiful Soup and os.
from bs4 import BeautifulSoup as bs
import os
Step 2: Now, remove the last segment of the path by entering the name of the Python file in which you are currently working.
base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working))
Step 3: Then, open the HTML file from which you want to read the value.
html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))
Step 4: Moreover, parse the HTML file in Beautiful Soup
soup=bs(html, 'html.parser')
Step 5: Next, find the button for which you want to obtain the data.
btn=soup.find("button", {"id":"#Id name of the button"})
Step 6: Now, for obtaining the text stored inside the button tag in the HTML, use:
btn_text=btn.text
Step 7: Further, for finding the onclick link inside the button tag, you can write the code as follows:
btn_onclick=btn['onclick']
Step 8: Finally, printing the text and onclick link of the button tag obtained in steps 6 and 7.
print(btn_text)
print(btn_onclick)
Python
# Python program to get data inside# a button tag using BeautifulSoup  # Import the libraries BeautifulSoup # and osfrom bs4 import BeautifulSoup as bsimport os  # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath(__file__))  # Open the HTML in which you want to make# changeshtml = open(os.path.join(base, 'run.html'))  # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser')  # Finding the location of buttonbtn = soup.find("button", {"id": "enjoy"})  # Obtaining the text stored inside button tagbtn_text = btn.text  # Obtaining the onclick link of button tagbtn_onclick = btn['onclick']  # Printing the valuesprint(btn_text)print(btn_onclick)
Output:
Picked
Python BeautifulSoup
Python bs4-Exercises
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
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Create a table inside a MySQL stored procedure and insert a record on calling the procedure

Create a table inside the stored procedure and use INSERT as well −
mysql> DELIMITER //
mysql> CREATE PROCEDURE create_TableDemo(id int,name varchar(100),age int)
   BEGIN
   CREATE TABLE DemoTable
   (
      ClientId int NOT NULL,
      ClientName varchar(30),
      ClientAge int,
      PRIMARY KEY(ClientId)
   );
   INSERT INTO DemoTable VALUES(id,name,age);
   SELECT *FROM DemoTable;
   END
//
Query OK, 0 rows affected (0.17 sec)
mysql> DELIMITER ;
Call the stored procedure using CALL command −
mysql> CALL create_TableDemo(100,'Robert',28);
This will produce the following output −
+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
|      100 | Robert     |        28 |
+----------+------------+-----------+
1 row in set (0.76 sec)
Query OK, 0 rows affected (0.78 sec)
Python | Convert String ranges to list - GeeksforGeeks

26 Nov, 2019
Sometimes, while working in applications we can have a problem in which we are given a naive string which provides ranges separated by a hyphen and other numbers separated by commas. This problem can occur across many places. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sum() + split() + list comprehension + enumerate()The combination of above functions can be used to perform these tasks. In this, the split is performed on hyphen and comma and accordingly range, numbers are extracted and compiled into a list.
# Python3 code to demonstrate working of# Convert String ranges to list# Using sum() + list comprehension + enumerate() + split()  # initializing string test_str = "1, 4-6, 8-10, 11"  # printing original string print("The original string is : " + test_str)  # Convert String ranges to list# Using sum() + list comprehension + enumerate() + split()res = sum(((list(range(*[int(b) + c            for c, b in enumerate(a.split('-'))]))           if '-' in a else [int(a)]) for a in test_str.split(', ')), [])  # printing resultprint("List after conversion from string : " + str(res))
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

 
Method #2 : Using map() + split() + lambdaThis task can also be performed using above functions. Similar to method above. The only difference is that we use map() and lambda function to reduce complex readability. Works only with Python2.
# Python2 code to demonstrate working of# Convert String ranges to list# Using map() + lambda + split()  # initializing string test_str = "1, 4-6, 8-10, 11"  # printing original string print("The original string is : " + test_str)  # Convert String ranges to list# Using map() + lambda + split()temp = [(lambda sub: range(sub[0], sub[-1] + 1))(map(int, ele.split('-')))\        for ele in test_str.split(', ')]  res = [b for a in temp for b in a]  # printing resultprint("List after conversion from string : " + str(res))
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Python string-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Minimum Number of Platforms Required for a Railway Station using C++.

Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits.
We are given two arrays that represent arrival and departure times of trains that stop.
For below input, we need at least 3 platforms −
1. Sort arrival and departure time arrays in ascending order
2. Trace the number of trains at any time keeping track of trains that haves arrived, but not departed
#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int getPlatformCount(int *arrival, int *departure, int n){
   sort(arrival, arrival + n);
   sort(departure, departure + n);
   int platformCnt = 1;
   int result = 1;
   int i = 1;
   int j = 0;
   while (i < n && j < n) {
      if (arrival[i] <= departure[j]) {
         ++platformCnt;
         ++i;
         if (platformCnt > result) {
            result = platformCnt;
         }
      } else {
         --platformCnt;
         ++j;
      }
   }
   return result;
}
int main()
{
   int arrival[] = {900, 935, 940, 1100, 1430, 1800};
   int departure[] = {915, 1145, 1105, 1200, 1815, 1900};
   cout << "Minimum required platforms = " <<
   getPlatformCount(arrival, departure, SIZE(arrival)) << endl;
   return 0;
}
When you compile and execute the above program. It generates the following output −
Minimum required platforms = 3