code-rag-bench/online-tutorials huggingface dataset:
Python - assertGreaterEqual() function in unittest - GeeksforGeeks

24 Oct, 2020
assertGreaterEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition.
This function check that if the first given value is greater than or equal to the second value and returns true if it is so, else return false if the first value is not greater than or equal to the second value.
Syntax: assertGreaterEqual(first, second, message=None)
Parameters: assertGreaterEqual() accept three parameters which are listed below with explanation:
first: first input value (integer)
second:  second input value (integer)
message: a string sentence as a message which got displayed when the test case got failed.
Listed below is an example illustrating the positive and negative test case for a given assert function:
Example :
Python3
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):        # negative test function to test if values1 is greater or equal than value2    def test_negativeForGreaterEqual(self):        first = 4        second = 5                  # error message in case if test case got failed        message = "first value is not greater or equal than second value."                  # assert function() to check if values1 is greater or equal than value2        self.assertGreaterEqual(first, second, message)  if __name__ == '__main__':    unittest.main()
Output:
F======================================================================FAIL: test_negativeForGreaterEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last):File “p1.py”, line 13, in test_negativeForGreaterEqual  self.assertGreaterEqual(first, second, message)AssertionError: 4 not greater than or equal to 5 : first value is not greater or equal than second value.
———————————————————————-Ran 1 tests in 0.000s
FAILED (failures=1)
Example 2:
Python
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):      # positive test function to test if values1 is greater than or equal to value2    def test_positiveForGreaterEqual(self):        first = 4        second = 4                  # error message in case if test case got failed        message = "first value is not greater or equal than second value."                  # assert function() to check if values1 is greater or equal than value2        self.assertGreaterEqual(first, second, message)    if __name__ == '__main__':    unittest.main()
Output:
.———————————————————————-Ran 1 test in 0.000s
OK
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Difference Between Collection.stream().forEach() and Collection.forEach() in Java - GeeksforGeeks

02 Feb, 2021
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working.
Collection.stream().forEach() is basically used for iteration in a group of objects by converting a collection into the stream and then iterate over the stream of collection. While iterating over the collection, if any structural changes are made to collections, then it will throw the concurrent modification exception.
Collection.forEach() uses the collection’s iterator(whichever is specified). The majority of the collections do not allow modifications in the structure while iterating over that collection. If any changes happen to that collection, i.e. addition of an element or the removal of the element, then they will throw the concurrent modification error. If collection.forEach() is iterating over a synchronized collection, then they will lock the segment of collection and hold it over all the calls that can be made w.r.t to that collection.
  Collection.stream().forEach()
Below is a Java program to show the usage of the Collection.stream.forEach():
Java
// Java Program to show the demonstration of// Collection.stream().forEach()import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        List<Integer> list = new ArrayList<>();          list.add(5);        list.add(6);        list.add(3);        list.add(4);        // printing each element of list using forEach loop        list.stream().forEach(System.out::print);    }}
5634
Below is a Java program to show the usage of Collection.forEach() Method:
Java
// Java Program to show the demonstration of// Collection.forEach()import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        List<Integer> list = new ArrayList<>();          list.add(5);        list.add(6);        list.add(3);        list.add(4);        // printing each element of list        list.forEach(System.out::print);    }}
5634
Java-Collections
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Python | Merge two list of lists according to first element - GeeksforGeeks

20 May, 2019
Given two list of lists of equal length, write a Python program to merge the given two list of lists, according to the first common element of each sublist.
Examples:
Input : lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]
        lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]
Output : [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]

Input : lst1 = [ ['c', 'class'], ['g', 'greek'], ]
        lst2 = [['c', 'coder'], ['g', 'god'], ]
Output : [['c', 'class', 'coder'], ['g', 'greek', 'god']]

 Method #1 : Python zip() with list comprehension
# Python3 program to Merge two list of # lists according to first element  def merge(lst1, lst2):    return [a + [b[1]] for (a, b) in zip(lst1, lst2)]      # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]

 Method #2 : Python enumerate() with list comprehension
