code-rag-bench/online-tutorials huggingface dataset:
How to rotate only text in annotation in ggplot2? - GeeksforGeeks

03 Mar, 2021
R has ggplot2 which is a data visualization package for the statistical programming language R. After analyzing and plotting graphs, we can add an annotation in our graph by annotate() function.
Syntax: annotate()
Parameters:
geom : specify text
x : x axis location
y : y axis location
label : custom textual content
color : color of textual content
size : size of text
fontface : fontface of text
angle : angle of text
Approach
Import module
Create dataframe
Plot graph
Use annotate() function with required parameters
First, let’s create a simple line plot.
Program:
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                 b=c(5, 10, 15))  # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  # angle=90plot + annotate('text', x = 6, y = 10,                 label = 'GeeksForGeeks',                size = 10,                angle='90')
Output:
We can rotate text in annotation by angle parameter. To modify the angle of text, an “angle” argument is used. In the below example, the angle assigned to the text “GeeksForGeeks” is 180. 
To change the font face of text, use fontface argument and assign one type of font face like bold, Italic, etc. Here, an italic font-face is assigned to the text.
Program :
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                 b=c(5, 10, 15))  # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  plot + annotate('text', x = 6, y = 7.5,                   label = 'GeeksForGeeks',                  size = 10,                  fontface='bold',                  angle='180')
Output:
Example 2:
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                 b=c(5, 10, 15))   # Basic plotmyplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  myplot + annotate('text', x = 6, y = 10,                   label = 'GeeksForGeeks',                  size = 10,                  angle='90')
Output:
Picked
R-ggplot
Technical Scripter 2020
R Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
Wand noise() function – Python

04 Oct, 2021
The noise() function is an inbuilt function in the Python Wand ImageMagick library which is used to add noise to the image.
Syntax: 
noise(noise_type, attenuate, channel)
Parameters: This function accepts three parameters as mentioned above and defined below: 
noise_type: This parameter is used to store the noise type. Some of the available noise types are ‘undefined’, ‘uniform’, ‘gaussian’, ‘multiplicative_gaussian’, ‘impulse’, ‘laplacian’, ‘poisson’, ‘random’.
attenuate: This parameter stores the rate of distribution.
channel: This parameter stores the channel type as “green”, “yellow”, “red” etc.
Return Value: This function returns the Wand ImageMagick object.
Original Image:  
Example 1:  
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image:    # Clone the image in order to process    with image.clone() as noise:        # Invoke noise function with Channel "green" and noise poisson        noise.noise("poisson", 2, "green")        # Save the image        noise.save(filename ='noise1.jpg')
Output: 
Example 2:  
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw:    # Set Stroke color the circle to black    draw.stroke_color = Color('black')    # Set Width of the circle to 2    draw.stroke_width = 1    # Set the fill color to 'White (# FFFFFF)'    draw.fill_color = Color('white')     # Invoke Circle function with center at 50, 50 and radius 25    draw.circle((200, 200), # Center point                (100, 100)) # Perimeter point    # Set the font style    draw.font = '../Helvetica.ttf'    # Set the font size    draw.font_size = 30         with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic:        # Set the text and its location        draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !')        # Draw the picture        draw(pic)        # Invoke noise function with channel "yellow" and noise as impulse        pic.noise("impulse", 3, "yellow")        # Save the image        pic.save(filename ='noise2.jpg')
Output: 
 
sweetyty
gabaa406
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Underscore.js _.extend() Function

25 Nov, 2021
The _.extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.
Syntax:
_.extend(destination, *sources)
Parameters: This function accept two parameters as mentioned above and described below:
destination: This parameter holds the destination object file.
sources: This parameter holds the source object file.
Return Value: It returns a copy all of the properties of the source objects over the destination object, and return the destination object.
Example 1:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          var obj1 = {            key1: 'Geeks',        };          var obj2 = {            key2: 'GeeksforGeeks',        };          console.log(_.extend(obj1, obj2));    </script></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          var obj1 = {            key1: 'Geeks',        };          var obj2 = {            key2: 'GeeksforGeeks',        };          console.log(_.extend({            Company: 'GeeksforGeeks',            Address: 'Noida'        }, {            Contact: '+91 9876543210',            Email: 'abc@gfg.com'        }, {            Author: 'Ashok'        }));    </script></body>  </html>
Output:
JavaScript - Underscore.js
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Stream mapToLong() in Java with examples

