code-rag-bench/online-tutorials huggingface dataset:
Difference between Perl and Ruby - GeeksforGeeks

02 Nov, 2020
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. Perl was originally developed for text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++.
Perl
# Simple Perl program#!/usr/bin/perl   # Below line will print# "Welcome to GeeksforGeeks!"print "Welcome to GeeksforGeeks!\n";
Output: 
Welcome to GeeksforGeeks!


Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby has a similar syntax to that of many programming languages like C and Java, so it is easy for Java and C programmers to learn. It supports mostly all platforms like Windows, Mac, Linux.
Ruby
# Simple Ruby programputs "Welcome to GeeksforGeeks!"
Output:
Welcome to GeeksforGeeks!


Difference between Perl and Ruby :
Perl
Ruby
Perl is a high level, general-purpose, interpreted, dynamic 
programming language.
It has a very good number of libraries when it comes to 
supporting regular expression.
Perl is most often used in CGI (Common Gateway Interface) 
scripting along with C for web servers and hence used widely in the world of server technology.
balharatanvee
Difference Between
Perl
Ruby
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | Regular Expressions
Perl | String Operators
C library function - freopen()

The C library function FILE *freopen(const char *filename, const char *mode, FILE *stream) associates a new filename with the given open stream and at the same time closes the old file in the stream.
Following is the declaration for freopen() function.
FILE *freopen(const char *filename, const char *mode, FILE *stream)
filename − This is the C string containing the name of the file to be opened.
filename − This is the C string containing the name of the file to be opened.
mode − This is the C string containing a file access mode. It includes −
mode − This is the C string containing a file access mode. It includes −
"r"
Opens a file for reading. The file must exist.
"w"
Creates an empty file for writing. If a file with the same name already exists then its content is erased and the file is considered as a new empty file.
"a"
Appends to a file. Writing operations appends data at the end of the file. The file is created if it does not exist.
"r+"
Opens a file to update both reading and writing. The file must exist.
"w+"
Creates an empty file for both reading and writing.
"a+"
Opens a file for reading and appending.
stream − This is the pointer to a FILE object that identifies the stream to be re-opened.
stream − This is the pointer to a FILE object that identifies the stream to be re-opened.
If the file was re-opened successfully, the function returns a pointer to an object identifying the stream or else, null pointer is returned.
The following example shows the usage of freopen() function.
#include <stdio.h>

int main () {
   FILE *fp;

   printf("This text is redirected to stdout\n");

   fp = freopen("file.txt", "w+", stdout);

   printf("This text is redirected to file.txt\n");

   fclose(fp);
   
   return(0);
}
Let us compile and run the above program that will send the following line at STDOUT because initially we did not open stdout −
This text is redirected to stdout

After a call to freopen(), it associates STDOUT to file file.txt, so whatever we write at STDOUT that goes inside file.txt. So, the file file.txt will have the following content.
This text is redirected to file.txt

Now let's see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

    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
Tryit Editor v3.7

Tryit: JavaScript - change attribute value
How do you plot a vertical line on a time series plot in Pandas?

Using Pandas, we will create a dataframe and set the vertical lines on the created axes, using axvline lines.
Using panda we can create a data frame.
Using panda we can create a data frame.
Creating a data frame would help to create help.
Creating a data frame would help to create help.
Using axvline(), add a vertical line across the axes, where color is green, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is green, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is red, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is red, linestyle="dashed".
Using plt.show(), show the plot.
Using plt.show(), show the plot.
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame(index=pd.date_range("2019-07-01", "2019-07-31"))
df["y"] = 1
ax = df.plot()
ax.axvline("2019-07-24", color="green", linestyle="dashed")
ax.axvline("2019-07-31", color="red", linestyle="dashed")
plt.show()
Find total number of distinct years from a string in C++ Program

In this tutorial, we are going to write a program that finds distinct years in the given string. Let's see some examples. We are assuming the date format is DD/MM/YYYY.
Input − Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.
Output − 2
We have two distinct years in the given text 2020 and 2019.
We are going to use regex to extract all dates from the given string. If you are not familiar with regex in C++, go through this tutorial.
Let's jump into solving the problem.
Initialize the text.
Initialize the text.
Write the regex to extract dates from the text.
Write the regex to extract dates from the text.
Initialize an empty unordered set.
Initialize an empty unordered set.
Iterate over the dates and add year to the unordered set to find unique years.
Iterate over the dates and add year to the unordered set to find unique years.
Print the length of the set.
Print the length of the set.
Let's see the code.
 Live Demo
