code-rag-bench/online-tutorials huggingface dataset:
JavaScript - Array unshift() Method

Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Its syntax is as follows −
array.unshift( element1, ..., elementN );

element1, ..., elementN − The elements to add to the front of the array.
Returns the length of the new array. It returns undefined in IE browser.
Try the following example.
<html>
   <head>
      <title>JavaScript Array unshift Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var arr = new Array("orange", "mango", "banana", "sugar");         
         var length = arr.unshift("water");
         document.write("Returned array is : " + arr );
         document.write("<br /> Length of the array is : " + length );
      </script>      
   </body>
</html>
Returned array is : water,orange,mango,banana,sugar
Length of the array is : 5 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to Find the Power of a Number Using Recursion in Python?

Following program accepts a number and index from user. The recursive funcion rpower() uses these two as arguments. The function multiplies the number repeatedly and recursively to return power.
def rpower(num,idx):
    if(idx==1):
       return(num)
    else:
       return(num*rpower(num,idx-1))
base=int(input("Enter number: "))
exp=int(input("Enter index: "))
rpow=rpower(base,exp)
print("{} raised to {}: {}".format(base,exp,rpow))
Here is a sample run −
Enter number: 10
Enter index: 3
10 raised to 3: 1000
Understanding RSA Algorithm

RSA algorithm is a public key encryption technique and is considered as the most secure way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence name RSA algorithm.
The RSA algorithm holds the following features −
RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.
RSA algorithm is a popular exponentiation in a finite field over integers including prime numbers.
The integers used by this method are sufficiently large making it difficult to solve.
The integers used by this method are sufficiently large making it difficult to solve.
There are two sets of keys in this algorithm: private key and public key.
There are two sets of keys in this algorithm: private key and public key.
You will have to go through the following steps to work on RSA algorithm −
The initial procedure begins with selection of two prime numbers namely p and q, and then calculating their product N, as shown −
N=p*q

Here, let N be the specified large number.
Consider number e as a derived number which should be greater than 1 and less than (p-1) and (q-1). The primary condition will be that there should be no common factor of (p-1) and (q-1) except 1
The specified pair of numbers n and e forms the RSA public key and it is made public.
Private Key d is calculated from the numbers p, q and e. The mathematical relationship between the numbers is as follows −
ed = 1 mod (p-1) (q-1)

The above formula is the basic formula for Extended Euclidean Algorithm, which takes p and q as the input parameters.
Consider a sender who sends the plain text message to someone whose public key is (n,e). To encrypt the plain text message in the given scenario, use the following syntax −
C = Pe mod n

The decryption process is very straightforward and includes analytics for calculation in a systematic approach. Considering receiver C has the private key d, the result modulus will be calculated as −
Plaintext = Cd mod n


    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Using CountVectorizer to Extracting Features from Text

07 Jul, 2022
CountVectorizer is a great tool provided by the scikit-learn library in Python. It is used to transform a given text into a vector on the basis of the frequency (count) of each word that occurs in the entire text. This is helpful when we have multiple such texts, and we wish to convert each word in each text into vectors (for using in further text analysis). Let us consider a few sample texts from a document (each as a list element):
document = [ “One Geek helps Two Geeks”, “Two Geeks help Four Geeks”, “Each Geek helps many other Geeks at GeeksforGeeks.”]
CountVectorizer creates a matrix in which each unique word is represented by a column of the matrix, and each text sample from the document is a row in the matrix. The value of each cell is nothing but the count of the word in that particular text sample.  This can be visualized as follows –
Key Observations:
There are 12 unique words in the document, represented as columns of the table.There are 3 text samples in the document, each represented as rows of the table.Every cell contains a number, that represents the count of the word in that particular text.All words have been converted to lowercase.The words in columns have been arranged alphabetically.
There are 12 unique words in the document, represented as columns of the table.
There are 3 text samples in the document, each represented as rows of the table.
Every cell contains a number, that represents the count of the word in that particular text.
All words have been converted to lowercase.
The words in columns have been arranged alphabetically.
Inside CountVectorizer, these words are not stored as strings. Rather, they are given a particular index value. In this case, ‘at’ would have index 0, ‘each’ would have index 1, ‘four’ would have index 2 and so on. The actual representation has been shown in the table below –
A Sparse Matrix
This way of representation is known as a Sparse Matrix. Code: Python implementation of CountVectorizer 
python3
from sklearn.feature_extraction.text import CountVectorizer document = ["One Geek helps Two Geeks",            "Two Geeks help Four Geeks",            "Each Geek helps many other Geeks at GeeksforGeeks"] # Create a Vectorizer Objectvectorizer = CountVectorizer() vectorizer.fit(document) # Printing the identified Unique words along with their indicesprint("Vocabulary: ", vectorizer.vocabulary_) # Encode the Documentvector = vectorizer.transform(document) # Summarizing the Encoded Textsprint("Encoded Document is:")print(vector.toarray())
Output:
Vocabulary:  {'one': 9, 'geek': 3, 'helps': 7, 'two': 11, 'geeks': 4, 'help': 6, 'four': 2, 'each': 1, 'many': 8, 'other': 10, 'at': 0, 'geeksforgeeks': 5}

