code-rag-bench/online-tutorials huggingface dataset:
Vertical Concatenation in Matrix in Python

When it is required to concatenate a matrix vertically, the list comprehension can be used.
Below is a demonstration of the same −
 Live Demo
from itertools import zip_longest

my_list = [["Hi", "Rob"], ["how", "are"], ["you"]]

print("The list is : ")
print(my_list)

my_result = ["".join(elem) for elem in zip_longest(*my_list, fillvalue ="")]

print("The list after concatenating the column is : ")
print(my_result)
The list is :
[['Hi', 'Rob'], ['how', 'are'], ['you']]
The list after concatenating the column is :
['Hihowyou', 'Robare']
The required packages are imported.
The required packages are imported.
A list of list is defined, and is displayed on the console.
A list of list is defined, and is displayed on the console.
The list comprehension is used to zip the elements, and join them by eliminating the empty spaces.
The list comprehension is used to zip the elements, and join them by eliminating the empty spaces.
This is assigned to a variable.
This is assigned to a variable.
This variable is displayed as output on the console.
This variable is displayed as output on the console.
Groovy - matches()

It outputs whether a String matches the given regular expression.
Boolean matches(String regex)

Regex − the expression for comparison.
This method returns true if, and only if, this string matches the given regular expression.
Following is an example of the usage of this method
class Example { 
   static void main(String[] args) { 
      String a = "Hello World";
		
      println(a.matches("Hello")); 
      println(a.matches("Hello(.*)")); 
   } 
}
When we run the above program, we will get the following result −
false 
true


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Java Examples - User defined Exception

How to create user defined Exception ?
This example shows how to create user defined exception by extending Exception Class.
class MyException extends Exception {
   String s1;
   MyException(String s2) {
      s1 = s2;
   } 
   @Override
   public String toString() { 
      return ("Output String = "+s1);
   }
}
public class NewClass { 
   public static void main(String args[]) { 
      try {
         throw new MyException("Custom message");
      } catch(MyException exp) {
         System.out.println(exp);
      }
   }
}
The above code sample will produce the following result.
Output String = Custom message

 Print
 Add Notes
 Bookmark this page
Redis - Hashes

Redis Hashes are maps between the string fields and the string values. Hence, they are the perfect data type to represent objects.
In Redis, every hash can store up to more than 4 billion field-value pairs.
redis 127.0.0.1:6379> HMSET tutorialspoint name "redis tutorial" 
description "redis basic commands for caching" likes 20 visitors 23000 
OK 
redis 127.0.0.1:6379> HGETALL tutorialspoint  
1) "name" 
2) "redis tutorial" 
3) "description" 
4) "redis basic commands for caching" 
5) "likes" 
6) "20" 
7) "visitors" 
8) "23000"

In the above example, we have set Redis tutorials detail (name, description, likes, visitors) in hash named ‘tutorialspoint’.
Following table lists some basic commands related to hash.
Deletes one or more hash fields.
Determines whether a hash field exists or not.
Gets the value of a hash field stored at the specified key.
Gets all the fields and values stored in a hash at the specified key
Increments the integer value of a hash field by the given number
Increments the float value of a hash field by the given amount
Gets all the fields in a hash
Gets the number of fields in a hash
Gets the values of all the given hash fields
Sets multiple hash fields to multiple values
Sets the string value of a hash field
Sets the value of a hash field, only if the field does not exist
Gets all the values in a hash
Incrementally iterates hash fields and associated values

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Apache Configuration for PHP

Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement.
Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site − www.apache.org
The following section describe settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf:
This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; you must use the timeout value in php.ini instead
DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix −
DocumentRoot ./usr/local/apache_1.3.6/htdocs.

You can choose any directory as document root.
The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm.
AddType application/x-httpd-php .php
AddType application/x-httpd-phps .phps
AddType application/x-httpd-php3 .php3 .phtml
AddType application/x-httpd-php .html

You must uncomment this line for the Windows apxs module version of Apache with shared object support −
LoadModule php4_module modules/php4apache.dll

