code-rag-bench/online-tutorials huggingface dataset:
Expanding binomial expression using JavaScript

We are required to write a JavaScript function that takes in an expression in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any single character variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable.
Our function should return the expanded form as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one-character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order
Following is the code −
 Live Demo
const str = '(8a+6)^4';
const trim = value => value === 1 ? '' : value === -1 ? '-' : value
const factorial = (value, total = 1) =>
value <= 1 ? total : factorial(value - 1, total * value)
const find = (str = '') => {
   let [op1, coefficient, variable, op2, constant, power] = str
   .match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/)
   .slice(1)
   power = +power
   if (!power) {
      return '1'
   }
   if (power === 1) {
      return str.match(/\((.*)\)/)[1]
   }
   coefficient =
   op1 === '-'
   ? coefficient
   ? -coefficient
   : -1
   : coefficient
   ? +coefficient
   : 1
   constant = op2 === '-' ? -constant : +constant
   const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i))
   let result = ''
   for (let i = 0, p = power; i <= power; ++i, p = power - i) {
      let judge =
      factorials[power] / (factorials[i] * factorials[p]) *
      (coefficient * p * constant * i)
      if (!judge) {
         continue
      }
      result += p
      ? trim(judge) + variable + (p === 1 ? '' : `^${p}`)
      : judge
      result += '+'
   }
   return result.replace(/\+\-/g, '-').replace(/\+$/, '')
};
console.log(find(str));
576a^3+1152a^2+576a
Go - Array of pointers

Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers −
package main

import "fmt"
 
const MAX int = 3
 
func main() {
   a := []int{10,100,200}
   var i int

   for i = 0; i < MAX; i++ {
      fmt.Printf("Value of a[%d] = %d\n", i, a[i] )
   }
}
When the above code is compiled and executed, it produces the following result −
Value of a[0] = 10
Value of a[1] = 100
Value of a2] = 200

There may be a situation when we want to maintain an array, which can store pointers to an int or string or any other data type available. The following statement declares an array of pointers to an integer −
var ptr [MAX]*int;

This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. The following example makes use of three integers, which will be stored in an array of pointers as follows −
package main

import "fmt"
 
const MAX int = 3
 
func main() {
   a := []int{10,100,200}
   var i int
   var ptr [MAX]*int;

   for  i = 0; i < MAX; i++ {
      ptr[i] = &a[i] /* assign the address of integer. */
   }
   for  i = 0; i < MAX; i++ {
      fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] )
   }
}
When the above code is compiled and executed, it produces the following result −
Value of a[0] = 10
Value of a[1] = 100
Value of a[2] = 200


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
C++ program to read file word by word?

In this section we will see how we can read file content word by word using C++. The task is very simple. we have to use the file input stream to read file contents. The file stream will open the file by using file name, then using FileStream, load each word and store it into a variable called word. Then print each word one by one.
begin
   file = open file using filename
   while file has new word, do
      print the word into the console
   done
end
This is a test file. There are many words. The program will read this file word by word
#include<iostream>
#include<fstream>
using namespace std;
void read_word_by_word(string filename) {
   fstream file;
   string word;
   file.open(filename.c_str());
   while(file > word) { //take word and print
      cout << word << endl;
   }
   file.close();
}
main() {
   string name;
   cout << "Enter filename: ";
   cin >> name;
   read_word_by_word(name);
}
Enter filename: test_file.txt
This
is
a
test
file.
There
are
many
words.
The
program
will
read
this
file
word
by
word
Chef - Data Bags

Chef data bags can be defined as an arbitrary collection of data which one can use with cookbooks. Using data bags is very helpful when one does not wish to hardcode attributes in recipes nor to store attributes in cookbooks.
In the following setup, we are trying to communicate to http endpoint URL. For this, we need to create a data bag, which will hold the endpoint URL detail and use it in our recipe.
Step 1 − Create a directory for our data bag.
mma@laptop:~/chef-repo $ mkdir data_bags/hooks

Step 2 − Create a data bag item for request bin. One needs to make sure one is using a defined requestBin URL.
vipi@laptop:~/chef-repo $ subl data_bags/hooks/request_bin.json { 
   "id": "request_bin", 
   "url": "http://requestb.in/1abd0kf1" 
}
Step 3 − Create a data bag on the Chef server
vipin@laptop:~/chef-repo $ knife data bag create hooks 
Created data_bag[hooks] 

