code-rag-bench/online-tutorials huggingface dataset:
Sum of list (with string types) in Python

In this tutorial, we are going to write a program that adds all numbers from the list. List may contain numbers in string or integer format. See the example.
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
4051
Follow the below steps to write the program.
Initialize the list.
3Initialize a variable total with 0.
Iterate over the list.
If the element is int, then add it to the total by checking two conditions.The element will be int -> Check type.The element will be a number in string format -> Check using isdigit() method.
The element will be int -> Check type.
The element will be a number in string format -> Check using isdigit() method.
Print the total
 Live Demo
# initialzing the list
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
# initializing the variable total
total = 0
# iterating over the list
for element in random_list:
   # checking whether its a number or not
   if isinstance(element, int) or element.isdigit():
      # adding the element to the total
      total += int(element)
# printing the total
print(total)
If you run the above code, then you will get the following result.
4051
If you have any doubts in the tutorial, mention them in the comment section.
Can we override the main method in java?

Overriding is one of the mechanisms to achieve polymorphism. This is the case when we have two classes where one inherits the properties of another using the extends keyword and, these two classes have the same method including parameters and return type (say, sample()).
Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass (object).
When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.
 Live Demo
class Super{
   public static void sample(){
      System.out.println("Method of the superclass");
   }
}
public class OverridingExample extends Super {
   public static void sample(){
      System.out.println("Method of the subclass");
   }
   public static void main(String args[]){
      Super obj1 = (Super) new OverridingExample();
      OverridingExample obj2 = new OverridingExample();
      obj1.sample();
      obj2.sample();
   }
}
Method of the superclass
Method of the subclass
When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass.
This mechanism is known as method hiding in short, though super and subclasses have methods with the same signature if they are static, it is not considered as overriding.
You cannot override static methods and since the public static void main() method is static we cannot override it.
 Live Demo
class Super{
   public static void main(String args[]) {
      System.out.println("This is the main method of the superclass");
   }
}
class Sub extends Super{
   public static void main(String args[]) {
      System.out.println("This is the main method of the subclass");
   }
}
public class MainOverridingExample{
   public static void main(String args[]) {
      MainOverridingExample obj = new MainOverridingExample();
      Super.main(args);
      Sub.main(args);
   }
}
This is the main method of the superclass
This is the main method of the subclass
MoviePy – Creating Text Clip - GeeksforGeeks

18 Aug, 2020
In this article we will see how we can create a text clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Text clip is basically a clip here we can say it as image containing text.
In order to do this we will use TextClip method
Syntax : TextClip(text)
Argument : It takes string as necessary argument and color size other styling effect are optional argument
Return : It returns TextClip object
Below is the implementation
# importing editor from movie pyfrom moviepy.editor import *  # texttext = "GeeksforGeeks"  # creating a text clip# having font arial-bold# with font size = 70# and color = greenclip = TextClip(text, font ="Arial-Bold", fontsize = 70, color ="green")  # showing  clip clip.ipython_display() 
Output :
Another example
# importing editor from movie pyfrom moviepy.editor import *  # texttext = "Hello"  # creating a text clip# having font arial-bold# with font size = 50# and color = blackclip = TextClip(text, font ="Arial-Bold", fontsize = 50, color ="black")  # showing  clip clip.ipython_display() 
Output :
Python-MoviePy
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
Python OOPs Concepts
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Stack in Python
Reading and Writing to text files in Python
Python Classes and Objects
sum() function in Python
C# - Relational Operators

Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then −
The following example demonstrates all the relational operators available in C# −
using System;

