code-rag-bench/online-tutorials huggingface dataset:
Command Line Arguments in Golang

17 May, 2020
Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program.
In Golang, we have a package called as os package that contains an array called as “Args”. Args is an array of string that contains all the command line arguments passed.
The first argument will be always the program name as shown below.
Example 1: Try to use offline compiler for better results. Save the below file as cmdargs1.go
// Golang program to show how// to use command-line argumentspackage main  import (    "fmt"    "os")  func main() {      // The first argument    // is always program name    myProgramName := os.Args[0]          // it will display     // the program name    fmt.Println(myProgramName)}
Output: Here, you can see it is showing the program name with full path. Basically you can call this as Os Filepath output. If you will run the program with some dummy arguments then that will also print as a program name.
Example 2: Save the below file as cmdargs2.go
// Golang program to show how// to use command-line argumentspackage main  import (    "fmt"    "os")  func main() {      // The first argument    // is always program name    myProgramName := os.Args[0]      // this will take 4    // command line arguments    cmdArgs := os.Args[4]      // getting the arguments    // with normal indexing    gettingArgs := os.Args[2]      toGetAllArgs := os.Args[1:]      // it will display    // the program name    fmt.Println(myProgramName)          fmt.Println(cmdArgs)          fmt.Println(gettingArgs)          fmt.Println(toGetAllArgs)}
Output:
Picked
Go Language
Write From Home
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
Arrays in Go
Data Types in Go
Golang Maps
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
Python String upper()

03 Dec, 2020
upper() method converts all lowercase characters in a string into uppercase characters and returns it
Syntax :
string.upper()

Parameters :
The upper() method doesn’t take any parameters.
Returns :
returns a uppercased string of the given string

CODE 1: String with only alphabetic characters
# Python3 program to show the# working of upper() functiontext = 'geeKs For geEkS'  print("Original String:")print(text)  # upper() function to convert # string to upper_caseprint("\nConverted String:")print(text.upper())
Output :
Original String:
geeKs For geEkS

Converted String:
GEEKS FOR GEEKS
CODE 2: String with alphanumeric characters
# Python3 program to show the# working of upper() functiontext = 'g3Ek5 f0r gE3K5'  print("Original String:")print(text)  # upper() function to convert # string to upper_caseprint("\nConverted String:")print(text.upper())
Output :
Original String:
g3Ek5 f0r gE3K5

Converted String:
G3EK5 F0R GE3K5

Application: One of the common application of upper() method is to check if the two strings are same or not
# Python3 program to show the# working of upper() functiontext1 = 'geeks fOr geeks'  text2 = 'gEeKS fOR GeeKs'  # Comparison of strings using # upper() methodif(text1.upper() == text2.upper()):    print("Strings are same")else:     print("Strings are not same")
Output:
Strings are same
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE CS 2018 - GeeksforGeeks

22 Nov, 2021
What is the area of the circle which has the diagonal of the square as its diameter if the area of square is ' d ' ?
πd
πd2
(1/4) πd2
(1/2)πd
One important observation to solve 
the question :

Diagonal of Square = Diameter of Circle.

Let side of square be x. 

From Pythogorous theorem.
Diagonal = √(2*x*x)

We know area of square = x * x = d

Diameter = Diagonal =  √(2*d)

Radius = √(d/2)
Area of Circle = π * √(d/2) * √(d/2) = 1/2 * π * d
Let total males and females be 60x and
40x respectively.

Total number of people = (60x + 40x)
Total number of people who attended : 
                 0.8(60x + 40x) = 80x

Let y males attended. It is given all 
1females attended 

40x + y = 80x
y = 40x which is same as females.

If pqr ≠ 0 and p^(-x) = 1/q, q^(-y) = 1/r, r^(-z) = 1/p, find the value of the product xyz ?
-1
1 / pqr
1
pqr
Taking logs of given three values, we get
1/q = p-x -------(1)
1/r = q-y -------(2)
1/p = r-z -------(3)

1/q = p-x
    = r-xz [Putting value of p from (3)]
    = q-xyz  [Putting value of r from (2)]
    = 1 / qxyz

On comparing power of q both sides, we get xyz = 1
So, option (C) is correct.
Let there be x total men.

Total amount paid = x * 750 * 8/9 + (300 - x)*1000*2/3
                  = x*2000/3 + 300*1000*2/3 - x*2000/3
                  = 200000
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
How to add a citation in a plot created by using ggplot2 in R?