Encoded Document is:

[ [0 0 0 1 1 0 0 1 0 1 0 1]

  [0 0 1 0 2 0 1 0 0 0 0 1]

  [1 1 0 1 1 1 0 1 1 0 1 0] ]
mrdedhia
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Tweepy – Getting the ID of a status

18 Jun, 2020
In this article we will see how we can get the ID of a status. Each status or tweet has a unique ID. The id attribute of the Status object provides us with the ID of the status/tweet.
Identifying the ID in the GUI :
In the above mentioned status, the ID can be found in the URL, the ID here is : 1271031982189879297
In order to get the ID of a status, we have to do the following :
Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the id attribute present in it.
Identify the status ID of the status from the GUI.
Get the Status object of the status using the get_status() method with the status ID.
From this object, fetch the id attribute present in it.
Example 1 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the statusid = 1272771459249844224  # fetching the statusstatus = api.get_status(id)  # fetching the id attributeid = status.id   print("The ID of the status is : " + str(id))
Output :
The ID of the status is : 1272771459249844224

Example 2 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905.
# the ID of the statusid = 1272479136133627905  # fetching the statusstatus = api.get_status(id)  # fetching the id attributeid = status.id   print("The ID of the status is : " + str(id))
Output :
The ID of the status is : 1272479136133627905

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | Image.split() method

21 Jun, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities.
Image.split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image.Splitting an “RGB” image creates three new images each containing a copy of one of the original bands (red, green, blue).
Syntax:var = Image.Image.split(image_object)ORvar = Image.Image.split(path_of_image)
Return Value: It returns a tuple containing bands.
Code #1:
# importing Image class from PIL packagefrom PIL import Image  # opening a multiband image (RGB specifically)im = Image.open(r"C:\Users\Admin\Pictures\network.png")  # split() method# this will split the image in individual bands# and return a tupleim1 = Image.Image.split(im)  # showing each bandim1[0].show()im1[1].show()im1[2].show()
Output:
Code #2:
# importing Image class from PIL packagefrom PIL import Image  # opening a singleband imageim = Image.open(r"C:\Users\Admin\Pictures\singleband.png")  # split() method# this will split the image in individual bands# and return a tuple (of 1 element for singleband)im1 = Image.Image.split(im)  # showing imageim1[0].show()
Output:
Images Used:
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Finding the outlier points from Matplotlib

28 Jan, 2021
Outliers are the data points that differ from other observations or those which lie at a distance from the other data. They are mainly generated due to some experimental error which may cause several problems in statistical analysis. While in a big dataset it is quite obvious that some data will be further from the sample mean. These outliers need to be found and handle wisely.
We can use boxplots for the necessary.
Above is a diagram of boxplot created to display the summary of data values along with its median, first quartile, third quartile, minimum and maximum. And the data points out of the lower and upper whiskers are outliers. In between the first and third quartile of whisker lies the interquartile region above which a vertical line passes known as the median. For further details refer to the blog Box plot using python. Following are the methods to find outliers from a boxplot :
1.Visualizing through matplotlib boxplot using plt.boxplot().
2.Using 1.5 IQR rule.
Example:
Python3
# Adding librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # random integers between 1 to 20arr = np.random.randint(1, 20, size=30) # two outliers takenarr1 = np.append(arr, [27, 30]) print('Thus the array becomes{}'.format(arr1))
Output:
array([4, 12, 15,  7, 13,  2, 12, 11, 10, 12, 15,  5,  9, 16, 17,  2, 10, 15, 4, 16, 14, 19, 12,  8, 13,  3, 16, 10,  1, 13, 27, 30])
Visualizing by matplotlib boxplot using plt.boxplot()
Python3
plt.boxplot(arr1)fig = plt.figure(figsize =(10, 7))plt.show()
  