class Program {
   static void Main(string[] args) {
      int a = 21;
      int b = 10;
      
      if (a == b) {
         Console.WriteLine("Line 1 - a is equal to b");
      } else {
         Console.WriteLine("Line 1 - a is not equal to b");
      }
      
      if (a < b) {
         Console.WriteLine("Line 2 - a is less than b");
      } else {
         Console.WriteLine("Line 2 - a is not less than b");
      }
      
      if (a > b) {
         Console.WriteLine("Line 3 - a is greater than b");
      } else {
         Console.WriteLine("Line 3 - a is not greater than b");
      }
      
      /* Lets change value of a and b */
      a = 5;
      b = 20;
      
      if (a <= b) { 
         Console.WriteLine("Line 4 - a is either less than or equal to  b");
      }
      
      if (b >= a) {
         Console.WriteLine("Line 5-b is either greater than or equal to b");
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Ruby | Array collect() operation - GeeksforGeeks

08 Jan, 2020
Array#collect() : collect() is an Array class method which invokes the argument block once for each element of the array. A new array is returned which has the value returned by the block.
Syntax:  Array.collect()

Parameter:  Arrays in which we want elements to be invoked

Return:  array with all the envoked elements

Code #1 : Example for collect() method
# Ruby code for collect() method  # declaring arraya = [1, 2, 3, 4]  # invoking block for each elementputs "collect a : #{a.collect {|x| x + 1 }}\n\n"  puts "collect a : #{a.collect {|x| x - 5*7 }}\n\n"
Output :
collect a : [2, 3, 4, 5]

collect a : [-34, -33, -32, -31]

Code #2 : Example for collect() method
# Ruby code for collect() method  # declaring arraya = ["cat", "rat", "geeks"]  # invoking block for each elementputs "collect a : #{a.collect {|x| x + "!" }}\n\n"  puts "collect a : #{a.collect {|x| x + "_at" }}\n\n"
Output :
collect a : ["cat!", "rat!", "geeks!"]

collect a : ["cat_at", "rat_at", "geeks_at"]


Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Performing Null check using HANA SQL Script

You can go for using either NULLIF or COALESCE function to serve your requirement.
NULLIF (expression, expression"): This function will return the same type whatever is specified as the first expression.
Basically, NULLIF returns
The first expression if the two expressions are not equal.
The first expression if the two expressions are not equal.
NULL of type of first expressions if the expressions are equal
NULL of type of first expressions if the expressions are equal
The other function available is COALESCE which basically checks if the first Value provided is NULL then it will return the second value.
c = COALESCE(b , a)
If b is null then the function will return an otherwise b. So If you need to put a null check and use some default value in place of NULL then you can go ahead and use COALESCE.
cleardevice() function in C - GeeksforGeeks

23 Jan, 2018
The header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color.
Syntax :
void cleardevice();

Below is the implementation of cleardevice() in C:
// C Implementation for cleardevice()#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // set the background colour as GREEN    setbkcolor(GREEN);      // outtext function displays    // text at current position.    outtext("Press any key to clear the screen.");      getch();      // cleardevice function    cleardevice();      outtext("Press any key to exit...");      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output:
On executing the program, the output window looks like :

On pressing any key :

To exit, press any key.


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
Structures in C
Insert current date to the database in MySQL?

To insert current date to the database, you can use NOW(). Following is the syntax −
INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW());
If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE().
Let us first create a table −
mysql> create table insertcurrentdate
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> currentDate date
   -> );
Query OK, 0 rows affected (1.09 sec)
Following is the query to insert some records in the table using insert command. We have used both NOW() and CURDATE() to display current date −
mysql> insert into insertcurrentdate(currentDate) values(NOW());
Query OK, 1 row affected, 1 warning (0.24 sec)

mysql> insert into insertcurrentdate(currentDate) values(CURDATE());
Query OK, 1 row affected (0.18 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from insertcurrentdate;
This will produce the following output −
+----+-------------+
| Id | currentDate |
+----+-------------+
| 1  | 2019-04-05  |
| 2  | 2019-04-05  |
+----+-------------+
2 rows in set (0.00 sec)
Find MongoDB documents that contains specific field?

To find documents that contain specific field, use $exists. Let us create a collection with documents −
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2a31627c0c63e7dba69")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a")
}
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c")
}
Display all documents from a collection with the help of find() method −
> db.demo247.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e46b2a31627c0c63e7dba69"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "Chris",
         "ClientAge" : 34
      }
   ]
}
{
   "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "John",
         "ClientLastName" : "Smith",
         "ClientAge" : 31
      }
   ]
}
{
   "_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "David",
         "ClientAge" : 33
      }
   ]
}
{
   "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"),
   "ClientDetails" : [
      {
         "ClientFirstName" : "David",
         "ClientLastName" : "Miller",
         "ClientAge" : 31
      }
   ]
}
Following is the query to find documents that contains specific field −
> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});
This will produce the following output −
{
   "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [
      { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 }
   ]
}
{
   "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [
      { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 }
   ] 
}
Python 3 - Tkinter Bitmaps

