code-rag-bench/online-tutorials huggingface dataset:
How to get the last character of a string in JavaScript? - GeeksforGeeks

30 Apr, 2019
Given a string of size len, the task is to get the last character of a string. There are many methods to solve this problem some of them are discussed below:
Method 1: Using charAt() function: This function returns the character at given index.
Syntax:
character = str.charAt(index)
First count number of characters in a given string by using str.length function. Since the indexing starts from 0 so use str.charAt(str.length-1) to get the last character of string.
Example:
<!DOCTYPE html><html>  <head>    <title>        Get the last character        of a string    </title></head>  <body>    <h3>Given String: GeeksforGeeks</h3>          <p>        Click on button to display the        last character    </p>          <button onclick="myGeeks()">        Click Here!    </button>          <p id="GFG" style="font-size:30px; color:green;"></p>          <!-- Script to return the last character of string -->    <script>        function myGeeks() {            var str = "GeeksforGeeks";            var res = str.charAt(str.length-1);                          document.getElementById("GFG").innerHTML                    = res;        }    </script></body>  </html>                    
Output:
Before Clicking on the button:
After Clicking on the button:
Method 2: Using str.slice() function: The string.slice() function is used to return a part or slice of the given input string.
Syntax:
str.slice(startingindex, endingindex)
Example: This example uses slice() function to get the last character of string.
<!DOCTYPE html><html>  <head>    <title>        Get the last character        of a string    </title></head>  <body>    <h3>Given String: GeeksforGeeks</h3>          <p>        Click on button to display the        last character    </p>          <button onclick="myGeeks()">        Click Here!    </button>          <p id="GFG" style="font-size:30px; color:green;"></p>          <!-- Script to return the last character of string -->    <script>        function myGeeks() {            var str = "GeeksforGeeks";            var res = str.slice(-1);                          document.getElementById("GFG").innerHTML                    = res;        }    </script></body>  </html>                    
Output:
Before Clicking on the button:
After Clicking on the button:
javascript-string
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
array::max_size() in C++ STL - GeeksforGeeks

30 Jan, 2018
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays.
This function returns the maximum number of elements that the array container can contain.In case of an array, size() and max_size() function always return the same value
Syntax :
arrayname.max_size()
Parameters :
No parameter is passed.
Returns :
It returns the maximum number of
elements that the array can contain.

Examples:
Input  : myarray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
         myarray.max_size();
Output : 10

Input  : myarray = {1, 2, 3, 4, 5};
         myarray.max_size();
Output : 5

Errors and Exceptions
1. It throws an error if a parameter is passed.
2. It has a no exception throw guarantee otherwise.

// CPP program to illustrate// Implementation of max_size() function#include <array>#include <iostream>using namespace std;  int main(){    array<int, 5> myarray{ 1, 2, 3, 4, 5 };    cout << myarray.max_size();    return 0;}
Output:
5

cpp-array
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
Destructors in C++
new and delete operators in C++ for dynamic memory
Precedence and Associativity of Operators in Python

29 Oct, 2021
When dealing with operators in Python we have to know about the concept of Python operator precedence and associativity as these determine the priorities of the operator otherwise, we’ll see unexpected outputs.
Operator Precedence: This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
Example: Solve 
10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30

Code:
Python3
# Precedence of '+' & '*'expr = 10 + 20 * 30  print(expr)
Output:
610

Example: Now, let’s see an example on logical ‘or‘ & logical ‘and‘  operator.  ‘if‘ block is executed even if the age is 0. Because precedence of logical ‘and‘ is greater than the logical ‘or‘.
Python3
# Precedence of 'or' & 'and'name = "Alex"age = 0  if name == "Alex" or name == "John" and age >= 2 :    print("Hello! Welcome.")else :    print("Good Bye!!")
Output:
Hello! Welcome.