or on Unix flavors −
LoadModule php4_module modules/mod_php.so

You must uncomment this line for the static module version of Apache.
AddModule mod_php4.c


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to convert bool to int in MySQL?


To convert bool to int in MySQL, you can use CAST(). Let us first create a table:
mysql> create table convertBoolToIntDemo
   -> (
   -> isYoung bool
   -> );
Query OK, 0 rows affected (0.69 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into convertBoolToIntDemo values(true);
Query OK, 1 row affected (0.18 sec)

mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.09 sec)

mysql> insert into convertBoolToIntDemo values(true);
Query OK, 1 row affected (0.15 sec)

mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.18 sec)
Following is the query to display records from the table using select command:
mysql> select *from convertBoolToIntDemo;
This will produce the following output
+---------+
| isYoung |
+---------+
|       1 |
|       0 |
|       1 |
|       0 |
+---------+
4 rows in set (0.00 sec)
Following is the query to convert bool to int in MySQL:
mysql> select cast(isYoung=1 AS SIGNED INTEGER) from convertBoolToIntDemo;
This will produce the following output
+-----------------------------------+
| cast(isYoung=1 AS SIGNED INTEGER) |
+-----------------------------------+
|                                 1 |
|                                 0 |
|                                 1 |
|                                 0 |
+-----------------------------------+
4 rows in set (0.00 sec)
Angular Google Charts - Stacked Bar Chart

Following is an example of a Stacked Bar Chart.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Stacked Bar Chart.
We've used isStacked option to show bar based chart as stacked.
options = { 
   isStacked:true,
}
app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Population (in millions)';
   type = 'BarChart';
   data = [
      ["2012", 900, 390],
      ["2013", 1000, 400],
      ["2014", 1170, 440],
      ["2015", 1250, 480],
      ["2016", 1530, 540]
   ];
   columnNames = ['Year', 'Asia','Europe'];
   options = {   
      hAxis: {
         title: 'Year'
      },
      vAxis:{
         minValue:0
      },
      isStacked:true	  
   };
   width = 550;
   height = 400;
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Data Structures | Queue | Question 10 - GeeksforGeeks

28 Jun, 2021
Consider the following operation along with Enqueue and Dequeue operations onqueues, where k is a global parameter.
MultiDequeue(Q){
   m = k
   while (Q is not empty and m  > 0) {
      Dequeue(Q)
      m = m - 1
   }
}
What is the worst case time complexity of a sequence of n MultiDequeue() operations on an initially empty queue? (GATE CS 2013)(A) (B) (C) (D) 
(A) A(B) B(C) C(D) DAnswer: (A)Explanation: Since the queue is empty initially, the condition of while loop never becomes true. So the time complexity is .Quiz of this Question
Data Structures
Data Structures-Queue
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Difference between Singly linked list and Doubly linked list
Introduction to Data Structures | 10 most commonly used Data Structures
Data Structures | Stack | Question 6
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages of vector over array in C++
Data Structures | Stack | Question 4
How to plot a 2D matrix in Python with colorbar Matplotlib?

To plot a 2D matrix in Python with colorbar, we can use numpy to create a 2D array matrix and use that matrix in the imshow() method.
Create data2D using numpy.
Create data2D using numpy.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Create a colorbar for a ScalarMappable instance *mappable* using colorbar() method and imshow() scalar mappable image.
Create a colorbar for a ScalarMappable instance *mappable* using colorbar() method and imshow() scalar mappable image.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data2D = np.random.random((50, 50))
im = plt.imshow(data2D, cmap="copper_r")
plt.colorbar(im)
plt.show()
C# - Events

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber  class. Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.
To declare an event inside a class, first of all, you must declare a delegate type for the even as:
public delegate string BoilerLogHandler(string str);

then, declare the event using the event keyword −
event BoilerLogHandler BoilerEventLog;

The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised.
using System;

namespace SampleApp {
   public delegate string MyDel(string str);
	
   class EventProgram {
      event MyDel MyEvent;
		