Step 4 − Upload the data bag to the Chef server.
vipin@laptop:~/chef-repo $ knife data bag from file hooks requestbin.json 
Updated data_bag_item[hooks::RequestBin]

Step 5 − Update the default recipe of the cookbook to receive the required cookbook from a data bag.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb 
hook = data_bag_item('hooks', 'request_bin') 
http_request 'callback' do 
   url hook['url'] 
end 
Step 6 − Upload the modified cookbook to the Chef server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook 
Uploading my_cookbook [0.1.0] 

Step 7 − Run the Chef client on the node to check if the http request bin gets executed.
user@server:~$ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-02-22T20:37:35+00:00] INFO: http_request[callback] 
GET to http://requestb.in/1abd0kf1 successful 
...TRUNCATED OUTPUT...

Data bag is a named collection of structure data entries. One needs to define data entry and call the data bag item in JSON file. One can also search for data bag item from within the recipes to use the data stored in the data bags.
We created a data bag called hooks. A data bag is a directory within Chef repository. We used knife to create it on the server.
 Print
 Add Notes
 Bookmark this page
How to get timer ticks at a given time in Python?

To get the timer ticks at a given time, use the clock. The python docs state that this function should be used for benchmarking purposes. 
import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)
This will give the output −
Time elapsed:  0.0009403145040156798
Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note that clock returns different things on different platforms. On Unix, it returns the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
Tryit Editor v3.7

CSS Grid Item
Tryit: Sort grid items
C# program to convert floating to binary

Let’s say the following is our float −
float n = 50.5f;
Take an empty string to display the binary value and loop until the value of our float variable is greater than 1 −
string a = "";

while (n >= 1) {
   a = (n % 2) + a;
   n = n / 2;
}
Let us see the complete example −
 Live Demo
using System;
using System.IO;
using System.CodeDom.Compiler;

namespace Program {
   class Demo {
      static void Main(string[] args) {

         // float to binary
         Console.WriteLine("float to binary = ");
         float n = 50.5f;
         string a = "";

         while (n >= 1) {
            a = (n % 2) + a;
            n = n / 2;
         }
         Console.Write(a);
      }
   }
}
float to binary =
1.5781251.156250.31250.6251.250.5
How to get row index or column index based on their names in R?

We might prefer to use row index or column index during the analysis instead of using their numbers, therefore, we can get them with the help of grep function. While dealing with a large data set it becomes helpful because large data sets have large number of rows and columns so it is easier to recall them with their indexes instead of numbers. Specifically, column indexes are needed, on the other hand, rows are required in special cases only such as analysing a particular case.
Consider the below data frame −
> set.seed(1)
> x1<-rnorm(50,0.5)
> x2<-rnorm(50,0.8)
> x3<-rpois(50,2)
> x4<-rpois(50,5)
> x5<-runif(50,5,10)
> df<-data.frame(x1,x2,x3,x4,x5)
> head(df,20)
x1 x2 x3 x4 x5
1 -0.1264538  1.19810588 1 6 8.368561
2  0.6836433  0.18797361 1 9 5.474289
3 -0.3356286  1.14111969 2 5 7.462981
4  2.0952808 -0.32936310 1 5 7.307759
5  0.8295078  2.23302370 1 5 6.876083
6 -0.3204684  2.78039990 2 2 9.955496
7  0.9874291  0.43277852 2 3 5.881754
8  1.2383247 -0.24413463 0 5 9.067176
9  1.0757814  1.36971963 1 4 5.342233
10 0.1946116  0.66494540 3 9 7.002249
11 2.0117812  3.20161776 5 5 5.705722
12 0.8898432  0.76076000 0 4 5.966549
13 -0.1212406 1.48973936 3 4 9.206759
14 -1.7146999 0.82800216 5 7 8.599570
15 1.6249309  0.05672679 3 6 6.336060
16 0.4550664  0.98879230 1 3 7.475008
17 0.4838097 -1.00495863 2 2 5.415569
18 1.4438362  2.26555486 5 6 6.769421
19 1.3212212  0.95325334 5 6 9.846044
20 1.0939013  2.97261167 1 3 8.123571
Finding the index of columns based on their names −
> grep("x3", colnames(df))
[1] 3
> grep("x5", colnames(df))
[1] 5
> grep("x1", colnames(df))
[1] 1
Let’s change the row names because they are numbered from 1 to 50, so row index will be same as their name. We will change them to 50 to 1 as shown below −
> rownames(df)<-50:1
> head(df,20)
       x1          x2      x3  x4    x5
