code-rag-bench/online-tutorials huggingface dataset:
Difference between forEach and for loop in Javascript - GeeksforGeeks

04 Mar, 2021
This article describes the difference between a forEach and for loop in detail. The basic differences between the two are given below.
For Loop: The JavaScript for loop is used to iterate through the array or the elements for a specified number of times. If a certain amount of iteration is known, it should be used.
Syntax:
for (initialization; condition; increment)  
{  
   // code to be executed
}
Example:
Javascript
<script>for (let i = 1; i <= 5; i++){    document.write(i + "<br/>");}</script>
Output:
1
2
3
4
5
forEach loop: The forEach() method is also used to loop through arrays, but it uses a function differently than the classic “for loop”. It passes a callback function for each element of an array together with the below parameters:
Current Value (required): The value of the current array element
Index (optional): The index number of the current element
Array (optional): The array object the current element belongs to
We need a callback function to loop through an array by using the forEach method.
Syntax:
numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {
   // code to be executed
});
For every single element of the array, the function will be executed. The callback should have at least one parameter which represents the elements of an array.
Example 1: This example shows the forEach method with a callback function.
the 
Output:
1
2
3
4
5
Example 2: This example shows the use of the index parameter in the forEach method.
Javascript
numbers = [1, 2, 3, 4, 5];  numbers.forEach((number, index) => {    console.log('Index: ' + index +                 ', Value: ' + number);});
Output:
Index: 0, Value 1
Index: 1, Value 2
Index: 2, Value 3
Index: 3, Value 4
Index: 4, Value 5
javascript-basics
Picked
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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?
How to copy files from one server to another using Python?

The easiest way to copy files from one server to another over ssh is to use the scp command. For calling scp you'd need the subprocess module.
import subprocess
p = subprocess.Popen(["scp", "my_file.txt", "username@server:path"])
sts = os.waitpid(p.pid, 0)
You need the waitpid call to wait for the copying to complete.
Another solution is to open a ssh connection and use the scp module.
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('user@server:path')
with SCPClient(ssh.get_transport()) as scp:
    scp.put('my_file.txt', 'my_file.txt') # Copy my_file.txt to the server
isalnum() function in C Language - GeeksforGeeks

07 Dec, 2017
isalnum() function in C programming language checks whether the given character is alphanumeric or not. isalnum() function defined in ctype.h header file.
Alphanumeric: A character that is either a letter or a number.Syntax:
int isalnum(int x);
Examples:
Input : 1
Output : Entered character is alphanumeric
Input : A
Output : Entered character is alphanumeric
Input : &
Output : Entered character is not alphanumeric

// C code to illustrate isalphanum()#include <ctype.h>#include <stdio.h>  int main(){    char ch = 'a';      // checking is it alphanumeric or not?    if (isalnum(ch))        printf("\nEntered character is alphanumeric\n");    else        printf("\nEntered character is not alphanumeric\n");}
Output:
Entered character is alphanumeric

Application: isalnum() function is used to find out number of alphanumeric in a given sentence(or any input).Example:
Input: abc123@
Output: Number of alphanumerics in the given input is : 6
Input: a@#
Output: Number of alphanumerics in the given input is : 1
Input: ...akl567
Output: Number of alphanumerics in the given input is : 6