A footnote is generally used to give references to a document, text or image and it is called citation. It helps the reader or viewer to check out the original source using the new text or image is generated. If we want to give citation to a plot in R using ggplot2 package then we can add labs that has caption option to add the footnotes.
Consider the below data frame −
 Live Demo
> set.seed(1)
> x<-rnorm(10,1.5)
> y<-rnorm(10,2.5)
> df<-data.frame(x,y)
> df
      x       y
1 0.8735462 4.0117812
2 1.6836433 2.8898432
3 0.6643714 1.8787594
4 3.0952808 0.2853001
5 1.8295078 3.6249309
6 0.6795316 2.4550664
7 1.9874291 2.4838097
8 2.2383247 3.4438362
9 2.0757814 3.3212212
10 1.1946116 3.0939013
Loading ggplot2 package and creating a scatterplot between x and y −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Creating the plot with footnote −
> ggplot(df,aes(x,y))+geom_point()+labs(caption="Correlation Analysis")
Global and Local Variables in Python?

There are two types of variables: global variables and local variables.
The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined.
def func():
x = "Python"
print(x)
print(s)
s = "Tutorialspoint"
print(s)
func()
print(x)
In above program- x is a local variable whereas s is a global variable, we can access the local variable only within the function it is defined (func() above) and trying to call local variable outside its scope(func()) will through an Error. However, we can call global variable anywhere in the program including functions (func()) defined in the program.
Local variables can only be reached within their scope(like func() above).
Like in below program- there are two local variables – x and y.
def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))
15
The variables x and y will only work/used inside the function sum() and they don’t exist outside of the function.
So trying to use local variable outside their scope, might through NameError. So obviously below line will not work.
print(x)
A global variable can be used anywhere in the program as its scope is the entire program.
Let’s understand global variable with a very simple example -
z = 25
def func():
global z
print(z)
z=20
func()
print(z)
25
20
A calling func(), the global variable value is changed for the entire program.
Below example shows a combination of local and global variables and function parameters -
def func(x, y):
global a
a = 45
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a,b,x,y = 3,15,3,4
func(9,81)
print (a,b,x,y)
45 17 81 9
45 15 3 4
Image Thumbnail with Bootstrap

To add a thumbnail to the image, use the .img-thumbnail Bootstrap class.
You can try to run the following code to add a thumbnail to images
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Images</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>Styling images with Bootstrap</p>
      <h1>Original Image</h1>
      <img src = "https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg">
      <h1>Thumbnail Image</h1>
      <img src = "https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg" class = "img-thumbnail">
   </body>
</html>
Java - String replace() Method

This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Here is the syntax  of this method −
public String replace(char oldChar, char newChar)

Here is the detail of parameters −
oldChar − the old character.
oldChar − the old character.
newChar − the new character.
newChar − the new character.
It returns a string derived from this string by replacing every occurrence of oldChar with newChar.
It returns a string derived from this string by replacing every occurrence of oldChar with newChar.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.replace('o', 'T'));

      System.out.print("Return Value :" );
      System.out.println(Str.replace('l', 'D'));
   }
}
This will produce the following result −
Return Value :WelcTme tT TutTrialspTint.cTm
Return Value :WeDcome to TutoriaDspoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
C++ String Library - operator[]

It returns a reference to the character at position pos in the string.
Following is the declaration for std::string::operator[]
 char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
pos − Value with the position of a character within the string.
It returns a reference to the character at position pos in the string.
if an exception is thrown, there are no changes in the string.
In below example for std::string::operator[].
#include <iostream>
#include <string>

int main () {
   std::string str ("Sairamkrishna Mammahe");
   for (int i=0; i<str.length(); ++i) {
      std::cout << str[i];
   }
   return 0;
}
Sairamkrishna Mammahe 

 Print
 Add Notes
 Bookmark this page
How to Split large string in to n-size chunks in JavaScript?

There are two ways to split a large string in to n-sized sub strings.
This is a pure logic method in which only conventional methods are used such as for loop, concat, modulous etc. This method is not as sophisticated as regex method, because it's a predetermined method. The number of chunks that string to be divided should be predetermined before starting coding.
In the following example the string "tutorixtutorixtutorix" is divided in to 3-chunks of sub strings.
Live Demo
<html>
<body>
<script>
   var v = [];
   var str = "tutorixtutorixtutorix"
   var t = str.split("");
   document.write(t);
   document.write("</br>");
   for (var i = 0; i< t.length; i++){
      if((i % 3) == 2){
         v.push(t[i-2].concat(t[i-1],t[i]));
      }
   }
   document.write(v);