50 -0.1264538  1.19810588   1   6  8.368561
49  0.6836433  0.18797361   1   9  5.474289
48 -0.3356286  1.14111969   2   5  7.462981
47  2.0952808 -0.32936310   1   5  7.307759
46  0.8295078  2.23302370   1   5  6.876083
45 -0.3204684  2.78039990   2   2  9.955496
44 0.9874291   0.43277852   2   3  5.881754
43 1.2383247  -0.24413463   0   5  9.067176
42 1.0757814   1.36971963   1   4  5.342233
41 0.1946116   0.66494540   3   9  7.002249
40 2.0117812   3.20161776   5   5  5.705722
39 0.8898432   0.76076000   0   4  5.966549
38 -0.1212406  1.48973936   3   4  9.206759
37 -1.7146999  0.82800216   5   7  8.599570
36 1.6249309   0.05672679   3   6  6.336060
35 0.4550664   0.98879230   1   3  7.475008
34 0.4838097  -1.00495863   2   2  5.415569
33 1.4438362   2.26555486   5   6  6.769421
32 1.3212212   0.95325334   5   6  9.846044
31 1.0939013   2.97261167   1   3  8.123571
Now let’s find the row names that contains number 5 −
> grep(5, rownames(df))
[1] 1 6 16 26 36 46
Finding the row name of the tenth row −
> grep(10, rownames(df))
[1] 41
Finding the row names that contains number 4 −
> grep(4, rownames(df))
[1] 2 3 4 5 6 7 8 9 10 11 17 27 37 47
Logstash - Parsing the Logs

Logstash receives the logs using input plugins and then uses the filter plugins to parse and transform the data. The parsing and transformation of logs are performed according to the systems present in the output destination. Logstash parses the logging data and forwards only the required fields. Later, these fields are transformed into the destination system’s compatible and understandable form.
Parsing of the logs is performed my using the GROK (Graphical Representation of Knowledge) patterns and you can find them in Github −
https://github.com/elastic/logstash/tree/v1.4.2/patterns.
Logstash matches the data of logs with a specified GROK Pattern or a pattern sequence for parsing the logs like "%{COMBINEDAPACHELOG}", which is commonly used for apache logs.
The parsed data is more structured and easy to search and for performing queries. Logstash searches for the specified GROK patterns in the input logs and extracts the matching lines from the logs. You can use GROK debugger to test your GROK patterns.
The syntax for a GROK pattern is %{SYNTAX:SEMANTIC}. Logstash GROK filter is written in the following form −
%{PATTERN:FieldName}
Here, PATTERN represents the GROK pattern and the fieldname is the name of the field, which represents the parsed data in the output.
For example, using online GROK debugger https://grokdebug.herokuapp.com/
A sample error line in a log −
[Wed Dec 07 21:54:54.048805 2016] [:error] [pid 1234:tid 3456829102]
   [client 192.168.1.1:25007] JSP Notice:  Undefined index: abc in
   /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11

This GROK pattern sequence matches to the log event, which comprises of a timestamp followed by Log Level, Process Id, Transaction Id and an Error Message.
\[(%{DAY:day} %{MONTH:month} %{MONTHDAY} %{TIME} %{YEAR})\] \[.*:%{LOGLEVEL:loglevel}\]
   \[pid %{NUMBER:pid}:tid %{NUMBER:tid}\] \[client %{IP:clientip}:.*\]
   %{GREEDYDATA:errormsg}

The output is in JSON format.
{
   "day": [
      "Wed"
   ],
   "month": [
      "Dec"
   ],
   "loglevel": [
      "error"
   ],
   "pid": [
      "1234"
   ],
   "tid": [
      "3456829102"
   ],
   "clientip": [
      "192.168.1.1"
   ],
   "errormsg": [
      "JSP Notice:  Undefined index: abc in
      /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11"
   ]
}

 Print
 Add Notes
 Bookmark this page
How to flatten a list using LINQ C#?