// C code to illustrate isalphanum()#include <ctype.h>#include <stdio.h>  int ttl_alphanumeric(int i, int counter){    char ch;    char a[50] = "www.geeksforgeeks.org";    ch = a[0];      // counting of alphanumerics    while (ch != '\0') {        ch = a[i];        if (isalnum(ch))            counter++;          i++;    }      // returning total number of alphanumerics    // present in given input    return (counter);}  int main(){    int i = 0;      int counter = 0;    counter = ttl_alphanumeric(i, counter);      printf("\nNumber of alphanumerics in the "           "given input is : %d", counter);    return 0;}
Output:
Number of alphanumerics in the given input is : 19
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
UDP Server-Client implementation in C
How to dynamically allocate a 2D array in C?
Unordered Sets in C++ Standard Template Library
Python | Group strings at particular element in list - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let’s discuss certain way in which this problem can be performed.
Method : Using groupby() + list comprehension + lambdaThis task can be performed using combination of above functions. In this, we group the elements using groupby() and decision of grouping element logic is done in form of lambda function.
# Python3 code to demonstrate working of# Group strings at particular element in list# using groupby() + list comprehension + lambdafrom itertools import groupby  # initialize liststest_list = ['gfg', 'is', 'best', 'and', 'is', 'popular']  # printing original listprint("The original list is : " + str(test_list))  # initialize partition elementele = 'is'  # Group strings at particular element in list# using groupby() + list comprehension + lambdares = [list(j) for i, j in groupby(test_list, lambda x:x == ele) if not i]  # printing resultprint("Resultant list after grouping : " + str(res))
The original list is : ['gfg', 'is', 'best', 'and', 'is', 'popular']
Resultant list after grouping : [['gfg'], ['best', 'and'], ['popular']]

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
CSS Box Model

All HTML elements can be considered as boxes.
In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. 
It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is 
transparent
The box model allows us to add a border around elements, and to define space 
between elements. 
Demonstration of the box model:
In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
Important: When you set the width and height properties of an 
element with CSS, you just set the width and height of the content area. To 
calculate the full size of an element, you must also add padding, borders and margins.
This <div> element will have a total width of 350px: 
Here is the calculation:

The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left 
border + right border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top 
border + bottom border + top margin + bottom margin
Set the width of the <div> element to "200px".
<style>
 {
  : ;
}
</style>

<body>

<div>
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
</div>

</body>

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.
C# | Check if the specified string is in the StringCollection - GeeksforGeeks

01 Feb, 2019
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.
StringCollection.Contains(String) method is used to check whether the specified string is in the StringCollection or not.
Syntax:
public bool Contains (string value);

Here, value is the string to locate in the StringCollection. The value can be null.
Return Value: This method returns true if value is found in the StringCollection, otherwise it returns false.
Note:
The Contains method can confirm the existence of a string before performing further operations.
This method performs a linear search, therefore, this method is an O(n) operation, where n is Count.
Below programs illustrate the use of StringCollection.Contains(String) Method:
Example 1 :
// C# code to check if the specified// string is in the StringCollectionusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // creating a StringCollection named myCol        StringCollection myCol = new StringCollection();          // creating a string array named myArr        String[] myArr = new String[] { "A", "B", "C", "D", "E" };          // Copying the elements of a string        // array to the end of the StringCollection.        myCol.AddRange(myArr);          // checking if StringCollection        // Contains "A"        Console.WriteLine(myCol.Contains("A"));    }}
True

Example 2:
// C# code to check if the specified// string is in the StringCollectionusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // creating a StringCollection named myCol        StringCollection myCol = new StringCollection();          // creating a string array named myArr        String[] myArr = new String[] { "2", "3", "4", "5", "6" };          // Copying the elements of a string        // array to the end of the StringCollection.        myCol.AddRange(myArr);          // checking if StringCollection        // Contains "8"        Console.WriteLine(myCol.Contains("8"));    }}
False

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.contains?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-method
CSharp-Specialized-Namespace
CSharp-Specialized-StringCollection
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
How to Run Python Flask App Online using Ngrok?

04 Jan, 2021
Python Flask is a popular web framework for developing web applications, APIs, etc. Running flask apps on the local machine is very simple, but when it comes to sharing the app link to other users, you need to setup the whole app on another laptop. This article provides an interesting way to setup your web app online. Then, you can send the link to your peers before deploying it. Generally while running flask apps from our local machine we need to use LOCAL-HOST, but services such as google colab provides VM(virtual machine) hence we do not access the local-host. We will use it in to a public URL using ngrok. The Python library flask-ngrok.
Installation – 
Run from your terminal – 
pip install flask-ngrok
Create a Flask App – 
Now create a simple Flask application app.py – 
Python3
from flask import Flaskfrom flask_ngrok import run_with_ngrok  app = Flask(__name__)run_with_ngrok(app)  @app.route("/")def hello():    return "Hello Geeks!! from Google Colab"  if __name__ == "__main__":  app.run()
Run the app – 
Run the app using – 
python run.py
After clicking on the secure URL provided by ngrok in terminal, you can access your application – 
Here You go!!
Now you can use this URL on Google-colab or anywhere to access your running app.
data-science
Deep-Learning
Python Flask
Python Framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 5