Hence, To run the ‘else‘ block we can use parenthesis( ) as their precedence is highest among all the operators.
Python3
# Precedence of 'or' & 'and'name = "Alex"age = 0  if ( name == "Alex" or name == "John" ) and age >= 2 :  print("Hello! Welcome.")else :  print("Good Bye!!")
Output:
Good Bye!!

Operator Associativity: If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
Example: ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Code:
Python3
# Left-right associativity# 100 / 10 * 10 is calculated as # (100 / 10) * 10 and not # as 100 / (10 * 10)print(100 / 10 * 10)  # Left-right associativity# 5 - 2 + 3 is calculated as # (5 - 2) + 3 and not # as 5 - (2 + 3)print(5 - 2 + 3)  # left-right associativityprint(5 - (2 + 3))  # right-left associativity# 2 ** 3 ** 2 is calculated as # 2 ** (3 ** 2) and not # as (2 ** 3) ** 2print(2 ** 3 ** 2)
Output:
100
6
0
512

Operators Precedence and Associativity are two main characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets.
Example: Solve 
100 + 200 / 10 - 3 * 10

100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10)
and not as (100 + 200) / (10 - 3) * 10

Code:
Python3
expression  = 100 + 200 / 10 - 3 * 10print(expression )
Output:
90.0

Please see the following precedence and associativity table for reference. This table lists all operators from the highest precedence to the lowest precedence.
is,  is not
in, not in
Identity
Membership operators
python-basics
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Python OOPs Concepts
GATE | GATE-CS-2004 | Question 90

04 Jun, 2018
Consider the following relation schema pertaining to a students database:
Student (rollno, name, address)
Enroll (rollno, courseno, coursename)
where the primary keys are shown underlined. The number of tuples in the Student and Enroll tables are 120 and 8 respectively. What are the maximum and minimum number of tuples that can be present in (Student * Enroll), where ‘*’ denotes natural join ?(A) 8, 8(B) 120, 8(C) 960, 8(D) 960, 120Answer: (A)Explanation: The result of the natural join is the set of all combinations of tuples in R and S that are equal on their common attribute names.
What is the maximum possible number of tuples?The result of natural join becomes equal to the Cartesian product when there are no common attributes. The given tables have a common attribute, so the result of natural join cannot have more than the number of tuples in larger table.
        Student
-------------------------------------
Rollno          name         Address
-------------------------------------
1                a             abc
2                b             bcd
3                c             cde



                   Enroll
----------------------------------------------
Rollno           Courseno          Coursename
----------------------------------------------
1                 12                 pqr
1                 14                 qrs
1                 15                 rst 
2                 13                 uvw 
2                 14                 qrs 

Result of natural join
----------------------------------------------
Rollno  Name   Address   Courseno  Coursename
----------------------------------------------
1        a      abc         12      pqr
1        a      abc         14      qrs
1        a      abc         15      rst 
2        b      bcd         13      uvw
2        b      bcd         14      qrs 
What is the minimum possible number of tuples?It might be possible that there is no rollno common. In that case, the number of tuples would be 0. But in the question rollno is a primary key in Student table and it is a prime attribute in the Enroll table.
So there is no chance of having null values in the rollno column in enroll table and Student table and every tuple in Enroll will have a parent. So minimum number of tuples possible are 8 (only 8 tuples in the Enroll table).
Option (A) is correct.Quiz of this Question
krishnaswamy
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How could I write a for loop that adds up all the numbers in the array to a variable in JavaScript?

At first, declare and initialize the total variable with 0 and then you need to iterate over all the
array and extract all the values of array and add up with the updated total variable.
Let’s say the following is our array with numbers −
var listOfValues = [10,3,4,90,34,56,23,100,200];
var listOfValues = [10,3,4,90,34,56,23,100,200];
var total = 0;
for(let index = 0; index < listOfValues.length ; index++){
   total=total+listOfValues[index];
}
console.log("Total Values="+total);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo86.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo86.js
Total Values=520
Python – Suffix List Sum