Flattening a list means converting a List<List<T>> to List<T>. For example, let us
consider a List<List<int>> which needs to be converted to List<int>.
The SelectMany in LINQ is used to project each element of a sequence to an
IEnumerable<T> and then flatten the resulting sequences into one sequence. That
means the SelectMany operator combines the records from a sequence of results and
then converts it into one result.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         List<List<int>> listOfNumLists = new List<List<int>>{
            new List<int>{
               1, 2
            },
            new List<int>{
               3, 4
            }
         };
         var numList = listOfNumLists.SelectMany(i => i);
         Console.WriteLine("Numbers in the list:");
         foreach(var num in numList){
            Console.WriteLine(num);
         }
         Console.ReadLine();
      }
   }
}
Numbers in the list:
1
2
3
4
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         List<List<int>> listOfNumLists = new List<List<int>>{
            new List<int>{
               1, 2
            },
            new List<int>{
               3, 4
            }
         };
         var numList = from listOfNumList in listOfNumLists
         from value in listOfNumList
         select value;
         Console.WriteLine("Numbers in the list:");
         foreach(var num in numList){
            Console.WriteLine(num);
         }
         Console.ReadLine();
      }
   }
}
Numbers in the list:
1
2
3
4
MathF.Cbrt() Method in C# with Examples - GeeksforGeeks

28 Oct, 2019
MathF.Cbrt(Single) Method is used to return the cube root of a floating point value.
Syntax: public static float Cbrt (float x);Here, it takes a standard floating point number.
Return Value: This method returns the cube root of the given value.
Example 1:
// C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System;  class GFG {      // Main Method    public static void Main()    {          // Declaring and initializing value        float value = 27f;          // getting cube root of value        // using Cbrt() method        float round = MathF.Cbrt(value);          // Display the value        Console.WriteLine("Cube root of {0} is {1}",                                     value, round);    }}
Cube root of 27 is 3

Example 2:
// C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // calling get() method        Console.WriteLine("Cube root of given "+                    "numbers are respectively");        get(8f);        get(27.8967f);        get(64f);        get(125.2534f);    }      // defining get() method    public static void get(float value)    {          // getting cube root of given value        // using Cbrt() method        float round = MathF.Cbrt(value);          // Display the value        Console.WriteLine("Cube root of {0} is {1}",                                    value, round);    }}
Cube root of given numbers are respectively
Cube root of 8 is 2
Cube root of 27.8967 is 3.03285
Cube root of 64 is 4
Cube root of 125.2534 is 5.003376

Akanksha_Rai
CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Linked List Implementation in C#
MongoDB query to fetch date records (ISODate format) in a range

