code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.pyplot.gray() in Python

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The gray() function in pyplot module of matplotlib library is used to set the colormap to “gray”.
Syntax:
matplotlib.pyplot.gray()

Below examples illustrate the matplotlib.pyplot.gray() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np       ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad)      angles = np.linspace(0, 3 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis],                    rad, axis = 1)angles[:, 1::2] += np.pi / ang      x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten()      triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                < radm)      tpc = plt.tripcolor(triang, z, shading ='flat')  plt.colorbar(tpc)plt.gray()plt.title('matplotlib.pyplot.gray() function\Example\n\n', fontweight ="bold")  plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm               dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y)      extent = np.min(x), np.max(x), np.min(y), np.max(y)     Z1 = np.add.outer(range(8), range(8)) % 2  plt.imshow(Z1, cmap ="binary_r",            interpolation ='nearest',           extent = extent, alpha = 1)      def geeks(x, y):          return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))      Z2 = geeks(X, Y)      plt.imshow(Z2, alpha = 0.7,            interpolation ='bilinear',           extent = extent)plt.gray()plt.title('matplotlib.pyplot.gray() function Example\n\n',          fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sort all sublists in given list of strings

28 Feb, 2019
Given a list of lists, the task is to sort each sublist in the given list of strings.
Example:
Input:
lst = [['Machine', 'London', 'Canada', 'France'],
       ['Spain', 'Munich'],
       ['Australia', 'Mandi']]

Output:
flist = [['Canada', 'France', 'London', 'Machine'],
         ['Munich', 'Spain'],
         ['Australia', 'Mandi']]

There are multiple ways to sort each list in alphabetical order.
Method #1 : Using map
# Python code  to sort all sublists # in given list of strings  # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'],         ['Spain', 'Munich'],         ['Australia', 'Mandi']]  # Using map for sortingOutput = list(map(sorted, Input))  # Printing outputprint(Output)
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
 Method #2 : Using lambda and sorted
# Python code  to sort all sublists# in given list of strings  # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'],         ['Spain', 'Munich'],         ['Australia', 'Mandi']]  # using lambda and sortedOutput = [sorted(x, key = lambda x:x[0]) for x in Input]  # Printing outputprint(Output)
[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
 Method #3 : Using iteration and sort
# Python code  to sort all sublists# in given list of strings  # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'],         ['Spain', 'Munich'],         ['Australia', 'Mandi']]  # sorting sublistfor sublist in Input:    sublist.sort()  # Printing outputprint(Input)
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to concatenate two strings in Python?

Concatenating two strings refers to the merging of both the strings together. Concatenation of “Tutorials” and “Point” will result in “TutorialsPoint”.
We will be discussing different methods of concatenating two strings in Python.
Two strings can be concatenated in Python by simply using the ‘+’ operator between them.
More than two strings can be concatenated using ‘+’ operator.
 Live Demo
s1="Tutorials"
s2="Point"
s3=s1+s2
s4=s1+" "+s2
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
We can use the % operator to combine two string in Python. Its implementation is shown in the below example.
 Live Demo
s1="Tutorials"
s2="Point"
s3="%s %s"%(s1,s2)
s4="%s%s"%(s1,s2)
print(s3)
print(s4)
Tutorials Point
TutorialsPoint
The %s denotes string data type. The space between the two strings in the output depends on the space between “%s %s”, which is clear from the example above.
The join() is a string method that is used to join a sequence of elements. This method can be used to combine two strings.
 Live Demo
s1="Tutorials"
s2="Point"
s3="".join([s1,s2])
s4=" ".join([s1,s2])
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
The format() is a string formatting function. It can be used to concatenate two strings.
 Live Demo
s1="Tutorials"
s2="Point"
s3="{}{}".format(s1,s2)
s4="{} {}".format(s1,s2)
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
The {} set the position of the string variables. The space between the ‘{} {}’ is responsible for the space between the two concatenated strings in the output.
How to work with document.images in JavaScript?

Use the document.images property in JavaScript to get the number of <img> tags in a document.
You can try to run the following code to implement document.images property in JavaScript.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>JavaScript Example</title>
   </head>
   <body>
      <h1>TutorialsPoint Tutorials</h1>
      <img src="/javascript/images/javascript-mini-logo.jpg"/><br>
      <img src="/html5/images/html5-mini-logo.jpg"/>
      <script>
         var num = document.images.length;
         document.write("<br>How many images? "+num);
      </script>
   </body>
</html>
C# Program to Convert Character case

Let’s say your string is −
str = "AMIT";
To convert the above uppercase string in lowercase, use the ToLower() method −
Console.WriteLine("Converted to LowerCase : {0}", str.ToLower());
The following is the code in C# to convert character case.
Live Demo
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         string str;
         str = "AMIT";
         Console.WriteLine("UpperCase : {0}", str);
         // convert to lowercase
         Console.WriteLine("Converted to LowerCase : {0}", str.ToLower());
         Console.ReadLine();
      }
   }
}
UpperCase : AMIT
Converted to LowerCase : amit
Python | Pandas Series.is_monotonic_increasing

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.is_monotonic_increasing attribute return a boolean value. It returns True if the data in the given Series object is monotonically increasing else it return False.
Syntax:Series.is_monotonic_increasing
Parameter : None
Returns : boolean
Example #1: Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# check if monotonically increasingsr.is_monotonic_increasing
Output :
As we can see in the output, the Series.is_monotonic_increasing attribute has returned False indicating the underlying in the given series object is not monotonically increasing. Example #2 : Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# check if monotonically increasingsr.is_monotonic_increasing
Output :
As we can see in the output, the Series.is_monotonic_increasing attribute has returned True indicating the underlying in the given series object is monotonically increasing.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | sympy.sqrt() method