Output:                                                                                                                                                                                                                                                             
 
 
So from the above figure, we can witness the two outliers.
 
1.5 IQR Rule
Steps in 1.5IQR rule:-
Finding the median, quartile, and interquartile regions
Calculate 1.5*IQR below the first quartile and check for low outliers.
Calculate 1.5*IQR above the third quartile and check for outliers.
 
Python
# finding the 1st quartileq1 = np.quantile(arr1, 0.25) # finding the 3rd quartileq3 = np.quantile(arr1, 0.75)med = np.median(arr1) # finding the iqr regioniqr = q3-q1 # finding upper and lower whiskersupper_bound = q3+(1.5*iqr)lower_bound = q1-(1.5*iqr)print(iqr, upper_bound, lower_bound)
Output:
8.25 26.375 -6.625
Python3
outliers = arr1[(arr1 <= lower_bound) | (arr1 >= upper_bound)]print('The following are the outliers in the boxplot:{}'.format(outliers))
Output:
The following are the outliers in the boxplot:[27 30]
Thus, the outliers have been detected using the rule. Now eliminating them and plotting a graph with the data points- 
Python3
# boxplot of data within the whiskerarr2 = arr1[(arr1 >= lower_bound) & (arr1 <= upper_bound)]plt.figure(figsize=(12, 7))plt.boxplot(arr2)plt.show()
Output :
barnadipdey2510
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CPU control design and Interfaces - GeeksforGeeks

19 Nov, 2018
     MBR ← PC 
     MAR ← X  
     PC ← Y  
     Memory ← MBR
I. Function locals and parameters
II. Register saves and restores
III. Instruction fetches   
  M [SP]
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Epam Interview Experience for Junior Software Engineer
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
Top 10 Programming Languages to Learn in 2022
Bootstrap .btn-link class

Deemphasize a button by making it look like a link while maintaining button behavior using the btn-link class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <button type = "button" class = "btn btn-link">Link Button</button>
   </body>
</html>
Make an element invisible with Bootstrap

To make an element invisible with Bootstrap, use the invisible class.
You can try to run the following code to hide an element −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Cricket Boards</h2>
         <p>The <abbr title = "International Cricket Council">ICC</abbr> governs cricket boards.</p>
         <p class = "invisible">BCCI is also governed by ICC. (This element is invisible)</p>
      </div>
   </body>
</html>
Reverse Vowels of a string in C++