Let us create a collection with documents −
> db.demo178.insertOne({"DueDate":new ISODate("2019-01-10T06:18:20.474Z")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e397bd89e4f06af551997f5")
}
> db.demo178.insertOne({"DueDate":new ISODate("2020-11-10T18:05:11.474Z")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e397bf39e4f06af551997f6")
}
> db.demo178.insertOne({"DueDate":new ISODate("2020-03-15T07:05:10.474Z")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e397c039e4f06af551997f7")
}
> db.demo178.insertOne({"DueDate":new ISODate("2020-06-11T16:05:10.474Z")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e397c0f9e4f06af551997f8")
}
Display all documents from a collection with the help of find() method −
> db.demo178.find();
This will produce the following output −
{ "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") }
{ "_id" : ObjectId("5e397bf39e4f06af551997f6"), "DueDate" : ISODate("2020-11-10T18:05:11.474Z") }
{ "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
{ "_id" : ObjectId("5e397c0f9e4f06af551997f8"), "DueDate" : ISODate("2020-06-11T16:05:10.474Z") }
Following is the query to fetch date records in a range −
> db.demo178.aggregate([
...{
...   "$redact": {
...      "$cond": {
...         "if": {
...            "$and": [
...               { "$gt": [ {"$hour": "$DueDate"}, 5] },
...               { "$lt": [ {"$hour": "$DueDate"}, 9] }
...            ]
...         },
...         "then": "$$KEEP",
...         "else": "$$PRUNE"
...         }
...      }
...   }
...])
This will produce the following output −
{ "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") }
{ "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
Arrow functions in Javascript

According to MDN, An arrow function expression is a syntactically compact
alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill-suited as methods, and they cannot be used as constructors.
There are 3 subtle differences in regular functions and arrow functions
in JavaScript.
No own this bindingArrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope.
No own this binding
Arrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope.
this.a = 100;
let arrowFunc = () => {this.a = 150};
function regFunc() {
   this.a = 200;
}
console.log(this.a)
arrowFunc()
console.log(this.a)
regFunc()
console.log(this.a)
This will give the output −
100
150
150
See that the arrow function changed this object outside its scope. The regular function just made the changes within its own.
Arrow functions do not have a arguments array In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope.
Arrow functions are callable but not constructible If a function is constructible, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).
Functions created through function declarations / expressions are both
constructible and callable.
Arrow functions (and methods) are only callable. class constructors are only constructible.
If you are trying to call a non-callable function or to construct a nonconstructive function, you will get a runtime error.
let arrowFunc = () => {}
new arrowFunc()
This code gives the error −
arrowFunc is not a constructor
How to create a plot for the response variable grouped by two columns using ggplot2 in R?

When two categorical variables make an impact on the response variable together then it is necessary to visualize their effect graphically because this graph helps us to understand the variation in the effect. Therefore, we can create a plot for the response variable that changes with one or both of the categorical independent variables. This can be done with the help of using interaction function in ggplot2.
Consider the below data frame −
> set.seed(1)
> y<-rpois(30,2)
> Group1<-rep(c(letters[1:5]),times=6)
> Group2<-rep(c("Ph1","Ph2","Ph3"),each=10)
> df<-data.frame(y,Group1,Group2)
> head(df,20)
y Group1 Group2
1    1 a Ph1
2    1 b Ph1
3    2 c Ph1
4    4 d Ph1
5    1 e Ph1
6    4 a Ph1
7    4 b Ph1
8    2 c Ph1
9    2 d Ph1
10   0 e Ph1
11   1 a Ph2
12   1 b Ph2
13   3 c Ph2
14   1 d Ph2
15   3 e Ph2
16   2 a Ph2
17   3 b Ph2
18   6 c Ph2
19   1 d Ph2
20   3 e Ph2
Loading ggplot2 package −
> library(ggplot2)
Creating the plot with interaction
> qplot(Group1, y, data=df, group=Group2, color=Group2, geom='line')+
+ geom_smooth(aes(group=interaction(Group1, Group2)))
`geom_smooth()` using method = 'loess' and formula 'y ~ x'
Here, we can see that all the lines are crossing each other therefore there exists an interaction effect of independent variables, which means at least one level combination of both the independent variables (Group1 and Group2) has different mean that the others.
C Program for Merge Sort - GeeksforGeeks

13 Feb, 2018
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
/* C program for Merge Sort */#include<stdlib.h>#include<stdio.h>  // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){    int i, j, k;    int n1 = m - l + 1;    int n2 =  r - m;      /* create temp arrays */    int L[n1], R[n2];      /* Copy data to temp arrays L[] and R[] */    for (i = 0; i < n1; i++)        L[i] = arr[l + i];    for (j = 0; j < n2; j++)        R[j] = arr[m + 1+ j];      /* Merge the temp arrays back into arr[l..r]*/    i = 0; // Initial index of first subarray    j = 0; // Initial index of second subarray    k = l; // Initial index of merged subarray    while (i < n1 && j < n2)    {        if (L[i] <= R[j])        {            arr[k] = L[i];            i++;        }        else        {            arr[k] = R[j];            j++;        }        k++;    }      /* Copy the remaining elements of L[], if there       are any */    while (i < n1)    {        arr[k] = L[i];        i++;        k++;    }      /* Copy the remaining elements of R[], if there       are any */    while (j < n2)    {        arr[k] = R[j];        j++;        k++;    }}  /* l is for left index and r is right index of the   sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){    if (l < r)    {        // Same as (l+r)/2, but avoids overflow for        // large l and h        int m = l+(r-l)/2;          // Sort first and second halves        mergeSort(arr, l, m);        mergeSort(arr, m+1, r);          merge(arr, l, m, r);    }}  /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){    int i;    for (i=0; i < size; i++)        printf("%d ", A[i]);    printf("\n");}  /* Driver program to test above functions */int main(){    int arr[] = {12, 11, 13, 5, 6, 7};    int arr_size = sizeof(arr)/sizeof(arr[0]);      printf("Given array is \n");    printArray(arr, arr_size);      mergeSort(arr, 0, arr_size - 1);      printf("\nSorted array is \n");    printArray(arr, arr_size);    return 0;}
Please refer complete article on Merge Sort for more details!
Merge Sort
C Programs
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
How to Append a Character to a String in C
Producer Consumer Problem in C
Program to calculate First and Follow sets of given grammar
time() function in C
Program to find Prime Numbers Between given Interval
C Program to Swap two Numbers
C program to find the length of a string
Flex (Fast Lexical Analyzer Generator )
Set, Clear and Toggle a given bit of a number in C
Python – Assigning Subsequent Rows to Matrix first row elements

30 Dec, 2020
Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix.
Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]]Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]}Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th
Input : test_list = [[5, 8], [2, 0], [5, 4]]Output : {5: [2, 0], 8: [5, 4]}Explanation : 5 paired with 2nd row, 8 with 3rd.
Method #1 : Using dictionary comprehension
This is one of the ways in which this task can be performed. In this, we iterate for rows and corresponding columns using loop and assign value list accordingly in one-liner way using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using dictionary comprehension  # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]  # printing original listprint("The original list : " + str(test_list))  # pairing each 1st col with next rows in Matrixres = {test_list[0][ele] :  test_list[ele + 1] for ele in range(len(test_list) - 1)}  # printing result print("The Assigned Matrix : " + str(res))
The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}