06 Dec, 2018
Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
LongStream mapToLong(ToLongFunction<? super T> mapper)

Where, LongStream is a sequence of primitive 
long-valued elements and T is the type 
of stream elements. mapper is a stateless function 
which is applied to each element and the function
returns the new stream.

Example 1 : mapToLong() function with operation of returning stream satisfying the given function.
// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          System.out.println("The stream after applying "                        + "the function is : ");          // Creating a list of Strings        List<String> list = Arrays.asList("25", "225", "1000",                                                  "20", "15");          // Using Stream mapToLong(ToLongFunction mapper)        // and displaying the corresponding LongStream        list.stream().mapToLong(num -> Long.parseLong(num))            .filter(num -> Math.sqrt(num) / 5 == 3 )            .forEach(System.out::println);    }}
Output :
The stream after applying the function is : 
225

Example 2 : mapToLong() function with returning number of set-bits in string length.
// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a list of Strings        List<String> list = Arrays.asList("Data Structures", "JAVA", "OOPS",                                             "GeeksforGeeks", "Algorithms");          // Using Stream mapToLong(ToLongFunction mapper)        // and displaying the corresponding LongStream        // which contains the number of one-bits in         // binary representation of String length        list.stream().mapToLong(str -> Long.bitCount(str.length()))            .forEach(System.out::println);    }}
Output :
4
1
1
3
2

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to List All Tables in a Schema in Oracle Database?

06 Jul, 2022
Prerequisite: Create Database in MS SQL Server
There are multiple ways to list all the tables present in a Schema in Oracle SQL. Such ways are depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database. 
Method 1: This method lists all the information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user).
Query:
SELECT * FROM SYSOBJECTS 
WHERE XTYPE='U';
Output:
Method 2: This method lists only selective information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user). Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected.
Query:
SELECT NAME,CRDATE,REFDATE 
FROM SYSOBJECTS WHERE XTYPE='U';
Output:
Method 3: This method lists all the information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators.
Query:
SELECT * FROM SYSOBJECTS;
Output:
Method 4: This method lists only selective information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators. Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected.
Query:
SELECT NAME,CRDATE,REFDATE
FROM SYSOBJECTS;
Output:
simmytarika5
Oracle
Picked
SQL-Server
SQL
Oracle
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
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
Python Regex | Program to accept string ending with alphanumeric character

10 Jun, 2021
Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples:  
Input: ankitrai326
Output: Accept

Input: ankirai@
Output: Discard
In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Alphanumeric characters in the POSIX/C locale consist of either 36 case-insensitive symbols (A-Z and 0-9) or 62 case-sensitive characters (A-Z, a-z and 0-9).Let’s see the Python program for this :  
Python3
# Python program to accept string ending# with only alphanumeric character.# import re module # re module provides support# for regular expressionsimport re # Make a regular expression to accept string# ending with alphanumeric characterregex = '[a-zA-z0-9]$'     # Define a function for accepting string# ending with alphanumeric characterdef check(string):      # pass the regular expression     # and the string in search() method    if(re.search(regex, string)):        print("Accept")             else:        print("Discard")      # Driver Codeif __name__ == '__main__' :         # Enter the string    string = "ankirai@"         # calling run function    check(string)     string = "ankitrai326"    check(string)     string = "ankit."    check(string)     string = "geeksforgeeks"    check(string)
Output :  
Discard
Accept
Discard
Accept
 
surinderdawra388
Python Regex-programs
python-regex
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
Python String | replace()
How to Install PIP on Windows ?
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
sympy.stats.Weibull() in Python