Given a string, the task is to reverse all the vowels present in the given string. For example,
Input-1 −
a = “tutor”
Output −
totur
Explanation − Reversing the string “tutor” will generate the output as “totur.
Input-2 −
a = “mathematics”
Output −
mithametacs
Explanation − Reversing the string “mathematics” will generate the output as “mithametacs”.
Given a string, we have to reverse all the vowels present in it. There are several approaches to solve this particular problem but we have to solve this in linear time O(n).
Thus, the better method to solve this problem is to use the Two-Pointer approach in which we will take two pointers low and high which will be pointing initially to the leftmost element and rightmost element. In two nested loops, we will check if the leftmost character is a vowel and the rightmost character is vowel also then swap the element and move the right pointer.
Take input a string.
Take input a string.
A Boolean function to check if the character is a vowel or not.
A Boolean function to check if the character is a vowel or not.
A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.
A function reverseVowel(string &str) takes a string as input and reverse the vowels present in the string.
Initialize two pointers low and high which point to ‘0’ and last character respectively.
Initialize two pointers low and high which point to ‘0’ and last character respectively.
Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.
Checking the leftmost and rightmost characters if they are vowels then swap the character in-place and decrement the rightmost pointer.
Repeating the steps until all the characters of the string are not visited.
Repeating the steps until all the characters of the string are not visited.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool isVowel(char ch) {
   return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
string reverseVowel(string &s){
   int low = 0;
   int high = s.size() - 1;
   while (low < high) {
      while (low < high && !isVowel(s[low])) {
         low ++;
      }
      while (low < high && !isVowel(s[high])) {
         high --;
      }
      swap(s[low++], s[high--]);
   }
   return s;
}
int main(){
   string a= "tutorialspoint";
   string ans= reverseVowel(a);
   cout<<ans;
   return 0;
}
Running the above code will generate the output as,
titorailspount
Since the given string “tutorialspoint” contains vowels, after reversing the vowels, it will generate the output as, “titorailspount”.
PHP ArgumentCountError

PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition. ArgumentCountError class is inherited from TypeError class
In Following example, a user defined function add() is defined to receive two arguments. However, if less than required number of arguments is provided while calling, ArgumentCountError will be thrown which can be handled with catch block.
 Live Demo
<?php
function add($x, $y){
   return $x+$y;
}
try{
   echo add(10);
}
catch (ArgumentCountError $e){
   echo $e->getMessage();
}
?>
This will produce following result −
Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 6 and exactly 2 expected
In Following example, setdata() method in myclass is defined to have two formal arguments. When this method is called with less arguments, ArgumentCountException is thrown
<?php
class myclass{
   private $name;
   private $age;
   function setdata($name, $age){
      $this->name=$name;
      $this->age=$age;
   }
}
try{
   $obj=new myclass();
   obj->setdata();
}
catch (ArgumentCountError $e){
   echo $e->getMessage();
}
?>
This will produce following result −
Too few arguments to function myclass::setdata(), 0 passed in C:\xampp\php\test.php on line 15 and exactly 2 expected
ArgumentCountException is also thrown in case built-in function is given inappropriate or invalid number of arguments. However, strict-types mode must be set
 Live Demo
<?php
declare(strict_types = 1);
try{
   echo strlen("Hello", "World");
}
catch (ArgumentCountError $e){
   echo $e->getMessage();
}
?>
This will produce following result −
strlen() expects exactly 1 parameter, 2 given
How to redefine a color for a specific value in a Matplotlib colormap?

To redefine a color for a specific value in matplotlib colormap, we can take the following steps −
Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap.
Get a colormap instance, defaulting to rc values if *name* is None using get_cmap() method, with gray colormap.
Set the color for low out-of-range values when "norm.clip = False" using set_under() method.
Set the color for low out-of-range values when "norm.clip = False" using set_under() method.
Using imshow() method, display data an image, i.e., on a 2D regular raster.
Using imshow() method, display data an image, i.e., on a 2D regular raster.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, cm
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
cmap = cm.get_cmap('gray')
cmap.set_under('red')
plt.imshow(np.arange(25).reshape(5, 5),
   interpolation='none',
   cmap=cmap,
   vmin=.001)
plt.show()
Ruby | String Interpolation - GeeksforGeeks

24 Sep, 2019
String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals. String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. This is how, string Interpolation works, it executes whatever that is executable.Let’s see how to execute numbers and strings.Syntax:
#{variable}
The above syntax specifies that the things inside {} are executable objects or variables.Below are the examples to understand :Example :
# Ruby Program of String Interpolationa = 1b = 4puts "The number #{a} is less than #{b}"
Output :
The number 1 is less than 4
Example:
# Ruby Program of String Interpolation  s = 'Groot';n = 16  # takes this as entire new stringputs "s age = n";  # interpolationputs "#{s} age=#{n}";  # if number not converted to string throws an errorputs s+" age="+n.to_s;
s age=n
Groot age=16
Groot age=16

So, the only advantage, We don’t have to convert numbers into a string because ruby takes care of it.
let’s say string=”weds” In string concatenation, if we are concatenating strings like (“hela “+string+” puri”), it creates 3 string objects, it moves from right-to-left, it first creates ” puri” object1, + method sticks the puri with the existing string together and returns weds puri object2 and this again gets stick by + method and forms the final hela weds puri object3. Eventually, the objects(1, 2) created in this process gets terminated as their are of no use.
In String Interpolation, it creates an only one object for (“hela “+string+” puri”) and embeds the existing string(weds)to it. In both the case, in the end, it creates one object but why prefer Interpolation over concatenation. Two reasons, no need for additional conversions of datatypes to string ruby takes care of it and this process is most of the developers kinda use.
Strings can not only contain text. They can also contain control characters. Difference between single or double quotes is that double quotes allow for escape sequences while single quotes do not allow for it.Example :
# Ruby program of sting Interpolationputs 'guardians\nGroot';  # gets executes and prints Groot on a newline.puts "guardians\nGroot";  # takes care of control characters.puts "hela\nweds\tpuri";
Output:
guardians\nGroot
guardians
Groot
hela
weds    puri

In above example, \n is the escape sequence that stands for the “newline” character.
Picked
Ruby-String
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Enumerable find() function
Ruby | pop() function
Ruby | Types of Variables
Ruby | Operators
Ruby | Class Method and Variables
Ruby | Types of Iterators
Ruby | Array collect() operation
Ruby | String concat Method
How to Map a Function Over NumPy Array? - GeeksforGeeks

28 Nov, 2021
In this article, we are going to see how to map a function over a NumPy array in Python.
The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like NumPy arrays. The nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.
Python3
import numpy as np  arr = np.array([1, 2, 3, 4, 5])  def addTwo(i):    return i+2    applyall = np.vectorize(addTwo)res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
Explanation: The function is passed to the vectorized method and again the array is passed to it and the function will return the array on which the array is applied.
The lambda is an anonymous function, it takes any number of arguments but evaluates one expression.
Python3
import numpy as np  arr = np.array([1, 2, 3, 4, 5])  def applyall(i):   return i + 2  res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
We can map a function over a NumPy array just by passing the array to the function.
Python3
import numpy as np  arr = np.array([1, 2, 3, 4, 5])  def applyall(a):    return a+2  res = applyall(arr)print(res)
Output:
[3 4 5 6 7]
Explanation: The array is passed to the applyall() method and it will map the function to the entire array and the resultant array is returned.
Picked
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Return Pointer from Functions in C++

As we have seen in last chapter how C++ allows to return an array from a function, similar way C++ allows you to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −
int * myFunction() {
   .
   .
   .
}

Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them using an array name which represents a pointer i.e., address of first array element.
#include <iostream>
#include <ctime>
 
using namespace std;
 
// function to generate and retrun random numbers.
int * getRandom( ) {
   static int  r[10];
 
   // set the seed
   srand( (unsigned)time( NULL ) );
   
   for (int i = 0; i < 10; ++i) {
      r[i] = rand();
      cout << r[i] << endl;
   }
 
   return r;
}
 
// main function to call above defined function.
int main () {
   // a pointer to an int.
   int *p;
 
   p = getRandom();
   for ( int i = 0; i < 10; i++ ) {
      cout << "*(p + " << i << ") : ";
      cout << *(p + i) << endl;
   }
 
   return 0;
}
When the above code is compiled together and executed, it produces result something as follows −
624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
How to call a JavaScript function from an onsubmit event?

The onsubmit event occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here, we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
<script>
   <!--
      function validation() {
         all validation goes here
         .........
         return either true or false
      }
   //-->
</script>
<form method="POST" action="new.cgi" onsubmit="return validate()">
   .......
   <input type="submit" value="Submit" />
</form>
Gulp - Optimizing CSS and JavaScript

In this chapter, you will learn how to optimize CSS and JavaScript. Optimizing is required to remove unnecessary data (for e.g. spaces and unused characters) from the source files. It reduces the size of the files and allows them to load faster
Go to “work” directory from your command line and install “gulp-uglify”, “gulp-minify-css” and “gulp-concat” plugins by using the following command −
npm install gulp-uglify gulp-minify-css gulp-concat

In your configuration file gulpfile.js, first declare the dependencies as shown in the following code.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');

Next, you need to create tasks for optimizing CSS and JavaScript as shown in the following code.
gulp.task('js', function(){
   gulp.src('src/scripts/*.js')
   .pipe(concat('script.js'))
   .pipe(uglify())
   .pipe(gulp.dest('build/scripts/'));
});

gulp.task('css', function(){
   gulp.src('src/styles/*.css')
   .pipe(concat('styles.css'))
   .pipe(minify())
   .pipe(gulp.dest('build/styles/'));
});

gulp.task('default',['js','css'],function(){
});
The js task will accepts .js files from src/scripts/ folder. It concatenates and uglifies the js files, then produces build/scripts/script.js file.
The CSS task will accept .css files from src/styles/ folder. It concatenates and minifies CSS files, then produces build/styles/styles.css file.
The configuration file is set up and ready to execute. Use the following command to run the task.
gulp

On running the task using the above command, you will receive the following result in the command prompt.
C:\work>gulp
[13:16:34] Using gulpfile C:\work\gulpfile.js
[13:16:34] Starting 'js'...
[13:16:34] Finished 'js' after 24 ms
[13:16:34] Starting 'css'...
[13:16:34] Finished 'css' after 6.05 ms
[13:16:34] Starting 'default'...
[13:16:34] Finished 'default' after 5.04 μs

 Print
 Add Notes
 Bookmark this page
How to toggle between a like/dislike button with CSS and JavaScript?

To toggle between like/dislike button with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      padding: 20px;
   }
   .fa {
      font-size: 50px;
      cursor: pointer;
      user-select: none;
   }
   .fa-thumbs-up {
      color: blue;
   }
   .fa-thumbs-down {
      color: red;
   }
   .fa:hover {
      transform: scale(1.2);
   }