      public EventProgram() {
         this.MyEvent += new MyDel(this.WelcomeUser);
      }
      public string WelcomeUser(string username) {
         return "Welcome " + username;
      }
      static void Main(string[] args) {
         EventProgram obj1 = new EventProgram();
         string result = obj1.MyEvent("Tutorials Point");
         Console.WriteLine(result);
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Welcome Tutorials Point


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
How to find all files with names containing a string on Linux?

In order to be able to find all files with names containing a string in Linux command line, we will make use of the grep command, and at first we must understand what a grep command is and how to use it on Linux.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
-R : stands for recurse, would go into subdirectories as well.
Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1.
grep -rni "word" *
In the above command replace the “word” placeholder with
For that, we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}
In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.
main.go:120:func main() {}
grep -R "apples" .
immukul@192 linux-dir1% grep -R "apples" .

./d1/file.txt:apples
./d1/file.txt:applesauce
./d1/file.txt:applesnits
./d1/file.txt:dapples
./d1/file.txt:grapples
./d1/file.txt:mayapples
./d1/file.txt:pineapples
./d1/file.txt:sapples
./d1/file.txt:scrapples
./d2/2.txt:orange apples is great together
./d2/2.txt:apples nto great
./d2/2.txt:is apples good
AWK - Arithmetic Operators

AWK supports the following arithmetic operators −
It is represented by plus (+) symbol which adds two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a + b) = ", (a + b) }'
On executing this code, you get the following result −
(a + b) = 70

It is represented by minus (-) symbol which subtracts two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a - b) = ", (a - b) }'
On executing this code, you get the following result −
(a - b) = 30

It is represented by asterisk (*) symbol which multiplies two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a * b) = ", (a * b) }'
On executing this code, you get the following result −
(a * b) = 1000

It is represented by slash (/) symbol which divides two or more numbers. The following example illustrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a / b) = ", (a / b) }'
On executing this code, you get the following result −
(a / b) = 2.5

It is represented by percent (%) symbol which finds the Modulus division of two or more numbers. The following example illustrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a % b) = ", (a % b) }'
On executing this code, you get the following result −
(a % b) = 10

 Print
 Add Notes
 Bookmark this page
How to assess your code performance in Python | by Sophia Yang | Towards Data Science

Profiling helps us identify bottlenecks and optimize performance in our code. If our code runs slowly, we can identify where our code is slow and then make corresponding improvements.
Here are the explanations of Python profilers from the Python documentation:
cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed...cProfile is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs.
cProfile is a Python built-in profiler, which is great for measuring the time spent at each function and how many times each function is executed. Let’s start with an example of cProfile.
Here is a Python script solving a linear system with the conjugate gradient method. Details of the calculation can be found in my other article. To run this Python script, we can simply do python conjugate_method_cprofile.py.
To profile with cProfile, run the following code in your terminal and save results to p0.prof.
python -m cProfile -o p0.prof conjugate_method.py 
Then we can use snakeviz to visualize the results.
conda install snakeviz snakeviz p0.prof
Here is what we get from snakeviz, which shows the name of the functions and time spent in each function. For example, in this example, our program conjugate_method.py takes most of the time, and calculating whether our matrix is symmetric positive definite, which includes calculating eigenvalues, takes some time as well.
The other profiling technique I use quite often is line profiling. Line profiling gives us information about the execution time for each line of our code. This is especially helpful when we have a specific function to dig into. To use line profiler, first we need to add a decorator @profile in front of our function in the Python script. See line 8 in this example:
Then we can run the following code to do the line profiling:
conda install line_profilerkernprof -l conjugate_method_lineprofile.pypython -m line_profiler conjugate_method_lineprofile.py.lprof
Results show the time spent on each line of our function. Here we can see most of the time spent on lines 19, 21, 23, and 10. If we want to improve our performance, we need to think of ways to optimize those lines.
These are my two favorite tools for profiling Python code. In the examples, I used them from the terminal, but you can also use them as magic in Jupyter Notebooks. See this video for details. There are other profiling tools you can use. For example, you can simply use timeit to get the time spent on the entire function. You can also profile memory usage. Hope you enjoy playing with profiling!
Node.js process.memoryUsage() Method - GeeksforGeeks