08 Jun, 2020
With the help of sympy.stats.Weibull() method, we can get the continuous random variable which represents the Weibull distribution.
Syntax : sympy.stats.Weibull(name, alpha, beta)Where, alpha and beta are real number.
Return : Return the continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.Weibull() method, we are able to get the continuous random variable representing Weibull distribution by using this method.
# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint  z = Symbol("z")a = Symbol("a", positive = True)l = Symbol("l", positive = True)  # Using sympy.stats.Weibull() methodX = Weibull("x", a, l)gfg = density(X)(z)  pprint(gfg)
Output :
l/z\l – 1 -|-|/z\ \a/l*|-| *e\a/—————–a
Example #2 :
# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint  z = 2a = 3l = 4  # Using sympy.stats.Weibull() methodX = Weibull("x", a, l)gfg = density(X)(z)  pprint(gfg)
Output :
-16—-8132*e——–81
Python SymPy-Stats
SymPy
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
turtle.register_shape() function in Python

28 Jul, 2020
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 function is used to add a turtle shape to TurtleScreen’s shapelist.
Syntax :
turtle.register_shape(name, shape=None)

Parameters:
Below is the implementation of the above method with an example :
Python3
# import packageimport turtle  # record a polygonturtle.begin_poly()  # form a polygonturtle.seth(-45)turtle.circle(20, 90)turtle.circle(10, 90)turtle.circle(20, 90)turtle.circle(10, 90)  turtle.end_poly()  # get polygonpairs = turtle.get_poly()  # register shape with# name : new_shape# polygon : pairsturtle.register_shape("new_shape", pairs)  # clear screenturtle.clearscreen()  # use new shape and# apply propertiesturtle.shape("new_shape")turtle.fillcolor("blue")  # do some motionfor i in range(50):    turtle.forward(5+2*i)    turtle.right(45)
Output :
Python-turtle
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
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Convex Polygon in C++

Suppose we have a list of points that form a polygon when joined sequentially, we have to find if this polygon is convex (Convex polygon definition). We have to keep in mind that there are at least 3 and at most 10,000 points. And the coordinates are in the range -10,000 to 10,000.
We can assume the polygon formed by given points is always a simple polygon, in other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other. So if the input is like: [[0,0],[0,1],[1,1],[1,0]], then it is convex, so returned value will be true.
To solve this, we will follow these steps −
Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −
Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −
BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by
BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by
From the main method do the following
From the main method do the following
neg := false and pos := false, n := size of points array
neg := false and pos := false, n := size of points array
for i in range 0 to n – 1a := i, b := (i + 1) mod n and c := (i + 2) mod ncross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := trueif neg and pos is true, then return false
for i in range 0 to n – 1
a := i, b := (i + 1) mod n and c := (i + 2) mod n
a := i, b := (i + 1) mod n and c := (i + 2) mod n
cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])
cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])
if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true
if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true
if neg and pos is true, then return false
if neg and pos is true, then return false
return true
return true
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool isConvex(vector<vector<int>>& points) {
      bool neg = false;
      bool pos = false;
      int n = points.size();
      for(int i = 0; i < n; i++){
         int a = i;
         int b = (i + 1) % n;
         int c = (i + 2) % n;
         int crossProduct = calc(points[a][0], points[a][1], points[b][0], points[b][1], points[c][0], points[c][1]);
         if(crossProduct < 0) neg = true;
         else if(crossProduct > 0) pos = true;
         if(neg && pos) return false;
      }
      return true;
   }
   int calc(int ax, int ay, int bx, int by, int cx, int cy){
      int BAx = ax - bx;
      int BAy = ay - by;
      int BCx = cx - bx;
      int BCy = cy - by;
      return (BAx * BCy - BAy * BCx);
   }
};
main(){
   vector<vector<int>> v = {{0,0},{0,1},{1,1},{1,0}};
   Solution ob;
   cout << (ob.isConvex(v));
}
[[0,0],[0,1],[1,1],[1,0]]
1
Java program to print all distinct elements of a given integer array in Java

