code-rag-bench/online-tutorials huggingface dataset:
Difference between std::vector and std::array in C++

The following are the differences between vector and array −
Vector is a sequential container to store elements and not index based.
Array stores a fixed-size sequential collection of elements of the same type and it is index based.
Vector is dynamic in nature so, size increases with insertion of elements.
As array is fixed size, once initialized can’t be resized.
Vector occupies more memory.
Array is memory efficient data structure.
Vector takes more time in accessing elements.
Array access elements in constant time irrespective of their location as elements are arranged in a contiguous memory allocation.
Vectors and arrays can be declared with the following syntax −
Vector declaration:vector<datatype>array name;
Array declaration:type array_name[array_size];
Vector initialization:vector<datatype>array name={values};
Array initialization:datatype arrayname[arraysize] = {values};
#include <iostream>
#include <vector>
using namespace std;
int main() {
   vector<vector<int>>v{ { 4, 5, 3 }, { 2, 7, 6 }, { 3, 2, 1 ,10 } };
   cout<<"the 2D vector is:"<<endl;
   for (int i = 0; i < v.size(); i++) {
      for (int j = 0; j < v[i].size(); j++)
         cout << v[i][j] << " ";
         cout << endl;
   }
   return 0;
}
the 2D vector is:
4 5 3
2 7 6
3 2 1 10
#include<iostream>
#include<array>
using namespace std;

int main() {
   array<int,4>a = {10, 20, 30, 40};
   cout << "The size of array is : ";
   //size of the array using size()
   cout << a.size() << endl;
   //maximum no of elements of the array
   cout << "Maximum number of elements array can hold is : ";
   cout << a.max_size() << endl;
   // Printing array elements using at()
   cout << "The array elements are (using at()) : ";
   for ( int i=0; i<4; i++)
      cout << a.at(i) << " ";
      cout << endl;
      // Filling array with 1
      a.fill(1);
      // Displaying array after filling
      cout << "Array after filling operation is : ";
   for ( int i=0; i<4; i++)
      cout << a[i] << " ";
      return 0;
}
The size of array is : 4
Maximum number of elements array can hold is : 4
The array elements are (using at()) : 10 20 30 40
Array after filling operation is : 1 1 1 1
DAX Aggregation - PRODUCTX function

Returns the product of the numbers resulted from an expression evaluated for each row in a table.
DAX PRODUCTX function is new in Excel 2016.
PRODUCTX (<table>, <expression>) 

table
The table containing the rows for which the expression will be evaluated.
expression
The expression to be evaluated for each row of the table.
A decimal number.
Only the numbers in the column are considered. Blanks, logical values, and text are ignored.
= [PresentValue] * PRODUCTX (AnnuityPeriods, 1 + [FixedInterestRate])

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
C++ Program to Represent Linear Equations in Matrix Form

This is a C++ program to represent Linear Equations in matrix form.
Begin
   1) Take the no of variables n and the coefficients of each variable as input.
   2) Declare a matrix[n][n] and constant[n][1].
   3) Make for loops i = 0 to n-1 and j = 0 to n-1
   to take the coefficients of each variable as the elements of the matrix.
   4) Display the matrix by using nested for loops.
End
#include<iostream>
using namespace std;
int main(void) {
   char variable[] = { 'x', 'y', 'z', 'd' };
   cout << "Enter the number of variables in the
   equations: ";
   int n;
   cin >> n;
   cout << "\nEnter the coefficients of each variable for
   each equation, ax + by + cz + ... = d:";
   int matrix[n][n];
   int constant[n][1];
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         cin >> matrix[i][j];
      }
      cin >> constant[i][0];
   }
   cout << "Matrix representation is: "<<endl;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         cout << " " << matrix[i][j];
      }
      cout << " " << variable[i];
      cout << " = " << constant[i][0];
      cout << "\n";
   }
   return 0;
}
Enter the number of variables in the equations: 3
Enter the coefficients of each variable for each equation,
ax + by + cz + ... = d:
1 2 3 4
5 6 7 9
8 5 2 1
Matrix representation is:
1 2 3 x = 4
5 6 7 y = 9
8 5 2 z = 1
Mahotas - Getting Mean Value of Image - GeeksforGeeks