</script>
</body>
</html>
tut,ori,xtu,tor,ixt,uto,rix
It is not a predetermined method. Regex method provides a slot to mention the size to chunk the string. 
In general, for any string out of which you want to extract at-most n-sized sub strings, the syntax is
   str.match(/.{1,n}/g); // Replace n with the size of the substring
If the string contains any newlines or carriage returns, then the syntax is
  str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
The original syntax of the code is
   function chunkString(str, size) {
     return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Live Demo
<html>
<body>
<script>
   stringChop = function(str, size){
      if (str == null)
         return [];
         str = String(str);
         return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
   }
   document.write(stringChop('tutorialspoint'));
   document.write("<br>");
   document.write(stringChop('tutorix',2));
   document.write("<br>");
   document.write(stringChop('tutorialspoint',3));
</script>
</body>
</html>
["tutorialspoint"]
["tu","to","ri","x"]
["tut","ori","als","poi","nt"]
Difference between Python iterable and iterator

An iterable can be loosely defined as an object which would generate an iterator when passed to in-built method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance mehtod: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator.
Let’s understand the below example, to understand the iterable −
string = "Tutorialspoint"
for char in string:
print (char)
T
u
t
o
r
i
a
l
s
p
o
i
n
t
Above the code use the __getitem__(index) method which would return the element at the position specified by index.
So, our above code −
Start with index 0
Call string.__getitem__(index)
IndexError raised? Stop
The run body of the loop
Increment index, revert back to step 2.
Iterators are defined as an object that counts interation via an iternal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration. This also means that iterated item will be iterated once only, like in below example −
my_list = ['itemOne', 'TutorialsPoints']
iterators_of_some_list = iter(my_list)
for i in iterators_of_some_list:
   print(i)
for j in iterators_of_some_list: # doesn't work
   print(j)
#However
for k in my_list:
   print(k)
for l in my_list: # it worked
   print(l)
itemOne
TutorialsPoints
itemOne
TutorialsPoints
itemOne
TutorialsPoints
Above code holds true because the iter() method on the iterator returns itself (is to remember the current state). So above we have a loop kind of implementation similar to “for” to terminate it.
How to store MongoDB result in an array?

To store MongoDB result in an array, use the toArray() method −
var anyVariableName=db.yourCollectionName.find().toArray();
Let us first create a collection with documents −
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"David Miller","CustomerAge":24,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99bd5b50a6c6dd317ad92")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Sam Williams","CustomerAge":46,"isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99beab50a6c6dd317ad93")
}
> db.mongoDbResultInArrayDemo.insertOne({"CustomerName":"Carol Taylor","CustomerAge":23,"isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd99bf9b50a6c6dd317ad94")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.mongoDbResultInArrayDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
   "CustomerName" : "David Miller",
   "CustomerAge" : 24,
   "isMarried" : false
}
{
   "_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
   "CustomerName" : "Sam Williams",
   "CustomerAge" : 46,
   "isMarried" : true
}
{
   "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
   "CustomerName" : "Carol Taylor",
   "CustomerAge" : 23,
   "isMarried" : false
}
Following is the query to store MongoDB result in an array −
> var mongoDbResultIntoArray=db.mongoDbResultInArrayDemo.find().toArray();
Let us display the records of above variable −
> mongoDbResultIntoArray
This will produce the following output −
[
   {
      "_id" : ObjectId("5cd99bd5b50a6c6dd317ad92"),
      "CustomerName" : "David Miller",
      "CustomerAge" : 24,
      "isMarried" : false
   },
   {
      "_id" : ObjectId("5cd99beab50a6c6dd317ad93"),
      "CustomerName" : "Sam Williams",
      "CustomerAge" : 46,
      "isMarried" : true
   },
   {
      "_id" : ObjectId("5cd99bf9b50a6c6dd317ad94"),
      "CustomerName" : "Carol Taylor",
      "CustomerAge" : 23,
      "isMarried" : false
   }
]
How can we use Python Ternary Operator Without else?

If you want to convert a statement like −
if <condition>:
   <some-code>
to a single line, You can use the single line if syntax to do so −
if <condition>: <some-code>
Another way to do this is leveraging the short-circuiting and operator like −
<condition> and <some-code>
If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and <some-code> will be evaluated.
Pushdown Automata Introduction