29 Dec, 2019
Nowdays, especially in the field of competitive programming, the utility of computing suffix sum is quite popular and features in many problems. Hence, having a one liner solution to it would possess a great help. Let’s discuss certain way in which this problem can be solved.
Method : Using list comprehension + sum() + list slicingThis problem can be solved using the combination of above two functions in which we use list comprehension to extend logic to each element, sum function to get the sum along, slicing is used to get sum till the particular index.
# Python3 code to demonstrate# Suffix List Sum # using list comprehension + sum() + list slicing   # initializing listtest_list = [3, 4, 1, 7, 9, 1]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + sum() + list slicing# Suffix List Sum test_list.reverse()res = [sum(test_list[ : i + 1 ]) for i in range(len(test_list))]  # print resultprint("The suffix sum list is : " + str(res))
The original list : [3, 4, 1, 7, 9, 1]
The suffix sum list is : [1, 10, 17, 18, 22, 25]

Python list-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 ?
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
Java Ternary Operator with Examples

09 Feb, 2022
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: 
Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operators
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators
This article explains all that one needs to know regarding Arithmetic Operators. 
Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
Syntax: 
variable = Expression1 ? Expression2: Expression3
If operates similarly to that of the if-else statement as in Exression2 is executed if Expression1 is true else Expression3 is executed.  
if(Expression1)
{
    variable = Expression2;
}
else
{
    variable = Expression3;
}
Example:  
num1 = 10;
num2 = 20;

res=(num1>num2) ? (num1+num2):(num1-num2)

Since num1<num2, 
the second operation is performed
res = num1-num2 = -10
Example 1: 
Java
// Java program to find largest among two// numbers using ternary operator import java.io.*; class Ternary {    public static void main(String[] args)    {         // variable declaration        int n1 = 5, n2 = 10, max;         System.out.println("First num: " + n1);        System.out.println("Second num: " + n2);         // Largest among n1 and n2        max = (n1 > n2) ? n1 : n2;         // Print the largest number        System.out.println("Maximum is = " + max);    }}
First num: 5
Second num: 10
Maximum is = 10
Example 2: 
Java
// Java code to illustrate ternary operator import java.io.*; class Ternary {    public static void main(String[] args)    {         // variable declaration        int n1 = 5, n2 = 10, res;         System.out.println("First num: " + n1);        System.out.println("Second num: " + n2);         // Performing ternary operation        res = (n1 > n2) ? (n1 + n2) : (n1 - n2);         // Print the largest number        System.out.println("Result = " + res);    }}
First num: 5
Second num: 10
Result = -5
moumitadeymusic
nishkarshgandhi
Java-Operators
Java
Java-Operators
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Generics in Java
Java Programming Examples
GATE | GATE-CS-2001 | Question 8