Method #2 : Using zip() + list slicing + dict()
This is yet another way in which this task can be performed. In this, we slice elements to be first row and subsequent rows using list slicing and zip() performs the task of required grouping. Returned 
Python3
# Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using zip() + list slicing + dict()  # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]  # printing original listprint("The original list : " + str(test_list))  # dict() to convert back to dict type # slicing and pairing using zip() and list slicingres = dict(zip(test_list[0], test_list[1:]))  # printing result print("The Assigned Matrix : " + str(res))
The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}

Python list-programs
Python matrix-program
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Difference between Pandas VS NumPy

09 Jun, 2022
Pandas is an open-source, BSD-licensed library written in Python Language. Pandas provide high performance, fast, easy-to-use data structures, and data analysis tools for manipulating numeric data and time series. Pandas is built on the numpy library and written in languages like Python, Cython, and C. In pandas, we can import data from various file formats like JSON, SQL, Microsoft Excel, etc.
Example:
Python3
# Importing pandas libraryimport pandas as pd # Creating and initializing a nested listage = [['Aman', 95.5, "Male"], ['Sunny', 65.7, "Female"],       ['Monty', 85.1, "Male"], ['toni', 75.4, "Male"]] # Creating a pandas dataframedf = pd.DataFrame(age, columns=['Name', 'Marks', 'Gender']) # Printing dataframedf
Output:
Numpy: It is the fundamental library of python, used to perform scientific computing. It provides high-performance multidimensional arrays and tools to deal with them. A numpy array is a grid of values (of the same type) that are indexed by a tuple of positive integers, numpy arrays are fast, easy to understand, and give users the right to perform calculations across arrays.
Example:
Python3
# Importing Numpy packageimport numpy as np # Creating a 3-D numpy array using np.array()org_array = np.array([[23, 46, 85],                      [43, 56, 99],                      [11, 34, 55]]) # Printing the Numpy arrayprint(org_array)
Output:
a [23 46 85]
[43 56 99]
[11 34 55]]
Table of Differences Between Pandas VS NumPy is as follows: 
PANDAS
NUMPY
siddharthredhu01
Python-numpy
Python-pandas
Difference Between
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Difference between Clustered and Non-clustered index
Difference between Process and Thread
Read JSON file using Python
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Get tag name using Beautifulsoup in Python

11 Oct, 2020
Prerequisite: Beautifulsoup Installation
Name property is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Name object corresponds to the name of an XML or HTML tag in the original document.
Syntax:
tag.name
Parameters: This function doesn’t accept any parameter.
Implementation:Example 1: Program to extract name of a XML tag.
Python3
# Import modulefrom bs4 import BeautifulSoup  # Initialize the object with a XMLsoup = BeautifulSoup('''    <root>        <name_of_tag>the first strong tag</name_of_tag>    </root>    ''', "lxml")  # Get the tagtag = soup.name_of_tag  # Get the tag namename = tag.name  # Print the outputprint(name)
Output:
name_of_tag