16 Apr, 2021
In this article we will see how we can get the mean value of image in mahotas. Mean value is the sum of pixel values divided by the total number of pixel values. Pixel Values Each of the pixels that represents an image stored inside a computer has a pixel value which describes how bright that pixel is, and/or what color it should be. In the simplest case of binary images, the pixel value is a 1-bit number indicating either foreground or background.Mean is most basic of all statistical measure. Means are often used in geometry and analysis; a wide range of means have been developed for these purposes. In contest of image processing filtering using mean is classified as spatial filtering and used for noise reduction.In order to do this we will use mean method  
Syntax : img.mean()Argument : It takes no argumentReturn : It returns float32  
Here img is the image loaded using mahotas, which can be done with the help of mahotas.imread(image_name) method.Note : The image should be filtered before getting mean because it can calculate for one channel at one timeExample 1 :  
Python3
# importing required librariesimport numpy as npimport mahotasfrom pylab import imshow, show  # loading imageimg = mahotas.imread('dog_image.png')  # filtering the imageimg = img[:, :, 0]    print("Image with filter")# showing the imageimshow(img)show()  # getting mean valuemean = img.mean()  # printing mean valueprint("Mean Value for 0 channel : " + str(mean))
Output :  
 
Mean Value for 0 channel : 129.05525723083971
Example 2 :  
Python3
# importing required librariesimport mahotas as mhimport mahotas.demosimport numpy as npfrom pylab import imshow, show # getting nuclear imagenuclear = mh.demos.nuclear_image()  # filtering the imagenuclear = nuclear[:, :, 0] print("Image with filter")# showing the imageimshow(nuclear)show() # getting mean valuemean = nuclear.mean() # printing mean valueprint("Mean Value for 0 channel : " + str(mean))
Output :  
 
Mean Value for 0 channel : 27.490094866071427
Note : For each channel there are different mean value and mean can be a good option to set the threshold value for an image. 
arorakashish0911
Image-Processing
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
How to remove white spaces using Java Regular Expression (RegEx)

The regular expression “\\s” matches the spaces in a string. The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.
public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      String input = "Hi welcome to tutorialspoint";
      String regex = "\\s";
      String result = input.replaceAll(regex, "");
      System.out.println("Result: "+result);
   }
}
Result: Hiwelcometotutorialspoint
Similarly, the appendReplacement() method accepts a string buffer and a replace string and, appends the matched characters with the given replace string and appends to the string buffer.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      String regex = "\\s";
      String constants = "";
      System.out.println("Input string: \n"+input);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString()+constants );
   }
}
Enter input string:
this is a sample text with white spaces
Input string:
this is a sample text with white spaces
Result:
thisisasampletextwithwhitespaces
public class Just {
   public static void main(String args[]) {
      String input = "This is a sample text with spaces";
      String str[] = input.split(" ");
      String result = "";
      for(int i=0; i<str.length; i++) {
         result = result+str[i];
      }
      System.out.println("Result: "+result);
   }
}
Result: Thisisasampletextwithspaces
eval() function in JavaScript

The eval() function accepts a string value which holds JavaScript code. This function executes the given code and returns the result of the code.
Its Syntax is as follows
eval(32*45);
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      document.write(eval(32*45));
      document.write("<br>");
      document.write(eval(new String("Hello welcome to Tutorialspoint")));
   </script>
</body>
</html>
1440
Hello welcome to Tutorialspoint
Common Character Count in Strings in JavaScript

We are required to write a JavaScript function that takes in two strings, let us say str1 and str2.
The function should count the number of common characters that exist in the strings.
For example −
const str1 = 'aabbcc';
const str2 = 'adcaa';
Then the output should be 3
Following is the code −
const str1 = 'aabbcc';
const str2 = 'adcaa';
const commonCharacterCount = (str1 = '', str2 = '') => {
   let count = 0;
   str1 = str1.split('');
   str2 = str2.split('');
   str1.forEach(e => {
      if (str2.includes(e)) {
         count++;
         str2.splice(str2.indexOf(e), 1);
      };
   });
   return count;
};
console.log(commonCharacterCount(str1, str2));
Following is the output on console −
3
Laravel - Delete Records

We can delete the record using the DB facade with the delete method. The syntax of delete method is shown in the following table.
$query(string) − query to execute in database
$bindings(array) − values to bind with queries
Step 1 − Execute the below command to create a controller called StudDeleteController.
php artisan make:controller StudDeleteController --plain