A pushdown automaton is a way to implement a context-free grammar in a similar way we design DFA for a regular grammar. A DFA can remember a finite amount of information, but a PDA can remember an infinite amount of information.
Basically a pushdown automaton is −
"Finite state machine" + "a stack"
A pushdown automaton has three components −
an input tape,
a control unit, and
a stack with infinite size.
The stack head scans the top symbol of the stack.
A stack does two operations −
Push − a new symbol is added at the top.
Push − a new symbol is added at the top.
Pop − the top symbol is read and removed.
Pop − the top symbol is read and removed.
A PDA may or may not read an input symbol, but it has to read the top of the stack in every transition.
A PDA can be formally described as a 7-tuple (Q, ∑, S, δ, q0, I, F) −
Q is the finite number of states
Q is the finite number of states
∑ is input alphabet
∑ is input alphabet
S is stack symbols
S is stack symbols
δ is the transition function: Q × (∑ ∪ {ε}) × S × Q × S*
δ is the transition function: Q × (∑ ∪ {ε}) × S × Q × S*
q0 is the initial state (q0 ∈ Q)
q0 is the initial state (q0 ∈ Q)
I is the initial stack top symbol (I ∈ S)
I is the initial stack top symbol (I ∈ S)
F is a set of accepting states (F ∈ Q)
F is a set of accepting states (F ∈ Q)
The following diagram shows a transition in a PDA from a state q1 to state q2, labeled as a,b → c −
This means at state q1, if we encounter an input string ‘a’ and top symbol of the stack is ‘b’, then we pop ‘b’, push ‘c’ on top of the stack and move to state q2.
The instantaneous description (ID) of a PDA is represented by a triplet (q, w, s) where
q is the state
q is the state
w is unconsumed input
w is unconsumed input
s is the stack contents
s is the stack contents
The "turnstile" notation is used for connecting pairs of ID's that represent one or many moves of a PDA. The process of transition is denoted by the turnstile symbol "⊢".
Consider a PDA (Q, ∑, S, δ, q0, I, F). A transition can be mathematically represented by the following turnstile notation −
(p, aw, Tβ) ⊢ (q, w, αb)

This implies that while taking a transition from state p to state q, the input symbol ‘a’ is consumed, and the top of the stack ‘T’ is replaced by a new string ‘α’.
Note − If we want zero or more moves of a PDA, we have to use the symbol (⊢*) for it.

    98 Lectures 
     10 hours 

 Arnab Chakraborty

    15 Lectures 
     2 hours 

 Anchal Kamra

    16 Lectures 
     1.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Java program to transpose a matrix.

Following is the required program.
Live Demo
public class Tester {
   public static void main(String args[]) {
      int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };
      int t[][] = new int[3][3];
      // transpose the matrix
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            t[i][j] = a[j][i];
         }
      }
      System.out.println("Original Matrix:");
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            System.out.print(a[i][j] + " ");
         }
         System.out.println();
      }
      System.out.println("Transposed Matrix:");
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            System.out.print(t[i][j] + " ");
         }
         System.out.println();
      }
   }
}
Original Matrix:
1 3 4
2 4 3
3 4 5
Transposed Matrix:
1 2 3
3 4 4
4 3 5
Replace Multiple of 3 and 5 With Fizz, Buzz in Python

Suppose we have a number n. We have to find a string that is representing all numbers from 1
to n, but we have to follow some rules.
When the number is divisible by 3, put Fizz instead of the number
When the number is divisible by 3, put Fizz instead of the number
When the number is divisible by 5, put Buzz instead of the number
When the number is divisible by 5, put Buzz instead of the number
When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number
When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number
To solve this, we will follow these steps −
For all number from 1 to n,if number is divisible by 3 and 5 both, put “FizzBuzz”otherwise when number is divisible by 3, put “Fizz”otherwise when number is divisible by 5, put “Buzz”otherwise write the number as string
if number is divisible by 3 and 5 both, put “FizzBuzz”
otherwise when number is divisible by 3, put “Fizz”
otherwise when number is divisible by 5, put “Buzz”
otherwise write the number as string
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def fizzBuzz(self, n):
      result = []
      for i in range(1,n+1):
         if i% 3== 0 and i%5==0:
            result.append("FizzBuzz")
         elif i %3==0:
            result.append("Fizz")
         elif i% 5 == 0:
            result.append("Buzz")
         else:
            result.append(str(i))
      return result
ob1 = Solution()
print(ob1.fizzBuzz(15))
15
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
How to sort the letters in a string alphabetically in Python?

