code-rag-bench/online-tutorials huggingface dataset:
How can I show image rollover with a mouse event in JavaScript?

To show image rollover with a mouse event, you can try to run the following code −
<html>
   <head>
      <title>Rollover with a Mouse Event</title>
      <script>
         <!--
            if(document.images) {
               var image1 = new Image(); // Preload an image
               image1.src = "/images/html.gif";
               var image2 = new Image(); // Preload second image
               image2.src = "/images/http.gif";
            }
         //-->
      </script>
   </head>
   <body>
      <p>Move your mouse over the image to see the result</p>

      <a href = "#" onMouseOver = "document.myImage.src = image2.src;" onMouseOut = "document.myImage.src = image1.src;">
         <img name = "myImage" src = "/images/html.gif" />
      </a>
   </body>
</html>
Let's see what we have used in the above example to automate animation −
At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
The Image() constructor creates and preloads a new image object called image1.
The src property is assigned the name of the external image file called /images/html.gif.
Similarly, we have created an image2 object and assigned /images/http.gif in this object.
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
Overlay an image segmentation with Numpy and Matplotlib

To overlay an image segmentation with numpy, we can take the following Steps −
Make a masked array of 10×10 dimension.
Make a masked array of 10×10 dimension.
Update the masked array with 1 for some region.
Update the masked array with 1 for some region.
Make image data using numpy.
Make image data using numpy.
Mask an array where a condition is met, to get the masked data.
Mask an array where a condition is met, to get the masked data.
Create a new figure or activate an existing figure using figure() mrthod.
Create a new figure or activate an existing figure using figure() mrthod.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
mask = np.zeros((10, 10))
mask[3:-3, 3:-3] = 1
im = mask + np.random.randn(10, 10) * 0.01
masked = np.ma.masked_where(mask == 0, mask)
plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(im, 'gray', interpolation='none')
plt.subplot(1, 2, 2)
plt.imshow(im, 'gray', interpolation='none')
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
plt.show()
How to draw images in the Tkinter window?

To process images with Tkinter and other Python packages, we generally refer to use Pillow Package or PIL in Python. It provides a way to load and process the images in the program wherever we need. Initially, we convert the image to an instance of PhotoImage object that allows images to be further used in many use cases. Further, the Canvas widget in Tkinter helps to draw the images in a Tkinter application, we can use the create_image(x,y, image_file) method to display the image in a particular application.
#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()
#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))
#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)
win.mainloop()
Running the above code will display a window that will display an image in the Canvas Widget.
In order to replace or change the Image file in the given output just import the image in Image.Open(file name) method.
Longest Common Subsequence

The longest common subsequence is a type of subsequence which is present in both of the given sequences or arrays.
We can see that there are many subproblems, which are computed again and again to solve this problem. By using the Overlapping Substructure Property of Dynamic programming, we can overcome the computational efforts. Once the result of subproblems is calculated and stored in the table, we can simply calculate the next results by use of the previous results.
Input:
Two strings with different letters or symbols.
string 1: AGGTAB
string 2: GXTXAYB
Output:
The length of the longest common subsequence. Here it is 4.
AGGTAB and GXTXAYB. The underlined letters are present in both strings and in correct sequence.
longestComSubSeq(str1, str2)
Input − Two strings to find the length of Longest Common Subsequence.
Output − The length of LCS.
Begin
   m := length of str1
   n := length of str2
   define longSubSeq matrix of order (m+1) x (n+1)

   for i := 0 to m, do
      for j := 0 to n, do
         if i = 0 or j = 0, then
           longSubSeq[i,j] := 0
         else if str1[i-1] = str2[j-1], then
            longSubSeq[i,j] := longSubSeq[i-1,j-1] + 1
         else
            longSubSeq[i,j] := maximum of longSubSeq[i-1, j] and
            longSubSeq[i, j-1]
      done
   done

   longSubSeq[m, n]
End
#include<iostream>
using namespace std;

int max(int a, int b) {
   return (a > b)? a : b;
}