# Python3 program to Merge two list of # lists according to first elementimport collections  def merge(lst1, lst2):    return [(sub + [lst2[i][-1]]) for i, sub in enumerate(lst1)]      # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]

 Method #3 : Python dictionaryIn this method, we initialise ‘dict1’ with collections.defaultdict and traverse through ‘lst1’+’lst2’ and append the first element of ‘lst1’ as key and tupled second element of both respective sublists as value. Finally we traverse through ‘dict1’ and initialize ‘dictlist’ with the desired output.
# Python3 program to Merge two list of # lists according to first elementimport collections  def merge(lst1, lst2):    dict1 = collections.defaultdict(list)          for e in lst1 + lst2:        dict1[e[0]].append(e[1])    dictlist = list()          for key, value in dict1.items():        dictlist.append([key]+value)          return dictlist      # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python - Append Multiple elements in set - GeeksforGeeks

02 Feb, 2021
In this article given a set and list of elements, the task is to write a Python program to append multiple elements in set at once.
Example:
Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]
Output : {1, 2, 4, 5, 6, 7, 9, 10}
Explanation : All elements are updated and reordered. (5 at 3rd position).
Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 8]
Output : {1, 2, 4, 5, 6, 7, 8, 9, 10}
Explanation : All elements are updated and reordered. (8 at 7th position).
Method #1 : Using update()
In this, we use in built update() to get all the elements in list aligned with the existing set.
Python3
# Python3 code to demonstrate working of# Append Multiple elements in set# Using update()  # initializing settest_set = {6, 4, 2, 7, 9}  # printing original setprint("The original set is : " + str(test_set))  # initializing adding elementsup_ele = [1, 5, 10]  # update() appends element in set# internally reorderstest_set.update(up_ele)  # printing resultprint("Set after adding elements : " + str(test_set))
Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Method #2 : Using | operator ( Pipe operator )
The pipe operator internally calls union(), which can be used to perform task of updating set with newer elements. 
Python3
# Python3 code to demonstrate working of# Append Multiple elements in set# Using | operator ( Pipe operator )  # initializing settest_set = {6, 4, 2, 7, 9}  # printing original setprint("The original set is : " + str(test_set))  # initializing adding elementsup_ele = [1, 5, 10]  # | performing task of updatingtest_set |= set(up_ele)  # printing resultprint("Set after adding elements : " + str(test_set))
Output:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to convert the content of the file into uppercase or lowercase?

To convert the content of the file into the upper case, you need to use the method ToUpper() and to convert into lower case, you need to use ToLower() method.
(Get-Content D:\Temp\PowerShellaliases.txt).ToUpper()
PS C:\WINDOWS\system32> (Get-Content D:\Temp\PowerShellaliases.txt).ToUpper()
COMMANDTYPE     NAME                                               VERSION    SOURCE
-----------     ----                                               -------    ------
ALIAS           % -> FOREACH-OBJECT
ALIAS           ? -> WHERE-OBJECT
ALIAS           AC -> ADD-CONTENT
ALIAS           ASNP -> ADD-PSSNAPIN
ALIAS           CAT -> GET-CONTENT
ALIAS           CD -> SET-LOCATION
ALIAS           CFS -> CONVERTFROM-STRING                          3.1.0.0    MICROSOFT.POWERSHELL.UTILITY
ALIAS           CHDIR -> SET-LOCATION
ALIAS           CLC -> CLEAR-CONTENT
ALIAS           CLEAR -> CLEAR-HOST
ALIAS           CLHY -> CLEAR-HISTORY
ALIAS           CLI -> CLEAR-ITEM
ALIAS           CLP -> CLEAR-ITEMPROPERTY
ALIAS           CLS -> CLEAR-HOST
(Get-Content D:\Temp\PowerShellaliases.txt).ToLower()
PS C:\WINDOWS\system32> (Get-Content D:\Temp\PowerShellaliases.txt).ToLower()
commandtype     name                                               version
-----------     ----                                               -------
alias           % -> foreach-object
alias           ? -> where-object
alias           ac -> add-content
alias           asnp -> add-pssnapin
alias           cat -> get-content
alias           cd -> set-location
alias           cfs -> convertfrom-string                          3.1.0.0
alias           chdir -> set-location
alias           clc -> clear-content
alias           clear -> clear-host
alias           clhy -> clear-history
alias           cli -> clear-item
alias           clp -> clear-itemproperty
alias           cls -> clear-host
alias           clv -> clear-variable
alias           cnsn -> connect-pssession
alias           compare -> compare-object
alias           copy -> copy-item
alias           cp -> copy-item
alias           cpi -> copy-item
alias           cpp -> copy-itemproperty
alias           curl -> invoke-webrequest
alias           cvpa -> convert-path
alias           dbp -> disable-psbreakpoint
alias           del -> remove-item
alias           diff -> compare-object
alias           dir -> get-childitem
Strictly increasing sequence JavaScript