04 Jul, 2019
With the help of sympy.sqrt() method, we can find the square root of any value in terms of values and also in terms of symbolically simplified mathematical expression.
Syntax: sqrt(val)
Parameters:val – It is the value on which square root operation is to be performed.
Returns: Returns square root in terms of values and symbolically simplified mathematical expression corresponding to the input expression.
Example #1:
# import sympy from sympy import *   val = 256    print("Value : {}".format(val))       # Use sympy.sqrt() method sqrt_val = sqrt(val)        print("Square root of value : {}".format(sqrt_val))  
Output:
Value : 256
Square root of value : 16

Example #2:
# import sympy from sympy import *   val = 8    print("Value : {}".format(val))       # Use sympy.sqrt() method sqrt_val = sqrt(val)        print("Square root of value : {}".format(sqrt_val))  
Output:
Value : 8
Square root of value : 2*sqrt(2)

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue.Dequeue Method in C#

04 Feb, 2019
The Dequeue() method is used to returns the object at the beginning of the Queue. This method is similar to the Peek() Method. The only difference between Dequeue and Peek method is that Peek() method will not modify the Queue but Dequeue will modify. This method is an O(1) operation and comes under System.Collections namespace.
Syntax:
public virtual object Dequeue ();

Return value: It returns the object which is removed from the beginning of the Queue.
Exception: The method throws InvalidOperationException on calling empty queue, therefore always check that the total count of a queue is greater than zero before calling the Dequeue() method.
Below programs illustrate the use of the above-discussed method:
// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections;  class GFG {      // Main Method    public static void Main()    {        Queue queue = new Queue();        queue.Enqueue(3);        queue.Enqueue(2);        queue.Enqueue(1);        queue.Enqueue("Four");          Console.WriteLine("Number of elements in the Queue: {0}",                                                    queue.Count);          // Retrieveing top element of queue        Console.WriteLine("Top element of queue is:");        Console.WriteLine(queue.Dequeue());          // printing the no of queue element         // after dequeue operation        Console.WriteLine("Number of elements in the Queue: {0}",                                                    queue.Count);    }}
Number of elements in the Queue: 4
Top element of queue is:
3
Number of elements in the Queue: 3

// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections;  class GFG {      // Main Method    public static void Main()    {        Queue queue = new Queue();          // Adding elements in Queue        queue.Enqueue(2);        queue.Enqueue("Four");          Console.WriteLine("Number of elements in the Queue: {0}",                                                    queue.Count);          // Retrieveing top element of queue        Console.WriteLine("Top element of queue is:");        Console.WriteLine(queue.Dequeue());          // printing the no. of queue element        // after dequeue operation        Console.WriteLine("Number of elements in the Queue: {0}",                                                    queue.Count);    }}
Number of elements in the Queue: 2
Top element of queue is:
2
Number of elements in the Queue: 1

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.dequeue?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Multiple inheritance using interfaces
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
Python – Group Sublists by another List

22 Jun, 2020
Sometimes, while working with lists, we can have a problem in which we need to group all the sublists, separated by elements present in different list. This type of custom grouping is uncommon utility but having solution to these can always be handy. Lets discuss certain way in which this task can be performed.
Method #1 : Using loop + generator(yield)This is brute force way in which this task can be performed. In this, we iterate the list and make groups dynamically using yield. We keep track of elements occurred and restart list when we find element in second list.
# Python3 code to demonstrate # Group Sublists by another List# using loop + generator(yield)  # helper functiondef grp_ele(test_list1, test_list2):    temp = []    for i in test_list1:         if i in test_list2:            if temp:                  yield temp                 temp = []            yield i          else:             temp.append(i)    if temp:         yield temp  # Initializing liststest_list1 = [8, 5, 9, 11, 3, 7]test_list2 = [9, 11]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Group Sublists by another List# using loop + generator(yield)res = list(grp_ele(test_list1, test_list2))  # printing result print ("The Grouped list is : " + str(res))
The original list 1 is : [8, 5, 9, 11, 3, 7]
The original list 2 is : [9, 11]
The Grouped list is : [[8, 5], 9, 11, [3, 7]]

 
nidhi_biet
Python list-programs
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How to print a blank line in C#?

To display a line in C#, use the Console.WriteLine().
Under that set a blank line −
Console.WriteLine(" ");
The following is the code that displays a blank line −
 Live Demo
using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {

         Console.WriteLine(" ");
         Console.WriteLine("Displayed a blank line above!\n");
         Console.ReadLine();

      }
   }
}
Displayed a blank line above!
C++ Program to Check Whether Graph is DAG

A directed acyclic graph (DAG) is a graph that is directed and without cycles connecting the other edges. The edges of this graph go one way. This is a C++ program to check whether the graph is DAG.
Begin
Function checkDAG(int n):
   intialize count = 0
   intialize size = n - 1
   for i = 0 to n-1
      if (count == size)
         return 1
      done
      if (arr[i].ptr == NULL)
         increment count
         for j = 0 to n-1
            while (arr[j].ptr != NULL)
               if ((arr[j].ptr)->d == (arr[i].ptr)->d)
                  (arr[j].ptr)->d = -1
               done
            arr[i].ptr = (arr[i].ptr)->next
            done
         done
      done
   done
   return 0
End
 Live Demo