28 Jun, 2021
The following function reverse() is supposed to reverse a singly linked list. There is one line missing at the end of the function.
/* Link list node */struct node{    int data;    struct node* next;};  /* head_ref is a double pointer which points to head (or start) pointer   of linked list */static void reverse(struct node** head_ref){    struct node* prev   = NULL;    struct node* current = *head_ref;    struct node* next;    while (current != NULL)    {        next  = current->next;          current->next = prev;           prev = current;        current = next;    }    /*ADD A STATEMENT HERE*/}  
What should be added in place of “/*ADD A STATEMENT HERE*/”, so that the function correctly reverses a linked list.(A) *head_ref = prev;(B) *head_ref = current;(C) *head_ref = next;(D) *head_ref = NULL;Answer: (A)Explanation: *head_ref = prev;
At the end of while loop, the prev pointer points to the last node of original linked list. We need to change *head_ref so that the head pointer now starts pointing to the last node.
See the following complete running program.
#include<stdio.h>#include<stdlib.h>   /* Link list node */struct node{    int data;    struct node* next;};   /* Function to reverse the linked list */static void reverse(struct node** head_ref){    struct node* prev   = NULL;    struct node* current = *head_ref;    struct node* next;    while (current != NULL)    {        next  = current->next;          current->next = prev;           prev = current;        current = next;    }    *head_ref = prev;}   /* Function to push a node */void push(struct node** head_ref, int new_data){    /* allocate node */    struct node* new_node =            (struct node*) malloc(sizeof(struct node));                  /* put in the data  */    new_node->data  = new_data;                      /* link the old list off the new node */    new_node->next = (*head_ref);                  /* move the head to point to the new node */    (*head_ref)    = new_node;}   /* Function to print linked list */void printList(struct node *head){    struct node *temp = head;    while(temp != NULL)    {        printf("%d  ", temp->data);            temp = temp->next;      }}       /* Drier program to test above function*/int main(){    /* Start with the empty list */    struct node* head = NULL;          push(&head, 20);     push(&head, 4);     push(&head, 15);      push(&head, 85);                  printList(head);         reverse(&head);                           printf("\n Reversed Linked list \n");     printList(head);         return 0;}
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to Multiply Two Binary Numbers

23 Aug, 2021
Given two binary numbers, and the task is to write a Python program to multiply both numbers.
Example:
firstnumber = 110
secondnumber = 10
Multiplication Result = 1100
We can multiply two binary numbers in two ways using python, and these are:
Using bin() functions andWithout using pre-defined functions
Using bin() functions and
Without using pre-defined functions
Now, Let’s write a program by using Pre-Defined Functions:
Python3
firstnumber = 110secondnumber = 10  firstnumber = str(firstnumber)secondnumber = str(secondnumber)  Multiplication = int(firstnumber, 2) * int(secondnumber, 2)binaryMul = bin(Multiplication)  print("\nResult = " + binaryMul)
Output:
Result = 0b1100
We can also multiply any two Binary Numbers without using any pre-defined Function or by user-defined function.
Python
def binaryProduct(binaryOne, binaryTwo):    i = 0    remainder = 0    sum = []    binaryProd = 0      # if firstBinary number or second Binary number is not    # zero then calculate the product of two Binary numbers    while binaryOne != 0 or binaryTwo != 0:        sum.insert(i, (((binaryOne % 10) + (binaryTwo % 10) + remainder) % 2))        remainder = int(((binaryOne % 10) + (binaryTwo % 10) + remainder) / 2)        binaryOne = int(binaryOne/10)        binaryTwo = int(binaryTwo/10)        i = i+1      # if remainder value is not equal to    # zero then insert the digit to sum array    if remainder != 0:        sum.insert(i, remainder)        i = i+1    i = i-1    while i >= 0:        binaryProd = (binaryProd * 10) + sum[i]        i = i-1    return binaryProd    binaryMultiply = 0factor = 1firstBinary = 110  secondBinary = 10  # Now check if secondbinary number have any# digit or not and continue multiplying# each digit of the second binary number with# first binary number till the last digit of# second binary numberwhile secondBinary != 0:    digit = secondBinary % 10    if digit == 1:        firstBinary = firstBinary * factor        binaryMultiply = binaryProduct(firstBinary, binaryMultiply)    else:        firstBinary = firstBinary * factor    secondBinary = int(secondBinary/10)    factor = 10print("\nMultiplication Result = " + str(binaryMultiply))
Output:
Multiplication Result = 1100
Picked
school-programming
Python
Python Programs
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
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Program to find minimum largest sum of k sublists in C++