Example 2: Program that explains the above functionality for a HTML tag.
Python3
# Import modulefrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''    <html>        <h2> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Get the name of the tagname = tag.name  # Print the outputprint(name)
Output:
h2
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2016 (Set 1) | Question 10

28 Jun, 2021
In a process, the number of cycles to failure decreases exponentially with an increase in load. At a load of 80 units, it takes 100 cycles for failure. When the load is halved, it takes 10000 cycles for failure. The load for which the failure will happen in 5000 cycles is ________.
(A) 40.00
(B) 46.02(C) 60.01(D) 92.02Answer: (B)Explanation:
For exponential dependence we must have functions of form
f(x) = a.(k power x) : a,k are constants and f(0)=a

Let us assume: C = cycles for failure ; L = Load; a, k = constants
according to question C is an exponential function of L
Hence we can say,

1) C = a x (k^L) ---- > in case C is increasing exponentially
2) C = a / (k^L) ---- > in case C is decreasing exponentially

we take 2nd equation and apply log to both side we get:

log C + L x (log k) = log a ...... by logarithmic property

given (C=100 for L=80) and (C=10000 for L=40)
apply these to values to above equation, this gives us 2 equations
and 2 variables:

log a = log 100 + (80 x log k)...............(1)
log a = log 10000 + (40 x log k)...........(2)

we have 2 variables and 2 equations hence we find
log a = 6
log k= 1/20

now find, [ L = (log a - log C) / (log k) ] for C=5000 cycles

=> L = (6 - log 5000)*20 = 46.0206 ~ 46.02 => [ANS]

Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
p5.js | ellipse() Function

24 Oct, 2018
The ellipse() function is an inbuilt function in p5.js which is used to draw an ellipse.
Syntax:
ellipse(x, y, w, h)
ellipse(x, y, w, h, detail)

Parameters: This function accepts five parameters as mentioned above and described below:
x: This parameter takes the x-coordinate of the ellipse.
y: This parameter takes the y-coordinate of the ellipse.
w: This parameter takes the width of the ellipse.
h: This parameter takes the height of the ellipse.
detail: It is the optional parameter which takes the number of radial sectors to draw as integer.
Below program illustrates the ellipse() function in P5.js:
function setup() {    createCanvas(400, 400);}  function draw() {    background(220);    fill('yellow');          // An ellipse at 150, 150 with radius 280    ellipse(150, 150, 280, 180) } 
Output:
Reference: https://p5js.org/reference/#/p5/ellipse
JavaScript-p5.js
Technical Scripter 2018
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python program to generate a list of alphabets in lexical order

11 Oct, 2020
Prerequisite: chr()
The following methods explain how a python list with alphabets in lexical(alphabetic) order can be generated dynamically using chr() method.
Approach:
The core of the concept in both methods is almost same, they only differ in implementation:
Validate size of alphabet list(size=26).If size>26, change to 26.If size≤0, no meaning left to the function and to make it meaningful set size to 26.Use chr() to produce the list using any of following methods.
Validate size of alphabet list(size=26).
If size>26, change to 26.
If size≤0, no meaning left to the function and to make it meaningful set size to 26.
Use chr() to produce the list using any of following methods.
Method 1: Using loop
Python3
# function to get the list of alphabetsdef generateAlphabetListDynamically(size = 26):  size = 26 if (size > 26 or size <= 0) else size      # Empty list   alphabetList = []      # Looping from 0 to required size   for i in range(size):    alphabetList.append(chr(65 + i))      # return the generated list  return alphabetList    alphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList)
Output:
The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Method 2: using list comprehension
Python3
def generateAlphabetListDynamically(size=26):    size = 26 if (size > 26 or size <= 0) else size      # Here we are looping from 0 to upto specified size    # 65 is added because it is ascii equivalent of 'A'    alphabetList = [chr(i+65) for i in range(size)]      # returning the list    return alphabetList    # Calling the function to get the alphabetsalphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList)
Output:
The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to create a dynamic JSON file by fetching data from localserver database ?

22 Jun, 2020
JSON stands for JavaScript Object Notation and is a structured format used for storing and transporting data. It acts as an interface between a server and a web page. It is a lightweight data-interchange format. It is language independent and easy to understand. It is derived from Javascript. JSON objects can be converted to javascript objects and vice-versa using functions like stringify() and parse().Here, before going through the program, we need to create a MySQL database in our localhost server. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. Wampserver helps to start Apache and MySQL and connect them with the PHP file. In our PHP code, we are going to make an array of data fetched from the database and then convert them into JSON. A dynamic JSON file will be created to store the array of JSON objects.
Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails.json by converting them into an array of JSON objects.
Creating Database:
Example:
<?php  // PHP program to connect with// localserver database$user = 'root';$password = ''; $database = 'gfg'; $servername ='localhost:3308';  $mysqli = new mysqli($servername,     $user, $password, $database);   if ($mysqli->connect_error) {    die('Connect Error (' .         $mysqli->connect_errno . ') '.         $mysqli->connect_error);}  // SQL query to select data// from database$sql2 = "SELECT * FROM userdata";$result = $mysqli->query($sql2);  // Fetching data from the database// and storing in array of objectswhile($row = $result->fetch_array()) {    $studentdata[] = array(        "GFG_User_Name" => $row["username"],        "No_Of_Problems" => $row["problems"],        "Total_Score" => $row["score"],        "Articles" => $row["articles"],    );}  // Creating a dynamic JSON file$file = "gfguserdetails.json";  // Converting data into JSON and putting// into the file// Checking for its creationif(file_put_contents($file,         json_encode($studentdata)))    echo("File created");else    echo("Failed");  // Closing the database$mysqli->close();  ?>
Output:
The dynamic JSON file created after running the code on the browser:
PHP-Misc
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to ORDER BY FIELD with GROUP BY in a single MySQL query?

For this, let us first create a table −
mysql> create table DemoTable
(
   Message text
);
Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Good');
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Awesome');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Good');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Amazing');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Awesome');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Bye');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+
| Message |
+---------+
| Good    |
| Bye     |
| Awesome |
| Bye     |
| Good    |
| Amazing |
| Awesome |
| Bye     |
+---------+
8 rows in set (0.00 sec)
Following is the query to ORDER BY FIELD with GROUP BY in a single MySQL query −
mysql> select *from DemoTable
   group by Message
   order by field(Message,'Amazing','Awesome','Good','Bye');