To sort letters in a string alphabetically, you need to use the sorted function that returns a sorted list of letters which you can then join to get a string. For example,
>>> s = "helloworld"
>>> ''.join(sorted(s))
'dehllloorw'
If you want only unique characters sorted, you can use sets to get the result. For example,
>>> s = "helloworld"
>>> ''.join(sorted(set(s)))
'dehlorw'
How to use a switch case 'or' in PHP? - GeeksforGeeks

11 Nov, 2018
Problem: How to use a switch case ‘or’ in PHP?Solution: This can be achieved in 2 ways. They are as follows:Method 1: Without using break keyword in one of the switch case.Example:
<?php$option = 1;switch ($option){    case 1:    case 2:        echo "The option is either 1 or 2.";    break;}?>
Output:
The option is either 1 or 2.

Method 2: Using or operator in switch case.Example:
<?php$option = 1;switch ($option) {    case ($option == 1 || $option == 2):        echo 'The option is either 1 or 2';        break;}?>
Output:
The option is either 1 or 2

Reference: http://php.net/manual/en/control-structures.switch.php
PHP-basics
PHP-Control-Statement
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
How to fetch data from localserver database and display on HTML table using PHP ?
How to receive JSON POST with PHP ?
Download file from URL using PHP
How to pass JavaScript variables to PHP ?
Best way to initialize empty array in PHP
How to create a high resolution timer with C++ and Linux?

To create high resolution timer we can use the chrono library. This library has high resolution clock. This can count in nanoseconds.
In this program we will see the execution time in nanoseconds. We will take the time value at first, then another time value at the last, then find the difference to get elapsed time. Here we are using blank loop to pause the effect for sometimes.
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
main(){
   auto start_time = Clock::now();
   for(int i = 0; i<200000000; i++) {
      //create one empty loop ;
   }
   auto end_time = Clock::now();
   std::cout << "Time difference:"
      << std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count() << " nanoseconds" << std::endl;
}
Time difference: 536395307 nanoseconds
p5.js | Mouse | mouseDragged() Function - GeeksforGeeks

22 Apr, 2019
The mouseDragged() function in p5.js is used to check the mouse drags (mouse moves and mouse button pressed). It is invoked each time when the mouse drags. If mouseDragged() function is not defined, then touchMoved() function will be used instead of mouseDragged() function.
Syntax:
mouseDragged(Event)
Below programs illustrate the mouseDragged() function in p5.js:
Example 1: This example uses mouseDragged() function to change the background color.
function setup() {      // Create Canvas    createCanvas(500, 500);}   let value = 0;  function draw() {          // Set background color    background(200);          // Set filled color    fill(value);          // Create rectangle    rect(25, 25, 460, 440);          // Set text color    fill('lightgreen');          // Set font size    textSize(15);          // Display result    text('Drag Mouse Across the page to change its value.',        windowHeight/6, windowWidth/4);}  function mouseDragged() {    value = value + 5;          if (value > 255) {        value = 0;    }}
Output:
Example 2: This example uses mouseDragged() function to change the mouse cursor circle color.
let value;  function setup() {          // Create Canvas    createCanvas(500, 500);}   function draw() {          // Set background color    background(200);           // Set filled color    fill('green');          // Set text and text size    textSize(25);          text('Drag mouse to change color', 30, 30);          // Fill color according to    // mouseMoved() function    fill(value, 255-value, 255-value);          // Draw ellipse      ellipse(mouseX, mouseY, 115, 115);}  function mouseDragged() {    value = mouseX%255;}
Output:
Reference: https://p5js.org/reference/#/p5/mouseDragged
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python | Count occurrences of an element in a list

05 Jul, 2022
Given a list in Python and a number x, count the number of occurrences of x in the given list.
Examples: 
Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
         x = 10
Output : 3 
10 appears three times in given list.

Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
        x = 16
Output : 0
We keep a counter that keeps on increasing if the required element is found in the list.
Python3
# Python code to count the number of occurrencesdef countX(lst, x):    count = 0    for ele in lst:        if (ele == x):            count = count + 1    return count # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))
Output:
8 has occurred 5 times
The idea is to use the list method count() to count the number of occurrences. 
Python3
# Python code to count the number of occurrencesdef countX(lst, x):    return lst.count(x) # Driver Codelst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print('{} has occurred {} times'.format(x, countX(lst, x)))
Output:
8 has occurred 5 times 
The counter method returns a dictionary with occurrences of all elements as a key-value pair, where the key is the element and the value is the number of times that element has occurred. 
Python3
from collections import Counter # declaring the listl = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 3d = Counter(l)print('{} has occurred {} times'.format(x, d[x]))
Output:
3 has occurred 2 times
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.
Python3
import operator as op # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] # driver programx = 2print(f"{x} has occurred {op.countOf(l, x)} times")
Output:
2 has occurred 3 times
Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
Python3
lis = ['a', 'd', 'd', 'c', 'a', 'b', 'b', 'a', 'c', 'd', 'e']occurrence = {item: lis.count(item) for item in lis}print(occurrence.get('e'))
Output:
1
Pandas Series.value_counts() function return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.
Python3
import pandas as pd # declaring the listl = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5] count = pd.Series(l).value_counts()print ("Element    Count")print(count)
Output:
Element    Count
2    3
1    2
3    2
4    2
5    2
dtype: int64
BhushanBorole
Akanksha_Rai
nidhi_biet
simranarora5sos
surajkumarguptaintern
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
Algorithms | Graph Traversals | Question 12

28 Jun, 2021
What are the appropriate data structures for following algorithms?
1) Breadth First Search                           
2) Depth First Search                            
3) Prim's Minimum Spanning Tree                 
4) Kruskal' Minimum Spanning Tree                