Given a sequence of integers as an array, we have to determine whether it is possible to obtain
a strictly increasing sequence by removing no more than one element from the array.
For example −
For sequence = [1, 3, 2, 1], the output should be function(sequence) = false. There is no one
element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2], the output should be function(sequence) = true. You can remove 3
from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get
the strictly increasing sequence [1, 3].
It is a mathematical term that represents an arrangement of numbers where every succeeding
number is greater than its preceding number. Other than this there exists increasing sequence
where the succeeding element is greater than or equal to the preceding element.
The same logic applies for decreasing sequence and strictly decreasing sequence.
We will loop over the array checking whether the succeeding element is greater than preceding
element or not. If it’s greater, then it’s fine with us, but if it is not greater (remember it has to be
greater and not greater or equal because we want to form a strictly increasing sequence.) we
will keep a count of unwantedElements and increase it by 1 every time this happens.
If during iteration, the count exceeds 1, we return false then and there otherwise if we go
through the whole with unwantedElements <= 1, we return true.
Therefore, let’s write the code for this function −
const isStrictlyIncreasing = (arr) => {
   let unwantedElements = 0;
   for(let i = 0; i < arr.length - 1; i++){
      if(arr[i] >= arr[i+1]){
         unwantedElements++;
         if(unwantedElements > 1){
            return false;
         };
      };
   };
   return true;
};
console.log(isStrictlyIncreasing([1, 3, 2, 1]));
console.log(isStrictlyIncreasing([1, 3, 2]));
The output in the console will be −
false
true
Different Methods to find Prime Number in Python

First we need to know what a prime number is.
A prime number always a positive integer number and divisible by exactly 2 integers (1 and the number itself), 1 is not a prime number.
Now we shall discuss some methods to find Prime Number.
Using For loops
Example
def primemethod1(number):
   # Initialize a list
   my_primes = []
   for pr in range(2, number):
      isPrime = True
   for i in range(2, pr):
   if pr % i == 0:
      isPrime = False
   if isPrime:
      my_primes.append(pr)
   print(my_primes)
primemethod1(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
For Loops with Break
Example
def primemethod2(number):
   # Initialize a list
   my_primes = []
   for pr in range(2, number + 1):
      isPrime = True
   for num in range(2, pr):
   if pr % num == 0:
      isPrime = False
   break
      if isPrime:
   my_primes.append(pr)
return(my_primes)
print(primemethod2(50))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
For Loop, Break, and Square Root
Example
def primemethod3(number):
   # Initialize a list
   primes = []
   for pr in range(2, number):
      isPrime = True
   for num in range(2, int(pr ** 0.5) + 1):
   if pr % num == 0:
      isPrime = False
      break
   if (isPrime):
print("Prime number: ",pr)
primemethod3(50)
Prime number: 2
Prime number: 3
Prime number: 5
Prime number: 7
Prime number: 11
Prime number: 13
Prime number: 17
Prime number: 19
Prime number: 23
Prime number: 29
Prime number: 31
Prime number: 37
Prime number: 41
Prime number: 43
Prime number: 47
Manual compression of a table in SAP HANA

It is also possible to compress a table in SAP HANA system manually by executing the following SQL statement.
UPDATE "table_name" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'YES')
This results in deciding whether a compression is required or an existing compression can be optimized. In this scenario, HANA system uses most suitable compression algorithm.
When you run the above SQL command, compression status remains the same. You can also force the database to reevaluate compression using the following SQL status 
UPDATE "AA_HANA11"."SHOP_FACTS" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'FORCE')
How to get a value from the cell of a Pandas DataFrame?

To get a value from the cell of a DataFrame, we can use the index and col variables.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Print the input DataFrame, df.
Initialize the index variable.
Initialize the index variable.
Initialize the col variable.
Initialize the col variable.
Get the cell value corresponding to index and col variable.
Get the cell value corresponding to index and col variable.
Print the cell value.
Print the cell value.
 Live Demo
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print("Input DataFrame is:\n", df)