int longestComSs( string str1, string str2) {
   int m = str1.size();
   int n = str2.size();
   
   int longSubSeq[m+1][n+1];
   
   //longSubSeq[i,j] will hold the LCS of str1 (0 to i-1) and str2 (0 to j-1)
   for (int i=0; i<=m; i++) {
      for (int j=0; j<=n; j++) {
         if (i == 0 || j == 0)
            longSubSeq[i][j] = 0;
         else if (str1[i-1] == str2[j-1])
            longSubSeq[i][j] = longSubSeq[i-1][j-1] + 1;
         else
            longSubSeq[i][j] = max(longSubSeq[i-1][j], longSubSeq[i][j-1]);
      }
   }
   return longSubSeq[m][n];
}

int main() {
   string str1 = "AGGTAB";
   string str2 = "GXTXAYB";

   cout << "Length of Longest Common Subsequence is: " <<  longestComSs( str1, str2);
}
Length of Longest Common Subsequence is: 4
Algorithms | Analysis of Algorithms (Recurrences) | Question 6 - GeeksforGeeks

28 Jun, 2021
The running time of an algorithm is represented by the following recurrence relation:
    if  n <= 3  then   T(n) = n
    else T(n) = T(n/3) + cn

Which one of the following represents the time complexity of the algorithm?(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n)(A) A(B) B(C) C(D) DAnswer: (A)Explanation:
T(n) = cn + T(n/3)
     = cn + cn/3 + T(n/9)
     = cn + cn/3 + cn/9 + T(n/27)
Taking the sum of infinite GP series. The value of T(n) will
be less than this sum.
T(n) <= cn(1/(1-1/3))
     <= 3cn/2

or we can say 
cn <= T(n) <= 3cn/2
Therefore T(n) = (n)

This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.Quiz of this Question
Algorithms-Analysis of Algorithms (Recurrences)
Analysis of Algorithms (Recurrences)
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Greedy Algorithms | Question 1
Algorithms | Recursion | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
Algorithms | Sorting | Question 23
Algorithms | NP Complete | Question 4
How do you remove an array element by its index in MongoDB