20 May, 2021
The process.memoryUsage() method is an inbuilt method of the process module that provides information about the current processes or runtime of a Node.js program. The memory usage method returns an object describing the memory usage in bytes of the Node.js process.
Syntax:
process.memoryUsage()   
Parameters: This method does not accept any parameter:
Return Value: This method returns an object with the description of the memory usage. 
Below examples illustrate the use of process.memoryUsage() method in Node.js.
Example 1:
index.js
// Requiring modulevar process = require('process')  // Prints the output as an objectconsole.log(process.memoryUsage())
Run the index.js file using the following command:
node index.js
Output:
{
  rss: 23851008,     
  heapTotal: 4907008,
  heapUsed: 2905912, 
  external: 951886,  
  arrayBuffers: 17574
}
Example 2: 
index.js
// Requiring modulevar process = require('process')  // An example displaying the respective memory// usages in megabytes(MB)for (const [key,value] of Object.entries(process.memoryUsage())){    console.log(`Memory usage by ${key}, ${value/1000000}MB `)}
Run the index.js file using the following command:
node index.js
Output:
Memory usage by rss, 23.87968MB 
Memory usage by heapTotal, 4.907008MB
Memory usage by heapUsed, 2.907088MB
Memory usage by external, 0.951886MB
Memory usage by arrayBuffers, 0.017574MB
Reference: https://nodejs.org/api/process.html#process_process_memoryusage
Node.js-Methods
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
C# Linq TakeWhile() Method

Get elements as long as the condition is true in a sequence using the TakeWhile() method.
The following is our list with strings.
IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
Now, let’s say we need the strings whose length is less than 4. For that, use Lambda Expressions and add it as a condition in the TakeWhile() method.
str.TakeWhile(a => a.Length < 4);
Here is the example that displays elements until the condition is trie.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
      var res = str.TakeWhile(a => a.Length < 4);
      foreach(var arr in res)
      Console.WriteLine(arr);
   }
}
Car
Bus
Maximum sum difference | Practice | GeeksforGeeks

Given a number N. We have to find maximum sum of all permutations of numbers from 1 to N. The maximum sum will be sum of absolute difference of adjacent elements in array.
Example 1:
Input: N = 2
Output: 1
Explaination: Permutations of 2 are: 
{1, 2} = 1, {2, 1} = 1.
Example 2:
Input: N = 3
Output: 3
Explaintation: Permutations of size 3 are: 
{1, 2, 3} = 1 + 1, {1, 3, 2} = 2 + 1 
{2, 1, 3} = 1 + 2, {2, 3, 1} = 1 + 2 
{3, 1, 2} = 2 + 1, {3, 2, 1} = 1 + 1 
Your Task:
You do not need to read input or print anything. Your task is to complete the function maxSum() which takes N as input parameter and returns the maximum possible difference sum from all permutations of N numbers.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
2 ≤ N ≤ 1000
0
himanshubarak123 months ago
class Solution{
public:
    int maxSum(int n){
        // code here
        if(n==1)  return 1;
        return ((n*(n-1))/2 +n/2 -1);
    }
};
 
To understand the logic check out this post.
https://www.geeksforgeeks.org/maximum-sum-difference-adjacent-elements/
 
-2
vermasumit9236 months ago
class Solution{public:   int maxSum(int N)   {       int sum = (N*(N-1))/2;       int arr[1001];       arr[1] = 1;       int k = 0;       for(int i = 2; i <= 1000; i += 2)       {           arr[i] = k;           arr[i+1] = k;           k++;       }       sum += arr[N];       return sum;   }};
0
ANKIT SINHA9 months ago
ANKIT SINHA
https://uploads.disquscdn.c...
0
Tulsi Dey1 year ago
Tulsi Dey
Solution in Java:time complexity : O(1)space complexity: O(1)Execution time : 0.28
class Solution{    static int maxSum(int N){        if(N == 1) return 1;        return N*(N+1)/2 + N/2 - (N+1);    }}
0
Tulsi Dey1 year ago
Tulsi Dey
Solution in C++:time complexity : O(1)space complexity: O(1)Execution time : 0.02
class Solution{public:    int maxSum(int N){        if(N == 1) return 1;        return N*(N+1)/2 + N/2 - (N+1);    }};
0
Jihye Sofia Seo5 years ago
Jihye Sofia Seo
Input:
189
Its Correct output is:
17859
And Your Code's Output is:
17766
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
GATE | GATE CS 2021 | Set 2 | Question 45 - GeeksforGeeks