Step 2 − After successful execution, you will receive the following output −
Step 3 − Copy the following code to file
app/Http/Controllers/StudDeleteController.php
app/Http/Controllers/StudDeleteController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudDeleteController extends Controller {
   public function index() {
      $users = DB::select('select * from student');
      return view('stud_delete_view',['users'=>$users]);
   }
   public function destroy($id) {
      DB::delete('delete from student where id = ?',[$id]);
      echo "Record deleted successfully.<br/>";
      echo '<a href = "/delete-records">Click Here</a> to go back.';
   }
}
Step 4 − Create a view file called
resources/views/stud_delete_view.blade.php and copy the following code in that file.
resources/views/stud_delete_view.blade.php
<html>
   
   <head>
      <title>View Student Records</title>
   </head>
   
   <body>
      <table border = "1">
         <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Edit</td>
         </tr>
         @foreach ($users as $user)
         <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td><a href = 'delete/{{ $user->id }}'>Delete</a></td>
         </tr>
         @endforeach
      </table>
   </body>
</html>
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('delete-records','StudDeleteController@index');
Route::get('delete/{id}','StudDeleteController@destroy');

Step 6 −The output will appear as shown in the following image.
Step 7 − Click on delete link to delete that record from database. You will be redirected to a page where you will see a message as shown in the following image.
Step 8 − Click on “Click Here” link and you will be redirected to a page where you will see all the records except the deleted one.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
C# program to print all the numbers divisible by 3 and 5 for a given number

To print the numbers divisible by 3 and 5, use the && operator and check two conditions −
f (num % 3 == 0 && num % 5 == 0) {}
If the above condition is true, that would mean the number is divisible by 3 as well as 5.
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int num;
         num = 15;

         Console.WriteLine("Number: "+num);

         // checking if the number is divisible by 3 and 5
         if (num % 3 == 0 && num % 5 == 0) {
            Console.WriteLine("Divisible by 3 and 5");
         } else {
            Console.WriteLine("Not divisible by 3 and 5");
         }
         Console.ReadLine();
      }
   }
}
Number: 15
Divisible by 3 and 5
Get natural logarithm value using Math.log in Java

To obtain the natural log of a number, we use the java.lang.Math.log() method. The Math.log() method returns the natural logarithm i.e. log to the base e of a double value. If the value passed is NaN or negative, the result is NaN. If the value passed is positive infinity, then the value returned is positive infinity. When the parameter is positive zero or negative zero, then negative infinity is returned.
Declaration - The java.lang.Math.log() method is declared as follows
public static double log(double a)
where a is a value whose natural logarithm is to be found.
Let us see a program to get the natural logarithm of a number in Java using the Math.log() method
 Live Demo
import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and initializing two double values
      double x = 300.01d;
      double y = 290.344d;
      // printing their natural logarithms
      System.out.println("Natural logarithm of "+ x + " is " + Math.log(x));
      System.out.println("Natural logarithm of "+ y + " is " + Math.log(y));
   }
}
Natural logarithm of 300.01 is 5.703815807433991
Natural logarithm of 290.344 is 5.671066426889541
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider the store and forward packet switched network given below. Assume that the bandwidth of each link is 106 bytes / sec. A user on host A sends a file of size 103 bytes to host B through routers R1 and R2 in three different ways. In the first case a single packet containing the complete file is transmitted from A to B. In the second case, the file is split into 10 equal parts, and these packets are transmitted from A to B. In the third case, the file is split into 20 equal parts and these packets are sent from A to B. Each packet contains 100 bytes of header information along with the user data. Consider only transmission time and ignore processing, queuing and propagation delays. Also assume that there are no errors during transmission. Let T1, T2 and T3 be the times taken to transmit the file in the first, second and third case respectively. Which one of the following is CORRECT?
(A) T1 < T2 < T3
(B) T1 > T2 > T3(C) T2 = T3, T3 < T1(D) T1 = T3, T3 > T2Answer: (D)Explanation: The important thing to note here is in first case, the whole packet is being transmitted, so no piplelining of packet happens.
In second and third case, we have advantage of pipelining (While packet ‘i’ is being transmitted from R1 to R2,packet ‘i-1’ is being transmitted from A to R1 at the same time).
Following are complete calculations.
File Size = 1000 bytes
Header Size = 100 bytes
Transmission Speed of all  links = 10^6 bytes/sec

Ist Case: 
 Transmission time for one link 
                = packetsize/bandwidth
                = (1000 + 100)/10^6
                = 1100 micros
 Total time = 3*1100
            = 3300 microsec.

Second case: 
  Transmission time for one link and one part
                   = (100 + 100)/10^6
                   =  200 microsec

  [Note the pipe-lining in packets.  While
  packet 'i' is being transmitted from R1 to R2,
  packet 'i-1' is being transmitted from A to R1
  at the same time]
  Total time = 3*200 + 9*200
             = 2400 micro sec