index = 2
col = "y"
cell_val = df.iloc[index][col]
print "Cell value at ", index, "for column ", col, " : ", cell_val

index = 0
col = "x"
cell_val = df.iloc[index][col]
print "Cell value at ", index, "for column ", col, " : ", cell_val

index = 1
col = "z"
cell_val = df.iloc[index][col]
print "Cell value at ", index, "for column ", col, " : ", cell_val
Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

Cell value at 2 for column y: 5
Cell value at 0 for column x: 5
Cell value at 1 for column z: 1
Python | Group tuples in list with same first value - GeeksforGeeks

08 Apr, 2019
Given a list of tuples, the task is to print another list containing tuple of same first element. Below are some ways to achieve above tasks.
Example:
Input : [('x', 'y'), ('x', 'z'), ('w', 't')]

Output: [('w', 't'), ('x', 'y', 'z')]

Method #1: Using extend
# Python code to find common # first element in list of tuple  # Function to solve the taskdef find(Input):    out = {}    for elem in Input:        try:            out[elem[0]].extend(elem[1:])        except KeyError:            out[elem[0]] = list(elem)    return [tuple(values) for values in out.values()]  # List initializationInput = [('x', 'y'), ('x', 'z'), ('w', 't')]  # Calling functionOutput = (find(Input))  # Printingprint("Initial list of tuple is :", Input)print("List showing common first element", Output)
Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')]
List showing common first element [('w', 't'), ('x', 'y', 'z')]

 
Method #2: Using defaultdict
# Python code to find common first# element in list of tuple  # Importingfrom collections import defaultdict  # Function to solve the taskdef find(pairs):    mapp = defaultdict(list)    for x, y in pairs:        mapp[x].append(y)    return [(x, *y) for x, y in mapp.items()]  # Input list initializationInput = [('p', 'q'), ('p', 'r'),         ('p', 's'), ('m', 't')]  # calling functionOutput = find(Input)  # Printingprint("Initial list of tuple is :", Input)print("List showing common first element", Output)
Initial list of tuple is : [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')]
List showing common first element [('m', 't'), ('p', 'q', 'r', 's')]

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to make Matplotlib show all X coordinates?

To show all X coordinates (or Y coordinates), we can use xticks() method (or yticks()).
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Set x=0 and y=0 margins on the axes.
Set x=0 and y=0 margins on the axes.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
Use xticks() method to show all the X-coordinates in the plot.
Use xticks() method to show all the X-coordinates in the plot.
Use yticks() method to show all the Y-coordinates in the plot.
Use yticks() method to show all the Y-coordinates in the plot.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(0, 10, 1)
y =np.arange(0, 10, 1)
plt.margins(x=0, y=0)
plt.plot(x, y)
plt.xticks(x)
plt.yticks(y)
plt.show()
Find value in a MongoDB Array with multiple criteria?

To find value in the array with multiple criteria, for example, you can use elemMatchalongwithgt and $lt. The syntax is as follows −
db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPo sitiveValue}}}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Larry","StudentMarks":[-150,150]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77daf6fc4e719b197a12f5")
}
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Mike","StudentMarks":[19]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77db09fc4e719b197a12f6")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findValueInArrayWithMultipleCriteriaDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c77daf6fc4e719b197a12f5"),
   "StudentName" : "Larry",
   "StudentMarks" : [
      -150,
      150
   ]
}
{
   "_id" : ObjectId("5c77db09fc4e719b197a12f6"),
   "StudentName" : "Mike",
   "StudentMarks" : [
      19
   ]
}
Here is the query to find value in the array with multiple criteria. For example, here we are considering marks greater than -20 and less than 20 −
> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c77db09fc4e719b197a12f6"),
   "StudentName" : "Mike",
   "StudentMarks" : [
      19
   ]
}
Create many JavaScript objects as the same type?

It is very easy to create a single object than to create multiple objects of the same type. To breach this hurdle, javascript has provided object constructor function. Using this function, initially, we have to create the type of the object and later on, we need to declare the properties of the object.
In the following example, initially, we have declared the type of object that contains the "name", "property", "age", and "designation". Later on, using that type we have created two objects and the corresponding properties were displayed in the output based on our requirement.
Live Demo
<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   var person1 = new Business("Trump", "$28.8b", "73", "President");
   var person2 = new Business("Jackma", "$35.6b", "54", "entrepeneur");
   document.write(
      "My inpiration is " + person1.Name + " and i want to be an " + person2.designation + ".");