28 Jun, 2021
Which of the following statements is false?(A) Virtual memory implements the translation of a program‘s address space into physical memory address space(B) Virtual memory allows each program to exceed the size of the primary memory(C) Virtual memory increases the degree of multiprogramming(D) Virtual memory reduces the context switching overheadAnswer: (D)Explanation: See question 4 of https://www.geeksforgeeks.org/operating-systems-set-2/Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
The readUTF() and writeUTF() methods in Java

Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode Consortium. if you want to create documents that use characters from multiple character sets, you will be able to do so using the single Unicode character encodings. It provides 3 types of encodings.
UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width.
UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width.
UTF-16-8 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width.
UTF-16-8 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width.
UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length.
UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length.
The writeUTF() method of the java.io.DataOutputStream class accepts a String value as a parameter and writes it in using modified UTF-8 encoding, to the current output stream. Therefore to write UTF-8 data to a file −
The readUTF() method of the java.io.DataOutputStream reads data that is in modified UTF-8 encoding, into a String and returns it. Therefore to read UTF-8 data to a file −
The following Java example writes UTF-8 data into a file and reads it back using the writeUTF() and readUTF() methods.
 Live Demo
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class Read_Write_UTF {
   public static void main(String args[]) {
      FileOutputStream fileOut = null;
      DataOutputStream outputStream = null;
      FileInputStream fileIn = null;
      DataInputStream inputStream = null;
      StringBuffer buffer = new StringBuffer();
      try {
         //Instantiating the FileOutputStream class
         fileOut = new FileOutputStream("D:\\utfText.txt");
         //Instantiating the DataOutputStream class
         outputStream = new DataOutputStream(fileOut);
         //Writing UTF data to the output stream
         outputStream.writeUTF("టుటోరియల్స్ పాయింట్ కి స్వాగతిం");
         outputStream.flush();
         System.out.println("Data inserted into the file");
         //Instantiating the FileInputStream class
         fileIn = new FileInputStream("D:\\utfText.txt");
         //Instantiating the DataInputStream class
         inputStream = new DataInputStream(fileIn);
         //Reading UTF data from the DataInputStream
         while(inputStream.available()>0) {
            buffer.append(inputStream.readUTF());
         }
      }
      catch(EOFException ex) {
         System.out.println(ex.toString());
      }
      catch(IOException ex) {
         System.out.println(ex.toString());
      }
      System.out.println("Contents of the file: "+buffer.toString());
   }
}
Data inserted into the file
Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
Python String Methods

29 Dec, 2021
Python string is a sequence of Unicode characters that is enclosed in the quotations marks. In this article, we will discuss the in-built function i.e. the functions provided by the Python to operate on strings. 
Note: Every string method does not change the original string instead returns a new string with the changed attributes. 
The below functions are used to change the case of the strings.
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
Example: Changing the case of Python Strings.
Python3
# Python3 program to show the# working of upper() functiontext = 'geeKs For geEkS' # upper() function to convert# string to upper caseprint("\nConverted String:")print(text.upper()) # lower() function to convert# string to lower caseprint("\nConverted String:")print(text.lower()) # converts the first character to# upper case and rest to lower caseprint("\nConverted String:")print(text.title()) # original string never changesprint("\nOriginal String")print(text)
Output:
Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Original String
geeKs For geEkS
Note: For more information about Python Strings, refer to Python String Tutorial. 
sataindras
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to use HTML5 Geolocation Latitude/Longitude API?

HTML5 Geolocation API lets you share your location with your favorite websites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.
The geolocation APIs work with a new property of the global navigator object ie. Geolocation object.
You can try to run the following code to find the current location using the Geolocation API, with Latitude and Longitude coordinates
Live Demo
<!DOCTYPE HTML>
<html>
   <head>
      <script type="text/javascript">
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            } else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         function getLocation(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               navigator.geolocation.getCurrentPosition
               (showLocation, errorHandler, options);
            } else{
               alert("Sorry, browser does not support geolocation!");
            }
         }
      </script>
   </head>
   <body>
      <form>
         <input type="button" onclick="getLocation();" value="Get Location"/>
      </form>
   </body>
</html>
How to run multiple Python file in a folder one after another?

03 Mar, 2021
In this article, we will discuss how to run multiple python files in a folder one after another. There can be many ways to this task, here, we will discuss a few of them. For doing this program, we have to create some python files in one folder and give some names to that folder. 
The content inside a.py file:
print("a")
The content inside b.py file:
print("b")
The content inside c.py file:
print("c")
Method 1: Using Bash Script:
We have created another folder named two. In which, test.sh exist.
Syntax:
#!/bin/bash
for python_file_name in $(find $Folder_Path -name *.py)
do
   python $python_file_name
done
For running dynamically all the python program files in a given folder <FOLDER_NAME>, we can run a bash script file for doing this task. With the help of this above script, We can run all .py extension file which is located in the given folder path. With each iteration, This program will run every python file.
Now, Let see its implementation,
#!/bin/bash

for py_file in $(find ../one -name *.py)
do
    python $py_file