13 Aug, 2021
Consider the following ANSI C program:
#include < stdio.h >
#include < stdlib.h >
struct Node{
        int value;
        struct Node *next;};
int main( ) {
    struct Node *boxE, *head, *boxN; int index=0;
    boxE=head= (struct Node *) malloc(sizeof(struct Node));
    head → value = index;
    for (index =1; index<=3; index++){
        boxN = (struct Node *) malloc (sizeof(struct Node));
        boxE → next = boxN;
        boxN → value = index;
        boxE = boxN; }
for (index=0; index<=3; index++) {
    printf(“Value at index %d is %d\n”, index, head → value);
    head = head → next;
    printf(“Value at index %d is %d\n”, index+1, head → value); } } 
Which one of the following statements below is correct about the program?(A) Upon execution, the program creates a linked-list of five nodes(B) Upon execution, the program goes into an infinite loop(C) It has a missing return which will be reported as an error by the compiler(D) It dereferences an uninitialized pointer that may result in a run-time errorAnswer: (D)Explanation:
When you debug loop 1 you will get the linked list of size 4 
In the second loop value will be printed 0 0 1 1 2 2 3 3 after that head will be pointing to some random location and result in run-time error. Correct Option (D)
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2021 (Set1 and Set2) with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0046:14 / 54:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=I43aLH5qEBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
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 65
GATE | GATE CS 2008 | Question 69
GATE | GATE CS 2018 | Question 45
GATE | GATE CS 2019 | Question 50
GATE | GATE CS 1997 | Question 25
GATE | GATE CS 2010 | Question 33
GATE | GATE CS 2011 | Question 43
GATE | GATE CS 2020 | Question 16
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 46
How to get the current time in millisecond using JavaScript?

To get the current time in a millisecond, use the date getMilliseconds() method. JavaScript date getMilliseconds() method returns the milliseconds in the specified date according to local time. The value returned by getMilliseconds() is a number between 0 and 999.
 You can try to run the following code to get the current time in milliseconds −
<html>
   <head>
      <title>JavaScript getMilliseconds() Method</title>
   </head>
   <body>
      <script>
         var dt = new Date( );
         document.write("getMilliseconds() : " + dt.getMilliseconds() );
      </script>
   </body>
</html>
Express.js – express.raw() function

express.raw() is a built-in middleware function in Express. It parses the incoming requests into a buffer and it is based upon the body-parser. This method returns the middleware that parses all JSON bodies as buffer and only looks at the requests where the content-type header matches the type option.
express.raw([options])
Following are the different options available with this method
options –inflate – This enables or disables the handling of the deflated or compressed bodies. Default: truelimit – Controls the maximum size of the request body.type – Determines the media type for the middleware that will be parsed.
options –
inflate – This enables or disables the handling of the deflated or compressed bodies. Default: true
inflate – This enables or disables the handling of the deflated or compressed bodies. Default: true
limit – Controls the maximum size of the request body.
limit – Controls the maximum size of the request body.
type – Determines the media type for the middleware that will be parsed.
type – Determines the media type for the middleware that will be parsed.
Create a file with the name "expressRaw.js" and copy the following code snippet. After creating the file, use the command "node expressRaw.js" to run this code.
// express.raw() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Using the express.raw middleware
app.use(express.raw());

// Reading content-type
app.post('/', function (req, res) {
   console.log(req.body)
   res.end();
})