This attribute to displays a bitmap.  There are following type of bitmaps available −
"error"
"gray75"
"gray50"
"gray25"
"gray12"
"hourglass"
"info"
"questhead"
"question"
"warning"
# !/usr/bin/python3
from tkinter import *
import tkinter

top = Tk()

B1 = Button(top, text = "error", relief = RAISED,\ bitmap = "error")
B2 = Button(t vcop, text = "hourglass", relief = RAISED,\ bitmap = "hourglass")
B3 = Button(top, text = "info", relief = RAISED,\ bitmap = "info")
B4 = Button(top, text = "question", relief = RAISED,\ bitmap = "question")
B5 = Button(top, text = "warning", relief = RAISED,\ bitmap' = "warning")

B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
map::empty() in C++ STL

In this article we will be discussing the working, syntax and examples of map::empty() function in C++ STL.
Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.
map::empty() function is an inbuilt function in C++ STL, which is defined in  header file. empty() is used to check whether the associated map container is empty or not
This function checks if the size of the container is 0 then returns true, else if there are some values then it returns false.
map_name.empty();
The function accepts no parameter.
This function returns true if the map is empty and false if it is not.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.empty();
false
std::map<int> mymap;
mymap.empty();
true
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   if(TP_1.empty()) {
      cout<<"Map is NULL";
   } else {
      cout<<"Map isn't NULL";
   }
   return 0;
}
Map isn't NULL
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   if(TP_1.empty()) {
      cout<<"Map_1 is NULL";
   } else {
      cout<<"Map_1 isn't NULL";
   }
   if(TP_2.empty()) {
      cout<<"\nMap_2 is NULL";
   } else {
      cout<<"Map_2 isn't NULL";
   }
   return 0;
}
Map_1 isn't NULL
Map_2 is NULL
How to change background color in R using ggplot2? - GeeksforGeeks