</script>
</body>
</html>
My inpiration is Trump and i want to be an entrepeneur.
Sorting string in reverse order in JavaScript

We are required to write a JavaScript function that takes in a lowercase string and sorts it in the reverse order i.e., b should come before a, c before b and so on.
For example: If the input string is −
const str = "hello";
Then the output should be −
const output = "ollhe";
Following is the code −
const string = 'hello';
const sorter = (a, b) => {
   const legend = [-1, 0, 1];
   return legend[+(a < b)];
}
const reverseSort = str => {
   const strArr = str.split("");
   return strArr
   .sort(sorter)
   .join("");
};
console.log(reverseSort(string));
Following is the output in the console −
ollhe
C# Enum GetName Method

The GetName() method returns the names of the constants in the Enumeration.
Here is the enum.
enum Stock { Appliance, Clothing, Footwear };
Now, get the names using the Enum.GetName() method. Just set the constant and retrieve the individual name.
Enum.GetName(typeof(Stock), 1
Let us see the example now.
 Live Demo
using System;
class Demo {
   enum Stock { Appliance, Clothing, Footwear };
   static void Main() {
      Console.WriteLine("The value of second stock category = {0}",Enum.GetName(typeof(Stock), 1));
      Console.WriteLine("The value of third stock category = {0}",Enum.GetName(typeof(Stock), 2));
   }
}
The value of second stock category = Clothing
The value of third stock category = Footwear
Batch Script - SYSTEMINFO

This batch command shows configuration of a computer and its operating system.
systeminfo

@echo off
systeminfo
The above command will show the system information on the current system. Following is a subset of the output.
Host Name:                WIN-50GP30FGO75 
OS Name:                  Microsoft Windows Server 2012 R2 Standard 
OS Version:               6.3.9600 N/A Build 9600
OS Manufacturer:          Microsoft Corporation 
OS Configuration:         Standalone Server 
OS Build Type:            Multiprocessor Free 
Registered Owner:         Windows User 
Registered Organization:  
Product ID:               00252-70000-00000-AA535 
Original Install Date:    12/13/2015, 12:10:16 AM 
System Boot Time:         12/28/2015, 4:43:04 PM 
System Manufacturer:      LENOVO 
System Model:             20287 
System Type:              x64-based PC

 Print
 Add Notes
 Bookmark this page
How to Verify Tooltip using Selenium WebDriver?

We can verify the tooltip of an element using Selenium webdriver using the getAttribute method. A tooltip text is the one which gets displayed while we hover on that element.
It disappears once we move the mouse away from the element. A tooltip text generally displays the title attribute value of an element. First, we identify the element then apply the getAttribute method on it. The parameter to be passed to this method is title.
Let us investigate the html code of an element - Tools having a tooltip text.
Here, the tooltip text displayed from Tools menu is Tools - Online Development and Testing Tools which is the value set for the title attribute in the html.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class TooltipVerfy{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      WebElement n = driver.findElement(By.linkText("Tools"));

      //obtain title attribute
      String s = n.getAttribute("title");
      //verify tooltip text

      if(s.equals("Tools - Online Development and Testing Tools")) {
         System.out.println("Tooltip text matched");
      }else{
         System.out.println("Tooltip text not matched");
      }
      driver.quit();
   }
}
C++ Program to Implement Segmented Sieve to Generate Prime Numbers Between Given Range

This is C++ program to implement Segmented Sieve to Generate Prime Numbers Between Given Range. Segmented Sieve first uses Simple Sieve to find primes smaller than or equal to √(n). The idea of this algorithm is to divide the range [0 ... n-1] in different segments and compute primes in all segments one by one.
Begin
   Create function to find all primes smaller than limit
   using simple sieve of eratosthenes.
   Finds all prime numbers in given range using
   segmented sieve
   A) Compute all primes smaller or equal to square root of high using simple sieve
   B) Count of elements in given range
   C) Declaring boolean only for [low, high]
   D) Find the minimum number in [low ... high] that is a multiple of prime[i] (divisible by prime[i])
   E) Mark multiples of prime[i] in [low ... high]
   F) Numbers which are not marked in range, are prime