// Listening to the port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Before hitting the API endpoint, set the following two properties −
Set the content-type as application/octet-stream in headers.
Set the content-type as application/octet-stream in headers.
Pass the following body in the POST request – {"name": "TutorialsPoint"}
Pass the following body in the POST request – {"name": "TutorialsPoint"}
C:\home\node>> node expressRaw.js
Server listening on PORT 3000


Let’s take a look at one more example.
// express.raw() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Commenting the express.raw middleware

// app.use(express.raw());

// Reading content-type
app.post('/', function (req, res) {
   console.log(req.body)
   res.end();
})

// Listening to the port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
Before hitting the API endpoint, set the following two properties −
Set the content-type as application/octet-stream in headers.
Set the content-type as application/octet-stream in headers.
Pass the following body in the POST request – {"name": "TutorialsPoint"}
Pass the following body in the POST request – {"name": "TutorialsPoint"}
C:\home\node>> node expressRaw.js
Server listening on PORT 3000
undefined
How to change the background color of a tkinter Canvas dynamically?

The Canvas widget is one of the most useful widgets in Tkinter. It has various functionalities and features to help developers customize the application according to their need. The Canvas widget is used to display the graphics in an application. You can create different types of shapes and draw objects using the Canvas widget.
To change the background color of the Canvas widget, you can use the configure() method. Here, you can specify the background color of the Canvas widget which you want to change explicitly.
In the following example, we have created a canvas widget with a default background color "skyblue", which can be changed after its creation.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame
win= Tk()

# Define the size of the window
win.geometry("700x300")

# Function to change the color of the canvas
def change_color():
   canvas.configure(bg='blue')

# Create a canvas widget
canvas= Canvas(win, bg='skyblue')
canvas.pack()

# Create a button
button=Button(win, text= "Change Color", font=('Helvetica 10 bold'), command=change_color)
button.pack()

win.mainloop()
It will produce the following output −
Clicking the "Change Color" button would change the background color of the canvas.
What is isErrorPage attribute in JSP?

The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown −
<%@ page errorPage = "MyErrorPage.jsp" %>
The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.
For example, the handleError.jsp sets the isErrorPage option to true because it is supposed to handle errors −
<%@ page isErrorPage = "true" %>
How can bubble charts be created using Matplotlib?

Matplotlib library is built upon Numpy. It is a Python library that is used to visualize data. It is a tree-like hierarchical structure which consists of objects that makeup each of these plots. A ’Figure’ in Matplotlib can be understood as the outermost storage for a graph. This ‘Figure’ can contains multiple ‘Axes’ objects. ‘Axes’ object is NOT the plural form of ‘Axis’ in this case.
‘Axes’ can be understood as a part of ‘Figure’, a subplot. It can be used to manipulate every part of the graph inside it. A ‘Figure’ object in Matplotlib is a box that stores one or more ‘Axes’ objects. Under ‘Axes’ comes the tick marks, lines, legends, and text boxes in the hierarchy. Every object in the Matplotlib can be manipulated. Let us see an example
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
colors = np.random.rand(50)
plt.scatter(x, y, s=z*2000,c=colors)
plt.title("Bubble chart")
plt.xlabel("x−axis")
plt.ylabel("Y−axis")
plt.show()
The required packages are imported and aliased.
The required packages are imported and aliased.
The ‘rand’ function present in ‘random’ class is used to generate data.
The ‘rand’ function present in ‘random’ class is used to generate data.
The ‘title’, x label, and y label of the plot is defined.
The ‘title’, x label, and y label of the plot is defined.
The ‘scatter’ function is called by passing the data.
The ‘scatter’ function is called by passing the data.
The show function is used to display the data on the console.
The show function is used to display the data on the console.
Tryit Editor v3.7

CSS Grid Intro
Tryit: The gap shorthand property
How to resize a navigation bar on scroll with CSS and JavaScript?