done
Save this content inside a bash script file( means .sh extension ). Now, It’s time to run this file. If we are using windows, so, we have to run this file in Git Bash.
Run this command in Git Bash Terminal. We can use “./” (or any valid directory spec) before the filename:
./test.sh
Output:
a
b
c
Method 2: Using Command Prompt:
If we want to run multiple python files from another folder using our command prompt. Then, we need to take the path of the files. As in folder One, We have created three files, and now we are in folder Two. 
Simple command to run our python file within a folder:
python a.py
But here, we are in another folder so, we need to take the path of the python file like below...
python ../One/a.py
Now, Let see its implementation of how to run multiple files from another folder:
python ../One/a.py & python ../One/b.py & python ../One/c.py
Output: 
a
b
c
This discussed method is not effective one, because we can not write this complex command to run just few files.
Method 3: Using Python File:
With the help of os module, we can execute the script that can run our python files from another folder. First, We need to import the os module. 
import os
Inside os module, there is one method named system(). We will call our run script command an argument.
os.system('python ../One/a.py')
Now, Let see its implementation:
Python3
import os  os.system('python ../One/a.py')os.system('python ../One/b.py')os.system('python ../One/c.py')
Output:
a
b
c
Video Demo:
Picked
python-utility
Technical Scripter 2020
Python
Technical Scripter
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
Python | datetime.timedelta() function
Matplotlib.dates.DateFormatter class in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.dates.DateFormatter class is used to format a tick (in seconds since the epoch) with a string of strftime format. Its base class is matplotlib.ticker.Formatter.
Syntax: class matplotlib.dates.DateFormatter(fmt, tz=None)
Parameters:
fmt: It accepts a strftime format string for formatting and is a required argument.tz: It holds information regarding the timezone. If set to none it ignores the timezone information while formatting of the date string.
fmt: It accepts a strftime format string for formatting and is a required argument.
tz: It holds information regarding the timezone. If set to none it ignores the timezone information while formatting of the date string.
Example 1:
import numpyimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport pandas     total_bars = 25numpy.random.seed(total_bars)   dates = pandas.date_range('3/4/2020',                           periods=total_bars,                          freq='m')  diff = pandas.DataFrame(    data=numpy.random.randn(total_bars),     index=dates,    columns=['A'])   figure, axes = plt.subplots(figsize=(10, 6))  axes.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))  axes.bar(diff.index,         diff['A'],          width=25,          align='center')
Output:
Example 2:
import matplotlibimport matplotlib.pyplot as pltfrom datetime import datetime  origin = ['2020-02-05 17:17:55',          '2020-02-05 17:17:51',           '2020-02-05 17:17:49']  a = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in origin]  b = ['35.764299', '20.3008', '36.94704']  x = matplotlib.dates.date2num(a)formatter = matplotlib.dates.DateFormatter('%H:%M:%S')  figure = plt.figure()axes = figure.add_subplot(1, 1, 1)  axes.xaxis.set_major_formatter(formatter)plt.setp(axes.get_xticklabels(), rotation = 15)  axes.plot(x, b)plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CHAR vs VARCHAR in SQL