End
#include <bits/stdc++.h>
using namespace std;
void simpleSieve(int lmt, vector<int>& prime) {
   bool mark[lmt + 1];
   memset(mark, false, sizeof(mark));
   for (int i = 2; i <= lmt; ++i) {
      if (mark[i] == false) {
         prime.push_back(i);
         for (int j = i; j <= lmt; j += i)
            mark[j] = true;
      }
   }
}
void PrimeInRange(int low, int high) {
   int lmt = floor(sqrt(high)) + 1;
   vector<int> prime;
   simpleSieve(lmt, prime);
   int n = high - low + 1;
   bool mark[n + 1];
   memset(mark, false, sizeof(mark));
   for (int i = 0; i < prime.size(); i++) {
      int lowLim = floor(low / prime[i]) * prime[i];
      if (lowLim < low)
         lowLim += prime[i];
      for (int j = lowLim; j <= high; j += prime[i])
         mark[j - low] = true;
   }
   for (int i = low; i <= high; i++)
      if (!mark[i - low])
         cout << i << " ";
}
int main() {
   int low = 10, high = 50;
   PrimeInRange(low, high);
   return 0;
}
11 13 17 19 23 29 31 37 41 43 47
MySQL Tryit Editor v1.0

SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
The debugger statement in JavaScript