Suppose we have a list of numbers called nums and another value k. We can split the list into k non-empty sublists. We have to find the minimum largest sum of the k sublists.
So, if the input is like nums = [2, 4, 3, 5, 12] k = 2, then the output will be 14, as we can split the list like: [2, 4, 3, 5] and [12].
To solve this, we will follow these steps −
Define a function ok(), this will take array v, k, x,
Define a function ok(), this will take array v, k, x,
cnt := 0, sum := 0
cnt := 0, sum := 0
for each element i in v −if sum + i > x, then −sum := i(increase cnt by 1)Otherwisesum := sum + i
for each element i in v −
if sum + i > x, then −sum := i(increase cnt by 1)
if sum + i > x, then −
sum := i
sum := i
(increase cnt by 1)
(increase cnt by 1)
Otherwisesum := sum + i
Otherwise
sum := sum + i
sum := sum + i
return true when cnt <= k, otherwise false
return true when cnt <= k, otherwise false
From the main method do the following −
From the main method do the following −
low := 0, ret := 0, high := 0
low := 0, ret := 0, high := 0
for each element i in numshigh := high + iret := ret + ilow := maximum of low and i
for each element i in nums
high := high + i
high := high + i
ret := ret + i
ret := ret + i
low := maximum of low and i
low := maximum of low and i
while low <= high, do −mid := low + (high - low) / 2if ok(nums, k - 1, mid) is true, then −ret := midhigh := mid - 1Otherwiselow := mid + 1
while low <= high, do −
mid := low + (high - low) / 2
mid := low + (high - low) / 2
if ok(nums, k - 1, mid) is true, then −ret := midhigh := mid - 1
if ok(nums, k - 1, mid) is true, then −
ret := mid
ret := mid
high := mid - 1
high := mid - 1
Otherwiselow := mid + 1
Otherwise
low := mid + 1
low := mid + 1
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool ok(vector <int>& v, int k, int x){
   int cnt = 0;
   int sum = 0;
   for(int i : v){
      if(sum + i > x){
         sum = i;
         cnt++;
      }
      else{
         sum += i;
      }
   }
   return cnt <= k;
}
int solve(vector<int>& nums, int k) {
   int low = 0;
   int ret = 0;
   int high = 0;
   for(int i : nums){
      high += i;
      ret += i;
      low = max(low, i);
   }
   while(low <= high){
      int mid = low + ( high - low) / 2;
      if(ok(nums, k - 1, mid)){
         ret = mid;
         high = mid - 1;
      }
      else{
         low = mid + 1;
      }
   }
   return ret;
}
int main(){
   vector<int> v = {2, 4, 3, 5, 12};
   int k = 2;
   cout << solve(v, k);
}
{2, 4, 3, 5, 12}, 2
14
How to draw tick mark with circle background shape in android?

This example demonstrates How to draw tick mark with circle background shape in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <ImageView
      android:layout_width="100dp"
      android:layout_height="100dp"
      android:background="@drawable/background"/>