Following is the code to resize a navigation bar on scroll using CSS and JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
*,
*::before,
*::after {
   box-sizing: border-box;
}
body {
   margin: 0px;
   margin-top: 60px;
   padding: 0px;
}
nav {
   position: fixed;
   top: 0px;
   width: 100%;
   background-color: rgb(39, 39, 39);
   overflow: auto;
   height: auto;
   transition: 0.5s;
   padding: 50px 10px;
}
.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(178, 137, 253);
   text-decoration: none;
   font-size: 17px;
}
.links:hover {
   background-color: rgb(100, 100, 100);
}
.selected {
   background-color: rgb(0, 18, 43);
}
.sample-content {
   height: 150vh;
}
.company-logo {
   font-size: 50px;
   color: white;
   position: absolute;
   right: 30px;
   transition: 0.3s;
}
</style>
</head>
<body>
<nav>
<a class="company-logo">€</a>
<a class="links selected" href="#">Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
</nav>
<div class="sample-content">
<h1>Here are some headers</h1>
<h2>Here are some headers</h2>
<h3>Here are some headers</h3>
<h4>Here are some headers</h4>
<h1>Here are some headers</h1>
<h2>Here are some headers</h2>
<h3>Here are some headers</h3>
<h4>Here are some headers</h4>
</div>
<script>
window.onscroll = scrollShowNav;
function scrollShowNav() {
   if (
      document.body.scrollTop > 20 ||
      document.documentElement.scrollTop > 20
   )
   {
      document.getElementsByTagName("nav")[0].style.padding = "10px 10px";
      document.querySelector(".company-logo").style.fontSize = "20px";
   } else {
      document.getElementsByTagName("nav")[0].style.padding = "40px 50px";
      document.querySelector(".company-logo").style.fontSize = "50px";
   }
}
</script>
</body>
</html>
The above code will produce the following output −
On scrolling the page the nav will shrink as follows −
Declare char arrays in C#

Declare a char array and set the size −
char[] arr = new char[5];
Now set the elements −
arr[0] = 'h';
arr[1] = 'a';
arr[2] = 'n';
arr[3] = 'k';
arr[4] = 's';
Let us see the complete code now to declare, initialize and display char arrays in C# −
 Live Demo
using System;

public class Program {
   public static void Main() {
      char[] arr = new char[5];
      arr[0] = 'h';
      arr[1] = 'a';
      arr[2] = 'n';
      arr[3] = 'k';
      arr[4] = 's';
      Console.WriteLine("Displaying string elements...");

      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}
Displaying string elements...
h
a
n
k
s
Vertical and Horizontal Scrollbars on Tkinter Widget

Scrollbars are useful to provide dynamic behavior in an application. In a Tkinter application, we can create Vertical as well as Horizontal Scrollbars. Scrollbars are created by initializing the object of Scrollbar() widget.
To create a horizontal scrollbar, we have to provide the orientation, i.e., "horizontal" or "vertical". Scrollbars can be accessible once we configure the particular widget with the scrollbars.
#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x350")

#Create some dummy Text
text_v = "Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming."
text_h = ("\nNASA \n Google \nNokia \nFacebook \n Netflix \n Expedia \n Reddit \n Quora \n MIT\n Udemy \n Shutterstock \nSpotify\nAmazon\nMozilla\nDropbox")

#Add a Vertical Scrollbar
scroll_v = Scrollbar(win)
scroll_v.pack(side= RIGHT,fill="y")

#Add a Horizontal Scrollbar
scroll_h = Scrollbar(win, orient= HORIZONTAL)
scroll_h.pack(side= BOTTOM, fill= "x")
#Add a Text widget
text = Text(win, height= 500, width= 350, yscrollcommand= scroll_v.set,
xscrollcommand = scroll_h.set, wrap= NONE, font= ('Helvetica 15'))
text.pack(fill = BOTH, expand=0)
text.insert(END, text_v)
text.insert(END, text_h)

#Attact the scrollbar with the text widget
scroll_h.config(command = text.xview)
scroll_v.config(command = text.yview)

win.mainloop()
Running the above code will display a window containing context about Python Programming language. The context can be dynamically viewed using horizontal and vertical scrollbars.
strtol() function in C++

The strol() function is used to convert the string to long integers. It sets the pointer to point to the first character after the last one. The syntax is like below. This function is present into the cstdlib library.
long int strtol(const char* str, char ** end, int base)
This function takes three arguments. These arguments are like below −
str: This is the starting of a string.
str_end: The str_end is set by the function to the next character, after the last valid character, if there is any character, otherwise null.
base: This specifies the base. The base values can be of (0, 2, 3, ..., 35, 36)
This function returns the converted long int. When the character points to NULL, it returns 0.
#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "777HelloWorld";
   char string2[] = "565Hello";
   char* End; //The end pointer
   int base = 10;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}