To remove array element by its index in MongoDB, you can use unsetandpull operator. There are two steps to remove array elements from an array.The syntax for the same is as follows:
db.yourCollectionName.update({},{$unset:{"yourArrayListName.yourPosition":yourPositionValue}};
db.yourCollectionName.update({},{$pull:{"yourArrayListName":null}});
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
>db.removeArrayElements.insertOne({"StudentName":"Larry","StudentAge":23,"TechnicalSub
ject":["C","C++","Java","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea4879c4643706aef56d2")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.removeArrayElements.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "TechnicalSubject" : [
      "C",
      "C++",
      "Java",
      "MongoDB"
   ]
}
Here is the query to remove array element by its index:
> db.removeArrayElements.update({},{$unset:{"TechnicalSubject.3":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.removeArrayElements.update({},{$pull:{"TechnicalSubject":null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Above, we have removed array element “MongoDB”, which is at index 3. Let us display documents from a collection. The query is as follows:
> db.removeArrayElements.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "TechnicalSubject" : [
      "C",
      "C++",
      "Java"
   ]
}
Look at the above sample output, the index 3 i.e. position 4 has been removed from the array i.e. the element “MongoDB”.
“register” keyword in C

Register variables tell the compiler to store the variable in CPU register instead of memory. Frequently used variables are kept in registers and they have faster accessibility. We can never get the addresses of these variables. “register” keyword is used to declare the register variables.
Scope − They are local to the function.
Default value − Default initialized value is the garbage value.
Lifetime − Till the end of the execution of the block in which it is defined.
Here is an example of register variable in C language,
 Live Demo
#include <stdio.h>
int main() {
   register char x = 'S';
   register int a = 10;
   auto int b = 8;
   printf("The value of register variable b : %c\n",x);
   printf("The sum of auto and register variable : %d",(a+b));
   return 0;
}
The value of register variable b : S
The sum of auto and register variable : 18
Register keyword can be used with pointer also. It can have address of memory location. It will not create any error.
Here is an example of register keyword in C language
 Live Demo
#include<stdio.h>
int main() {
   int i = 10;
   register int *a = &i;
   printf("The value of pointer : %d", *a);
   getchar();
   return 0;
}
The value of pointer : 10
Byte Streams in Java

These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.
The InputStream and OutputStream classes (abstract) are the super classes of all the input/output stream classes: classes that are used to read/write a stream of bytes. Following are the byte array stream classes provided by Java −
Following Java program reads data from a particular file using FileInputStream and writes it to another, using FileOutputStream.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOStreamsExample {
   public static void main(String args[]) throws IOException {
      //Creating FileInputStream object
      File file = new File("D:/myFile.txt");
      FileInputStream fis = new FileInputStream(file);
      byte bytes[] = new byte[(int) file.length()];
      //Reading data from the file
      fis.read(bytes);
      //Writing data to another file
      File out = new File("D:/CopyOfmyFile.txt");
      FileOutputStream outputStream = new FileOutputStream(out);
      //Writing data to the file
      outputStream.write(bytes);
      outputStream.flush();
      System.out.println("Data successfully written in the specified file");
   }
}
Data successfully written in the specified file
What is the difference between JavaScript and C++?

The following are the differences between JavaScript and C++.
JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complementary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform.
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
JavaScript is a scripting whereas C++ is a programming language.
C++ program is to be compiled and executed, whereas a script in JavaScript is interpreted.
JavaScript is dynamically typed whereas C++ is statically typed.
In Java, you have to declare the type of the variable with the variable, for example,
int a;
float f;
In JavaScript, you need to only write the variable name, without adding the type. After that, you can assign the value like 5 for int, “amit” for string, etc.
var a; var f
JavaScript supports Java virtual machine implementation, whereas C++ does not support Java virtual machine implementation.
C++ support procedural and generic programming. JavaScript support reflective programming
Check if all digits of a number divide it in Python

Suppose we have a number n. We have to check whether all digits of it can divide n or not.
So, if the input is like n = 135, then the output will be True, because (135 / 1 = 135), (135 / 3 = 45) and (135 / 5 = 27).
To solve this, we will follow these steps −
val := n
while val > 0, dod := val mod 10if n is not divisible by d, thenreturn Falseval := quotient of (val / 10)
d := val mod 10
if n is not divisible by d, thenreturn False
return False
val := quotient of (val / 10)
return True
Let us see the following implementation to get better understanding −
 Live Demo
def is_divisible(n, d) :
   return d != 0 and n % d == 0
def solve(n) :
   val = n
   while (val > 0) :
      d = val % 10
   if not is_divisible(n, d):
      return False
      val = val // 10
   return True
n = 135
print(solve(n))
135
True
How to call multiple JavaScript functions in onclick event?

To call multiple JavaScript functions in on click event, use a semicolon as shown below −
onclick="Display1();Display2()"
Live Demo
<html>
   <head>
      <script>
         function Display1() {
            document.write ("Hello there!");
         }
         function Display2() {
            document.write ("Hello World!");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "Display1(); Display2()" value = "Result">
      </form>
   </body>
</html>
numpy.zeros_like() in Python - GeeksforGeeks

28 Mar, 2022
This numpy method returns an array of given shape and type as given array, with zeros.  
Syntax: numpy.zeros_like(array, dtype = None, order = 'K', subok = True)
Parameters : 
array : array_like input
subok  : [optional, boolean]If true, then newly created array will be sub-class of array; 
                 otherwise, a base-class array
order  : C_contiguous or F_contiguous
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
dtype  : [optional, float(byDefault)] Data type of returned array.  
Returns : 
ndarray of zeros having given shape, order and datatype.
Code 1 :  
Python
# Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array)  b = geek.zeros_like(array, float)print("\nMatrix b : \n", b) array = geek.arange(8)c = geek.zeros_like(array)print("\nMatrix c : \n", c)
Output: 
Original array : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Matrix b : 
 [[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]

Matrix c : 
 [0 0 0 0 0 0 0 0]
Code 2 : 
Python
# Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) array = geek.arange(4).reshape(2, 2)c = geek.zeros_like(array, dtype = 'float')print("\nMatrix  : \n", c) array = geek.arange(8)c = geek.zeros_like(array, dtype = 'float', order ='C')print("\nMatrix  : \n", c)
Output : 
Original array : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Matrix  : 
 [[ 0.  0.]
 [ 0.  0.]]

Matrix  : 
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.zeros_like.html#numpy.zeros_like Note : Also, these codes won’t run on online IDE’s. Please run them on your systems to explore the workingThis article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
kapoorsagar226
avtarkumar719
kothavvsaakash
Pyhton numpy-arrayCreation
Python-numpy
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 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
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Pandas Period.qyear - GeeksforGeeks

06 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Period.qyear attribute return the fiscal year the Period lies in according to its starting-quarter. The year and the qyear of the period will be the same if the fiscal and calendar years are the same. When they are not, the fiscal year can be different from the calendar year of the period.
Syntax : Period.qyear
Parameters : None
Return : fiscal year
Example #1: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2,                  day = 21, hour = 8, minute = 21)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.qyear attribute to find the fiscal year
# return the fiscal yearprd.qyear
Output :
As we can see in the output, the Period.qyear attribute has returned 2000 indicating that the given period lies in the year of 2000.
Example #2: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10,                            hour = 15, minute = 49)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.qyear attribute to find the fiscal year
# return the fiscal yearprd.qyear
Output :
As we can see in the output, the Period.qyear attribute has returned 2006 indicating that the given period lies in the year of 2006.
Pandas scalar-period
Python-pandas
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
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Add elements to LinkedHashMap collection in Java

Use the put() method to add elements to LinkedHashMap collection.
First, let us create a LinkedHashMap −
LinkedHashMap<String, String> l = new LinkedHashMap<String, String>();
Now, add elements −
l.put("1", "Jack");
l.put("2", "Tom");
l.put("3", "Jimmy");
l.put("4", "Morgan");
l.put("5", "Tim");
l.put("6", "Brad");
The following is an example to add elements to LinkedHashMap collection −
 Live Demo
import java.util.LinkedHashMap;
public class Demo {
   public static void main(String[] args) {
      LinkedHashMap<String, String> l = new LinkedHashMap<String, String>();
      l.put("1", "Jack");
      l.put("2", "Tom");
      l.put("3", "Jimmy");
      l.put("4", "Morgan");
      l.put("5", "Tim");
      l.put("6", "Brad");
      System.out.println("LinkedHashMap elements\n"+l);
   }
}
LinkedHashMap elements
{1=Jack, 2=Tom, 3=Jimmy, 4=Morgan, 5=Tim, 6=Brad}
Python Number uniform() Method

Python number method uniform() returns a random float r, such that x is less than or equal to r and r is less than y.
Following is the syntax for uniform() method −
uniform(x, y)

Note − This function is not accessible directly, so we need to import uniform module and then we need to call this function using random static object.
x − Sets the lower limit of the random float.
x − Sets the lower limit of the random float.
y − Sets the upper limit of the random float.
y − Sets the upper limit of the random float.
This method returns a floating point number.
The following example shows the usage of uniform() method.
#!/usr/bin/python
import random

print "Random Float uniform(5, 10) : ",  random.uniform(5, 10)
print "Random Float uniform(7, 14) : ",  random.uniform(7, 14)
Let us run the above program, this will produce the following result −
Random Float uniform(5, 10) :  5.52615217015
Random Float uniform(7, 14) :  12.5326369199


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
StringBuilder appendCodePoint() method in Java with Examples - GeeksforGeeks

13 Dec, 2021
The appendCodePoint(int codePoint) method of StringBuilder class is the inbuilt method used to append the string representation of the codePoint argument to this sequence. The argument is appended to this StringBuilder content and length of the object is increased by Character.charCount(codePoint). The effect is the same as if the int value in parameter is converted to a char array and the character in that array were then appended to this character sequence. Syntax: 
public StringBuilder appendCodePoint(int codePoint)
Parameters: This method accepts only one parameter codePoint which is int type value refers to a Unicode code point. Return Value: This method returns reference to this object.Below programs illustrate the java.lang.StringBuilder.appendCodePoint() method:Example 1:  
Java
// Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks {    public static void main(String[] args)    {         // create StringBuilder object        StringBuilder            str            = new StringBuilder("GeeksforGeeks");        System.out.println("StringBuilder = "                           + str);         // Append 'C'(67) to the String        str.appendCodePoint(67);         // Print the modified String        System.out.println("Modified StringBuilder = "                           + str);    }}
StringBuilder = GeeksforGeeks
Modified StringBuilder = GeeksforGeeksC
 
Example 2: 
Java
// Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks {    public static void main(String[] args)    {         // create StringBuilder object        StringBuilder            str            = new StringBuilder("GeeksforGeeks");        System.out.println("StringBuilder = "                           + str);         // Append ', '(44) to the String        str.appendCodePoint(44);         // Print the modified String        System.out.println("Modified StringBuilder = "                           + str);    }}
StringBuilder = GeeksforGeeks
Modified StringBuilder = GeeksforGeeks,
 
References: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#appendCodePoint(int) 
Akanksha_Rai
gabaa406
java-basics
Java-Functions
Java-StringBuilder
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
Bootstrap .nav-justified class

Make tabs or pills of equal widths as of their parent at screens wider than 768px using class .nav-justified along with .nav, .nav-tabs or .nav, .nav-pills respectively. On smaller screens, the nav links are stacked.
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 style = "background: #FADBD8;">
      <h2>Subjects</h2>
         <ul class = "nav nav-tabs nav-justified">
            <li class = "active"><a href = "#">Home</a></li>
            <li><a href = "#">Team</a></li>
            <li><a href = "#">Authors</a></li>
            <li><a href = "#">MVPs</a></li>
         </ul>
   </body>
</html>
Memset in C++ - GeeksforGeeks

08 Dec, 2021
Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is defined in <cstring> header file.
Syntax:
void* memset( void* str, int ch, size_t n);
Memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[]. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behavior is undefined. 
Parameters:
str[] : Pointer to the object to copy the character.
ch : The character to copy.
n : Number of bytes to copy.
Return value: The memset() function returns str, the pointer to the destination string. 
CPP
// CPP program to demonstrate memset#include <cstring>#include <iostream>using namespace std; // Driver Codeint main(){    char str[] = "geeksforgeeks";    memset(str, 't', sizeof(str));    cout << str;    return 0;}
tttttttttttttt
Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.  
CPP
// CPP Program to demonstrate that we can use memset() to// set all values as 0 or -1 for integral data types also#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){    int a[5];     // all elements of A are zero    memset(a, 0, sizeof(a));    for (int i = 0; i < 5; i++)        cout << a[i] << " ";    cout << endl;     // all elements of A are -1    memset(a, -1, sizeof(a));    for (int i = 0; i < 5; i++)        cout << a[i] << " ";    cout << endl;     // Would not work    memset(a, 5, sizeof(a)); // WRONG    for (int i = 0; i < 5; i++)        cout << a[i] << " ";}
0 0 0 0 0 
-1 -1 -1 -1 -1 
84215045 84215045 84215045 84215045 84215045 
See Also:
memcpy() in C/C++
memcmp() in C++
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.  
balajimarisetti
anshikajain26
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
Operator Overloading in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Iterators in C++ STL
Copy Constructor in C++
time.Time.Unix() Function in Golang with Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Unix() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Unix() int64

Here, “t” is the stated time.
Note: A Unix like operating system frequently stores time as a 32-bit count of seconds. And on the other hand, the Unix() method here returns a 64-bit value so it’s period of validity is for billions of years into the past or the future.
Return value: It returns “t” as a Unix time which is of type int64.
Example 1:
// Golang program to illustrate the usage of// Time.Unix() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Defining t in UTC for Unix method    t := time.Date(2020, 11, 14, 11, 30, 32, 0, time.UTC)      // Calling Unix method    unix := t.Unix()      // Prints output    fmt.Printf("%v\n", unix)}
Output:
1605353432

Example 2:
// Golang program to illustrate the usage of// Time.Unix() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Defining t in UTC for Unix method    t := time.Date(2013, 11, 14, 1e3, 3e5, 7e1, 0, time.UTC)      // Calling Unix method    unix := t.Unix()      // Prints output    fmt.Printf("%v\n", unix)}
Output:
1405987270

Here, the time “t” stated in the above code has values which contain constant “e” which are converted in usual range while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fmt.Sprintf() Function in Golang With Examples
Inheritance in GoLang
Slices in Golang
How to Trim a String in Golang?
How to Split a String in Golang?
How to compare times in Golang?
How to print string with double quotes in Golang?
Command Line Arguments in Golang
fmt.print() Function in Golang With Examples
strings.Replace() Function in Golang With Examples
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

17 Sep, 2021
A variable x is said to be live at a statement Si in a program if the following three conditions hold simultaneously:
1. There exists a statement Sj that uses x
2. There is a path from Si to Sj in the flow
   graph corresponding to the program
3. The path has no intervening assignment to x 
   including at Si and Sj
The variables which are live both at the statement in basic block 2 and at the statement in basic block 3 of the above control flow graph are(A) p, s, u(B) r, s, u(C) r, u(D) q, vAnswer: (C)Explanation: Live variable analysis is useful in compilers to find variables in each program that may be needed in future.
As per the definition given in question, a variable is live if it holds a value that may be needed in the future. In other words,  it is used in future before any new assignment.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0040:22 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2004 | Question 69
GATE | GATE-CS-2006 | Question 49
HTML DOM Button type Property

The HTML DOM Button type property is associated with the HTML <button> element. The button element by default has type=”submit” i.e clicking on any button on the form will submit the form. The button type property sets or returns the type of button.
Following is the syntax for −
Setting the button type property −
buttonObject.type = "submit|button|reset"
Here, the submit|button|reset are button type values. Submit is set by default.
Submit − Makes the button a submit button.
Button − Makes a normal clickable button.
Reset − Makes a reset button that resets the form data.
Let us see an example of the HTML DOM button type property −
<!DOCTYPE html>
<html>
<body>
<form id="Form1" action="/sample.php">
<label>First Name: <input type="text" name="fname"><br><br></label>
<label>Surname: <input type="text" name="lname"><br><br></label>
<button id="Button1" type="submit">Submit</button>
</form>
<p>Click the below button below to change the type of the above button from "submit" to "reset".</p>
<button onclick="changeType()">CHANGE</button>
<p id="Sample"></p>
<script>
   function changeType() {
      document.getElementById("Button1").type = "reset";
      document.getElementById("Sample").innerHTML = "The Submit button is now a reset
      button";
   }
</script>
</body>
</html>
This will produce the following output −
On filling the details and clicking CHANGE −
Now clicking on Submit (which is now reset) −
In the above example −
We have first created two text fields and a button with type “submit” that will submit our data −
<label>First Name: <input type="text" name="fname"><br><br></label>
<label>Surname: <input type="text" name="lname"><br><br></label>
<button id="Button1" type="submit">Submit</button>
We have then created the CHANGE button that will execute changeType() method on click −
<button onclick="changeType()">CHANGE</button>
The changeType() method gets the button element by using its id and sets its type to reset. Then the message regarding the change is reflected in the paragraph with “Id” sample. Now when you click on the submit button it will reset i.e clear the form data instead of submitting it −
function changeType() {
   document.getElementById("Button1").type = "reset";
   document.getElementById("Sample").innerHTML = "The Submit button is now a reset button";
}
Armstrong number within a range in JavaScript

Armstrong Numbers: A positive integer is called an Armstrong number (of order n) if −
abcd... = a^n + b^n + c^n + d^n + ...
We are required to write a JavaScript function that takes in an array of exactly two numbers
specifying a range.
The function should return an array of all the Armstrong numbers that falls in that range
(including the start and end numbers if they are Armstrong).
We will first separately write a function to detect Armstrong numbers and then iterate through
the range to fill the array with desired numbers.
Following is the code −
const range = [11, 1111];
const isArmstrong = (num) => {
   const numberOfDigits = ('' + num).length;
   let sum = 0;
   let temp = num;
   while (temp > 0) {
      let remainder = temp % 10;
      sum += remainder ** numberOfDigits;
      temp = parseInt(temp / 10);
   }
   return sum === num;
};
const findAllArmstrong = ([start, end]) => {
   const res = [];
   for(let i = start; i <= end; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(findAllArmstrong(range));
Following is the console output −
[ 153, 370, 371, 407 ]
How to get all the services based on their status in PowerShell?

Below commands will filter out services based on their Status (Running, Stopped).
To get all the running services on the local computer.
Get-Service | where{$_.Status -eq "Running"}
Running  TimeBrokerSvc      Time Broker
Running  TokenBroker        Web Account Manager
Running  TrkWks             Distributed Link Tracking Client
Running  UnistoreSvc_158379 User Data Storage_158379
Running  UserDataSvc_158379 User Data Access_158379
Running  UserManager        User Manager
Running  UsoSvc             Update Orchestrator Service
Running  VaultSvc           Credential Manager
Running  VMUSBArbService    VMware USB Arbitration Service
Running  WavesSysSvc        Waves Audio Services
Running  WbioSrvc           Windows Biometric Service
To get all the stopped services on the local computer.
Get-Service | where{$_.Status -eq "Stopped"}

Stopped  vmicvss            Hyper-V Volume Shadow Copy Requestor
Stopped  VSS                Volume Shadow Copy
Stopped  VSStandardColle... Visual Studio Standard Collector Se...
Stopped  W32Time            Windows Time
Stopped  WaaSMedicSvc       Windows Update Medic Service
Stopped  WalletService      WalletService
Stopped  WarpJITSvc         WarpJITSvc
Stopped  wbengine           Block Level Backup Engine Service
Stopped  wcncsvc            Windows Connect Now - Config Registrar
Stopped  WdNisSvc           Windows Defender Antivirus Network ...
Stopped  Wecsvc             Windows Event Collector
Stopped  WEPHOSTSVC         Windows Encryption Provider Host Se...
Tryit Editor v3.7

HTML Input types
Tryit: HTML input element
What are the rules for calling the superclass constructor C++?

In C++, we can derive some classes. Sometimes we need to call the super class (Base class) constructor when calling the constructor of the derived class. Unlike Java there is no reference variable for super class. If the constructor is non-parameterized, then it will be called automatically with the derived class, otherwise we have to put the super class constructor in the initializer list of the derived class.
In this example at first we will see constructor with no argument.
 Live Demo
#include <iostream>
using namespace std;
class MyBaseClass {
   public:
      MyBaseClass() {
         cout << "Constructor of base class" << endl;
      }
};
class MyDerivedClass : public MyBaseClass {
   public:
      MyDerivedClass() {
         cout << "Constructor of derived class" << endl;
      }
};
int main() {
   MyDerivedClass derived;
}
Constructor of base class
Constructor of derived class
Now let us see constructor which can take parameter.
 Live Demo
#include <iostream>
using namespace std;
class MyBaseClass {
   public:
   MyBaseClass(int x) {
      cout << "Constructor of base class: " << x << endl;
   }
};
class MyDerivedClass : public MyBaseClass { //base constructor as initializer list
   public:
      MyDerivedClass(int y) : MyBaseClass(50) {
         cout << "Constructor of derived class: " << y << endl;
      }
};
int main() {
   MyDerivedClass derived(100);
}
Constructor of base class: 50
Constructor of derived class: 100
list::begin() and list::end() in C++ STL - GeeksforGeeks

07 Dec, 2021
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.
begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.Syntax : 
listname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.

Examples:  
Input  : mylist{1, 2, 3, 4, 5};
         mylist.begin();
Output : returns an iterator to the element 1

Input  : mylist{8, 7};
         mylist.begin();
Output : returns an iterator to the element 8

Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. 
CPP
// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <list>using namespace std;  int main(){    // declaration of list container    list<int> mylist{ 1, 2, 3, 4, 5 };      // using begin() to print list    for (auto it = mylist.begin(); it !=                             mylist.end(); ++it)        cout << ' ' << *it;    return 0;}
Output: 
1 2 3 4 5

Time Complexity: O(1) 
end() function is used to return an iterator pointing to the last element of the list container. It is different from the back() function because the back() function returns a reference to the last element of the container but end() function returns a bidirectional iterator to the past last element of the container.Syntax : 
listname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the past last element.

Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. 
CPP
// CPP program to illustrate// Implementation of end() function#include <iostream>#include <list>using namespace std;  int main(){    // declaration of list container    list<int> mylist{ 1, 2, 3, 4, 5 };      // using end() to print list    for (auto it = mylist.begin(); it !=                                mylist.end(); ++it)        cout << ' ' << *it;    return 0;}
Output: 
1 2 3 4 5

Time Complexity: O(1) 
adityapal754
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Bitwise Operators in C/C++
Operator Overloading in C++
Copy Constructor in C++
Virtual Function in C++
Templates in C++ with Examples
rand() and srand() in C/C++
Map numbers to characters in JavaScript

Suppose we have the number 12145. We are required to write a function that maps the digits of
the number to English alphabets according to the following norms. The alphabets are to be mapped according to the 1 based index, like 'a' for 1 and 'b' for 2 'c' for 3 and so on.
There can be several ways for mapping a number. Let's take the above number 121415 for
example,
It can be mapped as −
12145->1,2,1,4,5->a,b,a,d,e
It also can be −
12145->12,1,4,5->l,a,d,e
It can also be −
12145->12,14,5->l,n,e
and so on, but 12145 can't be 1,2,1,45 because there’s is no mapping for 45 in the alphabets.
So, our function should return an array of all the permutations of the alphabet mappings.
The code for this will be −
const num = 12145;
const mapToAlphabets = num => {
   const numStr = '' + num;
   let res = [];
   const shoveElements = (left, right) => {
      if (!left.length) {
         res.push(right.map(el => {
            return (+el + 9).toString(36);
         }).join(''));
         return;
      };
      if(+left[0] > 0){
         shoveElements(left.slice(1), right.concat(left[0]));
      };
      if(left.length >= 2 && +(left.slice(0, 2)) <= 26){
         shoveElements(left.slice(2), right.concat(left.slice(0, 2)));
      };
   };
   shoveElements(numStr, []);
   return res;
}
console.log(mapToAlphabets(num));
The output in the console −
[ 'abade', 'abne', 'aude', 'lade', 'lne' ]
Implementation of Contiguous Memory Management Techniques - GeeksforGeeks

13 Apr, 2020
Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories:
(i) Contiguous
(ii) Non-contiguous 
Contiguous Memory Management Techniques:In this technique, memory is allotted in a continuous way to the processes. It has two types:
Fixed Partition Scheme:In the fixed partition scheme, memory is divided into fixed number of partitions. Fixed means number of partitions are fixed in the memory. In the fixed partition, in every partition only one process will be accommodated. Degree of multi-programming is restricted by number of partitions in the memory. Maximum size of the process is restricted by maximum size of the partition. Every partition is associated with the limit registers.
Limit Registers: It has two limit:
Lower Limit: Starting address of the partition.
Upper Limit: Ending address of the partition.
Internal Fragmentation is found in fixed partition scheme.To overcome the problem of internal fragmentation, instead of fixed partition scheme, variable partition scheme is used.
Variable Partition Scheme:In the variable partition scheme, initially memory will be single continuous free block. Whenever the request by the process arrives, accordingly partition will be made in the memory. If the smaller processes keep on coming then the larger partitions will be made into smaller partitions.
External Fragmentation is found in variable partition scheme.To overcome the problem of external fragmentation, compaction technique is used or non-contiguous memory management techniques are used.
Compaction:Moving all the processes toward the top or towards the bottom to make free available memory in a single continuous place is called as compaction. Compaction is undesirable to implement because it interrupts all the running processes in the memory.
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Normal Forms in DBMS
LRU Cache Implementation
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Inter Process Communication (IPC)
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
LRU Cache Implementation
Introduction of Deadlock in Operating System