#include<iostream>
using namespace std;
int c = 0;
struct ad_list { //A structure of type adj_list
   int d;
   ad_list *next;
}
*np = NULL, *np1 = NULL, *p = NULL, *q = NULL;
struct Gr { //A structure of type Gr
   int v;
   ad_list *ptr;
}
arr[6];
void addRevEdge(int s, int d) { //add reverse edges in the graph
   np1 = new ad_list;
   np1->d = s;
   np1->next = NULL;
   if (arr[d].ptr == NULL) {
      arr[d].ptr = np1;
      q = arr[d].ptr;
      q->next = NULL;
   } else {
      q = arr[d].ptr;
      while (q->next != NULL) {
         q = q->next;
      }
      q->next = np1;
   }
}
void addEdge(int s, int d) { // add edges in the graph
   np = new ad_list;
   np->d = d;
   np->next = NULL;
   if (arr[s].ptr == NULL) {
      arr[s].ptr = np;
      p = arr[s].ptr;
      p->next = NULL;
   } else {
      p = arr[s].ptr;
      while (p->next != NULL) {
         p = p->next;
      }
      p->next = np;
   }
}
void print_g(int n) {
   for (int i = 0; i < n; i++) {
      cout << "Adjacency List of " << arr[i].v << ": ";
      while (arr[i].ptr != NULL) {
         cout << (arr[i].ptr)->d<< " ";
         arr[i].ptr = (arr[i].ptr)->next;
      }
      cout << endl;
   }
}
int checkDAG(int n) {
   int count = 0;
   int size = n - 1;
   for (int i = 0; i < n; i++) {
      if (count == size) {
         return 1;
      }
      if (arr[i].ptr == NULL) {
         count++;
         for (int j = 0; j < n; j++) {
            while (arr[j].ptr != NULL) {
               if ((arr[j].ptr)->d == (arr[i].ptr)->d) {
                  (arr[j].ptr)->d = -1;
               }
               arr[i].ptr = (arr[i].ptr)->next;
            }
         }
      }
   }
   return 0;
}
int main() {
   int v = 4;
   cout << "Number of vertices: " << v << endl;
   for (int i = 0; i < v; i++) {
      arr[i].v = i;
      arr[i].ptr = NULL;
   }
   addEdge(1, 0);
   addEdge(3, 1);
   addEdge(2, 1);
   addEdge(0, 3);
   addEdge(4, 1);
   print_g(v);
   cout << "The given graph is 'Directed Acyclic Graph' :";
   if (checkDAG(v) == 1)
      cout << " yes";
   else
      cout << " no";
}
Number of vertices: 4
Adjacency List of 0: 3
Adjacency List of 1: 0
Adjacency List of 2: 1
Adjacency List of 3: 1
The given graph is 'Directed Acyclic Graph' : yes
JSON with Ruby

This chapter covers how to encode and decode JSON objects using Ruby programming language. Let's start with preparing the environment to start our programming with Ruby for JSON.
Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your machine, otherwise let's follow the following single step assuming you already have gem installed −
$gem install json

The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let's keep the following content in a file called input.json.
{
   "President": "Alan Isaac",
   "CEO": "David Richardson",
  
   "India": [
      "Sachin Tendulkar",
      "Virender Sehwag",
      "Gautam Gambhir"
   ],

   "Srilanka": [
      "Lasith Malinga",
      "Angelo Mathews",
      "Kumar Sangakkara"
   ],

   "England": [
      "Alastair Cook",
      "Jonathan Trott",
      "Kevin Pietersen"
   ]
	
}
Given below is a Ruby program that will be used to parse the above mentioned JSON document −
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'

json = File.read('input.json')
obj = JSON.parse(json)

pp obj
On executing, it will produce the following result −
{
   "President"=>"Alan Isaac",
   "CEO"=>"David Richardson",

   "India"=>
   ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],

   "Srilanka"=>
   ["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],

   "England"=>
   ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}


    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to convert the Integer variable to the string variable in PowerShell?

To convert the integer variable to the string variable, you need to use the explicit conversion or the functional method. In the below example, we are assigning an integer value to the variable $X.
$x = 120
$x.GetType().Name
Now when you check the data type of that variable, it will be Int32.
To convert it into the string variable, first, we will use the explicit method by using a square bracket and data type to convert inside the brackets.
[string]$x = 130
$x.GetType().Name
The data type of $x is the String.
In the second method, you can use the PowerShell functional method ToString() to convert. For example,
$x = $x.ToString()
$x.GetType().Name
In the same way, you can convert string value to the integer value but in its defined range. For example,
$x = "123"
[int]$x = $x
$x.GetType().Name
Here, we are declaring “123” as the string variable and to convert it we will use [int] data type ahead of $x so it will be converted to an integer variable. But when you convert a character string into an integer, you will get an error.
For example,
$x = "abc"
[int]$x = $x
Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$x = $x
+ ~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId :RuntimeException
How to concatenate all values of a single column in MySQL?