The string Value = 777HelloWorld
Long Long Int value = 777
End String = HelloWorld
The string Value = 565Hello
Long Long Int value = 565
End String = Hello
Now Let us see the example with a different base value. Here the base is 16. By taking the string of given base, it will print in decimal format.
#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "5EHelloWorld";
   char string2[] = "125Hello";
   char* End; //The end pointer
   int base = 16;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}
The string Value = 5EHelloWorld
Long Long Int value = 94
End String = HelloWorld
The string Value = 125Hello
Long Long Int value = 293
End String = Hello
Here the string is containing 5E so its value is 94 in decimal, and the second string is containing 125. This is 293 in decimal.
SQL Query to Convert Date to Datetime - GeeksforGeeks

18 Oct, 2021
In this article, we will look at how to convert Date to Datetime. We can convert the Date into Datetime in two ways. 
Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type.Convert() function is used to convert a value of any type to another datatype.
Using the CAST() function: SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another. The Cast() function is also used for the same purpose to convert the data type of any value.
To perform any queries we have to create a database. So, let us create a database first.
Step 1: Creating Database
Query:
CREATE DATABASE Test;
Output:
Step 2: Converting Date to Datetime
Method 1: Using CONVERT() function
In this example, we are converting the date 01-01-2021 into Datetime. The date is in the form ‘yyyy-mm-dd’.
Query:
SELECT CONVERT(datetime, '2021-01-01');
Output:
Method 2: Using CAST() function
In this example, we are converting the date 01-01-2021 into Datetime as shown below. The date is in the form ‘yyyy-mm-dd’.
Query:
SELECT CAST('2021-01-01' AS datetime);
Output:
Picked
SQL-Query
SQL-Server
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
Window functions in SQL
How to create and populate Java array of Hash tables?

One way to create an array of hash tables is to create Hashtable objects and to assign these to a Hashtable array using curly braces:
Live Demo
import java.util.Hashtable;

public class HashTableOfArrays {
   public static void main(String args[]) {
      Hashtable<String, String> ht1 = new Hashtable();
      ht1.put("Name", "Krishna");
      ht1.put("Age", "28");
      ht1.put("City", "Visakhapatnam");
      ht1.put("Phone", "9848022338");
     
      Hashtable<String, String> ht2 = new Hashtable();
      ht2.put("Name", "Raju");
      ht2.put("Age", "30");
      ht2.put("City", "Chennai");
      ht2.put("Phone", "9848033228");
     
      Hashtable<String, String> ht3 = new Hashtable();
      ht3.put("Name", "Satish");
      ht3.put("Age", "35");
      ht3.put("City", "Hyderabad");
      ht3.put("Phone", "9848023848");
      Hashtable [] hashArray = {ht1, ht2, ht3};
     
      for(int i = 0; i<hashArray.length; i++){
         System.out.println(hashArray[i]);
      }
   }
}
{Name=Krishna, City=Visakhapatnam, Phone=9848022338, Age=28}
{Name=Raju, City=Chennai, Phone=9848033228, Age=30}
{Name=Satish, City=Hyderabad, Phone=9848023848, Age=35}
Matplotlib - Violin Plot

Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different "categories".
A violin plot is more informative than a plain box plot. In fact while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data.
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)

## combine these different collections into a list
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a figure instance
fig = plt.figure()

# Create an axes instance
ax = fig.add_axes([0,0,1,1])

# Create the boxplot
bp = ax.violinplot(data_to_plot)
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page