21 Jun, 2022
1. CHAR Datatype: It is a datatype in SQL which is used to store character string of fixed length specified. If the length of the string is less than set or fixed-length then it is padded with extra blank spaces so that its length became equal to the set length when PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled. The storage size of the CHAR datatype is n bytes(set length). We should use this datatype when we expect the data values in a column are of the same length. 
Example: Consider the Query:  
CREATE TABLE Student(Name VARCHAR(30), Gender CHAR(6));
INSERT into Student VALUES('Herry', 'Male');
INSERT into Student VALUES('Mahi', 'Female');
SELECT LENGTH(Gender) FROM Student;
OUTPUT:  
LENGTH(Gender)
6
6
2. VARCHAR Datatype: It is a datatype in SQL which is used to store character string of variable length but a maximum of the set length specified. If the length of the string is less than set or fixed-length then it will store as it is without padded with extra blank spaces. The storage size of the VARCHAR datatype is equal to the actual length of the entered string in bytes. We should use this datatype when we expect the data values in a column are of variable length. 
Example: Consider the Query:  
CREATE TABLE Student(Name VARCHAR(20), Gender CHAR(6));
INSERT into Student VALUES('Herry', 'Male');
INSERT into Student VALUES('Mahi', 'Female');
SELECT LENGTH(Name) FROM Student;
OUTPUT:  
LENGTH(Name)
5
4
Conclusion: VARCHAR saves space when there is variation in the length of values, but CHAR might be performance-wise better.
varshagumber28
jsathu07
DBMS-SQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL Interview Questions
SQL | Views
Introduction of ER Model
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE
Difference between Primary Key and Foreign Key
Indexing in Databases | Set 1
Wand border() function – Python

10 Aug, 2021
The border() function is an inbuilt function in the Python Wand ImageMagick library which is used to apply the border around the image. 
Syntax: 
border(color, height, width)
Parameters: This function accepts three parameters as mentioned above and defined below: 
Color: This parameter is used to specify the value of color which is a string type variable.
Height: This parameter is used to specify the value of border height which is an integer variable.
Width: This parameter is used to specify the value of border width which is an integer variable.
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 border:        # Invoke border function border with color aas Green, Height as 12        # Width as 18        border.border('Green', int(12), int(18))        # Save the image        border.save(filename ='border1.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 border function with color as red, width as 10        # Height as 10        pic.border('Red', int(10), int(10))        # Save the image        pic.save(filename ='border2.jpg')
Output:  
 
anikakapoor
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
Python | datetime.timedelta() function
Golang Pointer to an Array as Function Argument

22 Jul, 2019
Prerequisite: Pointers in Golang
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Whereas an array is a fixed-length sequence which is used to store homogeneous elements in the memory.
You can use the pointers to an array and pass that one as an argument to the function. To understand this concept let’s take an example. In the below program we are taking a pointer array arr which has 5 elements. We want to update this array using a function. Means modifying the array(here the array is {78, 89, 45, 56, 14}) inside the function and that will reflect at the caller. So here we have taken function updatearray which has pointer to array as argument type. Using updatearray(&arr) line of code we are passing the address of the array. Inside function (*funarr)[4] = 750 or funarr[4] = 750 line of code is using dereferencing concept to assign new value to the array which will reflect in the original array. Finally, the program will give output [78 89 45 56 750].
// Golang program to pass a pointer to an// array as an argument to the functionpackage main  import "fmt"  // taking a functionfunc updatearray(funarr *[5]int) {      // updating the array value    // at specified index    (*funarr)[4] = 750          // you can also write     // the above line of code    // funarr[4] = 750}  // Main Functionfunc main() {      // Taking an pointer to an array    arr := [5]int{78, 89, 45, 56, 14}      // passing pointer to an array    // to function updatearray    updatearray(&arr)      // array after updating    fmt.Println(arr)}
Output:
[78 89 45 56 750]

Note: In Golang it is not recommended to use Pointer to an Array as an Argument to Function as the code become difficult to read. Also, it is not considered a good way to achieve this concept. To achieve this you can use slice instead of passing pointers.
Example:
// Golang program to illustrate the// concept of passing a pointer to an// array as an argument to the function// using a slicepackage main  import "fmt"  // taking a functionfunc updateslice(funarr []int) {      // updating the value    // at specified index    funarr[4] = 750}  // Main Functionfunc main() {      // Taking an slice    s := [5]int{78, 89, 45, 56, 14}      // passing slice to the    // function updateslice    updateslice(s[:])      // displaying the result    fmt.Println(s)}
Output:
[78 89 45 56 750]

Golang
Golang-Pointers
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
How to Trim a String in Golang?
How to compare times in Golang?
C++ String Library - find_first_of