All distinct elements of an array are printed i.e. all the elements in the array are printed only once and duplicate elements are not printed. An example of this is given as follows.
Array = 1 5 9 1 4 9 6 5 9 7
Distinct elements of above array = 1 5 9 4 6 7
A program that demonstrates this is given as follows.
 Live Demo
public class Example {
   public static void main (String[] args) {
      int arr[] = {1, 5, 9, 1, 4, 9, 6, 5, 9, 7};
      int n = arr.length;
      int i, j;
      System.out.print("The array is: ");
      for (i = 0; i < n; ++i)
      System.out.print(arr[i] + " ");
      System.out.print("\nThe distinct elements of above array are: ");
      for (i = 0; i < n; i++) {
         for (j = 0; j < i; j++)
         if (arr[i] == arr[j])
            break;
         if (i == j)
         System.out.print( arr[i] + " ");
      }
   }
}
The array is: 1 5 9 1 4 9 6 5 9 7
The distinct elements of above array are: 1 5 9 4 6 7
Now let us understand the above program.
First the original array is displayed. This array may contain duplicate elements. The code snippet that demonstrates this is given as follows −
System.out.print("The array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
Now, a nested for loop is used to make sure only distinct elements of the array are displayed. The outer loop runs from 0 to n and the inner loop makes sure that an element is printed only if has not occured before. The code snippet that demonstrates this is given as follows −
System.out.print("\nThe distinct elements of above array are: ");
for (i = 0; i < n; i++) {
   for (j = 0; j < i; j++)
   if (arr[i] == arr[j])
   break;
   if (i == j)
   System.out.print( arr[i] + " ");
}
How to write partial title of X-axis in italics using ggplot2 of R?

Of course, writing axes titles help viewers to understand the plot in a better way because they add more information to the plot. In general, the axes titles have simple font but we can change partial or complete title to italics to get the viewers attraction. This is needed when we want to highlight the title by making it different. In ggplot2, we can do this by using expression.
Consider the below data frame −
set.seed(1)
x<-rnorm(10)
y<-rnorm(10,1)
df<-data.frame(x,y)
df
      x       y
1 -0.6264538  2.5117812
2  0.1836433  1.3898432
3 -0.8356286  0.3787594
4  1.5952808 -1.2146999
5  0.3295078  2.1249309
6 -0.8204684  0.9550664
7  0.4874291  0.9838097
8  0.7383247  1.9438362
9  0.5757814  1.8212212
10 -0.3053884 1.5939013
> library(ggplot2)
Creating the scatterplot between x and y −
ggplot(df,aes(x,y))+geom_point()+
+ labs(x=expression(paste("X comes from normal distribution")))
Now suppose we want to write normal distribution in italics then it can be done as shown below −
ggplot(df,aes(x,y))+geom_point()+labs(x=expression(paste("X comes from ",italic("normal distribution"))))
Lateral Keyword in SQL - GeeksforGeeks

04 Oct, 2021
The lateral keyword represents a lateral join between two or more tables. It joins the output of the outer query with the output of the underlying lateral subquery. It is like a for-each loop in SQL where the subquery iterates through each row of the concerned table, evaluating the subquery for each row. 
The output rows returned by the inner subquery are then added to the result of the join with the outer query. Without Lateral, each subquery would be evaluated independent of each others and could not refer to the items in the table referenced in the outer query. 
Syntax of Lateral: A Lateral join is denoted by the keyword Lateral which precedes the inner subquery, as shown below: 
 
SELECT <Column Name>
FROM <Reference Table Name>
LATERAL <Inner Subquery> 
Example: Let us assume that we have to find the top 3 students of a class with the highest marks. The query would be a simple one as follows: 
 
SELECT studId, marks 
FROM student 
ORDER BY marks DESC FETCH FIRST 3 ROWS ONLY 
Now assuming that each class has ‘n’ sections and we need to find section-wise top 3 students with the highest marks. Now we would need to join the section tables to get the result and find the top 3 students using the Rank() function. The query would be like this: 
 
SELECT secId, studId, marks 
FROM ( SELECT sec.secId, stud.studId, stud.marks, 
       RANK() OVER (PARTITION BY sec.secId ORDER BY marks DESC) rn 
       FROM student stud, section sec WHERE sec.secId = stud.secId )
WHERE rn <= 3 
This is where Lateral comes to the rescue. We will use our first query where we fetched the top 3 students with the highest marks as the inner subquery. Next, we join the Section table with the inner subquery using the Lateral keyword. The inner query which is to the right of Lateral would be evaluated for every single row in the left table. Here’s how the query would look like: 
 
SELECT sec.secId, stud.studId, stud.marks 
FROM section sec,
LATERAL (SELECT studId, marks FROM student stud 
         WHERE sec.secId = stud.secId 
         ORDER BY marks DESC FETCH FIRST 3 ROWS ONLY) 
Why Use Lateral ? In simple terms, Lateral provides a simpler and cleaner approach for returning more than one columns as the output. Although since the inner subquery has to run for every row of the main query, it makes the query a little slow. Some important applications of Lateral keyword are aggregation of two or more tables and in activity logs where logging might require a lot of temporary data. 
varshachoudhary
SQL-basics
DBMS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Structure of Database Management System
Difference between File System and DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
Aggregation in LINQ

Performs any type of desired aggregation and allows creating custom aggregations in LINQ.
Module Module1

   Sub Main()
   
      Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

      Dim intDivByTwo = Aggregate n In num
                       Where n > 6
                       Into Count()
      Console.WriteLine("Count of Numbers: " & intDivByTwo)

      Dim intResult = Aggregate n In num
                     Where n > 6
                     Into Average()
							
      Console.WriteLine("Average of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Where n > 6
                 Into LongCount()
					  
      Console.WriteLine("Long Count of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Max()
					  
      Console.WriteLine("Max of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Min()
					  
      Console.WriteLine("Min of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Sum()
					  
      Console.WriteLine("Sum of Numbers: " & intResult)

      Console.ReadLine()

   End Sub
   
End Module
When the above VB code is compiled and executed, it produces the following result −
Count of Numbers: 3
Average of Numbers: 8
Long Count of Numbers: 3
Max of Numbers: 9
Min of Numbers: 1
Sum of Numbers: 45


    23 Lectures 
     1.5 hours 

 Anadi Sharma

    37 Lectures 
     13 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
How do I customize the display of edge labels using networkx in Matplotlib?

To set the networkx edge labels offset, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a graph with edges, name, or graph attributes.
Add multiple nodes.
Position the nodes using Fruchterman-Reingold force-directed algorithm.
Draw the graph G with Matplotlib.
Draw edge labels.
To display the figure, use show() method.
import matplotlib.pylab as plt
import networkx as nx

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])

pos = nx.spring_layout(G)

for u, v, d in G.edges(data=True):
d['weight'] = 3

edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())

nx.draw(G, pos, node_color='b', edge_color=weights,
width=2, with_labels=True)

nx.draw_networkx_edge_labels(G, pos,
                              {
                                 (1, 2): "x", (2, 3): "y", (3, 4): "w",
                                 (4, 1): "z", (1, 3): "v"
                              },
                              label_pos=0.75
                              )
plt.show()
Python – Uppercase Nth character

30 Jan, 2020
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to uppercase. Let’s discuss certain ways in which this can be performed.
Method #1 : Using string slicing + upper()This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the uppercase Nth character.
# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # initializing N N = 4  # Using upper() + string slicing# Uppercase Nth characterres = test_str[:N] + test_str[N].upper() + test_str[N + 1:]  # printing result print("The string after uppercasing Nth character : " + str(res))
The original string is : GeeksforGeeks
The string after uppercasing Nth character : GeekSforGeeks

 
Method #2 : Using lambda + string slicing + upper()The recipe of lambda function has to be added if we need to perform the task of handling None values or empty strings as well, and this becomes essential to handle edge cases.
# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing + lambda  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # initializing N N = 4  # Using upper() + string slicing + lambda# Uppercase Nth characterres = lambda test_str: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''  # printing result print("The string after uppercasing initial character : " + str(res(test_str)))
The original string is : GeeksforGeeks
The string after uppercasing Nth character : GeekSforGeeks

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
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
Vue.js | v-html directive

07 Jun, 2022
The v-html directive is a Vue.js directive used to update a element’s inner HTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML. First, we will create a div element with id as app and let’s apply the v-html directive to this element with data as a message. Now we will create this message by initializing a Vue instance with the data attribute containing our message.
Scoped styles won’t apply to v-html, because Vue doesn’t compile that HTML. In order to apply styles to it try using global styles or some other CSS Modules.
Syntax:
v-html="data"
Parameters: This directive accepts a single parameter which is the data in the form of a string. Example: This example uses VueJS to update the html of a element with v-html.
HTML
<!DOCTYPE html><html> <head>    <title>        VueJS | v-html directive    </title>     <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script>    </script></head> <body>    <div style="text-align: center;width: 600px;">        <h1 style="color: green;">            GeeksforGeeks        </h1>        <b>            VueJS | v-html directive        </b>    </div>     <div id="canvas" style="border:1px solid #000000;                            width: 600px;height: 200px;">        <div v-html="message" id="app">        </div>    </div>     <script>        var app = new Vue({            el: '#app',            data: {                message: '<h1>HELLO '+                           '<span style="color:blue;">'+                              'WORLD</span>'+                         '</h1>'            }        })    </script></body> </html>
Output:
satyamm09
Vue.JS
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Queue.Contains() Method in C#

05 Feb, 2021
This method is used to check whether an element is in the Queue. This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. And this method comes under the System.Collections namespace.
Syntax:  
public virtual bool Contains(object obj);
Here, obj is the Object to locate in the Queue. The value can be null.
Return Value: The function returns True if the element exists in the Queue and returns False if the element doesn’t exist in the Queue.
Below given are some examples to understand the implementation in a better way:
Example 1: 
C#
// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG {     // Driver code    public static void Main()    {         // Creating a Queue        Queue myQueue = new Queue<int>();         // Inserting the elements into the Queue        myQueue.Enqueue(5);        myQueue.Enqueue(10);        myQueue.Enqueue(15);        myQueue.Enqueue(20);        myQueue.Enqueue(25);         // Checking whether the element is        // present in the Queue or not        // The function returns True if the        // element is present in the Queue, else        // returns False        Console.WriteLine(myQueue.Contains(7));    }}
False
 
Example 2:
C#
// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG {     // Driver code    public static void Main()    {         // Creating a Queue of strings        Queue myQueue = new Queue();         // Inserting the elements into the Queue        myQueue.Enqueue("Geeks");        myQueue.Enqueue("Geeks Classes");        myQueue.Enqueue("Noida");        myQueue.Enqueue("Data Structures");        myQueue.Enqueue("GeeksforGeeks");         // Checking whether the element is        // present in the Queue or not        // The function returns True if the        // element is present in the Queue, else        // returns False        Console.WriteLine(myQueue.Contains("GeeksforGeeks"));    }}
True
 
Reference: 
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.contains?view=netframework-4.7.2
 
arorakashish0911
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Stack | Question 5

09 Feb, 2013
Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced:
declare a character stack while ( more input is available){   read a character   if ( the character is a '(' )       push it on the stack   else if ( the character is a ')' and the stack is not empty )      pop a character off the stack   else      print "unbalanced" and exit } print "balanced"
Which of these unbalanced sequences does the above code think is balanced?
Source: http://www.cs.colorado.edu/~main/questions/chap07q.html(A) ((())(B) ())(()(C) (()()))(D) (()))()Answer: (A)Explanation: At the end of while loop, we must check whether the stack is empty or not. For input ((()), the stack doesn’t remain empty after the loop. See https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/ for details.
Data Structures
Data Structures-Stack
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Advantages and Disadvantages of Linked List
Data Structures | Binary Search Trees | Question 8
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Hash | Question 5
Data Structures | Linked List | Question 16
Difference between Singly linked list and Doubly linked list
Data Structures | Binary Trees | Question 1
HTML | Change Background color using onmouseover property

31 Jul, 2018
In this post, the working of onmouseover event is shown by changing the colours of a paragraph by taking the mouse over a particular colour.
Syntax:
document.bgColor = 'nameOfColor'

HTML code that will change the colour of the background when the mouse is moved over a particular colour. Background colour property specifies the background colour of an element.
<html>  <p>    <!-- when mouse is move over the colour name, colour change -->    <a onmouseover="document.bgColor='greem'">Bright Green</a><br>    <a onmouseover="document.bgColor='red'">Red</a><br>    <a onmouseover="document.bgColor='magenta'">Magenta</a><br>    <a onmouseover="document.bgColor='purple'">Purple</a><br>    <a onmouseover="document.bgColor='blue'">Blue</a><br>    <a onmouseover="document.bgColor='yellow'">Yellow</a><br>    <a onmouseover="document.bgColor='black'">Black</a><br>    <a onmouseover="document.bgColor='orange'">Orange</a><br>  </p></html>
Output:Initially, the background colour is white-
When the mouse is moved over the “Bright Green” color-
When the mouse is moved over the “Red” colour-
When the mouse is moved over the “magenta” colour-
When the mouse is moved over the “purple” colour-
When the mouse is moved over the “blue” colour-
When the mouse is moved over the “black” colour-
When the mouse is moved over the “orange” colour-
When the mouse is moved over “yellow” colour-
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
HTML | <caption> align Attribute

22 Feb, 2022
The HTML <caption> align Attribute is used to specify the alignment of the <caption> Element. It is used to align the caption to the left, right, top and Bottom of a table.This attribute is not supported in HTML5.
Note: By default , the table caption is aligned to center.
Syntax:
<caption align="left | right | top | bottom> 
Attribute Values
left: It sets the left-align caption of the table.
right: It sets the right-align caption of the Table
Top: It sets the top-align caption of the table. It is a default value.
Bottom: It sets the bottom-align caption of the table.
Example:
<!-- HTML code to show the working of caption tag --><!DOCTYPE html><html>  <head>    <style>        table,        th,        td {            border: 1px solid black;        }                  #GFG {            font-size: 25px;            color: green;        }    </style></head>  <body>    <h1 style="color:green;font-size:35px;">     GeeksForGeeks     </h1>    <h2>HTML Caption align  Attribute</h2>      <table>        <!-- Adding caption to the table -->        <caption id="GFG"                 align="top">          Students      </caption>        <tr>            <th>Firstname</th>            <th>Lastname</th>            <th>Age</th>        </tr>        <tr>            <td>Priya</td>            <td>Sharma</td>            <td>24</td>        </tr>        <tr>            <td>Arun</td>            <td>Singh</td>            <td>32</td>        </tr>        <tr>            <td>Sam</td>            <td>Watson</td>            <td>41</td>        </tr>    </table><br><br>    <table>        <!-- Adding caption to the table -->        <caption id="GFG"                 align="bottom">          Students      </caption>        <tr>            <th>Firstname</th>            <th>Lastname</th>            <th>Age</th>        </tr>        <tr>            <td>Priya</td>            <td>Sharma</td>            <td>24</td>        </tr>        <tr>            <td>Arun</td>            <td>Singh</td>            <td>32</td>        </tr>        <tr>            <td>Sam</td>            <td>Watson</td>            <td>41</td>        </tr>    </table></body>  </html>
Output :
Supported Browsers: The browsers supported by HTML <caption> align Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
hritikbhatnagar2182
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to Install Code Blocks for C++ on MacOS?

29 Oct, 2021
Code::Blocks is a free and open-source IDE that supports a plethora of C++ compilers like GCC, Clang, and Visual C++. It is written in C++ and makes use of wxWidgets as the GUI toolkit. Code::Blocks is focused on C, C++, and Fortran development. It has a custom build system and optional Make support. In this article, we will discuss methods using which we can install Code Blocks on MacOS.:
Cross-Platform: Works on MacOS, Linux and Windows.
Multiple C++ Compilers: It supports GCC, MinGW, Digital Mars, Microsoft Visual C++, Borland C++, LLVM Clang, Watcom, LCC, and the Intel C++ compiler. 
On MacOS, Code::Blocks relies on the Xcode distribution for its compiler. So, first, install Xcode from App Store and then continue with the following steps :
Step 1: Go to the official SourceForge of CodeBlocks project using this link, to download the application package. Click on the Download button.
Code::Blocks on SourceForge.com
Step 2: Open the downloaded file to initiate installation.
Package extraction begins.
Step 3: Drag the CodeBlocks icon to the application folder to begin copying Codeblocks to the application folder.
Step 5: Open the Code::Blocks app. The following prompt is displayed.
Step 5: Go to System Preferences -> Security and Privacy. Click the padlock in the lower-left corner of the dialog box, and then enter your system password when prompted, to allow changes.
Step 6: Select the option Allow Applications Downloaded from: App Store and identified developers. Close the Prompt appeared in Step 5.
Click on the Open Anyway button in the Security & Privacy dialog box. 
Step 7: Another Dialog box appears. On this dialog box, click on Open to start Code::Blocks.
Step 8: Go to File -> New -> Project. On the New from template dialog, select Console Application and click Go.
Step 9: Select the C++ option and click Next. Keep clicking Next and then click Finish to create your first C++ project.
Step 9: On the menu bar, go to Settings -> Environment. Change the text in the field “Terminal to launch console programs” to:
osascript -e 'tell app "Terminal"' -e 'activate' -e 'do script "$SCRIPT"' -e 'end tell'
Step 10: Open the main.cpp file from the left project pane. It contains Hello World program by default. Go to Build-> Build and Run. The program should run successfully on a terminal.
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 Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
Sum of the nodes of a Singly Linked List in C Program

A singly linked list is a data structure in which an element has two parts one is the value and other is the link to the next element. So to find the sum of all elements of the singly linked list, we have to navigate to each node of the linked list and add the element's value to a sum variable.
For example
Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5
sum = 2 + 27 + 32 + 1 + 5 = 67.
This can be done by using two methods :
Method 1 - Using a loop that loops over all the values of the linked list and finds the sum.
The loop runs till the end of the linked list i.e. when the pointer of an element points to null, this loop will run and find the sum of values of each element.
#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** nodeH, int nodeval) {
   struct Node* new_node = new Node;
   new_node->data = nodeval;
   new_node->next = (*nodeH);
   (*nodeH) = new_node;
}
int main() {
   struct Node* head = NULL;
   int sum = 0;
   push(&head, 95);
   push(&head, 60);
   push(&head, 87);
   push(&head, 6);
   push(&head, 12);
   struct Node* ptr = head;
   while (ptr != NULL) {
      sum += ptr->data;
      ptr = ptr->next;
   }
   cout << "Sum of nodes = "<< sum;
   return 0;
}
Sum of nodes = 260
Method 2 - Using a recursive function that calls itself until the linked list has elements. The recursive function calls itself again and again. The call to the recursive function sends the next node values as a parameter along with the sum address location.
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
void nodesum(struct Node* head, int* sum) {
   if (!head)
      return;
   nodesum(head->next, sum);
   *sum = *sum + head->data;
}
int main() {
   struct Node* head = NULL;
   int sum= 0;
   push(&head, 95);
   push(&head, 60);
   push(&head, 87);
   push(&head, 6);
   push(&head, 12);
   nodesum(head,&sum);
   cout << "Sum of nodes = "<<sum;
   return 0;
}
Sum of nodes = 260