You can use group_concat() along with concat() to concatenate all values of a single column. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20)
   );
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(FirstName) values('David');
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 −
+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | Larry     |
|  3 | Chris     |
|  4 | Robert    |
|  5 | David     |
+----+-----------+
5 rows in set (0.00 sec)
Following is the query to concatenate all values of a single column in MySQL.
mysql> select group_concat(concat('"', FirstName, '"')) AS FirstName from DemoTable;
This will produce the following output −
+-----------------------------------------+
| FirstName                               |
+-----------------------------------------+
| "John","Larry","Chris","Robert","David" |
+-----------------------------------------+
1 row in set (0.05 sec)
Angular 8 - Testing

Testing is a very important phase in the development life cycle of an application. It ensures an application quality. It needs careful planning and execution.
Unit testing is the easiest method to test an application. It is based on ensuring the correctness of a piece of code or a method of a class. But, it does not reflect the real environment and subsequently. It is the least option to find the bugs.
Generally, Angular 8 uses Jasmine and Karma configurations. To perform this, first you need to configure in your project, using the below command −
ng test
Now, you could see the following response −
Now, Chrome browser also opens and shows the test output in the “Jasmine HTML Reporter”. It looks similar to this,
Unit tests are small, simple and fast process whereas, E2E testing phase multiple components are involved and works together which cover flows in the application. To perform e2e test, type the below command −
ng e2e
You could see the below response −

    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
ReactJS – forceUpdate() Method

In this article, we are going to see how to execute a function by forcibly re-rendering a component.
The component in the React lifecycle only re-renders if the props passed to it or its state changes but to forcibly render the component, use the build it forceUpdate method. This method overrides the shouldComponentUpdate method defined in the component but will consider the shouldComponentUpdate method defined in the children component.
component.forceUpdate(callback)
In this example, we will build a React application that gets forcibly re-rendered on a button click.
App.jsx
import React from 'react';

class App extends React.Component {

   update = () => {
      // calling the forceUpdate() method
      this.forceUpdate();
   };
   render() {
      console.log('Component is rendered');
      return (
         <>
            <h2>TutorialsPoint</h2>
            <button onClick={this.update}>Render</button>
         </>
      );
   }
}
export default App;
This will produce the following result.
Logging in Python

In this article, we will learn about logging in Python and various stages in protection and security.
First of all, we need to import the logging module, followed by using the logger to checj=k the current status and log messages. We are having 5 severity levels namely −
Warning
Info
Error
Critical
Debug
The logging module allows us to get started directly without setting up the configuration manually.
Import logging
logging.debug('a debug message')
logging.info('an info message')
logging.warning('a warning message')
logging.error('an error message')
logging.critical('a critical message')
WARNING:root: a warning message
ERROR:root: an error message
CRITICAL:root: a critical message
As we didn’t set the configurations, by default the logging and info messages aren’t logged. To make them noticeable we need to set the configuration manually.
Now let’s see how we can implement the basic configurations.
By the help of level parameter − we can set which level of log messages must be recorded.
Import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This gets logged')
DEBUG:root: This gets logged
By using this statement all statements above the debug level get recorded.
Now switching to file logging over console logging.
Import logging
logging.basicConfig(filename='app.log', filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This gets logged to a file')
root - ERROR - This gets logged to a file
Here the file mode is said to write only so we have rights to rewrite the contents of the file. By default this configuration it opens in append mode only.
In this article, we learnt about logging in Python and various levels of logging available to us.
C Program to reverse a given number using Recursive function

"Recursive function" is something which calls itself again in the body of the function.
For example,
A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N.
A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N.
fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1.
fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) =5* fact (4)
   =5*4*3* fact (3)
   =5*4*3*2* fact (2)
   =5*4*3*2*1 fact (1)
   =5*4*3*2*1
   = 120.