04 Jul, 2021
In this article, we will discuss how to change the background color of a ggplot2 plot in R Programming Language.
To do so first we will create a basic ggplot2 plot.
Step 1: Create sample data for the plot.
sample_data <- data.frame(x = 1:10, y = 1:10)
Step 2: Load the package ggplot2.
library("ggplot2")
Step 3: Draw a basic ggplot2 plot without any color customization.
ggplot(sample_data, aes(x, y)) + geom_point()
R
# load ggplot2library("ggplot2")  # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10)  # Draw plot with ggplot2ggplot(sample_data, aes(x, y)) + geom_point()
Output:
Basic ggplot2 plot
We will use the argument panel.background of ggplot2 to change the background color of panel of plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(panel.background = element_rect(fill = “#00ab75”)
R
# load ggplot2library("ggplot2")  # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10)  # Draw plot with changed theme using # panel.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(panel.background = element_rect(fill = "#00ab75" ))
Output:
Plot with panel background color green
We will use the argument plot.background of ggplot2 to change the background color of the plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(plot.background = element_rect(fill = “#00ab75”))
R
# load ggplot2library("ggplot2")  # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10)  # Draw plot with changed theme using # plot.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(plot.background = element_rect(fill = "#00ab75" ))
Output:
Plot with background color green
We have some pre-built themes in ggplot2 that can be used to change the complete theme in ggplot2. Themes available in ggplot are,
theme_gray
theme_bw
theme_linedraw
theme_light
theme_dark
theme_minimal
theme_classic
theme_void
theme_test
Syntax:
ggplot(sample_data, aes(x, y)) + geom_point()+ theme_dark()
R
# load ggplot2library("ggplot2")  # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10)  # Draw plot with changed theme using # different prebuilt themesggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()
Output:
Plot with dark theme in ggplot2
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Python - globals() function - GeeksforGeeks

18 Nov, 2020
globals() function in Python returns the dictionary of current global symbol table.
Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method.
The functions, variables which are not associated with any class or function are stored in global scope.
Syntax: globals()

Parameters: No parameters required.
Code #1:
# Python3 program to demonstrate global() function  # global variablea = 5  def func():    c = 10    d = c + a          # Calling globals()    globals()['a'] = d    print (d)      # Driver Code    func()
Output:
15

Code #2:
# Python3 program to demonstrate global() function  # global variablename = 'gautam'  print('Before modification:', name)  # Calling global()globals()['name'] = 'gautam karakoti'print('After modification:', name)
Output:
Before modification: gautam
After modification: gautam karakoti

Note: We can also change the value of global variables by using globals() function. The changed value also updated in the symbol table.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to create a contingency table with sum on the margins from an R data frame?

The sum of rows and columns on the margins in a contingency table are always useful because they are used for different type of calculations such as odds ratio, probability etc. If an R data frame has factor columns then we can create a contingency table for that data frame and it can be done by using addmargins function.
Consider the below data frame −
 Live Demo
x1<-sample(LETTERS[1:4],20,replace=TRUE)
x2<-sample(c("India","USA","China"),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
   x1 x2
1 B China
2 B India
3 B India
4 D India
5 B India
6 D   USA
7 D   USA
8 A   USA
9 D   USA
10 C India
11 B China
12 D China
13 D China
14 A India
15 D   USA
16 A China
17 D India
18 A China
19 B China
20 A India
Creating contingency table for x1 and x2 with sum on the margins −
>CT1<-addmargins(table(df1$x1,df1$x2),c(1,2)) 
>CT1
  China India USA Sum
A   2    2     1   5
B   3    3     0   6
C   0    1     0   1
D   2    2     4   8
Sum 7    8     5  20
Let’s have a look at another example −
 Live Demo
y1<-sample(c("John","Christina","Michael","Sona"),20,replace=TRUE)
y2<-sample(c("1","2","3","4"),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
    y1        y2
1 Sona        2
2 John        3
3 John        4
4 Sona        2
5 Christina   4
6 Michael     2
7 Michael     4
8 John        1
9 John        4
10 John       1
11 Michael    3
12 Sona       1
13 Sona       2
14 Michael    2
15 Michael    2
16 Michael    1
17 Michael    3
18 Christina  1
19 Christina  4
20 Sona       1
Creating contingency table for y1 and y2 with sum on the margins −
>CT2<-addmargins(table(df2$y1,df2$y2),c(1,2)) 
>CT2
          1  2  3  4  Sum
Christina 1  0  0  2   3
John      2  0  1  2   5
Michael   1  3  2  1   7
Sona      2  3  0  0   5
Sum       6  6  3  5  20
C library function - time()

The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.
Following is the declaration for time() function.
time_t time(time_t *t)
seconds − This is the pointer to an object of type time_t, where the seconds value will be stored.
seconds − This is the pointer to an object of type time_t, where the seconds value will be stored.
The current calendar time as a time_t object.
The following example shows the usage of time() function.
#include <stdio.h>
#include <time.h>

int main () {
   time_t seconds;

   seconds = time(NULL);
   printf("Hours since January 1, 1970 = %ld\n", seconds/3600);
  
   return(0);
}
Let us compile and run the above program that will produce the following result −
Hours since January 1, 1970 = 393923


    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
Draw Graph Grid Using Turtle in Python - GeeksforGeeks

29 Aug, 2021
Prerequisite: Turtle Programming Basics
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Approach:
Following steps are used :
Import turtle
Set screen
Make turtle
Draw the y-axis lines
Draw the x-axis lines
Draw the x-axis and y-axis with labeling.
Below is the implementation :
Python3
# import package and making objectsimport turtle  sc=turtle.Screen()trtl=turtle.Turtle() # method to draw y-axis linesdef drawy(val):         # line    trtl.forward(300)         # set position    trtl.up()    trtl.setpos(val,300)    trtl.down()         # another line    trtl.backward(300)         # set position again    trtl.up()    trtl.setpos(val+10,0)    trtl.down()     # method to draw y-axis linesdef drawx(val):         # line    trtl.forward(300)         # set position    trtl.up()    trtl.setpos(300,val)    trtl.down()         # another line    trtl.backward(300)         # set position again    trtl.up()    trtl.setpos(0,val+10)    trtl.down()     # method to label the graph griddef lab():         # set position    trtl.penup()    trtl.setpos(155,155)    trtl.pendown()         # write 0    trtl.write(0,font=("Verdana", 12, "bold"))         # set position again    trtl.penup()    trtl.setpos(290,155)    trtl.pendown()         # write x    trtl.write("x",font=("Verdana", 12, "bold"))         # set position again    trtl.penup()    trtl.setpos(155,290)    trtl.pendown()         # write y    trtl.write("y",font=("Verdana", 12, "bold"))      # Main Section# set screensc.setup(800,800)    # set turtle featurestrtl.speed(100)trtl.left(90) trtl.color('lightgreen') # y linesfor i in range(30):    drawy(10*(i+1)) # set position for x linestrtl.right(90)trtl.up()trtl.setpos(0,0)trtl.down() # x linesfor i in range(30):    drawx(10*(i+1)) # axistrtl.color('green') # set position for x axistrtl.up()trtl.setpos(0,150)trtl.down() # x-axistrtl.forward(300) # set position for y axistrtl.left(90)trtl.up()trtl.setpos(150,0)trtl.down() # y-axistrtl.forward(300) # labelinglab() # hide the turtletrtl.hideturtle()
 
 
Output :
 
 
surinderdawra388
Python-turtle
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
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
Design and Analysis Radix Sort

Radix sort is a small method that many people intuitively use when alphabetizing a large list of names. Specifically, the list of names is first sorted according to the first letter of each name, that is, the names are arranged in 26 classes.
Intuitively, one might want to sort numbers on their most significant digit. However, Radix sort works counter-intuitively by sorting on the least significant digits first. On the first pass, all the numbers are sorted on the least significant digit and combined in an array. Then on the second pass, the entire numbers are sorted again on the second least significant digits and combined in an array and so on.
Algorithm: Radix-Sort (list, n) 
shift = 1 
for loop = 1 to keysize do 
   for entry = 1 to n do 
      bucketnumber = (list[entry].key / shift) mod 10 
      append (bucket[bucketnumber], list[entry]) 
   list = combinebuckets() 
   shift = shift * 10 

Each key is looked at once for each digit (or letter if the keys are alphabetic) of the longest key. Hence, if the longest key has m digits and there are n keys, radix sort has order O(m.n).
However, if we look at these two values, the size of the keys will be relatively small when compared to the number of keys. For example, if we have six-digit keys, we could have a million different records.
Here, we see that the size of the keys is not significant, and this algorithm is of linear complexity O(n).
Following example shows how Radix sort operates on seven 3-digits number.
In the above example, the first column is the input. The remaining columns show the list after successive sorts on increasingly significant digits position. The code for Radix sort assumes that each element in an array A of n elements has d digits, where digit 1 is the lowest-order digit and d is the highest-order digit.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
How to pass parameters to a method in C#?

To pass parameters to a method in C#, let us see how to pass parameters by value. In this mechanism, when a method is called, a new storage location is created for each value parameter.
The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument.
Here is the example showing how to pass parameters to a method −
 Live Demo
using System;

namespace Demo {
   class NumberManipulator {
      public void swap(int x, int y) {
         int temp;
         temp = x;
         x = y;
         y = temp;
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         int a = 50;
         int b = 150;
         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);
         /* calling a function to swap the values */
         n.swap(a, b);
         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
         Console.ReadLine();
      }
   }
}
Before swap, value of a : 50
Before swap, value of b : 150
After swap, value of a : 50
After swap, value of b : 150
Plot parallel coordinates in Matplotlib

To plot parallel coordinates, we can take the following Steps −
Load dataset iris using Seaborn (Need internet).
Load dataset iris using Seaborn (Need internet).
Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting.
Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting.
To display the figure, use the show() method.
To display the figure, use the show() method.
import matplotlib.pyplot as plt
from pandas.plotting import parallel_coordinates
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = sns.load_dataset('iris')
parallel_coordinates(data, 'species', colormap=plt.get_cmap("Set2"))
plt.show()
How to get the Tkinter Label text?

Tkinter Labels are used to create and display text or images on the window. It has several components and functions that can be used to customize the label information such as fontfamily, padding, width, height, etc. In order to get the Label text on the window, we can write the value for the text that has to be displayed on the window.
#Import the required library
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Define the geometry of the window
win.geometry("600x250")

#Create a Label with Text
my_text= Label(win, text= "This is a New Line Text", font=('Helvetica bold', 16))
my_text.pack(pady=15)

#Print the label text
print(my_text['text'])

win.mainloop()
The above code will display the Label “This is a New Line Text” which can be printed by the print function.
Find the minimum and maximum values that can be calculated by summing exactly four of the five integers in JavaScript

Given an array of five positive integers, we are required to find the minimum and maximum values that can be calculated by summing exactly four of the five integers.
Then print the respective minimum and maximum values as a single line of two spaceseparated long integers.
The array is not sorted all the times.
For example −
const arr = [1, 3, 5, 7, 9]
The minimum sum is −
1 + 3 + 5 + 7 = 16
and the maximum sum is −
3 + 5 + 7 = 24
The return value of the function should be −
[16, 24];
The code for this will be −
const arr = [1, 3, 5, 7, 9]
const findMinMaxSum = (arr = []) => {
   let numbers = arr.slice().sort();
   let maxScore = 0;
   let minScore = 0;
   for(let i = 0; i < numbers.length − 1; i++) {
      minScore += numbers[i];
   };
   for(let j = 1; j < numbers.length; j++) {
      maxScore += numbers[j];
   };
   return [minScore, maxScore];
};
console.log(findMinMaxSum(arr));
And the output in the console will be −
[16, 24]
Program to convert Byte array to IP Address

24 Apr, 2018
Given a Byte Array, convert it to the format of IP Address.
Examples:
Input : {16, 16, 16, 16}
Output : 16.16.16.16

Input : {172, 31, 102, 14}
Output : 172.31.102.14

Byte arrays:A byte is collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes and thus control the bits. Byte arrays provide a faster way of accessing each byte in use.For more details: https://msdn.microsoft.com/en-us/library/dd126860.aspx
Syntax:
byte[] ArrayName = new byte[] 
IPAddress Class:The IPAddress class contains the address of computer on IP network. IPAddress class accommodates IP Address values passed to or returned by Simple Network Management Protocol (SNMP) agents by extending the OctetString Class. IPAddress Class comes under ‘System.Net’ namespace.
Refer Link for details: http://snmpsharpnet.sourceforge.net/ver0-4/html/T_SnmpSharpNet_IpAddress.htm
Syntax:
[Serializable]
public class IPAddress
Using Byte Arrays with IPAddress Class
IPAddress ObjectName = new IPAddress(byte[])
Approach:The IPAddress Class is used to get the IP address. The IP Address is created with the Address property set to address. If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address otherwise, an IPv6 address with a scope of 0 is constructed. The Byte array is assumed to be in network byte order with the most significant byte in index position 0.
// C# code to convert Byte array to IP Addressusing System;using System.Net;  public class GFG {      public static void Main()    {          /* Initializes a new instance of the         IPAddress class with the address         specified as a Byte Array.*/        IPAddress add = new IPAddress(new byte[]                             { 172, 31, 102, 14 });          /* ToString() Converts an Internet address        to its standard notation and         console.WriteLine is used for printing*/        Console.WriteLine(add.ToString());    }}
Output:
172.31.102.14
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flatten a Matrix in Python using NumPy

29 Aug, 2020
Let’s discuss how to flatten a Matrix using NumPy in Python. By using ndarray.flatten() function we can flatten a matrix to one dimension in python.
Syntax:numpy_array.flatten(order=’C’)
order:‘C’ means to flatten in row-major.’F’ means to flatten in column-major.’A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.’K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
Return:Flattened 1-D matrix
Example 1:
python3
# importing numpy as npimport numpy as np  # declare matrix with npgfg = np.array([[2, 3], [4, 5]])  # using array.flatten() methodflat_gfg = gfg.flatten()print(flat_gfg)
Output:
[2 3 4 5]

Example 2:
python3
# importing numpy as npimport numpy as np  # declare matrix with npgfg = np.array([[6, 9], [8, 5], [18, 21]])  # using array.flatten() methodgfg.flatten()
Output:
array([ 6,  9,  8,  5, 18, 21])

Example 3:
python3
# importing numpy as npimport numpy as np  # declare matrix with npgfg = np.array([[6, 9, 12], [8, 5, 2], [18, 21, 24]])  # using array.flatten() methodflat_gfg = gfg.flatten(order='A')print(flat_gfg)
Output:
[ 6,  9, 12,  8,  5,  2, 18, 21, 24]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Joining NumPy Array

01 Oct, 2020
NumPy provides various functions to combine arrays. In this article, we will discuss some of the major ones.
numpy.concatenate
numpy.stack
numpy.block
Method 1: Using numpy.concatenate()
The concatenate function in NumPy joins two or more arrays along a specified axis. 
Syntax:
numpy.concatenate((array1, array2, ...), axis=0)

The first argument is a tuple of arrays we intend to join and the second argument is the axis along which we need to join these arrays. Check out the following example showing the use of numpy.concatenate.
Python3
import numpy as np  array_1 = np.array([1, 2])array_2 = np.array([3, 4])  array_new = np.concatenate((array_1, array_2))print(array_new)
Output: 
[1 2 4 5]

By default, the value of the axis is set to 0. You can change it by specifying a value for the axis in the second argument. The following code joins two arrays along rows.
Python3
import numpy as np  array_1 = np.array([[1, 2], [3, 4]])array_2 = np.array([[5, 6], [7, 8]])  array_new = np.concatenate((array_1, array_2), axis=1)print(array_new)
Output:
[[1 2 5 6]
 [3 4 7 8]]

Method 2: Using numpy.stack()
The stack() function of NumPy joins two or more arrays along a new axis.
Syntax:
numpy.stack(arrays, axis=0)

The following code demonstrates the use of numpy.stack().
Python3
import numpy as np  array_1 = np.array([1, 2, 3, 4])array_2 = np.array([5, 6, 7, 8])  array_new = np.stack((array_1, array_2), axis=1)print(array_new)
Output:
[[1 5]
 [2 6]
 [3 7]
 [4 8]]

The arrays are joined along a new axis.
Method 3: numpy.block()
numpy.block is used to create nd-arrays from nested blocks of lists.
Syntax:
numpy.block(arrays)

The following example explains the working of numpy.block().
Python3
import numpy as np  block_1 = np.array([[1, 1], [1, 1]])block_2 = np.array([[2, 2, 2], [2, 2, 2]])block_3 = np.array([[3, 3], [3, 3], [3, 3]])block_4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]])  block_new = np.block([    [block_1, block_2],    [block_3, block_4]])  print(block_new)
Output:
[[1 1 2 2 2]
 [1 1 2 2 2]
 [3 3 4 4 4]
 [3 3 4 4 4]
 [3 3 4 4 4]]

In this example, we assembled a block matrix( block_new ) from 4 separate 2-d arrays (block_1,block_2,block_3,block_4 ).
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Filter even values from a list

14 Feb, 2019
Given a list of numbers, the task is to make a new list containing only even values.
Examples:
Input: list = [1, 2, 3, 4, 5]
Output: [2, 4]

Input: list = [12, 14, 95, 3]
Output: [12, 14]

 Method #1 : Using For loopIterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then append it in output list.
# Python code to filter even values from a list  # Initialisation of listlis = [1,2,3,4,5]  # Output list initialisationout = []  for num in lis:           # checking condition     if num % 2 == 0:         out.append(num)            # printing outputprint(out)
[2, 4]

 Method #2 : Using While loop
# Python code to filter even values from a list  # Initialisation of listlis = [1,2,3,4,5]num = 0  # Output list initialisationout = []while(num < len(lis)):           # checking condition     if lis[num] % 2 == 0:         out.append(lis[num])    # increment num     num += 1    # printing outputprint(out)
[2, 4]

 Method #3 : Using list Comprehension
# Python code to filter even values from a list  # Initialisation of listlis = [1,2,3,4,5]  lis2 = [i for i in lis if i%2 == 0]  # Printing outputprint(lis2)
[2, 4]

 Method #4 : Using filter()
# Python code to filter even values from a list  # Initialisation of listlis1 = [1,2,3,4,5]  is_even = lambda x: x % 2 == 0  # using filterlis2 = list(filter(is_even, lis1))  # Printing outputprint(lis2)
[2, 4]

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Count overlapping substring in a given string

20 Apr, 2020
Given a string and a sub-string, the task is to get the count of overlapping substring from the given string.
Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider this example –
string = "GeeksforGeeksforGeeksforGeeks"  print(string.count("GeeksforGeeks"))
Output:
2
The output we got here is 2, but the expected output is 3 since we also wanted to count the occurrence of overlapped sub-string.
In order to solve this problem, we can use find() function in Python. It returns the start position of the first occurrence of substring in the given string, then we increment this position by 1 and continue the search from that position till the end of the string.
Below is the implementation –
def CountOccurrences(string, substring):      # Initialize count and start to 0    count = 0    start = 0      # Search through the string till    # we reach the end of it    while start < len(string):          # Check if a substring is present from        # 'start' position till the end        pos = string.find(substring, start)          if pos != -1:            # If a substring is present, move 'start' to            # the next position from start of the substring            start = pos + 1              # Increment the count            count += 1        else:            # If no further substring is present            break    # return the value of count    return count  # Driver Codestring = "GeeksforGeeksforGeeksforGeeks"print(CountOccurrences(string, "GeeksforGeeks"))
3

prituladima
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How to create a div that contains multiple fixed-size images ?

14 Jan, 2021
What is a <div> tag ?
A <div> tag can be defined as a divider of two blocks of HTML code. It is used as a container for HTML elements which can then be styled with CSS or Javascript. Class or id attribute can be used to easily style the element in the <div> tag.
Please read more about <div> tag from this article : https://www.geeksforgeeks.org/div-tag-html/
An example on how to use a <div> tag:
HTML
<!DOCTYPE html><html>  <head>    <style>        .firstDiv {            border: 5px outset black;            background-color: green;            text-align: center;        }    </style></head>  <body>    <div class="firstDiv">        <h2>Hello Geek!</h2>          <p>How was your day like?</p>    </div></body>  </html>
Output:
Create a <div> that contains multiple fixed size images:
Approach:
First, create the <div> tag as mentioned in the previous example and insert multiple images inside a common <div> tag so that all the images have a separate <div> tag and a class name. 
The following example shows how to make a <div> tag that contains multiple fixed-size images:
HTML
<!DOCTYPE html><html>  <head>    <style>        .images {            display: flex;            flex-wrap: wrap;            margin: 0 50px;            padding: 30px;        }          .photo {            max-width: 31.333%;            padding: 0 10px;            height: 240px;        }          .photo img {            width: 100%;            height: 100%;        }    </style></head>  <body>    <div class="images">        <div class="photo">            <img src="tom1.jpg" alt="photo" />        </div>          <div class="photo">            <img src="tom2.jpg" alt="photo" />        </div>                  <div class="photo">            <img src="tom3.jpg" alt="photo" />        </div>    </div></body>  </html>
Explanation: In the above code, we have created a main container <div> class of “images” which is used to store all the images and each image has its own container <div> class of “photo” which can be later used to add special CSS properties to the images.
Images shown are contained in <div> tag of class=”images”
CSS-Misc
HTML-Misc
Picked
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between getter and setter in JavaScript?

When a property is accessed, the value gets through calling a function implicitly. The get keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
When a property is set, it implicitly calls a function and the value is passed as an argument. With that, the return value is set to the property itself. The set keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
Here’s an example showing how to implement both getter and setter
Live Demo
<html>
   <body>
      <script>
         var department = {
            deptName: "Finance",
            deptZone: "South",
            deptID: 105,
            get details() {
               return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
            },
            set details(info) {
               var res = info.toString().split(' ');
               this.deptName = res[0] || '';
               this.deptZone = res[1] || '';
               this.deptID = res[2] || '';
            }
         }
         department.details = 'Marketing North 001';
         document.write(department.deptName);
         document.write(department.deptZone);
         document.write(department.deptID);
      </script>
   </body>
</html>
Python - end parameter in print()

The print() function in python always creates a newline. But there is also a parameter for this function which can put other characters instead of new line at the end. In this article we will explore various options for this parameter.
In the below example we see various ways we can assign values to the end parameter and see the result from it.
 Live Demo
print("Welcome to ")
print("Tutorialspoint")

print("Welcome to ", end = ' ')
print("Tutorialspoint")

print("emailid",end='@')
print("tutorialspoint.com")
Running the above code gives us the following result −
Welcome to
Tutorialspoint
Welcome to Tutorialspoint
emailid@tutorialspoint.com