The debugger statement in JavaScript is used for setting a breakpoint in the code. The code
stops execution as soon as it encounters the debugger statement and calls the debugger function (if available).
Following is the code to implement debugger statement in 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>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Debugger statement in JavaScript.</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the printTable() function</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function printTable(num) {
      for (let i = 1; i <= 10; i++) {
         debugger;
         resEle.innerHTML += i + " ";
      }
   }
   BtnEle.addEventListener("click", () => {
      printTable();
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button and opening the debugger −
Arithmetic Operators in VBScript

Following table shows all the arithmetic operators supported by VBScript language. Assume variable A holds 5 and variable B holds 10, then −
Try the following example to understand all the arithmetic operators available in VBScript −
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a : a = 5
         Dim b : b = 10
         Dim c

         c = a+b
         Document.write ("Addition Result is " &c)
         Document.write ("<br></br>")    'Inserting a Line Break for readability
         
         c = a-b
         Document.write ("Subtraction Result is " &c)
         Document.write ("<br></br>")   'Inserting a Line Break for readability
         
         c = a*b
         Document.write ("Multiplication Result is " &c)
         Document.write ("<br></br>")
         
         c = b/a
         Document.write ("Division Result is " &c)
         Document.write ("<br></br>")
         
         c = b MOD a
         Document.write ("Modulus Result is " &c)
         Document.write ("<br></br>")
         
         c = b^a
         Document.write ("Exponentiation Result is " &c)
         Document.write ("<br></br>")
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Addition Result is 15

Subtraction Result is -5

Multiplication Result is 50

Division Result is 2

Modulus Result is 0

Exponentiation Result is 100000


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) in C++

In this problem, we are given a number n which defines the nth term of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n). Our task is to create a program to find the sum of the series.
Input 
n = 3
Output
Explanation − sum = (2) + (2+4) + (2+4+6) = 2 + 6 + 12 = 20
A simple solution to the problem is to use a nested loop. The inner loop finds the ith element of the series and then add up all elements to the sum variable.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
   int sum = 0;
   for (int i = 1; i<=n; i++) {
      int even = 2;
      for (int j = 1; j<=i; j++) {
         sum += even;
         even += 2;
      }
   }
   return sum;
}
int main() {
   int n = 5;
   cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70
This is not the most effective way to solve the problem as the time complexity of the problem is of the order O(n2).
An effective solution to the problem is by using the mathematical formula for the sum of the series.
The series is 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)
The nth term of the series is
an = (2 + 4 + 6 + 8 + ... + 2n) = (n*n) + n
an is the sum of even numbers upto n.
The sum of the series is
sum = 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)
sum = ∑ (n2 + n)
sum = ∑ n2 + ∑ n
sum = [ (n*(n+1)*(2n + 1))/6 ] + [ (n*(n+1))/2 ]
sum = 1⁄2 (n*(n+1)) [(2n + 1)/3 + 1]
sum = 1⁄2 (n*(n+1)) [(2n + 1 + 3)/3]
sum = 1⁄2 (n*(n+1)) [2(n+2)/3]
sum = 1⁄3 n*(n+1)(n+2)
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
   return ((n)*(n+1)*(n+2)/3);
}
int main() {
   int n = 5;
   cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70
What's the difference between "update" and "update_idletasks" in Tkinter?

Update method processes all the pending idle tasks, unvisited events, calling functions, and callbacks. The method is applicable for updating and processing all the events or tasks such as redrawing widgets, geometry management, configuring the widget property, etc.
It also ensures that if the application has any pending tasks, then it will just update or refresh the value that affects the whole part of the application. Using update for a single pending task would be nasty, thus Tkinter also provides the update_idletasks() method. It only updates the idle pending task that is stable or not updating in the application for some reason. It calls all the events that are pending without processing any other events or callback.
The update() and update_idletask() methods are useful for processing any pending or idle tasks. However, the only difference between update() and update_idletasks() is that update() processes all the events present in the application, while update_idletasks() only processes those events which are not running or stable.
We can understand the use and application of update_idletasks() method through this example.
# Import the tkinter library
from tkinter import *
from tkinter import ttk
import time

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

# Set the size of the Tkinter window
win.geometry("700x350")
def add_Text():
   for i in range(10):
      label.config(text= "The loops starts from 1 to "+ str(i))
      # Wait for two seconds
      win.update_idletasks()
      time.sleep(2)
      label.config(text= i)

# Add a label text
label= Label(win, text="Original Text", font= ('Aerial 16'))
label.pack(pady= 30)

# Add a button to update the Label text
ttk.Button(win, text="Change Text", command= add_Text).pack(pady= 40)
win.mainloop()
Running the above code will display a window with a Label widget and a button.
When we press the button, the Label widget gets updated automatically in the given range of the loop.
How to draw a circle in OpenCV using C++?

A circle has a center and a radius. To draw a circle using OpenCV, we have to define the center and the radius. In OpenCV we have to include <imgproc.hpp> header because 'circle()' function is defined in this header.
The basic syntax of this method is as follows −
circle(whiteMatrix, center,radius, line_Color, thickness);
The following program represents how to draw a circle in OpenCV.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix
   Point center(100, 100);//Declaring the center point
   int radius = 50; //Declaring the radius
   Scalar line_Color(0, 0, 0);//Color of the circle
   int thickness = 2;//thickens of the line
   namedWindow("whiteMatrix");//Declaring a window to show the circle
   circle(whiteMatrix, center,radius, line_Color, thickness);//Using circle()function to draw the line//
   imshow("WhiteMatrix", whiteMatrix);//Showing the circle//
   waitKey(0);//Waiting for Keystroke//
   return 0;
}
Python - Find the length of the last word in a string

When it is required to find the length of the last word in a string, a method is defined that removes the extra empty spaces in a string, and iterates through the string. It iterates until the last word has been found. Then, its length is found and returned as output.
Below is a demonstration of the same
def last_word_length(my_string):
   init_val = 0

   processed_str = my_string.strip()

   for i in range(len(processed_str)):
      if processed_str[i] == " ":
         init_val = 0
      else:
         init_val += 1
   return init_val

my_input = "Hi how are you Will"
print("The string is :")
print(my_input)
print("The length of the last word is :")
print(last_word_length(my_input))
The string is :
Hi how are you Will
The length of the last word is :
4
A method named ‘last_word_length’ is defined that takes a string as a parameter.
A method named ‘last_word_length’ is defined that takes a string as a parameter.
It initializes a value to 0.
It initializes a value to 0.
The string is stripped of extra spaces, and is iterated over.
The string is stripped of extra spaces, and is iterated over.
When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1.
When an empty space is encountered, the value is kept as 0, otherwise it is incremented by 1.
Outside the method, a string is defined and is displayed on the console.
Outside the method, a string is defined and is displayed on the console.
The method is called by passing this string as a parameter.
The method is called by passing this string as a parameter.
The output is displayed on the console.
The output is displayed on the console.
Accessibility in React.js