</LinearLayout>
In the above code, we have taken image view and added background as background.xml.
Step 3 − Add the following code to drawable/ background.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
   android:width="24dp"
   android:height="24dp"
   android:autoMirrored="true"
   android:viewportWidth="426.667"
   android:viewportHeight="426.667">
   <path
      android:fillColor="#6AC259"
      android:pathData="M213.333,0C95.518,0 0,95.514 0,213.333s95.518,213.333 213.333,
                        213.333c117.828,0 213.333,-95.514 213.333,-213.333S331.157,
                        0213.333,0zM174.199,322.918l-93.935,-93.931l31.309,-31.309l62.626,
                        62.622l140.894,-140.898l31.309,31.309L174.199,322.918z" />
</vector>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
Fill the area under a curve in Matplotlib python on log scale

To fill the area under a curve in Matplotlib python on log scale, we can take the following steps−
Set the figure size and adjust the padding between and around the subplots.
Create x, y1 and y2 data points using numpy.
Plot x, y1 and y2 data points using plot() method.
Fill the area between the two curves.
Set the scale of the axes.
Place a legend on the plot.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

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

x = np.linspace(-1, 1, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label="y=sin(x)")
plt.plot(x, y2, label="y=cos(x)")

plt.fill_between(x, y1, y2, color="red", label="Area", alpha=0.3)

plt.xscale('log')
plt.yscale('log')

plt.legend(loc='lower right')

plt.show()
MongoDB projection on specific nested properties?