Following is the C program for use of recursive function to reverse a number −
#include<stdio.h>
main ( ){
   int n,f;
   int fact (int);
   clrscr ( );
   printf ("enter a number");
   scanf ("%d", &n);
   f= fact (n);
   printf (factorial value = %d",f);
}
int fact (int n){
   int f;
   if ( ( n==1) || (n==0))
      return 1;
   else
      f= n*fact (n-1);
   return f;
}
The output is given below −
Enter a number 5
Factorial value = 120
Given below is another C Program to reverse a given number using Recursive function −
#include<stdio.h>
int sum=0,rem;
int main(){
   int num,revNum;
   printf("enter number:\n");
   scanf("%d",&num);
   revNum=revNumFunction(num);//calling function to reverse the given number
   printf("the number after reverse :%d",revNum);
   return 0;
}
revNumFunction(int num){
   if(num){
      rem=num%10;
      sum=sum*10+rem;
      revNum(num/10);
   }
   else
      return sum;
}
The output is as follows −
enter number: 1357
the number after reverse is :7531
Tryit Editor v3.7

Tryit: HTML text-align
How can we merge two JSON arrays in Java?

A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can use org.json.simple.JSONArray class to merge two JSON arrays in Java.
We can merge two JSON arrays using the addAll() method (inherited from interface java.util.List) in the below program.
import org.json.simple.JSONArray;
import java.io.IOException;
public class MergeJSONArraysTest {
   public static void main(String[] args) throws IOException {
      JSONArray jsonArray1 = new JSONArray(); // first json array
      jsonArray1.add("Java");
      jsonArray1.add("Python");
      jsonArray1.add("Spark");
      JSONArray jsonArray2 = new JSONArray(); // second json array
      jsonArray2.add("Selenium");
      jsonArray2.add("ServiceNow");
      jsonArray1.addAll(jsonArray2); // merge two arrays using addAll() method
      System.out.println(jsonArray1);
   }
}
["Java","Python","Spark","Selenium","ServiceNow"]
Program to perform an Inorder Traversal of a binary tree in Python

Suppose we have a binary tree; we have to find a list that contains the inorder traversal of root as a list. As we know the inorder traversal is a way of traversing all nodes in a tree where we −
Recursively traverse the left subtree.
Recursively traverse the left subtree.
Traverse the current node.
Traverse the current node.
Recursively traverse the right subtree.
Recursively traverse the right subtree.
We have to try to solve this problem in iterative fashion.
So, if the input is like
then the output will be [12,13,4,16,7,14,22]
To solve this, we will follow these steps −
inorder := a new list
inorder := a new list
stack := an empty stack
stack := an empty stack
Do the following infinitely, doif root is not null, thenpush root into the stackroot := left of roototherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of roototherwise,come out from the loop
Do the following infinitely, do
if root is not null, thenpush root into the stackroot := left of root
if root is not null, then
push root into the stack
push root into the stack
root := left of root
root := left of root
otherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of root
otherwise when stack is not empty, then
root := top element of stack and pop from stack
root := top element of stack and pop from stack
insert value of root at the end of inorder
insert value of root at the end of inorder
root := right of root
root := right of root
otherwise,come out from the loop
otherwise,
come out from the loop
come out from the loop
return inorder
return inorder
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, value):
      self.val = value
      self.left = None
      self.right = None
class Solution:
   def solve(self, root):
      inorder = []
      stack = []
      while True:
         if root:
            stack.append(root)
            root = root.left
         elif stack:
            root = stack.pop()
            inorder.append(root.val)
            root = root.right
         else:
            break
      return inorder

ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root))
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
[12, 13, 4, 16, 7, 14, 22]
Get the number of columns in a MySQL table?