The aria-* attributes on html elements are also supported in React.js as well. The other attributes are generally written in camel-case but these aria-* are written in hyphen-cased.
<input
   type = "text"
   aria-label = {labelText}
   aria-required = "true"
   onChange = {changeHandler}
   value = {inputValue}
   name = "userInput"
/>
Sometimes we break the semantics of the html if we use parent div in React.js
render(){
   return(
      <div>
         <h1>Test</h1>
      </div>
   );
}
Div can cause semantics issue if working with table, list etc. To avoid this we can use React provided fragment as shown below −
import React, { Fragment } from ‘react’;
function MessageList({ message }) {
   return (
      <Fragment>
         <dt>{ message.key }</dt>
         <dd>{message.description}</dd>
      </Fragment>
   );
}
We can also use it with map a collection of items to an array of fragments −
function MessageList(props) {
   return (
      <dl>
         {props.messages.map( message => (
            // Fragments should also have a `key` prop when mapping collections
            <Fragment key = { message.id}>
               <dt>{message.from}</dt>
               <dd>{message.To}</dd>
            </Fragment>
         ))}
      </dl>
   );
}
The short syntax of fragment is writing just >>
import React, { Fragment } from ‘react’;
function MessageList({ message }) {
   return (
      <>
         <dt>{ message.key }</dt>
         <dd>{message.description}</dd>
      </>
   );
}
Instead of writing for attribute in label, we write it as htmlFor
<label htmlFor = "userID">Name:</label>
<input id = "userID" type = "text" name = "name"/>
Focus control with ref −
We can create ref as −
This.userInput = React.createRef();
getFocus() {
   // Explicitly focus the text input using the raw DOM API
   // Note: we're accessing "current" to get the DOM node
   this.userInput.current.focus();
}
To work the ref through the higher order components, its needed to use forward ref.
Java program to count upper and lower case characters in a given string

In order to count upper and lower case character we have to first find weather a given character is in upper case or in lower case.For this we would take concept of ASCII value of each character in Java.
In Java as we know for each character has corresponding ASCII value so we would compare each character that it lies in the range of upper case or in lower case.In below example first convert string to a character array for easy transverse,then find weather it lies in upper case or lower case range also setted counter for upper case and lower case which get increased as character lies accordingly.
 Live Demo
public class CountUpperLower {
   public static void main(String[] args) {
      String str1 = "AbRtt";
      int upperCase = 0;
      int lowerCase = 0;
      char[] ch = str1.toCharArray();
      for(char chh : ch) {
         if(chh >='A' && chh <='Z') {
            upperCase++;
         } else if (chh >= 'a' && chh <= 'z') {
            lowerCase++;
         } else {
            continue;
         }
      }
      System.out.println("Count of Uppercase letter/s is/are " + upperCase + " and of Lowercase       letter/s is/are " + lowerCase);
   }
}
Count of Uppercase letter/s is/are 2 and of Lowercase letter/s is/are 3
What is COBOL host variable equivalent for various DB2 data types?

Problem: How will the COBOL-DB2 program behave when there is a mismatch between the host variable and number of columns in the SELECT statement?
In case there is a mismatch in the number of columns and number of host variables, the query will fail. For example, if we have used the below query in a COBOL-DB2 program which processes the ORDERS DB2 table.
EXEC SQL
   SELECT ORDER_ID,
      ORDER_AMOUNT,
      ORDER_DATE,
      ORDER_STATUS
   INTO :WS-ORDER-ID,
      :WS-ORDER-AMOUNT,
      :WS-ORDER-DATE,
   FROM ORDERS WHERE ORDER_DATE = ‘2020-09-15’
END-EXEC
There is a mismatch in the number of columns and host variables. There are a total 4 columns used in the SELECT statement and for them only 3 host variables are used. In this case the query will fail and there are two ways in which we can detect this condition.
The SQLWARN3 field of SQLCA will get the value as ‘W’ in case there is a mismatch.
In some installations the SQLCODE field for SQLCA gets the error code as -804 when there is a mismatch.
We can use IF condition to check the value in SQLWARN3 or SQLCODE and direct the program processing accordingly.
Following is an example.
IF SQLWARN3 = ‘W’
   PERFORM X00-ABEND-SECTION
ELSE
   PERFORM A100-SELECT-RESULT
END-IF