(A)
1) Stack
2) Queue
3) Priority Queue
4) Union Find
(B)
1) Queue
2) Stack
3) Priority Queue
4) Union Find

(C)
1) Stack
2) Queue
3) Union Find
4) Priority Queue 
(D)
1) Priority Queue
2) Queue
3) Stack
4) Union Find
Answer: (B)Explanation: 1) Breadth First Search uses Queue2) Depth First Search uses Stack3) Prim’s Minimum Spanning Tree uses Priority Queue.4) Kruskal’ Minimum Spanning Tree uses Union Find.Quiz of this Question
Algorithms-Graph Traversals
Graph Traversals
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Why should we use <noscript> element in JavaScript?

To find whether the browser supports JavaScript or not, use the <noscript> tag. The HTML <noscript> tag is used to handle the browsers, which do recognize <script> tag but do not support scripting. This tag is used to display an alternate text message.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML noscript Tag</title>
   </head>

   <body>
      <script>
         <!--
            document.write("Hello JavaScript!")
         -->
      </script>
     
      <noscript>
         Your browser does not support JavaScript!
      </noscript>
   </body>
</html>
OffsetDateTime of(LocalDateTime) method in Java with Examples - GeeksforGeeks

05 Jun, 2020
The of(LocalDateTime dateTime, ZoneOffset offset) method of the OffsetDateTime class in Java is used to create an instance of OffsetDateTime from given instances of date-time and offset. This method creates an OffsetDateTime with the specified local date-time and offset.
Syntax:
public static OffsetDateTime
       of(LocalDateTime dateTime,
          ZoneOffset offset)

Parameters: This method accepts two parameters:
dateTime – It represents the local date-time.
offset – It represents the zone offset.
Return value: This method returns the OffsetDateTime.
Exception: This method does not throw any exception.
Below programs illustrate the of(LocalDateTime, ZoneOffset) method of OffsetDateTime class in Java:
Program 1:
// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // Create LocalDateTime object        LocalDateTime dateTime            = LocalDateTime.parse(                "2020-05-28T04:12:50");          // Create OffsetDateTime object        OffsetDateTime offsetdatetime            = OffsetDateTime.of(                dateTime, ZoneOffset.UTC);          // Print date-time        System.out.println("DATE-TIME: "                           + offsetdatetime);    }}
DATE-TIME: 2020-05-28T04:12:50Z

Program 2:
// Java program to demonstrate// OffsetDateTime of(LocalDateTime,// ZoneOffset) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {          // Create LocalDateTime object        LocalDateTime dateTime            = LocalDateTime.of(                2020, 5, 28, 4, 12, 50);          // Create OffsetDateTime object        OffsetDateTime offsetdatetime            = OffsetDateTime.of(                dateTime, ZoneOffset.UTC);          // Print date-time        System.out.println("DATE-TIME: "                           + offsetdatetime);    }}
DATE-TIME: 2020-05-28T04:12:50Z

References:https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#of(java.time.LocalDateTime, java.time.ZoneOffset)
Java-Functions
Java-OffsetDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
C++ continue statement

The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.
The syntax of a continue statement in C++ is −
continue;

#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a = 10;

   // do loop execution
   do {
      if( a == 15) {
         // skip the iteration.
         a = a + 1;
         continue;
      }
      cout << "value of a: " << a << endl;
      a = a + 1;
   } 
   while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