Third Case: 
  Transmission time for one link and one part
                                 = (50+100)/10^6 
                                 = 150microsec
  Total time = 3*150+19*150
             = 3300 microsec 
Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
Pandas DataFrame astype() Method

❮ DataFrame Reference

Return a new DataFrame where the data type of all columns has been set to 
  'int64':
The astype() method returns a new DataFrame 
where the data types has been changed to the specified type.
You can cast the entire DataFrame to one specific data type, or you can use a
Python Dictionary to specify a data type for each column, like this:

{
  'Duration': 'int64',
  'Pulse'   : 'float',
  'Calories': 'int64'
}
The copy and errors parameters are 
keyword arguments.
{
  'Duration': 'int64',
  'Pulse'   : 'float',
  'Calories': 'int64'
}
a Pandas DataFrame with the changes set according to the 
specified dtype(s).

❮ DataFrame Reference

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.
What is the super class of every class in Java?

The class named Object is the super class of every class in Java.
Let’s test it with an example. The java.lang.Class.getSuperclass() returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
So, Create a sample concrete class and lets try to get the name of its super class using this method.
 Live Demo
public class Test {
   public static void main(String args[]){
      Test obj = new Test();
      Class cls = obj.getClass().getSuperclass();
      System.out.println(cls.getName());
   }
}
Since the Object class is the super class of all classes it displays the name of the object class as shown below.
java.lang.Object
How to project specific elements in an array field with MongoDB?

To project-specific elements in an array field, use $project. Let us create a collection with documents −
>db.demo355.insertOne({"id":101,"details":[{"Name":"Chris",isMarried:1},{"Name":"David",isMarried:0},{"Name":"Mike",isMarried:1}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568928f8647eb59e5620c5")
}
Display all documents from a collection with the help of find() method −
> db.demo355.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e568928f8647eb59e5620c5"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "isMarried" : 1
      },
      {
         "Name" : "David",
         "isMarried" : 0
      },
      {
         "Name" : "Mike",
         "isMarried" : 1
      }
   ]
}
Following is the query to project-specific elements in an array field −
> db.demo355.aggregate([
...    {
...       $project: {
...          details: {
...             $filter: {
...                input: "$details",
...                as: "out",
...                cond: { $eq:["$$out.isMarried",1] }
...             }
...          }
...       }
...    }
... ])
This will produce the following output −
{
   "_id" : ObjectId("5e568928f8647eb59e5620c5"), "details" : [
      { "Name" : "Chris", "isMarried" : 1 },
      { "Name" : "Mike", "isMarried" : 1 }
   ] 
}
How to create histogram of all columns in an R data frame?

To create histogram of all columns in an R data frame, we can use hist.data.frame function of Hmisc package. For example, if we have a data frame df that contains five columns then the histogram for all the columns can be created by using a single line code as hist.data.frame(df).
Consider the below data frame −
 Live Demo
set.seed(9)
x1<-rnorm(20,5,1.09)
x2<-rnorm(20,5,0.80)
x3<-rnorm(20,5,0.50)
x4<-rnorm(20,5,0.02)
x5<-rnorm(20,5,0.15)
df<-data.frame(x1,x2,x3,x4,x5)
df
      x1       x2       x3       x4      x5
1 4.164192 6.405594 4.595772 5.005624 5.017111
2 4.110060 5.145802 3.990309 4.975946 4.841951
3 4.845727 4.786489 4.630638 5.009303 5.023400
4 4.697411 5.741137 5.191443 5.007040 5.195059
5 5.475575 4.445334 5.865432 4.988203 4.826617
6 3.706309 7.145592 4.898459 4.982928 5.032406
7 6.299266 5.178020 4.501801 4.995065 5.120672
8 4.980173 4.434662 4.346732 5.030787 4.890183
9 4.729588 5.333771 4.501084 5.010922 4.757285
10 4.604399 5.295645 4.717486 5.031299 5.125860
11 6.392552 4.268989 5.876029 5.004993 4.947284
12 4.488902 4.746468 4.726114 4.960752 4.892557
13 5.077449 5.839247 4.570737 4.983819 4.858956
14 4.710018 5.134489 5.024647 4.990026 5.109525
15 7.011330 5.025152 4.899978 5.006102 4.934319
16 4.085000 4.191736 4.448023 4.994216 4.962593
17 4.915582 5.306201 5.120294 5.029154 4.899189
18 2.146701 4.344243 5.190557 5.017475 5.120152
19 5.967794 5.289369 6.115229 4.980941 4.776671
20 4.228834 5.074697 5.599601 4.999366 5.068102
Loading Hmisc package and creating histograms for all columns of data frame df −
library(Hmisc)
hist.data.frame(df)
Let’s have a look at another example −
 Live Demo