#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int uniqueYearsCount(string text) {
   // regex
   regex date_regex("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}");
   smatch matching_date;
   // set to store unique dates
   unordered_set<string> dates;
   // finding all dates
   while (regex_search(text, matching_date, date_regex)) {
      string date = matching_date[0];
      dates.insert(date.substr(date.size() - 4));
      text = matching_date.suffix();
   }
   return dates.size();
}
int main() {
   string text = "Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.";
   cout << uniqueYearsCount(text) << endl;
   return 0;
}
If run the above code, then you will get the following result.
2
We can get dates in a different formats. If you get dates in different formats, then update the regex appropriately.
If you have any queries in the tutorial, mention them in the comment section.
What is the difference between attributes and properties in python?

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc.
Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.
However, there is a property decorator in Python which provides getter/setter access to an attribute Properties are a special kind of attributes. Basically, when Python encounters the following code:
foo = SomeObject()
print(foo.bar)
it looks up bar in foo, and then examines bar to see if it has a __get__, __set__, or __delete__ method and if it does, it's a property. If it is a property, instead of just returning the bar object, it will call the __get__ method and return whatever that method returns.
In Python, you can define getters, setters, and delete methods with the property function. If you just want the read property, there is also a @property decorator you can add above your method.
class C(object):
    def __init__(self):
        self._x = None
#C._x is an attribute
@property
    def x(self):
        """I'm the 'x' property."""
        return self._x
# C._x is a property   This is the getter method
@x.setter # This is the setter method
    def x(self, value):
        self._x = value
@x.deleter # This is the delete method
    def x(self):
        del self._x
How to pass Arrays to Methods in Java?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.
Suppose we have two methods min() and max() which accepts an array and these methods calculates the minimum and maximum values of the given array respectively:
 Live Demo
import java.util.Scanner;

public class ArraysToMethod {
   public int max(int [] array) {
      int max = 0;

      for(int i=0; i<array.length; i++ ) {
         if(array[i]>max) {
            max = array[i];
         }
      }
      return max;
   }

   public int min(int [] array) {
      int min = array[0];
   
      for(int i = 0; i<array.length; i++ ) {
         if(array[i]<min) {
            min = array[i];
         }
      }
      return min;
   }

   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      ArraysToMethod m = new ArraysToMethod();
      System.out.println("Maximum value in the array is::"+m.max(myArray));
      System.out.println("Minimum value in the array is::"+m.min(myArray));
   }
}
Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
45
12
48
53
55
Maximum value in the array is ::55
Minimum value in the array is ::12
DateTime.DaysInMonth() Method in C# - GeeksforGeeks