For projection on specific nested properties, use aggregate() in MongoDB. Let us first create a collection with documents −
> db.demo379.insertOne(
...    {
...       "details1" : {
...          "details2" : {
...             "details3" : {
...                "10" : "John",
...                "50" : "Chris",
...                "40" : "David",
...                "30":"Mike"
...             }
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a94f82ae06a1609a00b10")
}
Display all documents from a collection with the help of find() method −
> db.demo379.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e5a94f82ae06a1609a00b10"),
   "details1" : {
      "details2" : {
         "details3" : {
            "10" : "John",
            "30" : "Mike",
            "40" : "David",
            "50" : "Chris"
         }
      }
   }
}
Following is the query for projection on specific nested properties −
> db.demo379.aggregate([
...    { "$addFields": {
...       "details1.details2.details3": {
...          "$arrayToObject": {
...             "$filter": {
...                "input": { "$objectToArray": "$details1.details2.details3" },
...                "as": "out",
...                "cond": {
...                   "$and": [
...                      { "$gte": ["$$out.k", "35"] },
...                      { "$lte": ["$$out.k", "60"] },
...                   ]
...                }
...             }
...          }
...       }
...    } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "40" : "David", "50" : "Chris" } } } }
MATLAB - Data Types

MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a new variable name, it creates the variable and allocates appropriate memory space.
If the variable already exists, then MATLAB replaces the original content with new content and allocates new storage space, where necessary.
For example,
Total = 42

The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in it.
MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any size.
The following table shows the most commonly used data types in MATLAB −
int8
8-bit signed integer
uint8
8-bit unsigned integer
int16
16-bit signed integer
uint16
16-bit unsigned integer
int32
32-bit signed integer
uint32
32-bit unsigned integer
int64
64-bit signed integer
uint64
64-bit unsigned integer
single
single precision numerical data
double
double precision numerical data
logical
logical values of 1 or 0, represent true and false respectively
char
character data (strings are stored as vector of characters)
cell array
array of indexed cells, each capable of storing an array of a different dimension and data type
structure
C-like structures, each structure having named fields capable of storing an array of a different dimension and data type
function handle
pointer to a function
user classes
objects constructed from a user-defined class
java classes
objects constructed from a Java class
Create a script file with the following code −
str = 'Hello World!'
n = 2345
d = double(n)
un = uint32(789.50)
rn = 5678.92347
c = int32(rn)
When the above code is compiled and executed, it produces the following result −
str = Hello World!
n =  2345
d =  2345
un = 790
rn = 5678.9
c =  5679

MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions −
MATLAB provides various functions for identifying data type of a variable. 
Following table provides the functions for determining the data type of a variable −
Create a script file with the following code −
x = 3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
 
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
 
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
 
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
When you run the file, it produces the following result −
x = 3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x =

          1          2          3

ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
p5.js | clear() function - GeeksforGeeks

17 Apr, 2019
The clear() function in p5.js is used to clear the pixels within a buffer. This function only clears the canvas. This function clears everything to make all of the pixels 100% transparent. It can be used to reset the drawing canvas.
Syntax:
clear()
Parameters: This function does not accept any parameter.
Below program illustrates the clear() function in p5.js:
Example: This example uses clear() function to clear the canvas.
function setup() {      // Create canvas     createCanvas(700, 700);}   function draw() {          noStroke();          // Draw Ellipse at mouseX and mouseY    ellipse(mouseX, mouseY, 20, 20);       // Set color of the ellipse    fill('green');          // Set the text size    textSize(20);          // Set the text    text("Press Mouse To Clear The Screen", 20, 30);}   // Define the mousePressed functionfunction mousePressed() {    clear();}
Output:Before Clicking the mouse button:After Clicking the mouse button:
Reference: https://p5js.org/reference/#/p5/clear
ManasChhabra2
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
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Java Examples - Write to a file

How to write into a file ?
This example shows how to write to a file using write method of BufferedWriter.
import java.io.*;

public class Main {
   public static void main(String[] args) {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
         out.write("aString");
         out.close();
         System.out.println("File created successfully");
      }
      catch (IOException e) {
      }
   }
}
The above code sample will produce the following result.
File created successfully.

The following is the another example of write into a file in java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileExample {
   public static void main(String[] args) {
      try {
         String content = "TutorialsPoint is one the best site in the world";
         File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         if (!file.exists()) {
            file.createNewFile();
         } 
         FileWriter fw = new FileWriter(file.getAbsoluteFile());
         BufferedWriter bw = new BufferedWriter(fw);
         bw.write(content);
         bw.close();
         
         System.out.println("Done");
      } catch (IOException e) {
         e.printStackTrace();
      } 
   } 
}
The above code sample will produce the following result.
Done

 Print
 Add Notes
 Bookmark this page
Python - Extract string between two substrings - GeeksforGeeks

09 May, 2021
Given a string and two substrings, write a Python program to extract the string between the found two substrings. 
Input : test_str = “Gfg is best for geeks and CS”, sub1 = “is”, sub2 = “and” 
Output : best for geeks
Explanation : best for geeks is between is and ‘and’
Input : test_str = “Gfg is best for geeks and CS”, sub1 = “for”, sub2 = “and” 
Output : geeks
Explanation : geeks is between for and ‘and’
Method #1 : Using index() + loop
In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.
Python3
# Python3 code to demonstrate working# of Extract string between 2 substrings# Using loop + index()  # initializing stringtest_str = "Gfg is best for geeks and CS"  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringssub1 = "is"sub2 = "and"  # getting index of substringsidx1 = test_str.index(sub1)idx2 = test_str.index(sub2)  res = ''# getting elements in betweenfor idx in range(idx1 + len(sub1) + 1, idx2):    res = res + test_str[idx]  # printing resultprint("The extracted string : " + res)
Output:
The original string is : Gfg is best for geeks and CS
The extracted string : best for geeks 
Method #2 : Using index() + string slicing
Similar to the above method, just the task of slicing is performed using string slicing for providing a much compact solution. 
Python3
# Python3 code to demonstrate working # of Extract string between 2 substrings# Using index() + string slicing  # initializing stringtest_str = "Gfg is best for geeks and CS"  # printing original stringprint("The original string is : " + str(test_str))  # initializing substringssub1 = "is"sub2 = "and"  # getting index of substringsidx1 = test_str.index(sub1)idx2 = test_str.index(sub2)  # length of substring 1 is added to# get string from next characterres = test_str[idx1 + len(sub1) + 1: idx2]  # printing resultprint("The extracted string : " + res)
Output:
The original string is : Gfg is best for geeks and CS
The extracted string : best for geeks 
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Optional equals() method in Java with Examples - GeeksforGeeks

30 Jul, 2019
The equals() method of java.util.Optional class in Java is used to check for equality of this Optional with the specified Optional. This method takes an Optional instance and compares it with this Optional and returns a boolean value representing the same.
Syntax:
public boolean equals(Object obj)

Parameter: This method accepts a parameter obj which is the Optional to be checked for equality with this Optional.
Return Value: This method returns a boolean which tells if this Optional is equal to the specified Object.
Exception: This method do not throw any Exception.
Program 1:
// Java program to demonstrate// the above method  import java.text.*;import java.util.*;  public class OptionalDemo {    public static void main(String[] args)    {          Optional<Integer> op1            = Optional.of(456);          System.out.println("Optional 1: "                           + op1);          Optional<Integer> op2            = Optional.of(456);          System.out.println("Optional 2: "                           + op2);          System.out.println("Comparing Optional 1"                           + " and Optional 2: "                           + op1.equals(op2));    }}
Optional 1: Optional[456]
Optional 2: Optional[456]
Comparing Optional 1 and Optional 2: true

Program 2:
// Java program to demonstrate// the above method  import java.text.*;import java.util.*;  public class OptionalDemo {    public static void main(String[] args)    {          Optional<Integer> op1            = Optional.of(456);          System.out.println("Optional 1: "                           + op1);          Optional<Integer> op2            = Optional.empty();          System.out.println("Optional 2: "                           + op2);          System.out.println("Comparing Optional 1"                           + " and Optional 2: "                           + op1.equals(op2));    }}
Optional 1: Optional[456]
Optional 2: Optional.empty
Comparing Optional 1 and Optional 2: false

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#equals-java.lang.Object-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Set in Java
Application of Syntax Directed Translation - GeeksforGeeks

21 Aug, 2020
In this article, we are going to cover the application of Syntax Directed Translation where we will also see real example and how can solve the problem with these applications. let’s discuss one by one.
Pre-requisite : Introduction to Syntax Directed Translation
Syntax Directed Translation :It is used for semantic analysis and SDT is basically used to construct the parse tree with Grammar and Semantic action. In Grammar, need to decide who has the highest priority will be done first and In semantic action, will decide what type of action done by grammar.
Example :
SDT = Grammar+Semantic Action
Grammar = E -> E1+E2  
Semantic action= if (E1.type != E2.type) then print "type mismatching"
Application of Syntax Directed Translation :
SDT is used for Executing Arithmetic Expression.
In the conversion from infix to postfix expression.
In the conversion from infix to prefix expression.
It is also used for Binary to decimal conversion.
In counting number of Reduction.
In creating a Syntax tree.
SDT is used to generate intermediate code.
In storing information into symbol table.
SDT is commonly used for type checking also.
Example :Here, we are going to cover an example of application of SDT for better understanding the SDT application uses. let’s consider an example of arithmetic expression and then you will see how SDT will be constructed.
Let’s consider Arithmetic Expression is given.
Input : 2+3*4
output: 14
SDT for the above example.
SDT for 2+3*4
Semantic Action is given as following.
E -> E+T  { E.val = E.val + T.val then print (E.val)}
     |T   { E.val = T.val} 
T -> T*F  { T.val = T.val * F.val}
     |F   { T.val = F.val}
F -> Id   {F.val = id}
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Issues in the design of a code generator
Why FIRST and FOLLOW in Compiler Design?
Error Handling in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
How to Install Rust on Termux? - GeeksforGeeks

06 Dec, 2021
Rust is a general-purpose programming language. It is an open-source system programming language. Rust can be installed in Termux. Mainly C# programming language is used in Rust. Rust is famous for its speed, memory safety & parallelism. 
In this article, we will look into the process of installing rust on termux.
Step 1: Open Termux in mobile.
Step 2: Use the below command to  install rust on termux:
pkg install rust
Step 3: Press Y to continue & wait for some time.
Step 4: Then Progress will start & wait till finishes.
Step 5: After that installation will be completed. 
Step 6: Now use the below command to verify the installation:
rustc --version
Hence installation is successful.
how-to-install
Picked
How To
Installation Guide
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Random number generator in Java

To generate random numbers in Java, use.
import java.util.Random;
Now, take Random class and create an object.
Random num = new Random();
Now, in a loop, use the nextInt() method since it is used to get the next random integer value. You can also set a range, like for 0 to 20, write it as.
nextInt( 20 );
Let us see the complete example wherein the range is 1 to 10.
 Live Demo
import java.util.Random;
public class Demo {
   public static void main( String args[] ) {
      Random num = new Random();
      int res;
      for ( int i = 1; i <= 5; i++ ) {
         res = 1 + num.nextInt( 10 );
         System.out.printf( "%d ", res );
      }
   }
}
4 5 9 6 9
Java Program to Get the Basic File Attributes - GeeksforGeeks

05 Feb, 2021
Basic File Attributes are the attributes that are associated with a file in a file system, these attributes are common to many file systems. In order to get the basic file attributes, we have to use the BasicFileAttributes interface. This interface is introduced in 2007 and is a part of the nio package. 
The basic file attributes contain some information related to files like creation time, last access time, last modified time, size of the file(in bytes), this attributes also tell us that whether the file is regular or not, whether the file is a directory, or whether the file is a symbolic link or whether the file is something is other than a regular file, directory, or symbolic link.
Methods that are used to get the basic file attributes are:
Below is the Java Program to get the basic file attributes:
Java
// Java Program to get the basic file attributes of the fileimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.attribute.BasicFileAttributes;import java.sql.Timestamp;import java.util.Date;public class GFG {    public static void main(String args[])        throws IOException    {        // path of the file        String path = "C:/Users/elavi/Desktop/GFG_File.txt";          // creating a object of Path class        Path file = Paths.get(path);                // creating a object of BasicFileAttributes        BasicFileAttributes attr = Files.readAttributes(            file, BasicFileAttributes.class);        System.out.println("creationTime Of File Is  = "                           + attr.creationTime());        System.out.println("lastAccessTime Of File Is  = "                           + attr.lastAccessTime());        System.out.println("lastModifiedTime Of File Is = "                           + attr.lastModifiedTime());          System.out.println("size Of File Is = "                           + attr.size());        System.out.println("isRegularFile Of File Is = "                           + attr.isRegularFile());        System.out.println("isDirectory Of File Is = "                           + attr.isDirectory());        System.out.println("isOther Of File Is = "                           + attr.isOther());          System.out.println("isSymbolicLink Of File Is  = "                           + attr.isSymbolicLink());    }}
Note: Above Program will run only on system IDE, it will not run on an online IDE.
Java-Files
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
MySQL Database Connection

PHP provides mysql_connect function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success, or FALSE on failure.
connection mysql_connect(server,user,passwd,new_link,client_flag);

server
Optional − The host name running database server. If not specified then default value is localhost:3306.
user
Optional − The username accessing the database. If not specified then default is the name of the user that owns the server process.
passwd
Optional − The password of the user accessing the database. If not specified then default is an empty password.
new_link
Optional − If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned.
client_flags
Optional − A combination of the following constants −
MYSQL_CLIENT_SSL − Use SSL encryption
MYSQL_CLIENT_SSL − Use SSL encryption
MYSQL_CLIENT_COMPRESS − Use compression protocol
MYSQL_CLIENT_COMPRESS − Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection
NOTE − You can specify server, user, passwd in php.ini file instead of using them again and again in your every PHP scripts. Check php.ini file configuration.
Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on failure.
bool mysql_close ( resource $link_identifier );

If a resource is not specified then last opend database is closed.
Try out following example to open and close a database connection −
<?php
   
   $dbhost = 'localhost:3036';
   $dbuser = 'guest';
   $dbpass = 'guest123';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   echo 'Connected successfully';
   mysql_close($conn);
?>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page