y1<-rnorm(5000,5,1.09)
y2<-rnorm(5000,5,0.80)
y3<-rnorm(5000,5,0.50)
y4<-rnorm(5000,5,0.02)
df_y<-data.frame(y1,y2,y3,y4)
head(df_y,20)
      y1       y2       y3       y4
1 7.360122 2.477397 5.692058 4.997948
2 2.834658 5.737269 5.038057 4.995741
3 4.877497 4.688126 4.400630 5.018846
4 7.241674 5.875059 5.376843 4.987899
5 3.871008 3.597722 4.785035 5.012924
6 5.148704 5.933472 5.349004 4.952439
7 5.908375 5.956353 5.606131 4.966737
8 4.537790 4.034598 5.473110 4.969043
9 4.725682 4.965986 4.771915 5.027725
10 4.678440 4.453948 5.607061 5.011792
11 5.387485 5.280068 5.693234 4.979037
12 4.057784 6.449363 5.357565 5.004431
13 3.429349 5.513883 5.054941 5.018333
14 5.102066 5.222584 4.907678 4.966319
15 4.983114 4.286539 4.471304 5.009501
16 6.535382 4.201185 4.994638 5.006412
17 2.647908 4.998439 4.741445 5.006141
18 6.798399 4.785914 6.068729 5.003509
19 5.574891 4.538196 4.722987 5.017613
20 4.149567 5.098584 4.476465 4.990768
Creating histograms for all columns of data frame df_y −
hist.data.frame(df_y)
How to create a plot of Poisson distribution in R?

The Poisson distribution is a discrete distribution that has only one parameter named as lambda and it is the rate parameter. The rate parameter is defined as the number of events that occur in a fixed time interval. To create a plot of Poisson distribution in R, we can use the plot function with the density of the Poisson distribution using dpois function.
 Live Demo
plot(dpois(x=1:50,lambda=3))
 Live Demo
plot(dpois(x=1:50,lambda=3),type="l")
 Live Demo
plot(dpois(x=1:50,lambda=3),type="b")
C library function - fabs()