To get the number of columns, use the aggregate function count(*) with information_schema table from MySQL. The syntax is as follows to find the number of columns −
SELECT COUNT(*) as anyVariableName from INFORMATION_SCHEMA.COLUMNS where table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’;
To understand the above syntax, let us create a table with some columns. The following is the query to create a table −
mysql> create table CountColumns
−> (
   −> Bookid int,
   −> BookName varchar(200),
   −> BookAuthorName varchar(200),
   −> BookPublishedDate datetime
−> );
Query OK, 0 rows affected (0.69 sec)
Now, we have total 4 columns in my table ‘CountColumns’. You can apply the above syntax to count the number of columns. The query is as follows −
mysql> SELECT COUNT(*) as NumberofColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'business'
−> and table_name = 'CountColumns';
The output displays the count of columns −
+-----------------+
| NumberofColumns |
+-----------------+
| 4               |
+-----------------+
1 row in set (0.00 sec)
How to find the real user home directory using Python?

To get the homedir in python, you can use os.path.expanduser('~') from the os module. This also works if its a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. You can use it like −
import os
print(os.path.expanduser('~'))
You can also query the environment variables for the HOME variable −
import os
print(os.environ['HOME'])
If you're on Python 3.4+, you can also use pathlib module to get the home directory. 
from pathlib import Path
print(Path.home())
DAX Other - UNION function

Creates a union (join) table from the specified tables.
DAX UNION function is new in Excel 2016.
UNION (<table_expression1>, <table_expression2>, [<table_expression3>] ...) 

table_expression
Any DAX expression that returns a table.
A table that contains all the rows from each of the table expressions.
The tables must have the same number of columns.
The tables must have the same number of columns.
Columns are combined by the position in their respective tables.
Columns are combined by the position in their respective tables.
The column names in the return table will match the column names in table_expression1.
The column names in the return table will match the column names in table_expression1.
Duplicate rows are retained.
Duplicate rows are retained.
The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage.
The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage.
When data types differ, the resulting data type is determined based on the rules for data type coercion.
When data types differ, the resulting data type is determined based on the rules for data type coercion.
The returned table will not contain columns from related tables.
The returned table will not contain columns from related tables.
= SUMX (UNION (SalesOldData, SalesNewData), [Sales Amount]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to call a jQuery function after a certain delay?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.
You can try to run the following code to learn how to work with setTimeout() method in jQuery to call a jQuery function after a delay −
Live Demo
<!DOCTYPE html>
<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    $("#button1").bind("click",function() {
      setTimeout(function() {
        $('#list').fadeOut();}, 2000);
    });
  });
  </script>
</head>
<body>
  <input type="button" id="button1" value="Fade Out" />
  <br/>
  <br/>
  <div id="list">
   <ul>
     <li>Voice</li>  
     <li>Speak</li>
     <li>Write</li>
   </ul>
  </div>
  <p>The above content will fade out after 2 seconds</p>
</body>
</html>
How to invoke the IE browser in Selenium with python?