JavaScript DOM HTML

The HTML DOM allows JavaScript to change the content of HTML elements.
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a <p> element:
Example explained:
The HTML document above contains a <p> element with id="p1"
We use the HTML DOM to get the element with id="p1"
A JavaScript changes the content (innerHTML) of that element to "New 
  text!"
This example changes the content of an <h1> element:
Example explained:
The HTML document above contains an <h1> element with id="id01"
We use the HTML DOM to get the element with id="id01"
A JavaScript changes the content (innerHTML) of that element to "New 
  Heading"
To change the value of an HTML attribute, use this syntax: 
This example changes the value of the src attribute of an <img> element:
Example explained:
The HTML document above contains an <img> element with id="myImage"
We use the HTML DOM to get the element with id="myImage"
A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
JavaScript can create dynamic HTML content:
Date : Mon Apr 25 2022 02:15:55 GMT-0700 (Pacific Daylight Time)
In JavaScript, document.write() can be used to write directly to the HTML 
output stream:
Never use document.write() after the document is loaded. It will 
overwrite the document.
Use HTML DOM to change the value of the image's src attribute.
<img id="image" src="smiley.gif">

<script>
document.getElementById("image") = "pic_mountain.jpg";
</script>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Comments in Julia

11 Feb, 2022
Comments are the statements in a code that are ignored by the compiler at the time of execution. These statements are written to beautify the code, providing an explanation for the steps that are used in the code. During coding, proper use of comments makes maintenance easier and finding bugs easily.   In Julia, comments are used in a similar manner as in Python. Comments can be of two types, based on their usage. These are:  
Single Lined comments
Multi lined comments
Comments are generally used for the following purposes:  
Code Readability
Explanation of the code or Metadata of the project
Prevent execution of code
To include resources
 