The C library function double fabs(double x) returns the absolute value of x.
Following is the declaration for fabs() function.
double fabs(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns the absolute value of x.
The following example shows the usage of fabs() function.
#include <stdio.h>
#include <math.h>

int main () {
   int a, b;
   a = 1234;
   b = -344;
  
   printf("The absolute value of %d is %lf\n", a, fabs(a));
   printf("The absolute value of %d is %lf\n", b, fabs(b));
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
The absolute value of 1234 is 1234.000000
The absolute value of -344 is 344.000000


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
PHP: How do I display the contents of a textfile on my page?

The file_get_contents function takes the name of the php file and reads the contents of the text file and displays it on the console. get the contents, and echo it out.
<?php
   echo file_get_contents( "filename.php" );
?>
The contents of filename.php would be the output.
In the above code, the function ‘file_get_contents’ is called by passing the php file name. The output will be the contents present in the php file.
What is CDATA in HTML?

The CDATA Section interface is used within XML for including extended portions of text. This text is unescaped text, like < and & symbols. These symbols do not want to escape.
It is used like this:
<![CDATA[ ... ]]>
Here’s an example:
<p>The following is CDATA <![CDATA[ < > & ]]> with symbols that do not need escaping.
</p>
To avoid parsing <> &, it gets added in <script>...</script>. It is not needed in HTML. Let’s see how CDATA gets added in <script> tags:
<script type="text/javascript">
   //<![CDATA[
   document.write(">");
   //]]>
</script>
Note: CDATA is now deprecated. Do not use.
Java - Modifier Types

Modifiers are keywords that you add to those definitions to change their meanings. Java language has a wide variety of modifiers, including the following −
 Java Access Modifiers
 Java Access Modifiers
Non Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement, as in the following example.
public class className {
   // ...
}

private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;

public static void main(String[] arguments) {
   // body of method
}
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Java provides a number of non-access modifiers to achieve many other functionality.
The static modifier for creating class methods and variables.
The static modifier for creating class methods and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
The synchronized and volatile modifiers, which are used for threads.
In the next section, we will be discussing about Basic Operators used in Java Language. The chapter will give you an overview of how these operators can be used during application development.

    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
MID() function in MySQL - GeeksforGeeks

09 Dec, 2020
MID() :
This function in MySQL is used to extract a substring from a given input string. If the starting position is a positive number, then the substring of the given length will be extracted from the starting index. If negative, then the substring of the given length will be extracted from the ending index.
Syntax :
MID(str,pos,len)
Parameters :
This function accepts 3 parameters.
str –A string from which we want to extract a substring.
pos –It indicates the position in the input string from where extraction will be started.
len – It indicates the length of the string which we want to extract.
Returns : It extracts a substring from a given input string. 
Example-1 : 
Extracting a string of length 5 from the string ‘geeksforgeeks’ with the help of MID Function starting from pos 1.
SELECT MID('geeksforgeeks', 1, 5) As SUBSTRING;
Output :
Example-2 : 
Extracting a string of length 3 from the string ‘Learning MySQL is fun’ with the help of MID Function starting from pos -3.
SELECT MID('Learning MySQL is fun', -3, 3) As SUBSTRING;
Output :
Example-3 :
MID Function can also be used on column data. 
Creating a Student table –
CREATE TABLE StudentDetails
(
Student_id INT AUTO_INCREMENT,  
Student_name VARCHAR(100) NOT NULL,
Roll INT NOT NULL,
Department VARCHAR(10) NOT NULL,
PRIMARY KEY(Student_id )
);
Inserting values into the table –
INSERT INTO StudentDetails
(Student_name ,Roll, Department )
VALUES
('Anik Biswas ',10100,'CSE'),
('Bina Mallick', 11000,'ECE' ),
('Niket Sharma', 12000,'IT' ),
('Sayan Samanta',13000, 'ME'  ),
('Riya Shah ', 14000,'EE' ),  
('Bipin Kohli', 15000,'CE' );
The table will look as follows.
SELECT  * from StudentDetails;
Now, we are going to use MID Function on the Student_name column to find the first name of every student.
SELECT Student_id , MID(Student_name,1,5 ) AS First_Name,
Student_name ,Roll,Department FROM StudentDetails;
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
How to implement coin change problem using bottom-up approach using C#?

CoinChangeBottomUpApproach takes 3 parameters as input n is the amount, coins array contains the total number of coins, t contains total number of coins. Declare a dynamic array which stores the previously calculated values. loop through the array and calculate the minimum coins required to calculate the amount. If the calculation is already done the take the value from the dynamic array.
Time complexity − O(N)
Space complexity − O(N)
public class DynamicProgramming{
   public int CoinChangeBottomUpApproach(int n,int[] coins,int t){
      int[] dp = new int[100];
      for (int i = 1; i < n; i++){
         dp[i] = int.MaxValue;
         for (int j = 0; j < t; j++){
            if (i - coins[j] >= 0){
               int subProb = dp[i - coins[j]];
               dp[i] = Math.Min(dp[i], subProb + 1);
            }
         }
      }
      return dp[n]+1;
   }
}

static void Main(string[] args){
   DynamicProgramming dp = new DynamicProgramming();
   int[] coins = { 1, 7, 10 };
   int ss = dp.CoinChangeBottomUpApproach(15, coins, coins.Count());
   Console.WriteLine(ss);
}
3
CN Data Link Layer - GeeksforGeeks

13 Sep, 2021
Data should be transmitted at the rate of 500 Mbps.
Transmission Time >= 2*Propagation Time
=> 10000/(500*1000000) <= 2*length/200000
=> length = 2km (max)
so, answer will be: (B) 2km 
Data should be transmitted at the rate of 500 Mbps.
Transmission Time >= 2*Propagation Time
=> 10000/(500*1000000) <= 2*length/200000
=> length = 2km (max)
so, answer will be: (B) 2km 
P(X) = Probability that station X attempts to transmit = P
P (-X) = Probability that station X does not transmit = 1-P
Required is: Probability that only one station transmits = y
Y = (A1, -A2, -A3...... -An) + (-A1, A2, A3......-An) + (-A1, -A2, A3.....-An) + ........... + (-A1, -A2, -A3......An)
= (p*(1-p)*(1-p)*...... (1-p) + (1-p)*p*(1-p)........(1-p) + .............
= p*(1-p)^(n-1) + p*(1-p)^n-1 + .................................................... + p*(1-p)^(n-1)
= n*p*(1-p)^(n-1)
This solution is contributed Anil Saikrishna Devarasetty .
In a token ring network the transmission speed is 10^7 bps and the propagation speed is 200 meters/micro second. The 1-bit delay in this network is equivalent to: 
500 metres of cable. 
200 metres of cable. 
20 metres of cable. 
50 metres of cable. 
See question 4 of http://www.geeksforgeeks.org/computer-networks-set-9/ 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
Implementation of Bit Stuffing and Bit Destuffing
Tailwind CSS vs Bootstrap
How to pass property from a parent component props to a child component ?
BigInt (BIG INTEGERS) in C++ with Example
Python input() Function
How to Install Flutter on Visual Studio Code?
Python OpenCV - imdecode() Function
What is Zombie Process in Linux?

A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is known as reaping the zombie process.
A diagram that demonstrates the creation and termination of a zombie process is given as follows −
Some of the salient points related to zombie processes are as follows −
All the memory and resources allocated to a process are deallocated when the process terminates using the exit() system call. But the process’s entry in the process table is still available. This process is now a zombie process.
The exit status of the zombie process zombie process can be read by the parent process using the wait() system call. After that, the zombie process is removed from the system. Then the process ID and the process table entry of the zombie process can be reused.
If the parent process does not use the wait() system call, the zombie process is left in the process table. This creates a resource leak.
If the parent process is not running anymore, then the presence of a zombie process indicates an operating system bug. This may not be a serious problem if there are a few zombie processes but under heavier loads, this can create issues for the system such as running out of process table entries.
The zombie processes can be removed from the system by sending the SIGCHLD signal to the parent, using the kill command. If the zombie process is still not eliminated from the process table by the parent process, then the parent process is terminated if that is acceptable.
Zombie processes don't use any system resources but they do retain their process ID. If there are a lot of zombie processes, then all the available process ID’s are monopolized by them. This prevents other processes from running as there are no process ID’s available.
The presence of zombie processes also indicates an operating system bug if their parent processes are not running anymore. This is not a serious problem if there are a few zombie processes but under heavier loads, this can create issues for the system.
Zombie processes can be killed by sending the SIGCHLD signal to the parent, using the kill command. This signal informs the parent process to clean up the zombie process using the wait() system call. This signal is sent with the kill command. It is demonstrated as follows −
kill -s SIGCHLD pid
In the above command, the pid is the process ID of the parent process.
Display the maximum of three integer values in Java

The following is an example displaying the maximum of three integer values.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val1 = 10;
      int val2 = 20;
      int val3 = 30;
      System.out.println("Number 1 = "+val1);
      System.out.println("Number 2 = "+val2);
      System.out.println("Number 3 = "+val3);
      if (val2 > val1) {
         val1 = val2;
      }
      if (val3 > val1) {
         val1 = val3;
      }
      System.out.println("The greatest of three numbers: "+val1);
   }
}
Number 1 = 10
Number 2 = 20
Number 3 = 30
The greatest of three numbers: 30
In the above program, we have taken three integer variables, which will be compared.
int val1 = 10;
int val2 = 20;
int val3 = 30;
Now condition is used to check which of the integer value is the greatest.
if (val2 > val1) {
   val1 = val2;
}
if (val3 > val1) {
   val1 = val3;
}
The above returns the greatest value.
How to convert an array to CSV file in PHP ? - GeeksforGeeks

01 Aug, 2021
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.
Syntax :
fputcsv( file, fields, separator, enclosure, escape )
Example 1:
<?php  // Create an array of elements$list = array(    ['Name', 'age', 'Gender'],    ['Bob', 20, 'Male'],    ['John', 25, 'Male'],    ['Jessica', 30, 'Female']);   // Open a file in write mode ('w')$fp = fopen('persons.csv', 'w');  // Loop through file pointer and a lineforeach ($list as $fields) {    fputcsv($fp, $fields);}  fclose($fp);?>
After running the above PHP program you can find a file named persons.csv in the same directory where the program file is located. When you open this file with a CSV file reader application like Microsoft Excel you’ll see the contents as shown in the below image.
Output in Microsoft Excel
Example 2: Suppose you want to put all the form inputs in a CSV file then first create a form to take input from the user and store it into an array. Then convert the array element into csv file.
index.html
gfg.php
<!DOCTYPE html> <html>      <head>    <title>        How to Convert Array to        CSV file in PHP ?    </title></head>  <body>               <!-- form tag to create form -->     <form action = "gfg.php" method = "post">                       Name <input type = "text" name = "name" />                           <br><br>                       Email <input type = "text" name = "email" />                           <br><br>                      Phone <input type = "text" name = "phone" />                       <input type = "submit" name = "submit" value = "Submit">     </form> </body>  </html>
<?php   $data = array(    $_POST['name'],    $_POST['email'],    $_POST['phone']);  // Open file in append mode$fp = fopen('databse.csv', 'a');  // Append input data to the file  fputcsv($fp, $data);  // close the filefclose($fp);?>
Input form:
Input data display in excel as output:
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
CSV
PHP-Misc
Picked
PHP
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Solidity - Withdrawal Pattern

Withdrawal pattern ensures that direct transfer call is not made which poses a security threat. Following contract is showing the insecure use of transfer call to send ether.
pragma solidity ^0.5.0;

contract Test {
   address payable public richest;
   uint public mostSent;

   constructor() public payable {
      richest = msg.sender;
      mostSent = msg.value;
   }
   function becomeRichest() public payable returns (bool) {
      if (msg.value > mostSent) {
         // Insecure practice
         richest.transfer(msg.value);
         richest = msg.sender;
         mostSent = msg.value;
         return true;
      } else {
         return false;
      }
   }
}
Above contract can be rendered in unusable state by causing the richest to be a contract of failing fallback function. When fallback function fails, becomeRichest() function also fails and contract will stuck forever. To mitigate this problem, we can use Withdrawal Pattern.
In withdrawal pattern, we'll reset the pending amount before each transfer. It will ensure that only caller contract fails.
pragma solidity ^0.5.0;

contract Test {
   address public richest;
   uint public mostSent;

   mapping (address => uint) pendingWithdrawals;

   constructor() public payable {
      richest = msg.sender;
      mostSent = msg.value;
   }
   function becomeRichest() public payable returns (bool) {
      if (msg.value > mostSent) {
         pendingWithdrawals[richest] += msg.value;
         richest = msg.sender;
         mostSent = msg.value;
         return true;
      } else {
         return false;
      }
   }
   function withdraw() public {
      uint amount = pendingWithdrawals[msg.sender];
      pendingWithdrawals[msg.sender] = 0;
      msg.sender.transfer(amount);
   }
}

    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
How to send keyboard shortcut ALT SHIFT z (hotkey) with Selenium2?

We can send keyboard shortcut ALT SHIFT z(hotkey) with Selenium webdriver. This can be done with the help of the Keys class. We shall use the Keys.chord method and pass Keys.ALT, Keys.SHIFT and z as parameters to that method.
The entire value obtained from the Keys.chord method is obtained as a String. That is then sent as a parameter to the sendKeys method.
String s = Keys.chord(Keys.ALT, Keys.SHIFT,"z");
driver.findElement(By.tagName("html")).sendKeys(s);
Code Implementation with Keys.chord method.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class HtKeys{
   public static void main(String[] args) {
         System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // sending ALT,SHIFT and z by the Keys.Chord
      String s = Keys.chord(Keys.ALT, Keys.SHIFT,"z");
      driver.findElement(By.tagName("html")).sendKeys(s);
      driver.quit();
   }
}
This can also be down with the help of the Actions class. We have to create an object of the Actions class and apply keyUp and keyDown methods on the object and pass Keys.ALT, Keys.SHIFT and z to these methods.
Actions a = new Actions(driver);
a.keyDown(Keys.ALT).keyDown(Keys.SHIFT).
sendKeys("z").keyUp(Keys.ALT).keyUp(Keys.SHIFT).build().perform();
Code Implementation with Actions.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class HotKeyAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Actions class with keyUp and keyDown methods
      Actions a = new Actions(driver);
      a.keyDown(Keys.ALT).keyDown(Keys.SHIFT).
      sendKeys("z").keyUp(Keys.ALT).keyUp(Keys.SHIFT).build().perform();
      driver.quit();
   }
}
Structures in C

Structure is a user defined datatype. It is used to combine the different types of data into single type. It can have multiple members and structure variables. The keyword “struct” is used to define structures in C language. Structure members can be accessed by using dot(.) operator.
Here is the syntax of structures in C language,
struct structure_name {
   member definition;
} structure_variables;
Here,
structure_name − Any name given to the structure.
member definition − Set of member variables.
structure_variable − This is the object of structure.
Here is an example of structures in C language,
 Live Demo
#include <stdio.h>
#include <string.h>
struct Data {
   int i;
   long int f;
}data, data1;
int main( ) {
   data.i = 28;
   printf("The value of i : %d\n", (data.i));
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
   return 0;
}
The value of i : 28
Memory size occupied by data : 1616
In the above program, a structure Data is created with the objects of structure. The variable declared in structure is called in main() by using the object of structures.
struct Data {
   int i;
   long int f;
}data, data1;
int main( ) {
   data.i = 28;
   printf("The value of i : %d\n", (data.i));
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
}