22 Jan, 2019
This method returns the number of days in the specified month and year. This method always interprets month and year as the month and year of the Gregorian calendar even if the Gregorian calendar is not the current culture’s current calendar.
Syntax:
public static int DaysInMonth (int year, int month);
Return Value: This method return the number of days in the month for the specified year. For example, if month equals 2 for February, the return value will be 28 or 29 depending upon whether the year is a leap year.
Exception: This method will give ArgumentOutOfRangeException if month is less than 1 or greater than 12 or year is less than 1 or greater than 9999.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System;  class GFG {      // Main Method    static void Main()    {          // taking month values        int Dec = 12;        int Feb = 2;          // using the method        int daysindec = DateTime.DaysInMonth(2008, Dec);          Console.WriteLine(daysindec);          // daysinfeb1 gets 29 because the        // year 2016 was a leap year.        int daysinfeb1 = DateTime.DaysInMonth(2016, Feb);          Console.WriteLine(daysinfeb1);          // daysinfeb2 gets 28 because        // the year 2018 was not a leap year.        int daysinfeb2 = DateTime.DaysInMonth(2018, Feb);          Console.WriteLine(daysinfeb2);    }}
Output:
31
29
28

Example 2:
// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System;  class GFG {      // Main Method    static void Main()    {          // taking month and year's value        int y = 10000;        int m = 7;          // using the method will give error        // as the value of the year is greater        // than 10000        int res = DateTime.DaysInMonth(y, m);          Console.WriteLine(res);    }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Year must be between 1 and 9999.Parameter name: year
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.daysinmonth?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
Extension Method in C#
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
Common Language Runtime (CLR) in C#
Different ways to sort an array in descending order in C#
C# | Arrays
HashSet in C# with Examples
Implementing a Binary Search Tree in JavaScript

A tree is a collection of nodes connected by some edges. Conventionally, each node of a tree
holds some data and reference to its children.
Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right.
For instance, visual representation of a valid BST is −
     25
   /   \
  20   36
 / \   / \
10 22 30 40
Let’s now implement our very own Binary Search Tree in JavaScript language.
This class will represent a single node present at various points in the BST. A BST is nothing
but a collection of nodes storing data and child references placed according to the rules
described above.
class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
To create a new Node instance, we can call this class like this with some data −
const newNode = new Node(23);
This will create a new Node instance with data set to 23 and left and right reference both being null.
class BinarySearchTree{
   constructor(){
      this.root = null;
   };
};
This will create the Binary Search Tree class which we can call with the new keyword to make a
tree instance.
Now as we are done with the basic stuff let’s move on to inserting a new node at the right place (according to the rules of BST described in definition).
class BinarySearchTree{
   constructor(){
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);
How do I get rid of the Python Tkinter root window?

Sometimes, while testing a Tkinter application, we may need to hide the Tkinter
default window or frame. There are two general methods through which we can either hide our Tkinter window, or destroy it.
The mainloop() keeps running the Tkinter window until it is not closed by external events. In order to destroy the window we can use the destroy() callable method.
However, to hide the Tkinter window, we generally use the “withdraw” method that
can be invoked on the root window or the main window.
In this example, we have created a text widget and a button “Quit” that will close the root window immediately. However, we can also use the withdraw method to avoid displaying it on the screen.
#Import the library
from tkinter import *

#Create an instance of window
win= Tk()

#Set the geometry of the window
win.geometry("700x400")

def disable_button():
   win.destroy()
#Create a Label
Label(win,text="Type Something",font=('Helvetica bold', 25),
fg="green").pack(pady=20)

#Create a Text widget
text= Text(win, height= 10,width= 40)
text.pack()

#Create a Disable Button
Button(win, text= "Quit", command= disable_button,fg= "white",
bg="black", width= 20).pack(pady=20)

#win.withdraw()
win.mainloop()
The above python code hides the root window using the withdraw method. However, to destroy the window, we can use the destroy method.
When you click the Quit button, it will hide the root window.
Python - Characters Index occurrences in String - GeeksforGeeks

09 Mar, 2020
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using set() + regex + list comprehension + replace()The combination of above functions can be used to perform this task. In this, set() is used to get elements whose frequency has to be computed. The task of assembling to dictionary accordingly is performed using regex function and list comprehension.
# Python3 code to demonstrate working of # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()import re   # initializing stringtest_str = "Gfg is best for geeks"  # printing original stringprint("The original string is : " + test_str)  # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()temp = set(test_str.replace(' ', ''))res = {ele: [sub.start() for sub in re.finditer(ele, test_str)] for ele in temp}  # printing result print("Characters frequency index dictionary : " + str(res)) 
The original string is : Gfg is best for geeks
Characters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}

 
Method #2 : Using loop + enumerate()This is yet another way in which this task can be performed. In this we create a dictionary and then iterate the string to map the characters with their respective characters.
# Python3 code to demonstrate working of # Characters Index occurrences in String# Using loop + enumerate()import re   # initializing stringtest_str = "Gfg is best for geeks"  # printing original stringprint("The original string is : " + test_str)  # Characters Index occurrences in String# Using loop + enumerate()res = {ele : [] for ele in test_str}   for idx, ele in enumerate(test_str):    res[ele].append(idx)  # printing result print("Characters frequency index dictionary : " + str(res)) 
The original string is : Gfg is best for geeks
Characters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Double isNaN() method in Java with examples - GeeksforGeeks

26 Oct, 2018
The isNaN() method of Java Double class is a built in method in Java returns true if this Double value or the specified double value is Not-a-Number (NaN), or false otherwise.
Syntax:
public boolean isNaN()
        or
public static boolean isNaN(double val)
Parameters: The function accepts a single parameter val which specifies the value to be checked when called directly with the Double class as static method. The parameter is not required when the method is used as instance method.
Return Value: It returns true if the val is NaN else it return false.
Below programs illustrate isNaN() method in Java:
Program 1:
// Java code to demonstrate// Double isNaN() method// without parameter  class GFG {    public static void main(String[] args)    {          // first example        Double f1 = new Double(1.0 / 0.0);          boolean res = f1.isNaN();          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");          // second example        f1 = new Double(0.0 / 0.0);          res = f1.isNaN();          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");    }}
Infinity is not NaN
NaN is NaN

Program 2:
// Java code to demonstrate// Double isNaN() method// with parameter  class GFG {    public static void main(String[] args)    {          // first example        Double f1 = new Double(1.0 / 0.0);          boolean res = f1.isNaN(f1);          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");          // second example        f1 = new Double(0.0 / 0.0);          res = f1.isNaN(f1);          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");    }}
Infinity is not NaN
NaN is NaN

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#isNaN()
java-basics
Java-Double
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
How to Append Two Tables and Put the Result in a Table in SQL? - GeeksforGeeks

14 Sep, 2021
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will learn how to append two tables and store the result into a new table using UNION, UNION ALL.
Syntax:
SELECT column_one, column_two,..column_N INTO Table_name FROM table_name
UNION  SELECT column_one,column_two,column_three,.. column_N FROM table_name;
Syntax:
SELECT column_one, column_two,column_three,.. column_N INTO Table_name FROM
table_name UNION SELECT column_one, column_two, column_three,..column_N
 FROM table_name;
The difference between Union and Union All is UNION doesn’t include duplicates, but UNION ALL includes duplicates too. Both are used with similar syntax.
Consider the following tables of two departmental stores data
Database: Shop1
Command used to create the table
Query:
CREATE TABLE Shop1(Item_Id int,Name varchar(20),Count int)
Output:
Database: Shop2
Command used to create the table
Query:
CREATE TABLE Shop2(Item_Id int,Name varchar(20),Count int)
Output:
Method 1: Using UNION Keyword
In order to join the two tables i.e. Shop1 and Shop2 we run the following command:
Query:
SELECT * INTO joined FROM Shop1 UNION SELECT * FROM Shop2;
The above command joins Shop1 and Shop2 into a new table joined which is as follows and can be viewed by the following command:
Query:
SELECT * FROM joined;
So the joined table doesn’t include duplicates as we have used UNION Keyword
Here is the output when we execute the query
Output:
Method 2: Using UNION ALL Keyword
Query:
SELECT * INTO joined2 FROM Shop1 UNION ALL SELECT * FROM Shop2;
The above command creates a new table names joined2 which includes all the values of Shop1 and Shop2.
We run the following command for viewing the table
Query:
SELECT * FROM joined2;
Here is the output when we execute the query.
Output:
Picked
SQL-Query
How To
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
Streamline Plots in Plotly using Python - GeeksforGeeks

05 Sep, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, streamline plots are based on the representation on a 2-D vector field which is explained as velocity fields, which are consist of closed curves that are tangent to the velocity field. Streamlining is the fastest technique and more efficient for getting the data. Velocity values are interpolated when determining the streamlines. Streamlines are initialized on the boundary of the x-y domain.
Syntax: create_streamline(x, y, u, v, density=1, angle=0.3490658503988659, arrow_scale=0.09)
Parameters:
x: 1 dimensional, evenly spaced list or array
y: 1 dimensional, evenly spaced list or array
u: 2 dimensional array
v: 2 dimensional array
density: controls the density of streamlines in plot. This is multiplied by 30 to scale similiarly to other available streamline functions such as matplotlib. Default = 1
angle: angle of arrowhead. Default = pi/9
arrow_scale: value to scale length of arrowhead Default = .09
Example:
Python3
import plotly.figure_factory as ffimport numpy as np  x = np.linspace(-1, 1, 10)y = np.linspace(-1, 1, 10)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2  # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1)fig.show()
Output:
The source point can be plot using the scatterplot() method of the graph_objects class. In this, the streamline plot and the position of the marker in the scatterplot are tweaked in such a way that it seems that all the stream is originating from a particular source.
Example:
Python3
import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np  x = np.linspace(-1, 2, 50)y = np.linspace(-1, 1, 50)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.cos(y)*X  # Source for x and y coordinate# of scatter plotX, Y = 0, 0  # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1)  fig.add_trace(go.Scatter(x=[X], y=[Y],                          mode='markers',                          marker_size=15,                        ))  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python - turtle.pencolor() method - GeeksforGeeks

29 Jul, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to change the color of the ink of the turtle drawing. The default color is black.
Syntax: turtle.pencolor(*args) 
Arguments: This method have following arguments:
colorstring: (optional) colorstring A string of color name like “red”, “green”, etc.
(r, g, b): (optional) A tuple of three values r, g, and b using rgb color code.
r, g, b: (optional) Three values r, g, and b using rgb color code.
Return: None
Below is the implementation of above method with an example :
Python3
# importing turtle packageimport turtle # set turtle shapeturtle.shape("turtle") # set the colormodeturtle.colormode(255) # use forward by 100 pixel# default pen color is  blackturtle.forward(100) # change the pencolor# pencolor is redturtle.pencolor("red") # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is blueturtle.pencolor((41,41,253)) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is greenturtle.pencolor(41,253,41) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # This code is contributed# by Deepanshu Rustagi.
 
 
Output :
 
 
surindertarika1234
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Fork and Join Constructs in Concurrency

06 Jul, 2020
Prerequisite – Process SynchronizationFork :The fork instruction is the that instruction in the process execution that produces two concurrent executions in a program. One of the concurrent executions starts at statement labeled and other execution is the continuation of the execution at the statement following the fork instruction. The fork systems call assignment has one parameter i.e. Label (L).
Join :The join instruction is the that instruction in the process execution that provides the medium to recombine two concurrent computations into a single one. The join instruction has one parameter integer count that specifies the number of computations which are to be joined. It decrements the integer by one. If the value of the integer after decrement is non-zero then the process terminates otherwise the process continues execution with the next statement.
Example-1:Construct the precedence graph for the following fork/join program.
     S1;
     count1: = 2;
     fork L1;
     S2;
     S4;
     count2: = 2;
     fork L2;
     S5;
     Go to L3;
L1:  S3;
L2:  join count1;
     S6;
L3:  join count2;
     S7;

Solution :
Example-2 :Write a fork/join program for the following precedence graph.
Solution :After S1 fork statement is required to create a child.After S4 fork statement is required to create a child.All processes need to join before S7.
     S1;
     count: = 3;
     fork L1;
     S2;
     S4;
     fork L2;
     S5;
     Go to L3;
L2:  S6;
     GOTO L3;
L1:  S3;
L3:  join count;
     S7; 
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a MySQL Sequence?

In MySQL, a sequence refers to a list of integers that is generated in the ascending order beginning from 1 or 0 if specified. Many applications require sequences that will be used to generate unique numbers especially for identification.
Examples include customer ID in CRM, employee numbers in HR, and equipment numbers in the services management system.
To create a sequence in MySQL automatically, the AUTO_INCREMENT attribute for a column needs to be set. This would typically be a primary key column.
The following rules need to be followed while using the AUTO_INCREMENT attribute −
Every table has only one AUTO_INCREMENT column whose data type would be an integer
typically.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a PRIMARY
KEY or a UNIQUE index.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds the
NOT NULL constraint to the column on its own.
Let us see an example of creating a MySQL sequence −
CREATE TABLE tableName (
   emp_no INT AUTO_INCREMENT PRIMARY KEY,
   first_name VARCHAR(50),
   last_name VARCHAR(50)
)
Let us understand how the AUTO_INCREMENT column works −
The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement.
The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement.
To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used.
To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used.
The last generated sequence is unique across sessions.
The last generated sequence is unique across sessions.
If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function.
If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function.
If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column.
If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column.
Python | Insert character after every character pair

04 Jul, 2019
Sometimes, we can have a problem in which we need to insert a specific character after pair(second) character. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in Machine Learning domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using join() + list comprehensionThe combination of above method can be used to perform this particular task. List comprehension along with slicing can be used to convert string to list and join function can be used to rejoin them inserting required character between them.
# Python3 code to demonstrate working of# Insert character after every character pair# Using join() + list comprehension  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # Using join() + list comprehension# Insert character after every character pairres = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2))  # printing result print("The string after inserting comma after every character pair : " + res)
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek, s

 
Method #2 : Using zip() + join()The combination of above functions can be used to perform this particular task. In this, zip function converts the characters to iterable tuples, split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to list of strings and at last result is joined using the join function.
# Python3 code to demonstrate working of# Insert character after every character pair# Using zip() + join()  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # Using zip() + join()# Insert character after every character pairres = ', '.join(a + b for a, b in zip(test_str[::2], test_str[1::2]))  # printing result print("The string after inserting comma after every character pair : " + res)
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
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 | Convert string dictionary to dictionary
How to Install Eclipse for C++ on Linux?

16 Oct, 2021
Eclipse is an IDE (integrated development environment) used for building software. It was initially released by IBM on 7 November 2001. Using eclipse, we can develop applications with Java, PHP, and C/C++ programming languages. It’s one of the most popular open-source IDE among developers. In today’s article, we are going to cover how we can install Eclipse for C/C++ Developers to develop applications in C or C++ on a Linux machine.
Follow the below step-by-step guide to install Eclipse for C/C++:
Step 1: Download the eclipse launcher by going through this link:
downloading the eclipse
Step 2: Extract the downloaded file using the following command:
tar -xvf eclipse-cpp-2021-09-R-linux-gtk-x86_54.tar.gz
The tar is a utility tool to make operations on archives, to extract, to make, to list, and to rename the archives. Here, -xvf flag stands for extract, verbose, and file.
Extracting
Step 3: Navigate to the extracted folder and run the following commands to install Alacarte menu that will help us to create a desktop shortcut for Eclipse.
After extracting the eclipse installer, create a shortcut for the launcher:
Alacarte is a menu editor for the GNOME desktop. It is written in Python. It has been part of GNOME since the 2.16 release. To install the Alacarte for creating a custom shortcut icon.
sudo apt-get install alacarte
installing alacarte
Step 4: Configuring the shortcut by running the alacarte:
alacarte
Creating shortcut
In the first step click on the New item button on the right side, a pop-up window will open as in the above figure. Select executable from the extracted folder and click on the ok button. This will create a shortcut application in the programs.
Step 5: To launch the eclipse simple search for Eclipse, a icon will appear and click enter. This will launch the Eclipse IDE.
Eclipse installed
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
Create digital clock using Python-Turtle

02 Jul, 2021
Prerequisites: Turtle Programming in PythonTurtle is a special feature of Python. Using Turtle, we can easily draw on a drawing board. First, we import the turtle module. Then create a window, next we create a turtle object and using the turtle methods we can draw in the drawing board.Installation: To install this module type the below command in the terminal.  
pip install turtle
Note: To create a clock we will use the ‘time’ and ‘DateTime’ module of Python also, To install time use the following command:
Below is the implementation.  
Python3
import timeimport datetime as dtimport turtle       # create a turtle to display timet = turtle.Turtle() # create a turtle to create rectangle boxt1 = turtle.Turtle() # create screens = turtle.Screen() # set background color of the screens.bgcolor("green")  # obtain current hour, minute and second# from the systemsec = dt.datetime.now().secondmin = dt.datetime.now().minutehr = dt.datetime.now().hourt1.pensize(3)t1.color('black')t1.penup()  # set the position of turtlet1.goto(-20, 0)t1.pendown()  # create rectangular boxfor i in range(2):    t1.forward(200)    t1.left(90)    t1.forward(70)    t1.left(90)     # hide the turtlet1.hideturtle() while True:    t.hideturtle()    t.clear()    # display the time    t.write(str(hr).zfill(2)            +":"+str(min).zfill(2)+":"            +str(sec).zfill(2),            font =("Arial Narrow", 35, "bold"))    time.sleep(1)    sec+= 1         if sec == 60:        sec = 0        min+= 1         if min == 60:        min = 0        hr+= 1         if hr == 13:        hr = 1
Output:  
 
romy421kumari
anikaseth98
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Regex Lookahead

03 Jan, 2021
Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser’s current position. They don’t match anything. Hence, they are called as zero-width assertions.
Syntax:
# Positive lookahead
(?=<lookahead_regex>)

Example 1:
Python3
# importing regeximport re  # lookahead exampleexample = re.search(r'geeks(?=[a-z])', "geeksforgeeks")  # display outputprint("Pattern:", example.group())print("Pattern found from index:",      example.start(), "to",      example.end())
Output:
Pattern: geeks
Pattern found from index: 0 to 5
The lookahead assertion (?=[a-z]) specifies that what follows geeks must be a lowercase alphabetic character. In this case, it’s the character f, a match is found.
Example 2:
Python3
# importing regeximport re  # Lookahead exampleexample = re.search(r'geeks(?=[a-z])',                     "geeks123")  # outputprint(example)
Output:
None
In the above example, the output is None because the next character after geeks is 1. It is not a lowercase alphabetic character.
Lookahead portion is not part of the search string. Hence, it is termed as zero width assertion. They are important when you don’t want the output to return lookahead portion present in search string but want to use it to match pattern which is followed by a particular section. Below example will make this clear.
Example 3:
Python3
# import required moduleimport re  # using lookaheadexample1 = re.search(r'geeks(?=[a-z])',                     "geeksforgeeks")  print('Using lookahead:', example1.group())  # without using lookaheadexample2 = re.search(r'geeks([a-z])',                     "geeksforgeeks")  print('Without using lookahead:', example2.group())
Output:
Using lookahead: geeks
Without using lookahead: geeksf
Using lookahead the output generated is ‘geeks’ whereas without using lookahead the output generated is geeksf. The f is consumed by regex and it becomes part of the search string. 
Negative lookahead is opposite of lookahead. It is to assure that the search string is not followed by <lookahead_regex>.
Syntax:
# Negative Lookahead
(?!<lookahead_regex>) 

Example 4:
Python3
# import required moduleimport re  # positive lookaheadexample1 = re.search('geeks(?=[a-z])',                     'geeksforgeeks')print('Positive Lookahead:', example1.group())  # negative lookaheadexample2 = re.search('geeks(?![a-z])',                     'geeks123')print('Negative Lookahead:', example2.group())
Output:
Positive Lookahead: geeks
Negative Lookahead: geeks
In the above example, the output is geeks because search string geeks here is not followed by lowercase letters.
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
CONVERT_TZ() function in MySQL

25 Nov, 2020
CONVERT_TZ() function in MySQL is used to convert the given DateTime from One time zone to another time zone. If the arguments are invalid, the function will return NULL. 
Syntax :
CONVERT_TZ (dt, from_tz,to_tz) 
Parameters: This method accepts a three-parameter.
dt: The given DateTime which we want to convert.
from_tz: The time zone from which we want to convert DateTime.
to_tz: The time zone in which we want to convert DateTime.
Returns :It returns the DateTime after converting into a specified timezone.
Example-1 :
Converting the DateTime from GMT(Greenwich Mean Time) to IST(Indian Standard time)
SELECT CONVERT_TZ('2020-11-19 19:59:00', '+00:00', '+05:30') 
As IST_TIME;

Output :
Example-2 :
Converting the DateTime from GMT(Greenwich Mean Time) to GST (Gulf Standard Time)
SELECT CONVERT_TZ('2020-11-19 10:53:00', '+00:00', '+04:00') 
As GST_TIME;

Output :
Example-3 :
The CONVERT_TZ function can be used to set the value of columns. To demonstrate create a table named FlightDetails.
CREATE TABLE FlightDetails(
FlightId INT NOT NULL,
Source VARCHAR(20) NOT NULL,
Destination VARCHAR(20) NOT NULL,
DepartureTime DATETIME NOT NULL,
ArrivalTime DATETIME NOT NULL,
PRIMARY KEY(FlightId )
);



Now inserting values in FlightDetails table. We will use the CONVERT_TZ function to check departure and arrival times in both source and destination airports.
INSERT INTO  
FlightDetails(FlightId, Source, Destination, 
              DepartureTime , ArrivalTime )
VALUES
(12345, 'New York', 'New Delhi', '2020-11-19 10:53:00',
                                 '2020-11-20 12:53:00');

Now, checking the FlightDetails
SELECT 
FlightId , Source ,Destination , 
DepartureTime  AS DepTimeInEST ,
CONVERT_TZ(DepartureTime, '-05:00', '+05:30') 
As DepTimeInIST ,

ArrivalTime  AS ArrTimeInIST ,
CONVERT_TZ(ArrivalTime , '+05:30', '-05:00') 
As ArrTimeInEST 
FROM FlightDetails;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?