It searches the string for the first character that matches any of the characters specified in its arguments.
Following is the declaration for std::string::find_first_of.
size_t find_first_of (const string& str, size_t pos = 0) const;
size_t find_first_of (const string& str, size_t pos = 0) const noexcept;
size_t find_first_of (const string& str, size_t pos = 0) const noexcept;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::find_first_of.
#include <iostream>
#include <string>
#include <cstddef>

int main () {
   std::string str ("It replaces the vowels in this sentence by asterisks.");
   std::size_t found = str.find_first_of("aeiou");
   while (found!=std::string::npos) {
      str[found]='*';
      found=str.find_first_of("aeiou",found+1);
   }

   std::cout << str << '\n';

   return 0;
}
The sample output should be like this −
It r*pl*c*s th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.

 Print
 Add Notes
 Bookmark this page
Dart Programming - Object

Object-Oriented Programming defines an object as “any entity that has a defined boundary.” An object has the following −
State − Describes the object. The fields of a class represent the object’s state.
State − Describes the object. The fields of a class represent the object’s state.
Behavior − Describes what an object can do.
Behavior − Describes what an object can do.
Identity − A unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity.
Identity − A unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity.
The period operator (.) is used in conjunction with the object to access a class’ data members.
Dart represents data in the form of objects. Every class in Dart extends the Object class. Given below is a simple example of creating and using an object.
class Student { 
   void test_method() { 
      print("This is a  test method"); 
   } 
   
   void test_method1() { 
      print("This is a  test method1"); 
   } 
}  
void main()    { 
   Student s1 = new Student(); 
   s1.test_method(); 
   s1.test_method1(); 
}
It should produce the following output −
This is a test method 
This is a test method1

The above example invokes the methods in the class. However, every time a function is called, a reference to the object is required. The cascade operator can be used as a shorthand in cases where there is a sequence of invocations.
The cascade ( .. ) operator can be used to issue a sequence of calls via an object. The above example can be rewritten in the following manner.
class Student { 
   void test_method() { 
      print("This is a  test method"); 
   } 
   
   void test_method1() { 
      print("This is a  test method1"); 
   } 
}  
void main() { 
   new Student() 
   ..test_method() 
   ..test_method1(); 
}
It should produce the following output −
This is a test method 
This is a test method1

This function returns a string representation of an object. Take a look at the following example to understand how to use the toString method.
void main() { 
   int n = 12; 
   print(n.toString()); 
} 
It should produce the following output −
12


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
JavaScript | Object.getOwnPropertySymbols() Method - GeeksforGeeks