This will produce the following output −
+---------+
| Message |
+---------+
| Amazing |
| Awesome |
| Good    |
| Bye     |
+---------+
4 rows in set (0.04 sec)
How to set cell padding in HTML?

Cell padding is the space between cell borders and the content within a cell. To set cell padding in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <table> tag, with the CSS property padding.
HTML5 do not support the cellpadding attribute of <table>, so the CSS property padding is used with the style attribute to set cell padding.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to set cell padding in HTML. We’re also using the <style> tag and the style attribute to style the table
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>

   <body>
      <h1>Programming Language</h1>
      <table>
         <tr>
            <th style="padding:10px">Language</th>
         </tr>
         <tr>
            <td style="padding:10px">Ruby</td>
         </tr>
      </table>
   </body>
</html>
Underscore.js _.find() Function

27 Dec, 2021
The _.find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of list is not satisfy the condition then it returns the undefined value.
Syntax:
_.find(list, predicate, [context])
Parameters: This function accept three parameters as mentioned above and described below:
list: This parameter is used to hold the list of items.
predicate: This parameter is used to hold the truth condition.
context: The text content which need to be display. It is an optional parameter.
Return value: It returns the first occurrence of the element that satisfy the condition.
Example 1:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">        var oddNo = _.find([5, 6, 7, 8, 9, 10],            function (num) {                return num % 2 != 0;            });        console.log(oddNo);     </script></body>  </html>
Output:
5
Example 2:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">        var words = ['javascript', 'java', 'unix',                     'hypertext', 'underscore', 'CSS'];          const result = words.find(word => word.length == 9);        console.log(result);     </script></body>  </html>
Output:
hypertext
sumitgumber28
JavaScript - Underscore.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
MySQL query to find a value appearing more than once?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> value int
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.34 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| value |
+-------+
|    10 |
|   100 |
|    20 |
|    10 |
|    30 |
|    40 |
|    20 |
+-------+
7 rows in set (0.00 sec)
Following is the query to find a value appearing more than once −
mysql> select *from DemoTable group by value having count(*) > 1;
This will produce the following output −
+-------+
| value |
+-------+
|    10 |
|    20 |
+-------+
2 rows in set (0.00 sec)