Single line comments in Julia start with the hashtag symbol(#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Julia’s single lined comments are useful for supplying short explanations for function declarations, variables, and expressions. See the following code snippet demonstrating single line comment: Example:  
Python
# This is a comment # Print "GeeksforGeeks !" to console print("GeeksforGeeks") 
Output:  
In the above code, the compiler ignores the statement written after #, because it considers the line as a comment and skips its execution.  
Julia multi-line comment is a piece of text enclosed in a delimiter (#=) on start of the comment and (=#) on the end of the comment. A multiline comment is useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:  
Python
#= This would be a multiline comment in Julia that spans several lines and describes geeksforgeeks. A Computer Science portal for geeks. It contains  well written, well thought  and well-explained computer science  and programming articles,  quizzes and more.=# print("GeeksForGeeks")
Output:  
In the above code snippet, the statements that are enclosed within #= and =# are considered as comments and are ignored by the compiler at the time of Code execution. 
rkbhola5
Julia-Basics
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Tick Labels Font Size in Matplotlib?

26 Nov, 2020
Prerequisite: Matplotlib
In this article, we will learn how to change (increase/decrease) the font size of tick label of a plot in matplotlib. For this understanding of following concepts is mandatory:
Matplotlib : 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. It was introduced by John Hunter in the year 2002.
Tick Label : Ticks are the markers denoting data points on axes. Matplotlib’s default tick locators and formatters are designed to be generally sufficient in many common situations. Position and labels of ticks are often explicitly mentioned to suit specific requirements.
Font Size : The font size or text size is how large the characters displayed on a screen or printed on a page are.
Approach: To change the font size of tick labels, one should follow some basic steps that are given below:
Import Libraries.Create or import data.Plot a graph on data using matplotlib.Change the font size of tick labels. (this can be done by different methods)
Import Libraries.
Create or import data.
Plot a graph on data using matplotlib.
Change the font size of tick labels. (this can be done by different methods)
To change the font size of tick labels, any of three different methods in contrast with the above mentioned steps can be employed. These three methods are:
fontsize in  plt.xticks/plt.yticks()
fontsize in  ax.set_yticklabels/ax.set_xticklabels()
labelsize in  ax.tick_params()
Lets discuss implementation of these methods one by one with the help of examples:
Example 1: (Using plt.xticks/plt.yticks)
Python3
# importing librariesimport matplotlib.pyplot as plt  # creating datax = list(range(1, 11, 1))y = [s*s for s in x]  # ploting dataplt.plot(x, y)  # changing the fontsize of yticksplt.yticks(fontsize=20)  # showing the plotplt.show()
Output :
Example 2: (Using ax.set_yticklabels/ax.set_xticklabels)
Python3
# importing librariesimport matplotlib.pyplot as pltimport numpy as np  # create datax = list(range(1, 11, 1))y = np.log(x)  # make objects of subplotsfig, ax = plt.subplots()  # plot the dataax.plot(x, y)  # change the fontsizeax.set_xticklabels(x, fontsize=20)  # show the plotplt.show()
Output :
Example 3: (Using ax.tick_params)
Python3
# importing librariesimport matplotlib.pyplot as pltimport numpy as np  # create datax = list(range(1, 11, 1))y = np.sin(x)  # make objects of subplotsfig, ax = plt.subplots(1, 1)  # plot the dataax.plot(x, y)  # change the fontsizeax.tick_params(axis='x', labelsize=20)  # show the plotplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Taking input in Python
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
bool() in Python

15 Sep, 2021
Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure. 
Syntax: bool([x])
The bool() method in general takes only one parameter(here x), on which the standard truth testing procedure can be applied. If no parameter is passed, then by default it returns False. So, passing a parameter is optional. 
It can return one of the two values. 
It returns True if the parameter or value passed is True.
It returns False if the parameter or value passed is False.
 Here are a few cases, in which Python’s bool() method returns false. Except these all other values return True. 
If a False value is passed.
If None is passed.
If an empty sequence is passed, such as (), [], ”, etc
If Zero is passed in any numeric type, such as 0, 0.0 etc
If an empty mapping is passed, such as {}.
If Objects of Classes having __bool__() or __len()__ method, returning 0 or False
Example 1:
Python3
# Python program to illustrate# built-in method bool() # Returns False as x is Falsex = Falseprint(bool(x)) # Returns True as x is Truex = Trueprint(bool(x)) # Returns False as x is not equal to yx = 5y = 10print(bool(x == y)) # Returns False as x is Nonex = Noneprint(bool(x)) # Returns False as x is an empty sequencex = ()print(bool(x)) # Returns False as x is an empty mappingx = {}print(bool(x)) # Returns False as x is 0x = 0.0print(bool(x)) # Returns True as x is a non empty stringx = 'GeeksforGeeks'print(bool(x))
Output: 
False
True
False
False
False
False
False
True
Example 2:
Here is a program to find out even and odd by the use of bool() method. You may use other inputs and check out the results. 
Python3
# Python code to check whether a number# is even or odd using bool() def check(num):    return(bool(num % 2 == 0)) # Driver Codenum = 8if(check(num)):    print("Even")else:    print("Odd")
Output: 
Even
Here we take input in boolean( True/ False) in boolean type with bool() function and check whether it is returned true or false.
Python3
user_input = bool(input("Are you hungry? True or false: "))if user_input == "True":    print(" You need to eat some foods ")else:    print("Let's go for walk")
Output:
Are you hungry? True or false: False
Let's go for walk
amitofficial
kumar_satyam
sagartomar9927
Python-Built-in-functions
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
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
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
Multi-dimensional lists in Python

Lists are a very widely use data structure in python. They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists. In this article we will see how to create and access elements in a multidimensional list.
In the below program we create a multidimensional list of 4 columns and 3 rows using nested for loops.
 Live Demo
multlist = [[0 for columns in range(4)] for rows in range(3)]
print(multlist)
Running the above code gives us the following result −
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
We can add elements to the list created above using methods that are available to the lists. We will use the methods append and extend to achieve this. Both methods are shown in the program below.
 Live Demo
multlist = [["Mon","Tue","Wed"], [2, 4, 9,], [1,1.5, 2]]
multlist.append(["Phy","Chem","Math"])
print(multlist)

multlist[0].extend(["Thu","Fri"])
print(multlist)
Running the above code gives us the following result −
[['Mon', 'Tue', 'Wed'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]
[['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], [2, 4, 9], [1, 1.5, 2], ['Phy', 'Chem', 'Math']]
We can access the elements in multidimensional list using for loops as shown in the below program. We design nested for loops to first access the rows and then access the columns.
multlist = [[1,5,9], [2, 4, 9,], [1,1, 2]]
for i in range(len(multlist)) :
   for j in range(len(multlist[i])) :
      print(multlist[i][j], end=" ")
   print()
Running the above code gives us the following result −
1 5 9
2 4 9
1 1 2
HeapSort - GeeksforGeeks

28 Jun, 2021
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element ... More on Heap Sort 
(A) 
(B) 
(C) 
(d)  
 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022