We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package.
For invoking the internet explorer browser, we have to select the Ie class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation.
Every internet explorer browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser.
Next we need to download the internet explorer driver version as per our browser version. The path of the IEDriverServer.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Ie(executable_path="C:\\IEDriverServer.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close()
Iterator vs ListIterator in Java?

An Iterator is an interface in Java and we can traverse the elements of a list in a forward direction whereas a ListIterator is an interface that extends the Iterator interface and we can traverse the elements in both forward and backward directions. An Iterator can be used in these collection types like List, Set, and Queue whereas ListIterator can be used in List collection only. The important methods of Iterator interface are hasNext(), next() and remove() whereas important methods of ListIterator interface are add(), hasNext(), hasPrevious() and remove().
public interface Iterator<E>
import java.util.*;
public class IteratorTest {
   public static void main(String[] args) {  
      List<String> listObject = new ArrayList<String>();
      listObject.add("India");
      listObject.add("Australia");
      listObject.add("England");
      listObject.add("Bangladesh");
      listObject.add("South Africa");
      Iterator it = listObject.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
India
Australia
England
Bangladesh
South Africa
public interface ListIterator<E> extends Iterator<E>
import java.util.*;
public class ListIteratorTest {
   public static void main(String[] args) {
      List<String> listObject = new ArrayList<String>();
      listObject.add("Java");
      listObject.add("Selenium");
      listObject.add("Python");
      listObject.add("Java Script");
      listObject.add("Cloud Computing");
      ListIterator it = listObject.listIterator();
      System.out.println("Iterating the elements in forward direction: ");
      while (it.hasNext()) {
         System.out.println(it.next());
      }
      System.out.println("--------------------------------------------");
      System.out.println("Iterating the elements in backward direction: ");
      while (it.hasPrevious()) {
         System.out.println(it.previous());
      }
   }
}
Iterating the elementrs in forward direction:
Java
Selenium
Python
Java Script
Cloud Computing
-----------------------------------------------
Iterating the elements in backward direction:
Cloud Computing
Java Script
Python
Selenium
Java
How to mount windows drives in Ubuntu

23 Dec, 2018
Figure: Error occurred while accessing the windows drive
Following are the step wise instructions to access windows drives in Ubuntu (Any Version),
1. Open terminal and type sudo ntfsfix error mounting location as shown in above picture and press enter button.2. It will ask for system password, enter password and again press enter.3. It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully.”4. Again click on windows drive, now you are allow to access clicked drive.
For Example:Step 1:
Type sudo ntfsfix /dev/sda3 and press enter as shown in below picture then it will ask for system password, enter password and again press enter.
Step 2:It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully”, as shown in below picture.
linux-command
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.show() in Python

11 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
Sample Code –
# sample codeimport matplotlib.pyplot as plt     plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() 
Output:
The show() function in pyplot module of matplotlib library is used to display all figures.
Syntax:
matplotlib.pyplot.show(*args, **kw)

Parameters: This method accepts only one parameter which is discussed below:
block : This parameter is used to override the blocking behavior described above.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.show() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  fig = plt.figure()x = np.arange(20) / 50y = (x + 0.1)*2  val1 = [True, False] * 10val2 = [False, True] * 10  plt.errorbar(x, y,              xerr = 0.1,              xlolims = True,              label ='Line 1')  y = (x + 0.3)*3  plt.errorbar(x + 0.6, y,              xerr = 0.1,             xuplims = val1,             xlolims = val2,             label ='Line 2')  y = (x + 0.6)*4plt.errorbar(x + 1.2, y,             xerr = 0.1,              xuplims = True,             label ='Line 3')  plt.legend()  fig.suptitle('matplotlib.pyplot.show() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  x = np.linspace(0, 10, 500)y = np.sin(x**2)+np.cos(x)  fig, ax = plt.subplots()  ax.plot(x, y, label ='Line 1')  ax.plot(x, y - 0.6, label ='Line 2')  ax.legend()  fig.suptitle('matplotlib.pyplot.show() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2013 | Question 33

11 Oct, 2021
Consider the DFA given.
Which of the following are FALSE?
1. Complement of L(A) is context-free.
2. L(A) = L((11*0+0)(0 + 1)*0*1*)
3. For the language accepted by A, A is the minimal DFA.
4. A accepts all strings over {0, 1} of length at least 2. 
(A) 1 and 3 only(B) 2 and 4 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (D)Explanation: 1 is true. L(A) is regular, its complement would also be regular. A regular language is also context free.
2 is true.
3 is false, the DFA can be minimized to two states. Where the second state is final state and we reach second state after a 0.
4 is clearly false as the DFA accepts a single 0.
GATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.6K subscribersGATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0032:02 / 44:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pHUoDvqVSag" 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-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.