</style>
</head>
<body>
<h1>Like dislike button example</h1>
<i class="fa fa-thumbs-up"></i>
<script>
   document.querySelector(".fa").addEventListener("click", function(event) {
      toggleLike(event);
   });
   function toggleLike(ele) {
      ele.target.classList.toggle("fa-thumbs-down");
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the like button −
\iint - Tex Command

\iint - Used to draw two occurrences of integration symbol.
{ \iint }
\iint command is used to draw two occurrences of integration symbol.

\iint

∫∫



\iint

∫∫


\iint

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
jMeter - Listeners

Listeners provide access to the information JMeter gathers about the test cases while JMeter runs. The results or information gathered by listeners can be shown in the form of −
tree
tables
graphs
log file
All listeners write the same raw data to the output file when one is specified.
The default items to be saved can be defined in one of the following two ways −
In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −
In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −
jmeter.save.saveservice.output_format=

By using the Config popup as shown in the following screenshot −
By using the Config popup as shown in the following screenshot −
JMeter creates results of a test run as JMeter Text Logs(JTL). These are normally called JTL files, as that is the default extension − but any extension can be used.
If multiple tests are run using the same output file name, then JMeter automatically appends new data at the end of the file.
The listener can record results to a file but not to the UI. It is meant to provide an efficient means of recording data by eliminating GUI overhead.
When running in −
GUI mode − use the listener Simple Data Writer
GUI mode − use the listener Simple Data Writer
non-GUI mode − the -l flag can be used to create a data file.
non-GUI mode − the -l flag can be used to create a data file.
Listeners can use a lot of memory if there are a lot of samples. To minimize the amount of memory needed, use the Simple Data Write with CSV format.
The CSV log format depends on which data items are selected in the configuration. Only the specified data items are recorded in the file. The order of appearance of columns is fixed, and is as follows −
The response data can be saved in the XML log file if required. However it does not allow to save large files and images. In such cases, use the Post-Processor Save_Responses_to_a_file. This generates a new file for each sample, and saves the file name with the sample. The file name can then be included in the sample log output. The data will be retrieved from the file if necessary when the sample log file is reloaded.
To view an existing results file, you can use the file "Browse..." button to select a file. If necessary, just create a dummy testplan with the appropriate Listener in it.
JMeter is capable of saving any listener as a PNG file. To do so,
Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears.
Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears.
Enter the desired name.
Enter the desired name.
Save the listener.
Save the listener.

    59 Lectures 
     9.5 hours 

 Rahul Shetty

    54 Lectures 
     13.5 hours 

 Wallace Tauriac

    23 Lectures 
     1.5 hours 

 Anuja Jain

    12 Lectures 
     1 hours 

 Spotle Learn
 Print
 Add Notes
 Bookmark this page
How to force garbage collection in C#?

Yes it is possible to force garbage collector in C# to run by calling Collect() method
This is not considered a good practice because this might create a performance over
head. Collect() Forces an immediate garbage collection of all generations.
Collect(Int32)Forces an immediate garbage collection from generation 0 through a
specified generation.
 Live Demo
using System;
class MyGCCollectClass{
   private const int maxGarbage = 1000;
   static void Main(){
      // Put some objects in memory.
      MyGCCollectClass.MakeSomeGarbage();
      Console.WriteLine("Memory used before collection: {0:N0}",
      GC.GetTotalMemory(false));
      // Collect all generations of memory.
      GC.Collect();
      Console.WriteLine("Memory used after full collection: {0:N0}",
      GC.GetTotalMemory(true));
   }
   static void MakeSomeGarbage(){
      Version vt;
      // Create objects and release them to fill up memory with unused objects.
      for(int i = 0; i < maxGarbage; i++){
         vt = new Version();
      }
   }
}
Batch Script - Syntax

Normally, the first line in a batch file often consists of the following command.
@echo off

By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well.
Very often batch files also contains lines that start with the "Rem" command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments.
Let’s construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as “List.cmd”.
The code does the following −
Uses the echo off command to ensure that the commands are not shown when the code is executed.
Uses the echo off command to ensure that the commands are not shown when the code is executed.
The Rem command is used to add a comment to say what exactly this batch file does.
The Rem command is used to add a comment to say what exactly this batch file does.
The dir command is used to take the contents of the location C:\Program Files.
The dir command is used to take the contents of the location C:\Program Files.
The ‘>’ command is used to redirect the output to the file C:\lists.txt.
The ‘>’ command is used to redirect the output to the file C:\lists.txt.
Finally, the echo command is used to tell the user that the operation is completed.
Finally, the echo command is used to tell the user that the operation is completed.
@echo off 
Rem This is for listing down all the files in the directory Program files 
dir "C:\Program Files" > C:\lists.txt 
echo "The program has completed"
When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message “The program has completed” will be displayed.
 Print
 Add Notes
 Bookmark this page
XMLRPC server and client modules in Python

We can create our own cross-platform, language-independent server using the XML-RPC protocol.We use the SimpleXMLRPCServer to create the SimpleXMLRPCServer instance and tell it to listen for incoming requests. Next we define some functions to be part of the service and register those functions so that the server knows how to call it.
In the below example we create a server using the SimpleXMLRPCServer instance and register some pre-defined as well as custom functions. Finally, we put the server into an infinite loop receiving and responding to requests.
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
   rpc_paths = ('/RPC2',)
with SimpleXMLRPCServer(('localhost', 9000),
                        requestHandler=RequestHandler) as server:
   server.register_introspection_functions()
   # Register len() function;
   server.register_function(len)
   # Register a function under a different name
   @server.register_function(name='rmndr')
   def remainder_function(x, y):
      return x // y
   # Register a function under function.__name__.
   @server.register_function
   def modl(x, y):
      return x % y
   server.serve_forever()
Once the above server is started, it can be called by a client program which can refer to the functions and make the function calls.
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:9000')
print(s.len("Tutorialspoint"))
print(s.rmndr(12,5))
print(s.modl(7,3))
# Print list of available methods
print(s.system.listMethods())
Running the above code gives us the following result −
14
2
1
['len', 'modl', 'rmndr', 'system.listMethods', 'system.methodHelp', 'system.methodSignature']
Difference Between find( ) and index( ) in Python - GeeksforGeeks

24 Jan, 2021
In Python, to find the index of a substring in a string can be located by python’s in-built function using find() or index(). Both of them return the starting index of the substring in a string if it exists. This article discusses which one to use when and why.
The index() method returns the index of a substring or char inside the string (if found). If the substring or char is not found, it raises an exception.
Syntax:
string.index(<substring>)
Example:
Python3
string = 'geeks for geeks'  # returns index valueresult = string.index('for')print("Substring for:", result)  result3 = string.index("best")print("substring best:", result3)
Output:
Substring for: 6
Traceback (most recent call last):
 File “<string>”, line 8, in <module>
ValueError: substring not found
The find() method returns the index of first occurrence of the substring or char (if found). If not found, it returns -1.
Syntax:
string.find(<substring>)
Example:
Python3
string = 'geeks for geeks'  # returns index valueresult = string.find('for')print("Substring for:", result)  result = string.find('best')print("Substring best:", result)
Output:
Substring for: 6
Substring best: -1
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Find mismatch item on same index in two list in Python

Sometimes we may need to compare elements in two python lists in terms of both their value and position or index. In this article we will see how to find out the elements in two lists at the same position which do not match in their value.
we can design for loop to compare the values at similar indexes. Id the values do not match then we add the index to a result list. The for loop first fetches the value in the first index and then uses an if condition to compare it with values from the second list.
 Live Demo
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

# index variable
idx = 0

# Result list
res = []

# With iteration
for i in listA:
   if i != listB[idx]:
      res.append(idx)
   idx = idx + 1

# Result
print("The index positions with mismatched values:\n",res)
Running the above code gives us the following result −
The index positions with mismatched values:
[0, 3]
The zip function helps us to write a shorter code as we compare the elements from each index. The index values are captured for positions where the element’s value do not match.
 Live Demo
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

res = [listB.index(n) for m, n in
      zip(listA, listB) if n != m]

# Result
print("The index positions with mismatched values:\n",res)
Running the above code gives us the following result −
The index positions with mismatched values:
[0, 3]
It is similar to the approach in zip function except that here we have for loop to go through each element and index when applying enumerate function to one of the list.
 Live Demo
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

res = [idx for idx, elem in enumerate(listB)
                           if elem != listA[idx]]

# Result
print("The index positions with mismatched values:\n",res)
Running the above code gives us the following result −
The index positions with mismatched values:
[0, 3]
Scala Int abs() method with example - GeeksforGeeks

03 Nov, 2019
The abs() method is utilized to return the absolute value of the given integer value. The absolute value of any number is the magnitude of that number i.e, without any sign.
Method Definition: (Signed_Integer_Value).absReturn Type: It return the absolute value of the given signed integer value.
Example #1:
// Scala program of Int abs()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying abs method        val result = (-5).abs                  // Displays output        println(result)          }} 
5

Example #2:
// Scala program of Int abs()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying abs method        val result = (+65).abs                  // Displays output        println(result)          }} 
65

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Operators in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Constructors
Scala String substring() method with example
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example
What is runtime polymorphism or dynamic method overloading?

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Method overriding by a subclass is termed as runtime polymorphism. JVM determines the method to be executed at runtime instead of compile time. 
Live Demo
class SuperClass {
   SuperClass get(){
      System.out.println("SuperClass");
      return this;
   }
}
public class Tester extends SuperClass {
   Tester get(){
      System.out.println("SubClass");
      return this;
   }
   public static void main(String[] args) {
      SuperClass tester = new Tester();
 
      tester.get();
   }  
}
SubClass
Program to check if an Array is Palindrome or not using STL in C++

19 Mar, 2019
Given an array, the task is to determine whether an array is a palindrome or not, using STL in C++.
Examples:
Input: arr[] = {3, 6, 0, 6, 3}
Output: Palindrome

Input: arr[] = {1, 2, 3, 4, 5}
Output: Not Palindrome

Approach:
Get the reverse of the Array using reverse() method, provided in STL.
Initialise flag to unset int flag = 0.
Loop the array till size n and check if the original array and the reversed array are same. If not set flag = 1
After the loop has ended, If flag is set the print “Not Palindrome” else print “Palindrome”
Below is the implementation of above Approach:
// C++ program to check if an Array// is Palindrome or not using STL  #include <bits/stdc++.h>using namespace std;  void palindrome(int arr[], int n){    // Initialise flag to zero.    int flag = 0;      // Create another array    // to store the original array    int arr2[n];    memcpy(arr2, arr, n * sizeof(int));      // Reverse the array    reverse(arr, arr + n);      // Check if the array is Palindrome    for (int i = 0; i < n; i++)        if (arr[i] != arr2[i]) {            flag = 1;            break;        }      // Print the result    if (flag == 0)        cout << "Palindrome\n";    else        cout << "Not Palindrome\n";}  int main(){    // Get the array    int arr[] = { 1, 2, 3, 2, 1 };      // Compute the size    int n = sizeof(arr) / sizeof(arr[0]);      palindrome(arr, n);      return 0;}
Palindrome

Related Articles:
https://www.geeksforgeeks.org/program-to-check-if-an-array-is-palindrome-or-not/
https://www.geeksforgeeks.org/program-to-check-if-an-array-is-palindrome-or-not-using-recursion/
cpp-array
palindrome
STL
C++
C++ Programs
palindrome
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Polymorphism in C++
List in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Command line arguments in C/C++
Exception Handling in C++
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
C++ program for hashing with chaining
Passing a function as a parameter in C++