22 Sep, 2021
The Object.getOwnPropertySymbols() method in JavaScript is standard built-in objects which returns an array of all symbol property that are present in a given object.Syntax:  
Object.getOwnPropertySymbols(obj)
Parameters:  
obj: This parameter is the object whose symbol properties are to be returned.
Return value:This method returns an array of all symbol properties that correspond to the properties found directly in the given object.Here is the example of this method Example 1:  
javascript
<script>const object1 = {};let vala = Symbol('geek1');let valb = Symbol.for('geek2'); object1[vala] = 'localSymbol';object1[valb] = 'globalSymbol'; const objectSymbols = Object.getOwnPropertySymbols(object1);console.log(objectSymbols.length); const object2 = {}; let a = Symbol('a'); let b = Symbol.for('b'); const objectSymbols1 = Object.getOwnPropertySymbols(object2); console.log(objectSymbols1.length);</script>
Output:  
2
0
Example 2:  
javascript
<script>const object1 = {};let vala = Symbol('geek1');let valb = Symbol.for('geek2');let valc = Symbol.for('geek3'); object1[vala] = 'localSymbol';object1[valb] = 'globalSymbol';object1[valc] = 'globalSymbol'; const objectSymbols = Object.getOwnPropertySymbols(object1);console.log(objectSymbols.length);console.log(objectSymbols);     console.log(objectSymbols[0]);console.log(objectSymbols[2]);console.log(objectSymbols[1]);</script>
Output:  
3
Array [Symbol(geek1), Symbol(geek2), Symbol(geek3)]
Symbol(geek1)
Symbol(geek3)
Symbol(geek2)
Supported Browsers: 
Google Chrome 38 and above
Edge 12 and above
Firefox 36 and above
Opera 25 and above
Safari 9 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Create Heatmaps using graph_objects class in Plotly

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.
A heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors.
Syntax: plotly.graph_objects.Heatmap(arg=None, autocolorscale=None, colorbar=None, colorscale=None, x=None, y=None, z=None, **kwargs)
Parameters:
arg: dict of properties compatible with this constructor
autocolorscale: Determines whether the colorscale is a default palette (autocolorscale: true) or the palette determined by colorscale. 
colorbar: plotly.graph_objects.heatmap.ColorBar instance or dict with compatible properties
colorscale: Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string.
x: Sets the x coordinates.
y: Sets the y coordinates.
z: Sets the z coordinates.
Example:
Python3
import plotly.graph_objects as go  feature_x = np.arange(0, 50, 2) feature_y = np.arange(0, 50, 3)   # Creating 2-D grid of features [X, Y] = np.meshgrid(feature_x, feature_y)   Z = np.cos(X / 2) + np.sin(Y / 4)   fig = go.Figure(data =     go.Heatmap(x = feature_x, y = feature_y, z = Z,))  fig.show()
Output:
In plotly, it is possible to show the unequal sizes of the blocks as to make the data differentiate between each other to make it more clear while presenting as the data has different height and width compared to each other.
Example:
Python3
import plotly.graph_objects as go  feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3)  # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y)  Z = np.cos(X / 2) + np.sin(Y / 4)  fig = go.Figure(data=go.Heatmap(  x=feature_x, y=feature_y, z=Z,))  fig.update_layout(    margin=dict(t=200, r=200, b=200, l=200),    showlegend=False,    width=700, height=700,    autosize=False)    fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | box() Function

22 Apr, 2019
The box() function in p5.js is used to draw a box with given height, width and the depth.
Syntax:
box( width, height, depth, detailX, detailY )
Parameters: This function accepts five parameters as mentioned above and described below:
width: This parameter stores the width of the box.
height: This parameter stores the height of the box.
depth: This parameter stores the depth of the box.
detailX: This parameter stores the optional number of triangle subdivisions in x-dimension.
detailY: This parameter stores the optional number of triangle subdivisions in y-dimension.
Below programs illustrate the box() function in p5.js:
Example 1: This example uses box() function to draw a box.
function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of box    fill('green');         // box() function    box(300, 400, 200);}
Output:
Example 2: This example uses box() function to draw a box.
function setup() {        // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of box    fill('yellow');         // Rotate     rotateX(frameCount * 0.01);    rotate(frameCount*0.03);         // box() function called    box(140, 130, 120);}
Output:Reference: https://p5js.org/reference/#/p5/box
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between const int*, const int * const, and int const * in C

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer.
const int* and int const* says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant int.
const int* const says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant int.
Thumb rule is to naming syntax from right to left.
// constant pointer to constant int
const int * const
// pointer to constant int
const int *
Uncomment the commented erroneous codes and see the error.
 Live Demo
#include <stdio.h>
int main() {
   //Example: int const*
   //Note: int const* is same as const int*
   const int p = 5;
   // q is a pointer to const int
   int const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 7;
   const int r = 7;
   //q can point to another const int
   q = &r;
   printf("%d", *q);
   //Example: int const* const
   int const* const s = &p;
   // Invalid asssignment
   // value of s cannot be changed
   // error: assignment of read-only location '*s'
   // *s = 7;
   // Invalid asssignment
   // s cannot be changed
   // error: assignment of read-only variable 's'
   // s = &r;
   return 0;
}
7